diff options
Diffstat (limited to 'config')
295 files changed, 35253 insertions, 15299 deletions
diff --git a/config/apache_mod_security-dev/apache.template b/config/apache_mod_security-dev/apache.template new file mode 100644 index 00000000..69ffb9c7 --- /dev/null +++ b/config/apache_mod_security-dev/apache.template @@ -0,0 +1,572 @@ +<?php + // Mod_security enabled? + if($settings['memcachesize'] != "0") { + if(file_exists( APACHEDIR ."/libexec/apache22/mod_memcache.so")) + $mod_mem_cache = "LoadModule memcache_module libexec/apache22/mod_memcache.so\n"; + } + +/* +<IfModule mod_security2.c> + + + # Turn the filtering engine On or Off + SecFilterEngine On + + # XXX Add knobs for these + SecRuleEngine On + SecRequestBodyAccess On + SecResponseBodyAccess On + + SecRequestBodyInMemoryLimit {$secrequestbodyinmemorylimit} + SecRequestBodyLimit {$secrequestbodylimit} + + {$mod_security_custom} + + SecResponseBodyMimeTypesClear + SecResponseBodyMimeType (null) text/plain text/html text/css text/xml + + # XXX Add knobs for these + SecUploadDir /var/spool/apache/private + SecUploadKeepFiles Off + + # The audit engine works independently and + # can be turned On of Off on the per-server or + # on the per-directory basis + SecAuditEngine {$secauditengine} + + # XXX Add knobs for these + # Make sure that URL encoding is valid + SecFilterCheckURLEncoding On + + # XXX Add knobs for these + # Unicode encoding check + SecFilterCheckUnicodeEncoding On + + # XXX Add knobs for these + # Only allow bytes from this range + SecFilterForceByteRange 1 255 + + # Help prevent the effects of a Slowloris-type of attack + # $secreadstatelimit + + # Cookie format checks. + SecFilterCheckCookieFormat On + + # The name of the audit log file + SecAuditLog logs/audit_log + + #http-guardian Anti-dos protection + {$SecGuardianLog} + + # Should mod_security inspect POST payloads + SecFilterScanPOST On + + # Include rules from rules/ directory + {$mod_security_rules} + +</IfModule> + +*/ + +$apache_dir=APACHEDIR; + $apache_config = <<<EOF +################################################################################## +# NOTE: This file was generated by the pfSense package management system. # +# Please do not edit this file by hand! If you need to add functionality # +# then edit /usr/local/pkg/apache_mod_security* files. # +# # +# And don't forget to submit your changes to coreteam@pfsense.org # +################################################################################### +# +# This is the main Apache HTTP server configuration file. It contains the +# configuration directives that give the server its instructions. +# See <URL:http://httpd.apache.org/docs/2.2> for detailed information. +# In particular, see +# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html> +# for a discussion of each configuration directive. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "/var/log/foo_log" +# with ServerRoot set to "/usr/local" will be interpreted by the +# server as "/usr/local//var/log/foo_log". + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# Do not add a slash at the end of the directory path. If you point +# ServerRoot at a non-local disk, be sure to point the LockFile directive +# at a local disk. If you wish to share the same ServerRoot for multiple +# httpd daemons, you will need to change at least LockFile and PidFile. +# +ServerRoot "{$apache_dir}" + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the <VirtualHost> +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses. +# +Listen {$global_listen} +{$aliases} + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +# have to place corresponding `LoadModule' lines at this location so the +# LoadModule foo_module modules/mod_foo.so +LoadModule authn_file_module libexec/apache22/mod_authn_file.so +LoadModule authn_dbm_module libexec/apache22/mod_authn_dbm.so +LoadModule authn_anon_module libexec/apache22/mod_authn_anon.so +LoadModule authn_default_module libexec/apache22/mod_authn_default.so +LoadModule authn_alias_module libexec/apache22/mod_authn_alias.so +LoadModule authz_host_module libexec/apache22/mod_authz_host.so +LoadModule authz_groupfile_module libexec/apache22/mod_authz_groupfile.so +LoadModule authz_user_module libexec/apache22/mod_authz_user.so +LoadModule authz_dbm_module libexec/apache22/mod_authz_dbm.so +LoadModule authz_owner_module libexec/apache22/mod_authz_owner.so +LoadModule authz_default_module libexec/apache22/mod_authz_default.so +LoadModule auth_basic_module libexec/apache22/mod_auth_basic.so +LoadModule auth_digest_module libexec/apache22/mod_auth_digest.so +LoadModule file_cache_module libexec/apache22/mod_file_cache.so +LoadModule cache_module libexec/apache22/mod_cache.so +LoadModule disk_cache_module libexec/apache22/mod_disk_cache.so +LoadModule dumpio_module libexec/apache22/mod_dumpio.so +LoadModule include_module libexec/apache22/mod_include.so +LoadModule filter_module libexec/apache22/mod_filter.so +LoadModule charset_lite_module libexec/apache22/mod_charset_lite.so +LoadModule deflate_module libexec/apache22/mod_deflate.so +LoadModule log_config_module libexec/apache22/mod_log_config.so +LoadModule logio_module libexec/apache22/mod_logio.so +LoadModule env_module libexec/apache22/mod_env.so +LoadModule mime_magic_module libexec/apache22/mod_mime_magic.so +LoadModule cern_meta_module libexec/apache22/mod_cern_meta.so +LoadModule expires_module libexec/apache22/mod_expires.so +LoadModule headers_module libexec/apache22/mod_headers.so +LoadModule usertrack_module libexec/apache22/mod_usertrack.so +LoadModule unique_id_module libexec/apache22/mod_unique_id.so +LoadModule setenvif_module libexec/apache22/mod_setenvif.so +LoadModule version_module libexec/apache22/mod_version.so +LoadModule proxy_module libexec/apache22/mod_proxy.so +LoadModule proxy_connect_module libexec/apache22/mod_proxy_connect.so +LoadModule proxy_ftp_module libexec/apache22/mod_proxy_ftp.so +LoadModule proxy_http_module libexec/apache22/mod_proxy_http.so +LoadModule proxy_ajp_module libexec/apache22/mod_proxy_ajp.so +LoadModule proxy_balancer_module libexec/apache22/mod_proxy_balancer.so +LoadModule ssl_module libexec/apache22/mod_ssl.so +LoadModule mime_module libexec/apache22/mod_mime.so +LoadModule status_module libexec/apache22/mod_status.so +LoadModule autoindex_module libexec/apache22/mod_autoindex.so +LoadModule asis_module libexec/apache22/mod_asis.so +LoadModule info_module libexec/apache22/mod_info.so +LoadModule cgi_module libexec/apache22/mod_cgi.so +LoadModule vhost_alias_module libexec/apache22/mod_vhost_alias.so +LoadModule negotiation_module libexec/apache22/mod_negotiation.so +LoadModule dir_module libexec/apache22/mod_dir.so +LoadModule imagemap_module libexec/apache22/mod_imagemap.so +LoadModule actions_module libexec/apache22/mod_actions.so +LoadModule speling_module libexec/apache22/mod_speling.so +LoadModule userdir_module libexec/apache22/mod_userdir.so +LoadModule alias_module libexec/apache22/mod_alias.so +LoadModule rewrite_module libexec/apache22/mod_rewrite.so +LoadModule reqtimeout_module libexec/apache22/mod_reqtimeout.so +{$mod_mem_cache} + +<IfModule !mpm_netware_module> +<IfModule !mpm_winnt_module> +# +# If you wish httpd to run as a different user or group, you must run +# httpd as root initially and it will switch. +# +# User/Group: The name (or #number) of the user/group to run httpd as. +# It is usually good practice to create a dedicated user and group for +# running httpd, as with most system services. +# +User www +Group www + +</IfModule> +</IfModule> + +# 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# <VirtualHost> definition. These values also provide defaults for +# any <VirtualHost> containers you may define later in the file. +# +# All of these directives may appear inside <VirtualHost> containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# +# worker MPM +<IfModule worker.c> +{$performance_settings} +</IfModule> +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin {$global_site_email} + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# +ServerName {$servername} + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "{$apache_dir}/www/apache22" + +# +# Each directory to which Apache has access can be configured with respect +# to which services and features are allowed and/or disabled in that +# directory (and its subdirectories). +# +# First, we configure the "default" to be a very restrictive set of +# features. +# +<Directory /> + AllowOverride None + Order deny,allow + Deny from all +</Directory> + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# This should be changed to whatever you set DocumentRoot to. +# +#<Directory "{$apache_dir}/www/apachemodsecurity/"> +# # +# # Possible values for the Options directive are "None", "All", +# # or any combination of: +# # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews +# # +# # Note that "MultiViews" must be named *explicitly* --- "Options All" +# # doesn't give it to you. +# # +# # The Options directive is both complicated and important. Please see +# # http://httpd.apache.org/docs/2.2/mod/core.html#options +# # for more information. +# # +# Options Indexes FollowSymLinks +# +# # +# # AllowOverride controls what directives may be placed in .htaccess files. +# # It can be "All", "None", or any combination of the keywords: +# # Options FileInfo AuthConfig Limit +# # +# AllowOverride None +# +# # +# # Controls who can get stuff from this server. +# # +# Order allow,deny +# Allow from all +# +#</Directory> +# +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# +#<IfModule dir_module> +# DirectoryIndex index.html +#</IfModule> +# +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# +#<FilesMatch "^\.ht"> +# Order allow,deny +# Deny from all +# Satisfy All +#</FilesMatch> +# +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a <VirtualHost> +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a <VirtualHost> +# container, that host's errors will be logged there and not here. +# +ErrorLog "/var/log/httpd-error.log" + +# +# LogLevel: Control the number of messages logged to the error_log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + +<IfModule log_config_module> + # + # The following directives define some format nicknames for use with + # a CustomLog directive (see below). + # + LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined + LogFormat "%h %l %u %t \"%r\" %>s %b" common + + <IfModule logio_module> + # You need to enable mod_logio.c to use %I and %O + LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + </IfModule> + + # + # The location and format of the access logfile (Common Logfile Format). + # If you do not define any access logfiles within a <VirtualHost> + # container, they will be logged here. Contrariwise, if you *do* + # define per-<VirtualHost> access logfiles, transactions will be + # logged therein and *not* in this file. + # + #CustomLog "/var/log/httpd-access.log" common + + # + # If you prefer a logfile with access, agent, and referer information + # (Combined Logfile Format) you can use the following directive. + # + CustomLog "/var/log/httpd-access.log" combined +</IfModule> + +#<IfModule alias_module> +# # +# # Redirect: Allows you to tell clients about documents that used to +# # exist in your server's namespace, but do not anymore. The client +# # will make a new request for the document at its new location. +# # Example: +# # Redirect permanent /foo http://www.example.com/bar +# +# # +# # Alias: Maps web paths into filesystem paths and is used to +# # access content that does not live under the DocumentRoot. +# # Example: +# # Alias /webpath /full/filesystem/path +# # +# # If you include a trailing / on /webpath then the server will +# # require it to be present in the URL. You will also likely +# # need to provide a <Directory> section to allow access to +# # the filesystem path. +# +# # +# # ScriptAlias: This controls which directories contain server scripts. +# # ScriptAliases are essentially the same as Aliases, except that +# # documents in the target directory are treated as applications and +# # run by the server when requested rather than as documents sent to the +# # client. The same rules about trailing "/" apply to ScriptAlias +# # directives as to Alias. +# # +# ScriptAlias /cgi-bin/ "/usr/local/www/apache22/cgi-bin/" +# +#</IfModule> + +#<IfModule cgid_module> +# # +# # ScriptSock: On threaded servers, designate the path to the UNIX +# # socket used to communicate with the CGI daemon of mod_cgid. +# # +# #Scriptsock /var/run/cgisock +#</IfModule> + +# +# "/usr/local/www/apache22/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# +#<Directory "{$apache_dir}/www/apache22/cgi-bin"> +# AllowOverride None +# Options None +# Order allow,deny +# Allow from all +#</Directory> + +# +# DefaultType: the default MIME type the server will use for a document +# if it cannot otherwise determine one, such as from filename extensions. +# If your server contains mostly text or HTML documents, "text/plain" is +# a good value. If most of your content is binary, such as applications +# or images, you may want to use "application/octet-stream" instead to +# keep browsers from trying to display binary files as though they are +# text. +# +DefaultType text/plainm + +<IfModule mime_module> + # + # TypesConfig points to the file containing the list of mappings from + # filename extension to MIME-type. + # + TypesConfig etc/apache22/mime.types + + # + # AddType allows you to add to or override the MIME configuration + # file specified in TypesConfig for specific file types. + # + #AddType application/x-gzip .tgz + # + # AddEncoding allows you to have certain browsers uncompress + # information on the fly. Note: Not all browsers support this. + # + #AddEncoding x-compress .Z + #AddEncoding x-gzip .gz .tgz + # + # If the AddEncoding directives above are commented-out, then you + # probably should define those extensions to indicate media types: + # + AddType application/x-compress .Z + AddType application/x-gzip .gz .tgz + + # + # AddHandler allows you to map certain file extensions to "handlers": + # actions unrelated to filetype. These can be either built into the server + # or added with the Action directive (see below) + # + # To use CGI scripts outside of ScriptAliased directories: + # (You will also need to add "ExecCGI" to the "Options" directive.) + # + #AddHandler cgi-script .cgi + + # For type maps (negotiated resources): + #AddHandler type-map var + + # + # Filters allow you to process content before it is sent to the client. + # + # To parse .shtml files for server-side includes (SSI): + # (You will also need to add "Includes" to the "Options" directive.) + # + #AddType text/html .shtml + #AddOutputFilter INCLUDES .shtml +</IfModule> + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# +#MIMEMagicFile etc/apache22/magic + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: + +{$errordocument} + +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# EnableMMAP and EnableSendfile: On systems that support it, +# memory-mapping or the sendfile syscall is used to deliver +# files. This usually improves server performance, but must +# be turned off when serving from networked-mounted +# filesystems or if support for these functions is otherwise +# broken on your system. +# +#EnableMMAP off +#EnableSendfile off + +# Supplemental configuration +# +# The configuration files in the etc/apache22/extra/ directory can be +# included to add extra features or to modify the default configuration of +# the server, or you may simply copy their contents here and change as +# necessary. + +# Server-pool management (MPM specific) +#Include etc/apache22/extra/httpd-mpm.conf + +# Multi-language error messages +#Include etc/apache22/extra/httpd-multilang-errordoc.conf + +# Fancy directory listings +#Include etc/apache22/extra/httpd-autoindex.conf + +# Language settings +#Include etc/apache22/extra/httpd-languages.conf + +# User home directories +#Include etc/apache22/extra/httpd-userdir.conf + +# Real-time info on requests and configuration +#Include etc/apache22/extra/httpd-info.conf + +# Virtual hosts +#Include etc/apache22/extra/httpd-vhosts.conf + +# Local access to the Apache HTTP Server Manual +#Include etc/apache22/extra/httpd-manual.conf + +# Distributed authoring and versioning (WebDAV) +#Include etc/apache22/extra/httpd-dav.conf + +# Various default settings +#Include etc/apache22/extra/httpd-default.conf + +# Secure (SSL/TLS) connections +#Include etc/apache22/extra/httpd-ssl.conf +# +# Note: The following must must be present to support +# starting without SSL on platforms with no /dev/random equivalent +# but a statically compiled-in mod_ssl. +# +<IfModule ssl_module> +SSLRandomSeed startup builtin +SSLRandomSeed connect builtin +</IfModule> + +# Cache settings +{$mem_cache} +{$cache_root} + +#accf_http are not present on current build +AcceptFilter http none +AcceptFilter https none + +# Mod security +{$mod_security} + +# Proxysettings +{$mod_proxy} + +# Include anything else +Include etc/apache22/Includes/*.conf + +EOF; + +?>
\ No newline at end of file diff --git a/config/apache_mod_security-dev/apache_balancer.template b/config/apache_mod_security-dev/apache_balancer.template new file mode 100644 index 00000000..361a5ed4 --- /dev/null +++ b/config/apache_mod_security-dev/apache_balancer.template @@ -0,0 +1,40 @@ +<?php +$balancer_config= <<<EOF +################################################################################## +# NOTE: This file was generated by the pfSense package management system. # +# Please do not edit this file by hand! If you need to add functionality # +# then edit /usr/local/pkg/apache_* files. # +# # +# And don't forget to submit your changes to: # +# https://github.com/bsdperimeter/pfsense-packages # +################################################################################## +SetOutputFilter DEFLATE +SetInputFilter DEFLATE + +SetEnvIfNoCase Request_URI .(?:gif|jpe?g|png)$ no-gzip dont-vary +SetEnvIfNoCase Request_URI .(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary +SetEnvIfNoCase Request_URI .pdf$ no-gzip dont-vary + +AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/js text/javascript + +DeflateCompressionLevel 9 + +ProxyVia On +ProxyRequests Off +ProxyTimeout 600 + +<Proxy *> + Order Deny,Allow + Allow from all +</Proxy> + +<ProxyMatch \.(?i:cmd|exe|bat|com|vb?|ida|printer|htr|iso)$> + Order allow,deny + deny from all +</ProxyMatch> + +Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED + + +EOF; +?>
\ No newline at end of file diff --git a/config/apache_mod_security-dev/apache_balancer.xml b/config/apache_mod_security-dev/apache_balancer.xml new file mode 100755 index 00000000..b3acba57 --- /dev/null +++ b/config/apache_mod_security-dev/apache_balancer.xml @@ -0,0 +1,199 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + apache_balancer.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Marcello Coutinho + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code MUST retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form MUST reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>apachebalancer</name> + <version>none</version> + <title>Apache reverse proxy: Internal Web Servers Pool</title> + <include_file>/usr/local/pkg/apache_mod_security.inc</include_file> + <tabs> + <tab> + <text>Apache</text> + <url>/pkg_edit.php?xml=apache_settings.xml&id=0</url> + <active/> + </tab> + <tab> + <text>ModSecurity</text> + <url>/pkg_edit.php?xml=apache_mod_security_settings.xml</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=apache_mod_security_sync.xml</url> + </tab> + <tab> + <text>Daemon Options</text> + <url>/pkg_edit.php?xml=apache_settings.xml</url> + <tab_level>2</tab_level> + </tab> + <tab> + <text>Backends / Balancers</text> + <url>/pkg.php?xml=apache_balancer.xml</url> + <tab_level>2</tab_level> + <active/> + </tab> + <tab> + <text>Virutal Hosts</text> + <url>/pkg.php?xml=apache_virtualhost.xml</url> + <tab_level>2</tab_level> + </tab> + <tab> + <text>Logs</text> + <url>/apache_view_logs.php</url> + <tab_level>2</tab_level> + </tab> + + </tabs> + <adddeleteeditpagefields> + <columnitem> + <fielddescr>Status</fielddescr> + <fieldname>enable</fieldname> + </columnitem> + <columnitem> + <fielddescr>Alias</fielddescr> + <fieldname>name</fieldname> + </columnitem> + <columnitem> + <fielddescr>Protocol</fielddescr> + <fieldname>Proto</fieldname> + </columnitem> + <columnitem> + <fielddescr>Description</fielddescr> + <fieldname>description</fieldname> + </columnitem> + </adddeleteeditpagefields> + <fields> + <field> + <name>apache Reverse Peer Mappings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Enable</fielddescr> + <fieldname>enable</fieldname> + <description>If this field is checked, then this server poll will be available for virtual hosts config.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Balancer name</fielddescr> + <fieldname>name</fieldname> + <description><![CDATA[Name to identify this peer on apache conf<br> + example: www_site1]]></description> + <type>input</type> + <size>20</size> + </field> + <field> + <fielddescr>Description</fielddescr> + <fieldname>description</fieldname> + <description><![CDATA[Peer Description (optional)]]></description> + <type>input</type> + <size>60</size> + </field> + <field> + <fielddescr>Protocol</fielddescr> + <fieldname>proto</fieldname> + <description><![CDATA[Protocol listening on this internal server(s) port.]]></description> + <type>select</type> + <options> + <option> <name>HTTP</name> <value>http</value> </option> + <option> <name>HTTPS</name> <value>https</value> </option> + </options> + </field> +<field> + <fielddescr> + <![CDATA[Internal Servers]]> + </fielddescr> + <fieldname>additionalparameters</fieldname> + <type>rowhelper</type> + <rowhelper> + <rowhelperfield> + <fielddescr>fqdn or ip</fielddescr> + <fieldname>host</fieldname> + <description>Internal site IP or Hostnamesite</description> + <type>input</type> + <size>20</size> + </rowhelperfield> + <rowhelperfield> + <fielddescr>port</fielddescr> + <fieldname>port</fieldname> + <description>Internal site port</description> + <type>input</type> + <size>4</size> + </rowhelperfield> + <rowhelperfield> + <fielddescr>routeid</fielddescr> + <fieldname>routeid</fieldname> + <description>id to define stick connections</description> + <type>input</type> + <size>4</size> + </rowhelperfield> + <rowhelperfield> + <fielddescr>weight</fielddescr> + <fieldname>loadfactor</fieldname> + <description>Server weight</description> + <type>input</type> + <size>4</size> + </rowhelperfield> + <rowhelperfield> + <fielddescr>ping</fielddescr> + <fieldname>ping</fieldname> + <description>Server ping test interval</description> + <type>input</type> + <size>4</size> + </rowhelperfield> + <rowhelperfield> + <fielddescr>ttl</fielddescr> + <fieldname>ttl</fieldname> + <description>Server pint ttl</description> + <type>input</type> + <size>4</size> + </rowhelperfield> + </rowhelper> + </field> + + </fields> + <custom_php_resync_config_command> + apache_mod_security_resync(); + </custom_php_resync_config_command> +</packagegui>
\ No newline at end of file diff --git a/config/apache_mod_security-dev/apache_logs_data.php b/config/apache_mod_security-dev/apache_logs_data.php new file mode 100644 index 00000000..256ff144 --- /dev/null +++ b/config/apache_mod_security-dev/apache_logs_data.php @@ -0,0 +1,195 @@ +<?php +/* ========================================================================== */ +/* + apache_logs_data.php + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Marcello Coutinho + Copyright (C) 2012 Carlos Cesario + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code MUST retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form MUST reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ +# ------------------------------------------------------------------------------ +# Defines +# ------------------------------------------------------------------------------ +require_once("guiconfig.inc"); +# ------------------------------------------------------------------------------ +# Requests +# ------------------------------------------------------------------------------ + +if ($_GET) { + # Actions + $filter = preg_replace('/(@|!|>|<)/',"",htmlspecialchars($_REQUEST['strfilter'])); + $logtype = strtolower($_REQUEST['logtype']); + + // Get log type (access or error) + if ($logtype == "error") + $error="-error"; + + // Define log file name + $logfile ='/var/log/httpd-'. preg_replace("/(\s|'|\"|;)/","",$_REQUEST['logfile']) . $error.'.log'; + + if ($logfile == '/var/log/httpd-access-error.log') + $logfile = '/var/log/httpd-error.log'; + + //debug + echo "<tr valign=\"top\">\n"; + echo "<td colspan=\"5\" class=\"listlr\" align=\"center\" nowrap >$logfile</td>\n"; + if (file_exists($logfile)){ + + switch ($logtype) { + + case 'access': + //show table headers + show_tds(array("Time","Host","Response","Method","Request")); + + //fetch lines + $logarr=fetch_log($logfile); + + // Print lines + foreach ($logarr as $logent) { + // Split line by space delimiter + $logline = preg_split("/\n/", $logent); + /* + field 1: 189.29.36.26 + field 2: - + field 3: - + field 4: 04/Jul/2012 + field 5: 10:54:39 + field 6: -0300 + field 7: GET + field 8: / + field 9: HTTP/1.1 + field 10: 303 + field 11: - + field 12: - + field 13: Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.19 (KHTML, like Gecko) Ubuntu/12.04 Chromium/18.0.1025.151 Chrome/18.0.1025.151 Safari/535.19 + */ + $regex = '/^(\S+) (\S+) (\S+) \[([^:]+):(\d+:\d+:\d+) ([^\]]+)\] \"(\S+) (.*?) (\S+)\" (\S+) (\S+) "([^"]*)" "([^"]*)"$/'; + if (preg_match($regex, $logline[0],$line)) { + // Apply filter and color + if ($filter != "") + $line = preg_replace("@($filter)@i","<spam><font color='red'>$1</font></span>",$line); + $agent_info="onmouseover=\"jQuery('#bowserinfo').empty().html('{$line[13]}');\"\n"; + echo "<tr valign=\"top\" $agent_info>\n"; + echo "<td class=\"listlr\" align=\"center\" nowrap>{$line[5]}({$line[6]})</td>\n"; + echo "<td class=\"listr\" align=\"center\">{$line[1]}</td>\n"; + echo "<td class=\"listr\" align=\"center\">{$line[10]}</td>\n"; + echo "<td class=\"listr\" align=\"center\">{$line[7]}</td>\n"; + //echo "<td class=\"listr\" width=\"*\" onmouseout=\"this.style.color = ''; domTT_mouseout(this, event);\" onmouseover=\"domTT_activate(this, event, 'content', '{$line[13]}', 'trail', true, 'delay', 0, 'fade', 'both', 'fadeMax', 87, 'styleClass', 'niceTitle');\">{$line[8]}</td>\n"; + echo "<td class=\"listr\" width=\"*\">{$line[8]}</td>\n"; + echo "</tr>\n"; + } + } + break; + + case 'error': + //show table headers + show_tds(array("DateTime","Severity","Message")); + + //fetch lines + $logarr=fetch_log($logfile); + + // Print lines + foreach ($logarr as $logent) { + // Split line by space delimiter + $logline = preg_split("/\n/", $logent); + /* + field 1: Wed Jul 04 20:22:28 2012 + field 2: error + field 3: 187.10.53.87 + field 4: proxy: DNS lookup failure for: 192.168.15.272 returned by / + */ + $regex = '/^\[([^\]]+)\] \[([^\]]+)\] (?:\[client ([^\]]+)\])?\s*(.*)$/i'; + if (preg_match($regex, $logline[0],$line)) { + // Apply filter and color + if ($filter != "") + $line = preg_replace("@($filter)@i","<spam><font color='red'>$1</font></span>",$line); + + if ($line[3]) + $line[3] = gettext("Client address:") . " [{$line[3]}]"; + + echo "<tr valign=\"top\">\n"; + echo "<td class=\"listlr\" align=\"center\" nowrap>{$line[1]}</td>\n"; + echo "<td class=\"listr\" align=\"center\">{$line[2]}</td>\n"; + echo "<td class=\"listr\" width=\"*\">{$line[3]} {$line[4]}</td>\n"; + echo "</tr>\n"; + } + } + break; + } + } +} + +# ------------------------------------------------------------------------------ +# Functions +# ------------------------------------------------------------------------------ + +// From SquidGuard Package +function html_autowrap($cont) +{ + # split strings + $p = 0; + $pstep = 25; + $str = $cont; + $cont = ''; + for ( $p = 0; $p < strlen($str); $p += $pstep ) { + $s = substr( $str, $p, $pstep ); + if ( !$s ) break; + $cont .= $s . "<wbr/>"; + } + return $cont; +} + +// Show Logs +function fetch_log($log){ + global $filter; + // Get Data from form post + $lines = $_REQUEST['maxlines']; + if (preg_match("/!/",htmlspecialchars($_REQUEST['strfilter']))) + $grep_arg="-iv"; + else + $grep_arg="-i"; + + // Get logs based in filter expression + if($filter != "") { + exec("tail -2000 {$log} | /usr/bin/grep {$grep_arg} " . escapeshellarg($filter). " | tail -r -n {$lines}" , $logarr); + } + else { + exec("tail -r -n {$lines} {$log}", $logarr); + } + // return logs + return $logarr; +} + +function show_tds($tds){ + echo "<tr valign='top'>\n"; + foreach ($tds as $td){ + echo "<td class='listhdrr' align='center'>".gettext($td)."</td>\n"; + } + echo "</tr>\n"; +} + +?> diff --git a/config/apache_mod_security-dev/apache_logs_data.teste.php b/config/apache_mod_security-dev/apache_logs_data.teste.php new file mode 100644 index 00000000..c3f270bf --- /dev/null +++ b/config/apache_mod_security-dev/apache_logs_data.teste.php @@ -0,0 +1,186 @@ +<?php +/* ========================================================================== */ +/* + apache_logs_data.php + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Marcello Coutinho + Copyright (C) 2012 Carlos Cesario + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ +# ------------------------------------------------------------------------------ +# Defines +# ------------------------------------------------------------------------------ +require_once("guiconfig.inc"); + +# ------------------------------------------------------------------------------ +# Requests +# ------------------------------------------------------------------------------ + +if ($_GET) { + # Actions + $filter = preg_replace('/(@|!|>|<)/',"",htmlspecialchars($_GET['strfilter'])); + $logtype = strtolower($_GET['logtype']); + switch ($logtype) { + case 'access': + //192.168.15.227 - - [02/Jul/2012:19:57:29 -0300] "OPTIONS * HTTP/1.0" 200 - "-" "Apache/2.2.22 (FreeBSD) mod_ssl/2.2.22 OpenSSL/0.9.8q (internal dummy connection)" + $regex = '/^(\S+) (\S+) (\S+) \[([^:]+):(\d+:\d+:\d+) ([^\]]+)\] \"(\S+) (.*?) (\S+)\" (\S+) (\S+) "([^"]*)" "([^"]*)"$/i'; + + // Define log file + $log='/var/log/httpd-access.log'; + + //fetch lines + $logarr=fetch_log($log); + + /* + // Print lines + foreach ($logarr as $logent) { + // Split line by space delimiter + $logline = preg_split("/\n/", $logent); + + // Apply filter and color + // Need validate special chars + if ($filter != "") + $logline = preg_replace("@($filter)@i","<spam><font color='red'>$1</font></span>",$logline); + + echo $logline[0]."\n<br/>"; + } + */ + $x=1; + foreach ($logarr as $logent) { + + $logline = preg_split("/\n/", $logent); + if (preg_match($regex, $logline[0],$line)) { + echo "campo 1: $line[1] <br/>"; + echo "campo 2: $line[2] <br/>"; + echo "campo 3: $line[3] <br/>"; + echo "campo 4: $line[4] <br/>"; + echo "campo 5: $line[5] <br/>"; + echo "campo 6: $line[6] <br/>"; + echo "campo 7: $line[7] <br/>"; + echo "campo 8: $line[8] <br/>"; + echo "campo 9: $line[9] <br/>"; + echo "campo 10: $line[10] <br/>"; + echo "campo 11: $line[11] <br/>"; + echo "campo 12: $line[12] <br/>"; + echo "campo 13: $line[13] <br/>"; + } + echo "$x ===================<br>"; + $x++; + } + + + break; + + case 'error': + //[Wed Jul 04 20:22:28 2012] [error] [client 187.10.53.87] proxy: DNS lookup failure for: 192.168.15.272 returned by / + $regex = $regex = '/^\[([^\]]+)\] \[([^\]]+)\] (?:\[client ([^\]]+)\])?\s*(.*)$/i'; + + // Define log file + $log='/var/log/httpd-error.log'; + + //fetch lines + $logarr=fetch_log($log); + + /* + // Print lines + foreach ($logarr as $logent) { + // Split line by space delimiter + $logline = preg_split("/\n/", $logent); + + // Apply filter and color + // Need validate special chars + if ($filter != "") + $logline = preg_replace("@($filter)@i","<spam><font color='red'>$1</font></span>",$logline); + + echo $logline[0]."\n<br/>"; + } + */ + $x=1; + foreach ($logarr as $logent) { + + $logline = preg_split("/\n/", $logent); + if (preg_match($regex, $logline[0],$line)) { + echo "campo 1: $line[1] <br/>"; + echo "campo 2: $line[2] <br/>"; + echo "campo 3: $line[3] <br/>"; + echo "campo 4: $line[4] <br/>"; + echo "campo 5: $line[5] <br/>"; + echo "campo 6: $line[6] <br/>"; + echo "campo 7: $line[7] <br/>"; + echo "campo 8: $line[8] <br/>"; + echo "campo 9: $line[9] <br/>"; + echo "campo 10: $line[10] <br/>"; + echo "campo 11: $line[11] <br/>"; + echo "campo 12: $line[12] <br/>"; + echo "campo 13: $line[13] <br/>"; + } + echo "$x ===================<br>"; + $x++; + } + + + break; + } +} + +# ------------------------------------------------------------------------------ +# Functions +# ------------------------------------------------------------------------------ + + + +// Show Squid Logs +function fetch_log($log){ + global $filter; + // Get Data from form post + $lines = $_GET['maxlines']; + if (preg_match("/!/",htmlspecialchars($_GET['strfilter']))) + $grep_arg="-iv"; + else + $grep_arg="-i"; + + // Get logs based in filter expression + if($filter != "") { + exec("tail -2000 {$log} | /usr/bin/grep {$grep_arg} " . escapeshellarg($filter). " | tail -r -n {$lines}" , $logarr); + } + else { + exec("tail -r -n {$lines} {$log}", $logarr); + } + // return logs + return $logarr; +} + + + +foreach ($config['installedpackages']['apachevirtualhost']['config'] as $virtualhost){ + if (is_array($virtualhost['row']) && $virtualhost['enable'] == 'on'){ + if (preg_match("/(\S+)/",base64_decode($virtualhost['primarysitehostname']),$matches)) { + echo $matches[1]."<br>"; + } + } +} +?> diff --git a/config/apache_mod_security-dev/apache_mod_security.inc b/config/apache_mod_security-dev/apache_mod_security.inc new file mode 100644 index 00000000..cdee4f6b --- /dev/null +++ b/config/apache_mod_security-dev/apache_mod_security.inc @@ -0,0 +1,653 @@ +<?php +/* + apache_mod_security.inc + part of apache_mod_security package (http://www.pfSense.com) + Copyright (C) 2009, 2010 Scott Ullrich + Copyright (C) 2012 Marcello Coutinho + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code MUST retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form MUST reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. +*/ + +// Check to find out on which system the package is running +$pf_version=substr(trim(file_get_contents("/etc/version")),0,3); +if ($pf_version > 2.0) + define('APACHEDIR', '/usr/pbi/proxy_mod_security-' . php_uname("m")); +else + define('APACHEDIR', '/usr/local'); +// End of system check +define ('MODSECURITY_DIR','modsecurity-crs_2.2.5'); +// Rules directory location +define("rules_directory", APACHEDIR . "/". MODSECURITY_DIR); +function apache_textarea_decode($base64){ + return preg_replace("/\r\n/","\n",base64_decode($base64)); +} + +function apache_get_real_interface_address($iface) { + global $config; + if ($iface == "All") + return array("*", ""); + if (preg_match("/\d+\.\d+/",$iface)) + return array($iface, ""); + $iface = convert_friendly_interface_to_real_interface_name($iface); + $line = trim(shell_exec("ifconfig $iface | grep inet | grep -v inet6")); + list($dummy, $ip, $dummy2, $netmask) = explode(" ", $line); + return array($ip, long2ip(hexdec($netmask))); +} + +// Ensure NanoBSD can write. pkg_mgr will remount RO +conf_mount_rw(); + +// Needed mod_security directories +if(!is_dir(APACHEDIR . "/". MODSECURITY_DIR)) + safe_mkdir(APACHEDIR . "/". MODSECURITY_DIR); + +// Startup function +function apache_mod_security_start() { + exec(APACHEDIR . "/sbin/httpd -D NOHTTPACCEPT -k start"); +} + +// Shutdown function +function apache_mod_security_stop() { + exec(APACHEDIR . "/sbin/httpd -k stop"); +} + +// Restart function +function apache_mod_security_restart() { + if(is_process_running("httpd")) { + exec(APACHEDIR . "/sbin/httpd -k graceful"); + } else { + apache_mod_security_start(); + } +} + +// Install function +function apache_mod_security_install() { + global $config, $g; + + // We might be reinstalling and a configuration + // already exists. + generate_apache_configuration(); + + $filename = "apache_mod_security.sh"; + + $start = "/usr/local/bin/php -q -d auto_prepend_file=config.inc <<ENDPHP + <?php + require_once(\"functions.inc\"); + require_once(\"/usr/local/pkg/apache_mod_security.inc\"); + apache_mod_security_start(); + ?> +ENDPHP\n"; + + $stop = "/usr/local/bin/php -q -d auto_prepend_file=config.inc <<ENDPHP + <?php + require_once(\"functions.inc\"); + require_once(\"/usr/local/pkg/apache_mod_security.inc\"); + apache_mod_security_stop(); + ?> +ENDPHP\n"; + + write_rcfile(array( + "file" => $filename, + "start" => $start, + "stop" => $stop + ) + ); +} + +// Deinstall package routines +function apache_mod_security_deinstall() { + global $config, $g; + apache_mod_security_stop(); + exec("/bin/rm -rf " . APACHEDIR . "/". MODSECURITY_DIR); + exec("/bin/rm -f /usr/local/etc/rc.d/apache_mod_security.sh"); +} + +// Regenerate apache configuration and handle server restart +function apache_mod_security_resync() { + global $config, $g; + apache_mod_security_install(); + $dirs=array("base", "experimental","optional", "slr"); + if (! file_exists(APACHEDIR ."/". MODSECURITY_DIR . "/LICENSE")) + exec ("tar -xzf /usr/local/pkg/modsecurity-crs_2.2.5.tar.gz -C ".APACHEDIR); + $write_config=0; + foreach ($dirs as $dir){ + if ($handle = opendir(APACHEDIR ."/".MODSECURITY_DIR."/{$dir}_rules")) { + $write_config++; + $config['installedpackages']["modsecurityfiles{$dir}"]['config']=array(); + while (false !== ($entry = readdir($handle))) { + if (preg_match("/(\S+).conf/",$entry,$matches)) + $config["installedpackages"]["modsecurityfiles{$dir}"]["config"][]=array("file"=>$matches[1]); + } + closedir($handle); + } + } + if ($write_config > 0) + write_config(); + apache_mod_security_checkconfig(); + apache_mod_security_restart(); +} + +function apache_mod_security_checkconfig() { + global $config, $g; + $status = mwexec(APACHEDIR ."/sbin/httpd -t"); + if($status) { + $input_error = "apache_mod_security_package: There was an error parsing the Apache configuration: {$status}"; + log_error("apache_mod_security_package: There was an error parsing the Apache configuration: {$status}"); + } +} + +// Generate mod_proxy specific configuration +function generate_apache_configuration() { + global $config, $g; + $mod_proxy = ""; + $write_config=0; + // check current config + if (is_array($config['installedpackages']['apachesettings'])) + $settings=$config['installedpackages']['apachesettings']['config'][0]; + else + $setting=sarray(); + + // Set global site e-mail + if ($settings['globalsiteadminemail']){ + $global_site_email = $settings['globalsiteadminemail']; + } + else { + $global_site_email = "admin@admin.com"; + $config['installedpackages']['apachesettings']['config'][0]['globalsiteadminemail'] = "admin@admin.com"; + // update configuration with default value in this case + log_error("apache_mod_security_package: WARNING! Global site Administrator E-Mail address has not been set. Defaulting to bogus e-mail address."); + $write_config ++; + } + + // Set ServerName + if($settings['hostname'] != ""){ + $servername = $settings['hostname']; + } + else { + $servername = php_uname('n'); + $config['installedpackages']['apachesettings']['config'][0]['hostname'] = `hostname`; + // update configuration with default value in this case + $write_config ++; + } + + //check if servername has an valid ip + $ip=gethostbyname(php_uname('n')); + if ($ip==php_uname('n')){ + $error='apache_mod_security_package: Apache cannot start, hostname does not resolv. You can workaround this if you add a dns entry for '.php_uname('n').' or add a Host Overrides entry on services -> Dns Forwarder pointing '.php_uname('n').' to 127.0.0.1.'; + log_error($error); + file_notice("apache_mod_security", $error, "apache_mod_security", ""); + } + // Set global listening directive and ensure nothing is listening on this port already + $globalbind_ip = ($settings['globalbindtoipaddr'] ? $settings['globalbindtoipaddr'] : "*"); + $globalbind_port = $settings['globalbindtoport']; + if ($globalbind_port == ""){ + $globalbind_port ="80"; + $config['installedpackages']['apachesettings']['config'][0]['globalbindtoipport'] = $globalbind_port; + $write_config ++; + } + $global_listen ="{$globalbind_ip}:{$globalbind_port}"; + // update configuration with default value in this case + if ($write_config > 0) + write_config(); + + // check if any daemon is using apache ip/port + exec("/usr/bin/sockstat | grep -v ' httpd ' | awk '{ print $6 }' | grep ':{$globalbind_port}'",$socksstat); + unset ($already_binded); + if(is_array($socksstat)) { + foreach($socksstat as $ss) { + list($ss_ip,$ss_port)=explode(":",$ss); + #check if port is in use + if($ss_port == $globalbind_port) { + #check if it's the same ip or any ip + if ($globalbind_ip = "*" || $globalbind_ip == $ss_ip) + $already_binded = true; + $input_errors[] = "Sorry, there is a process already listening on port {$globalbind}"; + } + } + } + if(isset($already_binded)) + log_error("apache_mod_security_package: Could not start daemon on port {$global_listen}. Another process is already bound to this port."); + + //performance settings + //reference http://httpd.apache.org/docs/2.2/mod/mpm_common.html + $performance_settings="KeepAlive {$settings['keepalive']}\n"; + if ($settings['maxkeepalivereq']) + $performance_settings .= "MaxKeepAliveRequests {$settings['maxkeepalivereq']}\n"; + if ($settings['keepalivetimeout']) + $performance_settings .= "KeepAliveTimeout {$settings['keepalivetimeout']}\n"; + if ($settings['serverlimit']) + $performance_settings .= "ServerLimit {$settings['serverlimit']}\n"; + if ($settings['startservers']) + $performance_settings .= "StartServers {$settings['startservers']}\n"; + if ($settings['minsparethreads']) + $performance_settings .= "MinSpareThreads {$settings['minsparethreads']}\n"; + if ($settings['maxsparethreads']) + $performance_settings .= "MaxSpareThreads {$settings['maxsparethreads']}\n"; + if ($settings['threadslimit']) + $performance_settings .= "ThreadsLimit {$settings['threadslimit']}\n"; + if ($settings['threadstacksize']) + $performance_settings .= "ThreadStackSize {$settings['threadstacksize']}\n"; + if ($settings['threadsperchild']) + $performance_settings .= "ThreadsPerChild {$settings['threadsperchild']}\n"; + if ($settings['maxclients']) + $performance_settings .= "MaxClients {$settings['maxclients']}\n"; + if ($settings['maxrequestsperchild']) + $performance_settings .= "MaxRequestsPerChild {$settings['maxrequestsperchild']}\n"; + + // Setup mem_cache + if(file_exists(APACHEDIR ."/libexec/apache22/mod_memcache.so") && $settings['memcachesize'] != "0") { + //$mem_cache = "MCacheSize ".( $settings['memcachesize'] ? $settings['memcachesize'] : "100")."\n"; + } + + // CacheRoot Directive + if($settings['diskcachesize'] != "0") { + safe_mkdir("/var/db/apachemodsecuritycache"); + $cache_root .= "CacheRoot /var/db/apachemodsecuritycache\n"; + $cache_root .= "CacheMaxFileSize ".($settings['diskcachesize'] ? $settings['diskcachesize'] : "1000000")."\n"; + } + + // SecRequestBodyInMemoryLimit Directive + $secrequestbodyinmemorylimit = ($settings['secrequestbodyinmemorylimit'] ? $settings['secrequestbodyinmemorylimit'] : "131072"); + + // SecRequestBodyLimit + $secrequestbodylimit = ($settings['secrequestbodylimit'] ? $settings['secrequestbodylimit'] :"10485760"); + + // ErrorDocument + $errordocument = ($settings['errordocument'] ? $settings['errordocument'] : ""); + + // SecAuditEngine + $secauditengine = ($settings['secauditengine'] ? $settings['secauditengine'] : "RelevantOnly"); + + // SecReadStateLimit + $secreadstatelimit = ($settings['SecReadStateLimit'] ? $settings['SecReadStateLimit'] :""); + + //Configure balancers/backends + if (is_array($config['installedpackages']['apachebalancer'])){ + #load conf template + include("/usr/local/pkg/apache_balancer.template"); + + #check balancer members + foreach ($config['installedpackages']['apachebalancer']['config'] as $balancer){ + if (is_array($balancer['row']) && $balancer['enable'] == 'on'){ + $balancer_config.="# {$balancer['description']}\n"; + $balancer_config.="<Proxy balancer://{$balancer['name']}>\n"; + foreach($balancer['row'] as $server){ + $options =($server['port'] ? ":{$server['port']}" : ""); + + $options.=($server['routeid'] ? " route={$server['routeid']}" : ""); + $options.=($server['loadfactor'] ? " loadfactor={$server['loadfactor']}" : ""); + if (isset($server['ping'])){ + $options.= " ping={$server['ping']}"; + $options.=($server['ttl'] ? " ttl={$server['ttl']}" : ""); + } + $balancer_config.=" BalancerMember {$balancer['proto']}://{$server['host']}{$options}\n"; + } + #check if stick connections are set + if ($balancer['row'][0]['routeid'] !="") + $balancer_config.=" ProxySet stickysession=ROUTEID\n"; + $balancer_config.="</Proxy>\n\n"; + } + } + //write balancer conf + file_put_contents(APACHEDIR."/etc/apache22/Includes/balancers.conf",$balancer_config,LOCK_EX); + } + + //configure virtual hosts + if (is_array($config['installedpackages']['apachevirtualhost'])){ + $vh_config= <<<EOF +################################################################################## +# NOTE: This file was generated by the pfSense package management system. # +# Please do not edit this file by hand! If you need to add functionality # +# then edit /usr/local/pkg/apache_* files. # +# # +# And don't forget to submit your changes to: # +# https://github.com/bsdperimeter/pfsense-packages # +################################################################################## + + +EOF; + $default_port=array('http'=>'80', 'https'=> '443'); + foreach ($config['installedpackages']['apachevirtualhost']['config'] as $virtualhost){ + if (is_array($virtualhost['row']) && $virtualhost['enable'] == 'on'){ + $iface_address = apache_get_real_interface_address($virtualhost['interface']); + $ip=$iface_address[0]; + $port=($virtualhost['port'] ? $virtualhost['port'] : $default_port[$virtualhost['proto']]); + $vh_config.="# {$virtualhost['description']}\n"; + $vh_config.="<VirtualHost {$ip}:{$port}>\n"; + $vh_config.=" ServerName ". preg_replace ("/\r\n(\S+)/","\n ServerAlias $1",base64_decode($virtualhost['primarysitehostname'])) ."\n"; + $vh_config.=" ServerAdmin ".($virtualhost['siteemail'] ? $virtualhost['siteemail'] : $settings['globalsiteadminemail'])."\n"; + #check log + switch ($virtualhost['logfile']){ + case "default": + $vh_config.=" ErrorLog /var/log/httpd-error.log\n"; + $vh_config.=" CustomLog /var/log/httpd.log combined\n"; + break; + case "create": + if(preg_match("/(\S+)/",base64_decode($virtualhost['primarysitehostname']),$matches)) + $vh_config.=" ErrorLog /var/log/httpd-{$matches[1]}-error.log\n"; + $vh_config.=" CustomLog /var/log/httpd-{$matches[1]}.log combined\n"; + break; + } + + if($virtualhost['preserveproxyhostname']) + $vh_config .= " ProxyPreserveHost on\n"; + + #check ssl + if(isset($virtualhost["ssl_cert"]) && $virtualhost["ssl_cert"] !="none" && $virtualhost["proto"] == "https") { + $vh_config.= " SSLEngine on\n SSLProtocol all -SSLv2\n SSLProxyEngine on\n SSLProxyVerify none\n"; + $vh_config.= " SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL\n"; + + $svr_cert = lookup_cert($virtualhost["ssl_cert"]); + if ($svr_cert != false) { + if(base64_decode($svr_cert['crt'])) { + file_put_contents(APACHEDIR . "/etc/apache22/{$virtualhost["ssl_cert"]}.crt",apache_textarea_decode($svr_cert['crt']),LOCK_EX); + $vh_config.= " SSLCertificateFile ". APACHEDIR . "/etc/apache22/{$virtualhost["ssl_cert"]}.crt\n"; + } + if(base64_decode($svr_cert['prv'])) { + file_put_contents(APACHEDIR . "/etc/apache22/{$virtualhost["ssl_cert"]}.key",apache_textarea_decode($svr_cert['prv']),LOCK_EX); + $vh_config.= " SSLCertificateKeyFile ". APACHEDIR . "/etc/apache22/{$virtualhost["ssl_cert"]}.key\n"; + } + } + $svr_ca =lookup_ca($virtualhost["reverse_int_ca"]); + if ($svr_ca != false) { + file_put_contents(APACHEDIR . "/etc/apache22/{$virtualhost["reverse_int_ca"]}.crt",apache_textarea_decode($svr_ca['crt']),LOCK_EX); + $vh_config.= " SSLCACertificateFile ". APACHEDIR . "/etc/apache22/{$virtualhost["reverse_int_ca"]}.crt\n"; + } + } + #Custom Options + $vh_config.= apache_textarea_decode($virtualhost['custom'])."\n\n"; + + #Check virtualhost locations + foreach ($virtualhost['row'] as $backend){ + $vh_config.=" <Location ".($backend['sitepath'] ? $backend['sitepath'] : "/").">\n"; + $vh_config.=" ProxyPass balancer://{$backend['balancer']}{$backend['backendpath']}\n"; + $vh_config.=" ProxyPassReverse balancer://{$backend['balancer']}{$backend['backendpath']}\n"; + if ($backend['compress']== "no") + $vh_config.=" SetInputFilter INFLATE\n SetOutputFilter INFLATE\n"; + if (is_array($config['installedpackages']['apachemodsecuritymanipulation'])){ + foreach($config['installedpackages']['apachemodsecuritymanipulation']['config'] as $manipulation){ + if ($backend['modsecmanipulation'] == $manipulation['name']){ + if (is_array($manipulation['row'])) + foreach ($manipulation['row'] as $secrule) + $vh_config.=" {$secrule['type']} {$secrule['value']}\n"; + } + } + } + $vh_config.=" </Location>\n\n"; + } + $vh_config.="</VirtualHost>\n"; + } + } + //write balancer conf + file_put_contents(APACHEDIR."/etc/apache22/Includes/virtualhosts.conf",$vh_config,LOCK_EX); + } + // check/fix perl version on mod_security util files + $perl_files= array("httpd-guardian.pl","rules-updater.pl","runav.pl","arachni2modsec.pl","zap2modsec.pl","regression_tests/rulestest.pl"); + foreach ($perl_files as $perl_file){ + $file_path=rules_directory."/util/"; + if (file_exists($file_path.$perl_file)){ + $script=preg_replace("/#!\S+perl/","#!".APACHEDIR."/bin/perl",file_get_contents($file_path.$perl_file)); + file_put_contents($file_path.$perl_file,$script,LOCK_EX); + } + } + // check/fix spread libs location + $perl_libs= array("libspread.a","libspread.so.1"); + foreach ($perl_libs as $perl_lib){ + $file_path=APACHEDIR."/lib/"; + if (!file_exists("/lib/".$perl_lib) && file_exists("{$file_path}{$perl_lib}")){ + copy("{$file_path}{$perl_lib}","/lib/{$perl_lib}"); + if ($perl_lib == "libspread.so.1") + copy("{$file_path}{$perl_lib}","/lib/libspread.so"); + } + } + + //mod_security settings + if (is_array($config['installedpackages']['apachemodsecuritysettings']['config'])){ + $mods_settings=$config['installedpackages']['apachemodsecuritysettings']['config'][0]; + if ($mods_settings!="") + $SecGuardianLog="SecGuardianLog \"|".rules_directory."/util/httpd-guardian\""; + } + + //fix http-guardian.pl block bins + //$file_path=APACHEDIR.MODSECURITY_DIR."/util/".$perl_lib; + //if (file_exists("/lib/".$perl_lib) && file_exists($file_path.$perl_lib)){ + + //old code + $mod_proxy .= <<<EOF + +# Off when using ProxyPass +ProxyRequests off + +<Proxy *> + Order deny,allow + Allow from all +</Proxy> + +EOF; + + /* + ##################################################### + # Format for the Proxy servers: + # Please do not delete these from the source file + # in any "cleanups" that you feel you are performing. + # They are here for sanity checking the code. + #----------------1 backend ip--------------------- + #<VirtualHost IP:port> + # ServerAdmin $serveradmin + # ServerName $primarysitehostname + # ServerAlias $additionalsitehostnames + # ProxyPass / $backendwebserverURL + # ProxyPassReverse / $backendwebserverURL + #</VirtualHost> + #where serveralias will be a space-separated list of "additional site hostnames" + #i.e. if you have www1.example.com and www2.example.com there, it's "ServerAlias www1.example.com www2.example.com" + #------------------------------------------------- + #------------mutliple backend ips----------------- + # Add: + #<Proxy balancer://$sitename> + # BalancerMember $backend1 + # BalancerMember $backend2 + #</Proxy> + # Change: + # ProxyPass / balancer://$sitename/ + # ProxyPassReverse / balancer://$sitename/ + #------------------------------------------------- + ##################################################### + */ + $mod_proxy .= "\n"; + + $configuredaliases = array(); + // Read already configured addresses + if (is_array($settings['row'])){ + foreach($settings['row'] as $row) { + if ($row['ipaddress'] && $row['ipport']) + $configuredaliases[] = $row; + } + } + + // clear list of bound addresses before updating + $config['installedpackages']['apachesettings']['config'][0]['row'] = array(); + + // Process proxy sites + // Configure NameVirtualHost directives + $aliases = ""; + $processed = array(); + if(is_array($config['installedpackages']['apachemodsecurity'])) { + foreach($config['installedpackages']['apachemodsecurity']['config'] as $ams) { + if($ams['ipaddress'] && $ams['port']) + $local_ip_port = "{$ams['ipaddress']}:{$ams['port']}"; + else + $local_ip_port = $global_listen; + // Do not add entries twice. + if(!in_array($local_ip_port, $processed)) { + // explicit bind if not global ip:port + if ($local_ip_port != $global_listen) { + $aliases .= "Listen $local_ip_port\n"; + // Automatically add this to configuration + $config['installedpackages']['apachesettings']['config'][0]['row'][] = array('ipaddress' => $ams['ipaddress'], 'ipport' => $ams['port']); + } + $mod_proxy .= "NameVirtualHost $local_ip_port\n"; + $processed[] = $local_ip_port; + } + } + } + +//** Uncomment to allow adding ip/ports not used by any site proxies +//** Otherwise unused addresses/ports will be automatically deleted from the configuration +// foreach ($configuredaliases as $ams) { +// $local_ip_port = "{$ams['ipaddress']}:{$ams['ipport']}"; +// if(!in_array($local_ip_port, $processed)) { +// // explicit bind if not global ip:port +// if ($local_ip_port != $global_listen) { +// $aliases .= "Listen $local_ip_port\n"; +// // Automatically add this to configuration +// $config['installedpackages']['apachesettings']['config'][0]['row'][] = array('ipaddress' => $ams['ipaddress'], 'ipport' => $ams['ipport']); +// } +// } +// } + + // update configuration with actual ip bindings + write_config($pkg['addedit_string']); + + + // Setup mod_proxy entries $mod_proxy + if($config['installedpackages']['apachemodsecurity']) { + foreach($config['installedpackages']['apachemodsecurity']['config'] as $ams) { + // Set rowhelper used variables + $additionalsitehostnames = ""; + if (is_array($ams['row'])){ + foreach($ams['row'] as $row) { + if ($row['additionalsitehostnames']) + $additionalsitehostnames .= "{$row['additionalsitehostnames']} "; + } + } + $backend_sites = ""; + $sslproxyengine = ""; + $backend_sites_count = 0; + $balancer_members = ""; // not technically needed. + if (is_array($ams['row'])){ + foreach($ams['row'] as $row) { + if ($row['webserveripaddr']) { + $normalised_ipaddr = ""; + if (substr(trim($row['webserveripaddr']), 0, strlen("https:")) == "https:") { + // if backend is https, then enable SSLProxyEngine + $sslproxyengine = "SSLProxyEngine on"; + } else if (substr(trim($row['webserveripaddr']), 0, strlen("http:")) != "http:") { + // Ensure leading http(s):// + $normalised_ipaddr .= "http://"; + } + $normalised_ipaddr .= trim($row['webserveripaddr']); + $balancer_members .= " BalancerMember " . $normalised_ipaddr . "\n"; + // Ensure trailing / + if(substr($normalised_ipaddr,-1) != "/") { + $normalised_ipaddr .= "/"; + } + $backend_sites .= $normalised_ipaddr . " "; + $backend_sites_count++; + } + } + } + // Set general items + if($ams['siteemail']) + $serveradmin = $ams['siteemail']; + else + $serveradmin = $global_site_email; + if($ams['primarysitehostname']) + $primarysitehostname = $ams['primarysitehostname']; + $sitename = str_replace(" ", "", $ams['sitename']); + // Set local listening directive + if($ams['ipaddress'] && $ams['port']) + $local_ip_port = "{$ams['ipaddress']}:{$ams['port']}"; + else + $local_ip_port = $global_listen; + // Is this item a load balancer + if($backend_sites_count>1) { + $balancer = true; + $mod_proxy .= "<Proxy balancer://{$sitename}>\n"; + $mod_proxy .= $balancer_members; + $mod_proxy .= "</Proxy>\n"; + $backend_sites = " balancer://{$sitename}/"; + $sitename = ""; // we are not using sitename in this case + } + // Set SSL items + if($ams['siteurl']) + $siteurl = $ams['siteurl']; + if($ams['certificatefile']) + $certificatefile = $ams['certificatefile']; + if($ams['certificatekeyfile']) + $certificatekeyfile = $ams['certificatekeyfile']; + if($ams['certificatechainfile']) + $certificatechainfile = $ams['certificatechainfile']; + // Begin VirtualHost + $mod_proxy .= "\n<VirtualHost {$local_ip_port}>\n"; + if($siteurl == "HTTPS" && $certificatefile && $certificatekeyfile) { + $mod_proxy .= " SSLEngine on\n"; + if ($certificatefile) + $mod_proxy .= " SSLCertificateFile /usr/local/etc/apache22/$certificatefile\n"; + if ($certificatekeyfile) + $mod_proxy .= " SSLCertificateKeyFile /usr/local/etc/apache22/$certificatekeyfile\n"; + if ($certificatechainfile) + $mod_proxy .= " SSLCertificateChainFile /usr/local/etc/apache22/$certificatechainfile\n"; + } + if($sslproxyengine) + $mod_proxy .= " {$sslproxyengine}\n"; + if($additionalsitehostnames) + $mod_proxy .= " ServerAlias $additionalsitehostnames\n"; + if($serveradmin) + $mod_proxy .= " ServerAdmin $serveradmin\n"; + if($primarysitehostname) + $mod_proxy .= " ServerName $primarysitehostname \n"; + if($backend_sites) { + $mod_proxy .= " ProxyPassReverse /{$sitename} {$backend_sites}\n"; + $mod_proxy .= " ProxyPass / {$backend_sites}\n"; + } + if($ams['preserveproxyhostname']) + $mod_proxy .= " ProxyPreserveHost on\n"; + $mod_proxy .= "</VirtualHost>\n\n"; + // End VirtualHost + } + } + + if($config['installedpackages']['apachesettings']['config'][0]['modsecuritycustom']) + $mod_security_custom = $config['installedpackages']['apachesettings']['config'][0]['modsecuritycustom']; + + // Process and include rules + if(is_dir(rules_directory)) { + $mod_security_rules = ""; + $files = return_dir_as_array(rules_directory); + foreach($files as $file) { + if(file_exists(rules_directory . "/" . $file)) { + // XXX: TODO integrate snorts rule on / off thingie + $file_txt = file_get_contents(rules_directory . "/" . $file); + $mod_security_rules .= $file_txt . "\n"; + } + } + } + + #include file templates + include ("/usr/local/pkg/apache.template"); + + file_put_contents(APACHEDIR . "/etc/apache22/httpd.conf",$apache_config,LOCK_EX); +} + +?> diff --git a/config/apache_mod_security-dev/apache_mod_security.template b/config/apache_mod_security-dev/apache_mod_security.template new file mode 100644 index 00000000..e5a2c864 --- /dev/null +++ b/config/apache_mod_security-dev/apache_mod_security.template @@ -0,0 +1,210 @@ +<?php + // Mod_security enabled? + if($modsec_settings['enablemodsecurity']) { + $enable_mod_security = true; + $mod_security = <<< EOF +# -- Rule engine initialization ---------------------------------------------- + +# Enable ModSecurity, attaching it to every transaction. Use detection +# only to start with, because that minimises the chances of post-installation +# disruption. +# +SecRuleEngine DetectionOnly + + +# -- Request body handling --------------------------------------------------- + +# Allow ModSecurity to access request bodies. If you don't, ModSecurity +# won't be able to see any POST parameters, which opens a large security +# hole for attackers to exploit. +# +SecRequestBodyAccess On + + +# Enable XML request body parser. +# Initiate XML Processor in case of xml content-type +# +SecRule REQUEST_HEADERS:Content-Type "text/xml" \ + "phase:1,t:none,t:lowercase,pass,nolog,ctl:requestBodyProcessor=XML" + + +# Maximum request body size we will accept for buffering. If you support +# file uploads then the value given on the first line has to be as large +# as the largest file you are willing to accept. The second value refers +# to the size of data, with files excluded. You want to keep that value as +# low as practical. +# +SecRequestBodyLimit 13107200 +SecRequestBodyNoFilesLimit 131072 + +# Store up to 128 KB of request body data in memory. When the multipart +# parser reachers this limit, it will start using your hard disk for +# storage. That is slow, but unavoidable. +# +SecRequestBodyInMemoryLimit 131072 + +# What do do if the request body size is above our configured limit. +# Keep in mind that this setting will automatically be set to ProcessPartial +# when SecRuleEngine is set to DetectionOnly mode in order to minimize +# disruptions when initially deploying ModSecurity. +# +SecRequestBodyLimitAction Reject + +# Verify that we've correctly processed the request body. +# As a rule of thumb, when failing to process a request body +# you should reject the request (when deployed in blocking mode) +# or log a high-severity alert (when deployed in detection-only mode). +# +SecRule REQBODY_ERROR "!@eq 0" \ +"phase:2,t:none,log,deny,status:400,msg:'Failed to parse request body.',logdata:'%{reqbody_error_msg}',severity:2" + +# By default be strict with what we accept in the multipart/form-data +# request body. If the rule below proves to be too strict for your +# environment consider changing it to detection-only. You are encouraged +# _not_ to remove it altogether. +# +SecRule MULTIPART_STRICT_ERROR "!@eq 0" \ +"phase:2,t:none,log,deny,status:44,msg:'Multipart request body \ +failed strict validation: \ +PE %{REQBODY_PROCESSOR_ERROR}, \ +BQ %{MULTIPART_BOUNDARY_QUOTED}, \ +BW %{MULTIPART_BOUNDARY_WHITESPACE}, \ +DB %{MULTIPART_DATA_BEFORE}, \ +DA %{MULTIPART_DATA_AFTER}, \ +HF %{MULTIPART_HEADER_FOLDING}, \ +LF %{MULTIPART_LF_LINE}, \ +SM %{MULTIPART_SEMICOLON_MISSING}, \ +IQ %{MULTIPART_INVALID_QUOTING}, \ +IH %{MULTIPART_INVALID_HEADER_FOLDING}, \ +IH %{MULTIPART_FILE_LIMIT_EXCEEDED}'" + +# Did we see anything that might be a boundary? +# +SecRule MULTIPART_UNMATCHED_BOUNDARY "!@eq 0" \ +"phase:2,t:none,log,deny,status:44,msg:'Multipart parser detected a possible unmatched boundary.'" + +# PCRE Tuning +# We want to avoid a potential RegEx DoS condition +# +SecPcreMatchLimit 1000 +SecPcreMatchLimitRecursion 1000 + +# Some internal errors will set flags in TX and we will need to look for these. +# All of these are prefixed with "MSC_". The following flags currently exist: +# +# MSC_PCRE_LIMITS_EXCEEDED: PCRE match limits were exceeded. +# +SecRule TX:/^MSC_/ "!@streq 0" \ + "phase:2,t:none,deny,msg:'ModSecurity internal error flagged: %{MATCHED_VAR_NAME}'" + + +# -- Response body handling -------------------------------------------------- + +# Allow ModSecurity to access response bodies. +# You should have this directive enabled in order to identify errors +# and data leakage issues. +# +# Do keep in mind that enabling this directive does increases both +# memory consumption and response latency. +# +SecResponseBodyAccess On + +# Which response MIME types do you want to inspect? You should adjust the +# configuration below to catch documents but avoid static files +# (e.g., images and archives). +# +SecResponseBodyMimeType text/plain text/html text/xml + +# Buffer response bodies of up to 512 KB in length. +SecResponseBodyLimit 524288 + +# What happens when we encounter a response body larger than the configured +# limit? By default, we process what we have and let the rest through. +# That's somewhat less secure, but does not break any legitimate pages. +# +SecResponseBodyLimitAction ProcessPartial + + +# -- Filesystem configuration ------------------------------------------------ + +# The location where ModSecurity stores temporary files (for example, when +# it needs to handle a file upload that is larger than the configured limit). +# +# This default setting is chosen due to all systems have /tmp available however, +# this is less than ideal. It is recommended that you specify a location that's private. +# +SecTmpDir /tmp/ + +# The location where ModSecurity will keep its persistent data. This default setting +# is chosen due to all systems have /tmp available however, it +# too should be updated to a place that other users can't access. +# +SecDataDir /tmp/ + + +# -- File uploads handling configuration ------------------------------------- + +# The location where ModSecurity stores intercepted uploaded files. This +# location must be private to ModSecurity. You don't want other users on +# the server to access the files, do you? +# +#SecUploadDir /opt/modsecurity/var/upload/ + +# By default, only keep the files that were determined to be unusual +# in some way (by an external inspection script). For this to work you +# will also need at least one file inspection rule. +# +#SecUploadKeepFiles RelevantOnly + +# Uploaded files are by default created with permissions that do not allow +# any other user to access them. You may need to relax that if you want to +# interface ModSecurity to an external program (e.g., an anti-virus). +# +#SecUploadFileMode 0600 + + +# -- Debug log configuration ------------------------------------------------- + +# The default debug log configuration is to duplicate the error, warning +# and notice messages from the error log. +# +#SecDebugLog /opt/modsecurity/var/log/debug.log +#SecDebugLogLevel 3 + + +# -- Audit log configuration ------------------------------------------------- + +# Log the transactions that are marked by a rule, as well as those that +# trigger a server error (determined by a 5xx or 4xx, excluding 404, +# level response status codes). +# +SecAuditEngine RelevantOnly +SecAuditLogRelevantStatus "^(?:5|4(?!04))" + +# Log everything we know about a transaction. +SecAuditLogParts ABIJDEFHZ + +# Use a single file for logging. This is much easier to look at, but +# assumes that you will use the audit log only ocassionally. +# +SecAuditLogType Serial +SecAuditLog /var/log/modsec_audit.log + +# Specify the path for concurrent audit logging. +#SecAuditLogStorageDir /opt/modsecurity/var/audit/ + + +# -- Miscellaneous ----------------------------------------------------------- + +# Use the most commonly used application/x-www-form-urlencoded parameter +# separator. There's probably only one application somewhere that uses +# something else so don't expect to change this value. +# +SecArgumentSeparator & + +# Settle on version 0 (zero) cookies, as that is what most applications +# use. Using an incorrect cookie version may open your installation to +# evasion attacks (against the rules that examine named cookies). +# +SecCookieFormat 0 + diff --git a/config/apache_mod_security-dev/apache_mod_security_groups.xml b/config/apache_mod_security-dev/apache_mod_security_groups.xml new file mode 100644 index 00000000..92b41243 --- /dev/null +++ b/config/apache_mod_security-dev/apache_mod_security_groups.xml @@ -0,0 +1,211 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "./schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="./xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + apache_mod_security_settings.xml + part of apache_mod_security package (http://www.pfSense.com) + Copyright (C) 2008, 2009, 2010 Scott Ullrich + Copyright (C) 2012 Marcello Coutinho + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code MUST retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form MUST reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + <name>apachemodsecuritygroups</name> + <version>1.0</version> + <title>Services: Mod_Security+Apache+Proxy: Settings</title> + <tabs> + <tab> + <text>Apache</text> + <url>/pkg_edit.php?xml=apache_settings.xml&id=0</url> + </tab> + <tab> + <text>ModSecurity</text> + <url>/pkg_edit.php?xml=apache_mod_security_settings.xml</url> + <active/> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=apache_mod_security_sync.xml</url> + </tab> + <tab> + <text>Module options</text> + <url>/pkg_edit.php?xml=apache_mod_security_settings.xml</url> + <tab_level>2</tab_level> + </tab> + <tab> + <text>Rule Groups</text> + <url>/pkg.php?xml=apache_mod_security_groups.xml</url> + <tab_level>2</tab_level> + <active/> + </tab> + <tab> + <text>Rule Manipulation</text> + <url>/pkg.php?xml=apache_mod_security_manipulation.xml</url> + <tab_level>2</tab_level> + </tab> + </tabs> + <adddeleteeditpagefields> + <columnitem> + <fielddescr>Name</fielddescr> + <fieldname>name</fieldname> + </columnitem> + <columnitem> + <fielddescr>Description</fielddescr> + <fieldname>description</fieldname> + </columnitem> + </adddeleteeditpagefields> + <fields> + <field> + <name>Modsecurity group options</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Name</fielddescr> + <fieldname>name</fieldname> + <description>Enter group name</description> + <type>input</type> + <size>25</size> + </field> + <field> + <fielddescr>Description</fielddescr> + <fieldname>description</fieldname> + <description>Enter group description</description> + <type>input</type> + <size>45</size> + </field> + <field> + <fielddescr>Base Rules</fielddescr> + <fieldname>baserules</fieldname> + <description><![CDATA[Select Modsecurity Base rules to apply (all are recommended)<br> + Use CTRL + click to select.]]></description> + <type>select_source</type> + <source><![CDATA[$config['installedpackages']['modsecurityfilesbase']['config']]]></source> + <source_name>file</source_name> + <source_value>file</source_value> + <multiple/> + <size>10</size> + </field> + <field> + <fielddescr>Optional Rules</fielddescr> + <fieldname>optionalrules</fieldname> + <description><![CDATA[Select Modsecurity Optional rules to apply<br> + Use CTRL + click to select.]]></description> + <type>select_source</type> + <source><![CDATA[$config['installedpackages']['modsecurityfilesoptional']['config']]]></source> + <source_name>file</source_name> + <source_value>file</source_value> + <multiple/> + <size>10</size> + </field> + <field> + <fielddescr>SLR Rules</fielddescr> + <fieldname>slrrules</fieldname> + <description><![CDATA[Select Modsecurity SLR rules to apply<br> + Use CTRL + click to select.]]></description> + <type>select_source</type> + <source><![CDATA[$config['installedpackages']['modsecurityfilesslr']['config']]]></source> + <source_name>file</source_name> + <source_value>file</source_value> + <multiple/> + <size>10</size> + </field> + <field> + <fielddescr>Experimental Rules</fielddescr> + <fieldname>experimentalrules</fieldname> + <description><![CDATA[Select Modsecurity Experimental rules to apply<br> + Use CTRL + click to select.]]></description> + <type>select_source</type> + <source><![CDATA[$config['installedpackages']['modsecurityfilesexperimental']['config']]]></source> + <source_name>file</source_name> + <source_value>file</source_value> + <multiple/> + <size>10</size> + </field> + <field> + <name>Modsecurity Logging options</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Logging engine.</fielddescr> + <fieldname>secauditengine</fieldname> + <description>Configures ModSecurity audit logging engine.</description> + <type>select</type> + <options> + <option><name>RelevantOnly</name><value>RelevantOnly</value></option> + <option><name>All</name><value>On</value></option> + <option><name>Off</name><value>Off</value></option> + </options> + </field> + <field> + <fielddescr>Debug log file.</fielddescr> + <fieldname>SecDebugLogLevel</fieldname> + <description><![CDATA[Configures the verboseness of the debug log data.<br> + High logging levels are not recommended in production as it affects performance.]]> + </description> + <type>select</type> + <options> + <option><name>No logging (Default for performance)</name><value>0</value></option> + <option><name>Errors (intercepted requests) only</name><value>1</value></option> + <option><name>Warnings</name><value>2</value></option> + <option><name>Notices (Recommended for logging)</name><value>3</value></option> + <option><name>Details of how transactions are handled</name><value>4</value></option> + <option><name>As above, but including information about each piece of information handled</name><value>5</value></option> + <option><name>log everything, including very detailed debugging information</name><value>9</value></option> + </options> + </field> + + <field> + <name>Custom options</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Custom mod_security ErrorDocument</fielddescr> + <fieldname>errordocument</fieldname> + <description></description> + <type>textarea</type> + <rows>10</rows> + <cols>75</cols> + </field> + <field> + <fielddescr>Custom mod_security rules</fielddescr> + <fieldname>modsecuritycustom</fieldname> + <description>Paste any custom mod_security rules that you would like to use</description> + <type>textarea</type> + <rows>10</rows> + <cols>75</cols> + </field> + </fields> + <custom_php_resync_config_command> + apache_mod_security_resync(); + </custom_php_resync_config_command> + <include_file>/usr/local/pkg/apache_mod_security.inc</include_file> +</packagegui>
\ No newline at end of file diff --git a/config/apache_mod_security-dev/apache_mod_security_manipulation.xml b/config/apache_mod_security-dev/apache_mod_security_manipulation.xml new file mode 100644 index 00000000..54738d83 --- /dev/null +++ b/config/apache_mod_security-dev/apache_mod_security_manipulation.xml @@ -0,0 +1,144 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "./schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="./xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + apache_mod_security_manipulation.xml + part of apache_mod_security package (http://www.pfSense.com) + Copyright (C) 2008, 2009, 2010 Scott Ullrich + Copyright (C) 2012 Marcello Coutinho + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code MUST retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form MUST reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + <name>apachemodsecuritymanipulation</name> + <version>1.0</version> + <title>Services: Mod_Security+Apache+Proxy: Settings</title> + <tabs> + <tab> + <text>Apache</text> + <url>/pkg_edit.php?xml=apache_settings.xml&id=0</url> + </tab> + <tab> + <text>ModSecurity</text> + <url>/pkg_edit.php?xml=apache_mod_security_settings.xml</url> + <active/> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=apache_mod_security_sync.xml</url> + </tab> + <tab> + <text>Module options</text> + <url>/pkg_edit.php?xml=apache_mod_security_settings.xml</url> + <tab_level>2</tab_level> + </tab> + <tab> + <text>Rule Groups</text> + <url>/pkg.php?xml=apache_mod_security_groups.xml</url> + <tab_level>2</tab_level> + </tab> + <tab> + <text>Rule Manipulation</text> + <url>/pkg.php?xml=apache_mod_security_manipulation.xml</url> + <tab_level>2</tab_level> + <active/> + </tab> + </tabs> + <adddeleteeditpagefields> + <columnitem> + <fielddescr>Name</fielddescr> + <fieldname>name</fieldname> + </columnitem> + <columnitem> + <fielddescr>Description</fielddescr> + <fieldname>description</fieldname> + </columnitem> + </adddeleteeditpagefields> + <fields> + <field> + <name>Modsecurity group options</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Name</fielddescr> + <fieldname>name</fieldname> + <description>Enter group name</description> + <type>input</type> + <size>25</size> + </field> + <field> + <fielddescr>Description</fielddescr> + <fieldname>description</fieldname> + <description>Enter group description</description> + <type>input</type> + <size>45</size> + </field> + <field> + <fielddescr> + <![CDATA[Location(s)]]> + </fielddescr> + <fieldname>locations</fieldname> + <description><![CDATA[<br><strong>Rule Manipulation Samples:</strong><br><br> + SecRuleRemoveById 125<br> + SecRuleRemoveById 125-128<br> + SecRuleRemoveByMsg "Client error occurred"<br> + SecRuleUpdateActionById 125 pass<br> + SecRuleUpdateTargetsById 125 "!ARGS:username"]]></description> + <type>rowhelper</type> + <rowhelper> + <rowhelperfield> + <fielddescr><![CDATA[Type]]></fielddescr> + <fieldname>type</fieldname> + <description><![CDATA[Select the type of change you want to apply on this group.]]></description> + <type>select</type> + <options> + <option><name>Remove Rule By Id</name><value>SecRuleRemoveById</value></option> + <option><name>Remove Rule By Message</name><value>SecRuleRemoveByMsg</value></option> + <option><name>Update Action By Id</name><value>SecRuleUpdateActionById</value></option> + <option><name>Update Target By Id</name><value>SecRuleUpdateTargetsById</value></option> + </options> + </rowhelperfield> + <rowhelperfield> + <fielddescr><![CDATA[Value]]></fielddescr> + <fieldname>value</fieldname> + <description><![CDATA[Input the change value you want to apply on selected action.]]></description> + <type>input</type> + <size>30</size> + </rowhelperfield> + </rowhelper> + </field> + </fields> + <custom_php_resync_config_command> + apache_mod_security_resync(); + </custom_php_resync_config_command> + <include_file>/usr/local/pkg/apache_mod_security.inc</include_file> +</packagegui>
\ No newline at end of file diff --git a/config/apache_mod_security-dev/apache_mod_security_settings.xml b/config/apache_mod_security-dev/apache_mod_security_settings.xml new file mode 100644 index 00000000..985f6bcc --- /dev/null +++ b/config/apache_mod_security-dev/apache_mod_security_settings.xml @@ -0,0 +1,167 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "./schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="./xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + apache_mod_security_settings.xml + part of apache_mod_security package (http://www.pfSense.com) + Copyright (C) 2008, 2009, 2010 Scott Ullrich + Copyright (C) 2012 Marcello Coutinho + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code MUST retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form MUST reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + <name>apachemodsecuritysettings</name> + <version>1.0</version> + <title>Services: Mod_Security+Apache+Proxy: Settings</title> + <aftersaveredirect>pkg_edit.php?xml=apache_mod_security_settings.xml&id=0</aftersaveredirect> + <tabs> + <tab> + <text>Apache</text> + <url>/pkg_edit.php?xml=apache_settings.xml&id=0</url> + </tab> + <tab> + <text>ModSecurity</text> + <url>/pkg_edit.php?xml=apache_mod_security_settings.xml</url> + <active/> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=apache_mod_security_sync.xml</url> + </tab> + <tab> + <text>Module options</text> + <url>/pkg_edit.php?xml=apache_mod_security_settings.xml</url> + <active/> + <tab_level>2</tab_level> + </tab> + <tab> + <text>Rule Groups</text> + <url>/pkg.php?xml=apache_mod_security_groups.xml</url> + <tab_level>2</tab_level> + </tab> + <tab> + <text>Rule Manipulation</text> + <url>/pkg.php?xml=apache_mod_security_manipulation.xml</url> + <tab_level>2</tab_level> + </tab> + </tabs> + <fields> + <field> + <name>Security options</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>ModSecurity protection</fielddescr> + <fieldname>enablemodsecurity</fieldname> + <description><![CDATA[Enables ModSecurity protection for sites being proxied by apache<br> + More info about ModSecurity can be found here: http://www.modsecurity.org/]]></description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Disable Backend Compression</fielddescr> + <fieldname>secbackendcompression</fieldname> + <description><![CDATA[Disables backend compression while leaving the frontend compression enabled.<br> + This directive is mandatory in reverse proxy mode to ModSecurity be able to inspect response bodies.]]></description> + <type>select</type> + <options> + <option><name>On (Highly recommended)</name><value>on</value></option> + <option><name>Off</name><value>Of</value></option> + </options> + </field> + <field> + <fielddescr>Max request per IP</fielddescr> + <fieldname>SecReadStateLimit</fieldname> + <description> + //274 + <![CDATA[This option limits number of POSTS accepted from same IP address and help prevent the effects of a Slowloris-type of attack.<br> + More info about this attack can be found here: http://en.wikipedia.org/wiki/Slowloris + ]]> + </description> + <type>input</type> + <size>10</size> + </field> + <field> + <fielddescr>Maximum request body size in memory.</fielddescr> + <fieldname>secrequestbodyinmemorylimit</fieldname> + <description>Configures the maximum request body size ModSecurity will store in memory.</description> + <type>input</type> + <size>10</size> + </field> + <field> + <fielddescr>Maximum request body size for buffering.</fielddescr> + <fieldname>secrequestbodylimit</fieldname> + <description>Configures the maximum request body size ModSecurity will accept for buffering.</description> + <type>input</type> + <size>10</size> + </field> + <field> + <name>Modsecurity addons</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Http-guardian.pl</fielddescr> + <fieldname>enablehttpdguardian</fieldname> + <description><![CDATA[http-guardian script is designed to monitor all web server requests through the piped logging mechanism. + It keeps track of the number of requests sent from each IP address. Request speed is calculated at 1 minute and 5 minute intervals. + Once a threshold is reached, httpd-guardian can either emit a warning or execute a script to block the IP address.<br> + NOTE: In order for this script to be effective it must be able to see all requests coming to the web server, so no per-virtual host option for this script.]]></description> + <type>select</type> + <options> + <option><name>Disable</name><value></value></option> + <option><name>Enable and block when threshold is reached</name><value>block</value></option> + <option><name>Enable but just log when threshold is reached</name><value>log</value></option> + </options> + </field> + <field> + <fielddescr>Threshold 1min</fielddescr> + <fieldname>threshold1min</fieldname> + <description> + <![CDATA[Max. speed allowed, in requests per second measured over a 1-minute period.]]> + </description> + <type>input</type> + <size>5</size> + </field> + <field> + <fielddescr>Threshold 5min</fielddescr> + <fieldname>threshold5min</fieldname> + <description> + <![CDATA[Max. speed allowed, in requests per second measured over a 5-minute period.]]> + </description> + <type>input</type> + <size>5</size> + </field> + </fields> + <custom_php_resync_config_command> + apache_mod_security_resync(); + </custom_php_resync_config_command> + <include_file>/usr/local/pkg/apache_mod_security.inc</include_file> +</packagegui>
\ No newline at end of file diff --git a/config/apache_mod_security-dev/apache_mod_security_sync.xml b/config/apache_mod_security-dev/apache_mod_security_sync.xml new file mode 100755 index 00000000..0d8d8c8f --- /dev/null +++ b/config/apache_mod_security-dev/apache_mod_security_sync.xml @@ -0,0 +1,99 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "./schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="./xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + apache_sync.xml + part of the sarg package for pfSense + Copyright (C) 2012 Marcello Coutinho + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code MUST retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form MUST reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>apachesync</name> + <version>1.0</version> + <title>Proxy server: XMLRPC Sync</title> + <include_file>/usr/local/pkg/apache_mod_security.inc</include_file> + <tabs> + <tab> + <text>Apache</text> + <url>/pkg_edit.php?xml=apache_settings.xml&id=0</url> + </tab> + <tab> + <text>ModSecurity</text> + <url>/pkg_edit.php?xml=apache_mod_security_settings.xml</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=apache_mod_security_sync.xml</url> + <active/> + </tab> + </tabs> + <fields> + <field> + <name>XMLRPC Sync</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Automatically sync apache configuration changes</fielddescr> + <fieldname>synconchanges</fieldname> + <description>Automatically sync apache changes to the hosts defined below.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Remote Server</fielddescr> + <fieldname>none</fieldname> + <type>rowhelper</type> + <rowhelper> + <rowhelperfield> + <fielddescr>IP Address</fielddescr> + <fieldname>ipaddress</fieldname> + <description>IP Address of remote server</description> + <type>input</type> + <size>20</size> + </rowhelperfield> + <rowhelperfield> + <fielddescr>Password</fielddescr> + <fieldname>password</fieldname> + <description>Password for remote server.</description> + <type>password</type> + <size>20</size> + </rowhelperfield> + </rowhelper> + </field> + </fields> + <custom_php_resync_config_command> + apache_mod_security_resync(); + </custom_php_resync_config_command> +</packagegui> diff --git a/config/apache_mod_security-dev/apache_mod_security_view_logs.php b/config/apache_mod_security-dev/apache_mod_security_view_logs.php new file mode 100755 index 00000000..1956a217 --- /dev/null +++ b/config/apache_mod_security-dev/apache_mod_security_view_logs.php @@ -0,0 +1,182 @@ +<?php +/* ========================================================================== */ +/* + squid_monitor.php + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Marcello Coutinho + Copyright (C) 2012 Carlos Cesario - carloscesario@gmail.com + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code MUST retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form MUST reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + +require_once("/etc/inc/util.inc"); +require_once("/etc/inc/functions.inc"); +require_once("/etc/inc/pkg-utils.inc"); +require_once("/etc/inc/globals.inc"); +require_once("guiconfig.inc"); + +$pfSversion = str_replace("\n", "", file_get_contents("/etc/version")); +if(strstr($pfSversion, "1.2")) + $one_two = true; + +$pgtitle = "Apache Proxy: Logs"; +include("head.inc"); +?> + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + +<?php include("fbegin.inc"); ?> + +<?php if($one_two): ?> + + <p class="pgtitle"><?=$pgtitle?></font></p> + +<?php endif; ?> + +<?php if ($savemsg) print_info_box($savemsg); ?> + +<!-- Function to call programs logs --> +<script language="JavaScript"> + +</script> +<div id="mainlevel"> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr><td> + <?php + $tab_array = array(); + $tab_array[] = array(gettext("Apache"), false, "/pkg_edit.php?xml=apache_settings.xml&id=0"); + $tab_array[] = array(gettext("ModSecurity"), false, "/pkg_edit.php?xml=apache_mod_security_setttings.xml"); + $tab_array[] = array(gettext("Sync"), false, "/pkg_edit.php?xml=apache_mod_security_sync.xml"); + $tab_array[] = array(gettext("Backends"), false, "/pkg.php?xml=apache_mod_security_backends.xml",2); + $tab_array[] = array(gettext("VirtualHosts"), false, "/pkg.php?xml=apache_mod_security.xml",2); + $tab_array[] = array(gettext("Logs"), true, "/apache_mod_security_view_logs.php",2); + display_top_tabs($tab_array); + ?> +</td></tr> + <tr> + <td> +<div id="mainarea" style="padding-top: 0px; padding-bottom: 0px; "> + <form id="paramsForm" name="paramsForm" method="post"> + <table class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="6"> + <tbody> + <tr> + <td width="22%" valign="top" class="vncellreq"><?=gettext("Max. lines:");?></td> + <td width="78%" class="vtable"> + <select name="maxlines" id="maxlines"> + <option value="5">5 lines</option> + <option value="10" selected="selected">10 lines</option> + <option value="15">15 lines</option> + <option value="20">20 lines</option> + <option value="25">25 lines</option> + <option value="30">30 lines</option> + </select> + <br/> + <span class="vexpl"> + <?=gettext("Max. lines to be displayed.");?> + </span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncellreq"><?=gettext("Vhosts");?></td> + <td width="78%" class="vtable"> + <select name="vhosts" id="vhosts"> + <option value="10" selected="selected">xxxxx</option> + </select> + <br/> + <span class="vexpl"> + <?=gettext("Max. lines to be displayed.");?> + </span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncellreq"><?=gettext("String filter:");?></td> + <td width="78%" class="vtable"> + <input name="strfilter" type="text" class="formfld search" id="strfilter" size="50" value=""> + <br/> + <span class="vexpl"> + <?=gettext("Enter a grep like string/pattern to filterlog.");?><br> + <?=gettext("eg. username, ip addr, url.");?><br> + <?=gettext("Use <b>!</b> to invert the sense of matching, to select non-matching lines.");?> + </span> + </td> + </tr> + </tbody> + </table> + </form> + + <!-- Squid Table --> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tbody> + <tr> + <td> + <table class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="0"> + <tr> + <td colspan="6" class="listtopic"><center><?=gettext("Http access logs"); ?><center></td> + </tr> + <tbody id="httpaccesslog"> + <script language="JavaScript"> + // Call function to show squid log + //showLog('squidView', 'squid_monitor_data.php','squid'); + </script> + </tbody> + </table> + </td> + </tr> + </tbody> + </table> + <!-- SquidGuard Table --> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tbody> + <tr> + <td> + <table class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="0"> + <tr> + <td colspan="5" class="listtopic"><center><?=gettext("Http error logs"); ?><center></td> + </tr> + <tbody id="httperrorlog"> + <script language="JavaScript"> + // Call function to show squidGuard log + //showLog('sguardView', 'squid_monitor_data.php','sguard'); + </script> + </tbody> + </table> + </td> + </tr> + </tbody> + </table> +</div> +</td> +</tr> +</table> +</div> + + +<?php +include("fend.inc"); +?> + +</body> +</html> diff --git a/config/apache_mod_security-dev/apache_settings.xml b/config/apache_mod_security-dev/apache_settings.xml new file mode 100644 index 00000000..20ba59c2 --- /dev/null +++ b/config/apache_mod_security-dev/apache_settings.xml @@ -0,0 +1,286 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "./schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="./xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + apache_mod_security_settings.xml + part of apache_mod_security package (http://www.pfSense.com) + Copyright (C) 2008, 2009, 2010 Scott Ullrich + Copyright (C) 2012 Marcello Coutinho + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code MUST retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form MUST reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + <name>apachesettings</name> + <version>1.0</version> + <title>Apache reverse proxy: Settings</title> + <tabs> + <tab> + <text>Apache</text> + <url>/pkg_edit.php?xml=apache_settings.xml&id=0</url> + <active/> + </tab> + <tab> + <text>ModSecurity</text> + <url>/pkg_edit.php?xml=apache_mod_security_settings.xml</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=apache_mod_security_sync.xml</url> + </tab> + <tab> + <text>Daemon Options</text> + <url>/pkg_edit.php?xml=apache_settings.xml</url> + <tab_level>2</tab_level> + <active/> + </tab> + <tab> + <text>Backends / Balancers</text> + <url>/pkg.php?xml=apache_balancer.xml</url> + <tab_level>2</tab_level> + </tab> + <tab> + <text>Virutal Hosts</text> + <url>/pkg.php?xml=apache_virtualhost.xml</url> + <tab_level>2</tab_level> + </tab> + <tab> + <text>Logs</text> + <url>/apache_view_logs.php</url> + <tab_level>2</tab_level> + </tab> + </tabs> + <fields> + <field> + <name>General</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Global site E-mail administrator</fielddescr> + <fieldname>globalsiteadminemail</fieldname> + <description>Enter the site administrators e-mail address</description> + <type>input</type> + </field> + <field> + <fielddescr>Server hostname</fielddescr> + <fieldname>hostname</fieldname> + <description> + <![CDATA[Enter the servers hostname<br/ + NOTE: Leave blank to use this devices hostname.]]> + </description> + <type>input</type> + </field> + <field> + <fielddescr>Default Bind to IP Address</fielddescr> + <fieldname>globalbindtoipaddr</fieldname> + <description> + <![CDATA[ + This is the IP address the Proxy Server will listen on. + <br/> + NOTE: Leave blank to bind to * + ]]> + </description> + <type>input</type> + </field> + <field> + <fielddescr>Default Bind to port</fielddescr> + <fieldname>globalbindtoport</fieldname> + <description> + <![CDATA[ + This is the port the Proxy Server will listen on.<br> + NOTE: Leave blank to bind to 80 + ]]> + </description> + <type>input</type> + <size>5</size> + </field> + <field> + <name>Performance</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Keep alive</fielddescr> + <fieldname>keepalive</fieldname> + <description> + <![CDATA[Whether or not to allow persistent connections (more than one request per connection).]]> + </description> + <type>select</type> + <options> + <option><name>On</name><value>On</value></option> + <option><name>Off</name><value>Off</value></option> + </options> + </field> + <field> + <fielddescr>Max keep alive Requests</fielddescr> + <fieldname>maxkeepalivereq</fieldname> + <description> + <![CDATA[The maximum number of requests to allow during a persistent connection. Set to 0 to allow an unlimited amount.<br> + It's recommend to leave this number high, for maximum performance.<br>Leave empty to use apache defaults.]]> + </description> + <type>input</type> + <size>5</size> + </field> + <field> + <fielddescr>keep alive timeout</fielddescr> + <fieldname>keepalivetimeout</fieldname> + <description><![CDATA[Number of seconds to wait for the next request from the same client on the same connection.<br>Leave empty to use apache defaults.]]></description> + <type>input</type> + <size>5</size> + </field> + <field> + <fielddescr>Servers Limit</fielddescr> + <fieldname>serverlimit</fieldname> + <description><![CDATA[For the prefork MPM, this directive sets the maximum configured value for MaxClients for the lifetime of the Apache process. For the worker MPM, this directive in combination with ThreadLimit sets the maximum configured value for MaxClients for the lifetime of the Apache process. Any attempts to change this directive during a restart will be ignored, but MaxClients can be modified during a restart.<br>Leave empty to use apache defaults.]]></description> + <type>input</type> + <size>5</size> + </field> + <field> + <fielddescr>Start Servers</fielddescr> + <fieldname>startservers</fieldname> + <description><![CDATA[The StartServers directive sets the number of child server processes created on startup. As the number of processes is dynamically controlled depending on the load, there is usually little reason to adjust this parameter.<br>Leave empty to use apache defaults.]]></description> + <type>input</type> + <size>5</size> + </field> + <field> + <fielddescr>Min Spare Threads</fielddescr> + <fieldname>minsparethreads</fieldname> + <description><![CDATA[Minimum number of idle threads available to handle request spikes.]]></description> + <type>input</type> + <size>5</size> + </field> + <field> + <fielddescr>Max Spare Threads</fielddescr> + <fieldname>maxsparethreads</fieldname> + <description><![CDATA[Maximum number of idle threads.]]></description> + <type>input</type> + <size>5</size> + </field> + <field> + <fielddescr>Threads Limit</fielddescr> + <fieldname>threadslimit</fieldname> + <description><![CDATA[This directive sets the maximum configured value for ThreadsPerChild for the lifetime of the Apache process. Any attempts to change this directive during a restart will be ignored, but ThreadsPerChild can be modified during a restart up to the value of this directive.<br>Leave empty to use apache defaults.]]></description> + <type>input</type> + <size>5</size> + </field> + <field> + <fielddescr>Thread Stack Size</fielddescr> + <fieldname>threadstacksize</fieldname> + <description><![CDATA[The ThreadStackSize directive sets the size of the stack (for autodata) of threads which handle client connections and call modules to help process those connections. In most cases the operating system default for stack size is reasonable.<br>Leave empty to use apache defaults.]]></description> + <type>input</type> + <size>5</size> + </field> + <field> + <fielddescr>threadsperchild</fielddescr> + <fieldname>threadsperchild</fieldname> + <description><![CDATA[This directive sets the number of threads created by each child process. The child creates these threads at startup and never creates more. The total number of threads should be high enough to handle the common load on the server.<br>Leave empty to use apache defaults.]]></description> + <type>input</type> + <size>5</size> + </field> + <field> + <fielddescr>MaxClients</fielddescr> + <fieldname>maxclients</fieldname> + <description><![CDATA[The MaxClients directive sets the limit on the number of simultaneous requests that will be served. Any connection attempts over the MaxClients limit will normally be queued, up to a number based on the ListenBacklog directive. Once a child process is freed at the end of a different request, the connection will then be serviced.<br>Leave empty to use apache defaults.]]></description> + <type>input</type> + <size>5</size> + </field> + <field> + <fielddescr>MaxRequestsPerChild</fielddescr> + <fieldname>maxrequestsperchild</fieldname> + <description><![CDATA[The MaxRequestsPerChild directive sets the limit on the number of requests that an individual child server process will handle. After MaxRequestsPerChild requests, the child process will die. If MaxRequestsPerChild is 0, then the process will never expire.<br>Leave empty to use apache defaults.]]></description> + <type>input</type> + <size>5</size> + </field> + <field> + <name>Cache settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Memory cache size</fielddescr> + <fieldname>memcachesize</fieldname> + <description> + <![CDATA[Sets the memory usage in megabytes.<br>Leave empty to use default value or 0 to disable memory cache.<br> + Enables mod_mem_cache which stores cached documents in memory.]]> + </description> + <type>input</type> + <size>10</size> + </field> + <field> + <fielddescr>Disk Cache Max File Size</fielddescr> + <fieldname>diskcachesize</fieldname> + <description> + <![CDATA[Set the maximum size (in bytes) of a document to be placed in the cache.<br>Leave empty to use default value or 0 to disable disk cache.<br> + mod_disk_cache implements a disk based storage manager. It is primarily of use in conjunction with mod_cache.]]> + </description> + <type>input</type> + <size>10</size> + </field> + <field> + <name>Connection limits (DoS protection)</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>header</fielddescr> + <fieldname>header_time_out</fieldname> + <description> + <![CDATA[Set header timeouts for requests in min,max,MinRate format. Leave empty to do not limit request headers.<br> + Sample: To allow at least 10 seconds to receive the request including the headers and increase the timeout by 1 second for every 500 bytes received but do not allow more than 30 seconds for the request including the headers:<br> + <strong>10,30,500</strong>]]> + </description> + <type>input</type> + <size>10</size> + </field> + <field> + <fielddescr>body</fielddescr> + <fieldname>body_time_out</fieldname> + <description> + <![CDATA[Set body timeouts for requests in min,max,MinRate format. Leave empty to do not limit request bodies.<br> + Sample: To allow at least 10 seconds to receive the request body and if the client sends data, increase the timeout by 1 second for every 1000 bytes received, with no upper limit for the timeout (exept for the limit given indirectly by LimitRequestBody):<br> + <strong>10,1000</strong>]]> + </description> + <type>input</type> + <size>10</size> + </field> + <field> + <fielddescr>Limit Request Body</fielddescr> + <fieldname>LimitRequestBody</fieldname> + <description> + <![CDATA[This directive specifies the number of bytes from 0 (meaning unlimited) to 2147483647 (2GB) that are allowed in a request body.<br> + The LimitRequestBody directive allows the user to set a limit on the allowed size of an HTTP request message body within the context in which the directive is given (server, per-directory, per-file or per-location). If the client request exceeds that limit, the server will return an error response instead of servicing the request.]]> + </description> + <type>input</type> + <size>10</size> + </field> + </fields> + <custom_php_resync_config_command> + apache_mod_security_resync(); + </custom_php_resync_config_command> + <include_file>/usr/local/pkg/apache_mod_security.inc</include_file> +</packagegui>
\ No newline at end of file diff --git a/config/apache_mod_security-dev/apache_view_logs.php b/config/apache_mod_security-dev/apache_view_logs.php new file mode 100644 index 00000000..da82baaa --- /dev/null +++ b/config/apache_mod_security-dev/apache_view_logs.php @@ -0,0 +1,222 @@ +<?php +/* ========================================================================== */ +/* + apache_view_logs.php + part of pfSense (http://www.pfSense.com) + Copyright (C) 2009, 2010 Scott Ullrich <sullrich@gmail.com> + Copyright (C) 2012 Marcello Coutinho + Copyright (C) 2012 Carlos Cesario + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code MUST retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form MUST reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + +require_once("/etc/inc/util.inc"); +require_once("/etc/inc/functions.inc"); +require_once("/etc/inc/pkg-utils.inc"); +require_once("/etc/inc/globals.inc"); +require_once("guiconfig.inc"); +$pfSversion = str_replace("\n", "", file_get_contents("/etc/version")); +if(strstr($pfSversion, "1.2")) + $one_two = true; + +$pgtitle = "Status: Apache Vhosts Logs"; +include("head.inc"); +?> + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + +<?php include("fbegin.inc"); ?> + +<?php if($one_two): ?> + + <p class="pgtitle"><?=$pgtitle?></font></p> + +<?php endif; ?> + +<?php if ($savemsg) print_info_box($savemsg); ?> + +<!-- Function to call programs logs --> +<script language="JavaScript"> +function showLog(content,url,logtype) +{ + jQuery.ajax({ + type: 'get', + cache: false, + url: url, + dataType: 'json', + data: { + maxlines: jQuery('#maxlines').val(), + strfilter: jQuery('#strfilter').val(), + logfile: jQuery('#logs').val(), + logtype: logtype + }, + complete: function(data){ + jQuery('#'+content).empty().html(data.responseText); + } + }); +} + + + // Call function to show squid log + jQuery(document).ready(function() { + var refreshId = setInterval( function() + { + showLog('accesslog', 'apache_logs_data.php','access'); + showLog('errorlog', 'apache_logs_data.php','error'); + }, 1000); + }); + +</script> +<div id="mainlevel"> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr><td> + <?php + $tab_array = array(); + $tab_array[] = array(gettext("Apache"), true, "/pkg_edit.php?xml=apache_settings.xml&id=0"); + $tab_array[] = array(gettext("ModSecurity"), false, "/pkg_edit.php?xml=apache_mod_security_setttings.xml"); + $tab_array[] = array(gettext("Sync"), false, "/pkg_edit.php?xml=apache_mod_security_sync.xml"); + display_top_tabs($tab_array); + ?> + </td></tr> + <tr><td> + <?php + unset ($tab_array); + $tab_array[] = array(gettext("Daemon Options"), false, "pkg_edit.php?xml=apache_settings.xml"); + $tab_array[] = array(gettext("Backends / Balancers"), false, "/pkg.php?xml=apache_balancer.xml"); + $tab_array[] = array(gettext("Virtual Hosts"), false, "/pkg.php?xml=apache_virtualhost.xml"); + $tab_array[] = array(gettext("Logs"), true, "/apache_view_logs.php"); + display_top_tabs($tab_array); + ?> + </td></tr> + <tr> + <td> +<div id="mainarea" style="padding-top: 0px; padding-bottom: 0px; "> + <form id="paramsForm" name="paramsForm" method="post"> + <table class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="6"> + <tbody> + <tr> + <td width="22%" valign="top" class="vncellreq"><?=gettext("Max. lines:");?></td> + <td width="78%" class="vtable"> + <select name="maxlines" id="maxlines"> + <option value="5">5 lines</option> + <option value="10" selected="selected">10 lines</option> + <option value="15">15 lines</option> + <option value="20">20 lines</option> + <option value="25">25 lines</option> + <option value="30">30 lines</option> + </select> + <br/> + <span class="vexpl"> + <?=gettext("Max. lines to be displayed.");?> + </span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncellreq"><?=gettext("Log file:");?></td> + <td width="78%" class="vtable"> + <select name="logs" id="logs"> + <?php + if ($handle = opendir('/var/log')) { + /* This is the correct way to loop over the directory. */ + while (false !== ($entry = readdir($handle))) { + if (preg_match("/httpd-(\S+).log/",$entry,$matches)) + if (!preg_match("/error/",$matches[1])) + print "<option value={$matches[1]}>{$matches[1]}.log</option>\n"; + } + closedir($handle); + } + ?> + </select> + <br/> + <span class="vexpl"> + <?=gettext("Max. lines to be displayed.");?> + </span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncellreq"><?=gettext("String filter:");?></td> + <td width="78%" class="vtable"> + <input name="strfilter" type="text" class="formfld search" id="strfilter" size="50" value=""> + <br/> + <span class="vexpl"> + <?=gettext("Enter a grep like string/pattern to filterlog.");?><br> + <?=gettext("eg. username, ip addr, url.");?><br> + <?=gettext("Use <b>!</b> to invert the sense of matching, to select non-matching lines.");?> + </span> + </td> + </tr> + </tbody> + </table> + </form> + <div id="bowserinfo" style='padding: 5px; border: 1px dashed #990000; font-weight:bold; font-size: 0.9em; text-align: center; margin: 1px; display:block; height: 12px;'> + <span><span> + </div> + <!-- Squid Table --> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tbody> + <tr> + <td> + <table class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="0"> + <tr> + <td colspan="5" class="listtopic"><center><?=gettext("Httpd Access Log"); ?><center></td> + </tr> + <tbody id="accesslog"> + </tbody> + </table> + </td> + </tr> + </tbody> + </table> + <!-- SquidGuard Table --> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tbody> + <tr> + <td> + <table class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="0"> + <tr> + <td colspan="3" class="listtopic"><center><?=gettext("Http error logs"); ?><center></td> + </tr> + <tbody id="errorlog"> + + </tbody> + </table> + </td> + </tr> + </tbody> + </table> +</div> +</td> +</tr> +</table> +</div> + + +<?php +include("fend.inc"); +?> + +</body> +</html> diff --git a/config/apache_mod_security-dev/apache_virtualhost.xml b/config/apache_mod_security-dev/apache_virtualhost.xml new file mode 100644 index 00000000..2e29a9af --- /dev/null +++ b/config/apache_mod_security-dev/apache_virtualhost.xml @@ -0,0 +1,402 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "./schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="./xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ + /* $Id$ */ + /* ========================================================================== */ + /* + apache_virtualhost.xml + part of apache_mod_security package (http://www.pfSense.com) + Copyright (C)2009, 2010 Scott Ullrich + Copyright (C)2012 Marcello Coutinho + All rights reserved. + */ + /* ========================================================================== */ + /* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code MUST retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form MUST reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ + /* ========================================================================== */ + ]]> + </copyright> + <name>apachevirtualhost</name> + <version>1.0</version> + <title>Apache reverse proxy: Site Proxies</title> + <menu> + <name>Mod_Security+Apache+Proxy</name> + <tooltiptext></tooltiptext> + <section>Services</section> + <configfile>apache_virtualhost.xml</configfile> + </menu> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.com/packages/config/apache_mod_security-dev/apache_mod_security.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.com/packages/config/apache_mod_security-dev/apache_mod_security.template</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.com/packages/config/apache_mod_security-dev/apache_mod_security_groups.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.com/packages/config/apache_mod_security-dev/apache_mod_security_settings.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.com/packages/config/apache_mod_security-dev/apache_mod_security_view_logs.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.com/packages/config/apache_mod_security-dev/apache.template</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.com/packages/config/apache_mod_security-dev/apache_balancer.template</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.com/packages/config/apache_mod_security-dev/apache_balancer.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.com/packages/config/apache_mod_security-dev/apache_logs_data.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.com/packages/config/apache_mod_security-dev/apache_mod_security_manipulation.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.com/packages/config/apache_mod_security-dev/apache_mod_security_sync.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.com/packages/config/apache_mod_security-dev/apache_settings.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.com/packages/config/apache_mod_security-dev/apache_view_logs.php</item> + </additional_files_needed> + <tabs> + <tab> + <text>Apache</text> + <url>/pkg_edit.php?xml=apache_settings.xml&id=0</url> + <active/> + </tab> + <tab> + <text>ModSecurity</text> + <url>/pkg_edit.php?xml=apache_mod_security_settings.xml</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=apache_mod_security_sync.xml</url> + </tab> + <tab> + <text>Daemon Options</text> + <url>/pkg_edit.php?xml=apache_settings.xml</url> + <tab_level>2</tab_level> + </tab> + <tab> + <text>Backends / Balancers</text> + <url>/pkg.php?xml=apache_balancer.xml</url> + <tab_level>2</tab_level> + </tab> + <tab> + <text>Virutal Hosts</text> + <url>/pkg.php?xml=apache_virtualhost.xml</url> + <tab_level>2</tab_level> + <active/> + </tab> + <tab> + <text>Logs</text> + <url>/apache_view_logs.php</url> + <tab_level>2</tab_level> + </tab> + </tabs> + <adddeleteeditpagefields> + <columnitem> + <fielddescr>Status</fielddescr> + <fieldname>enable</fieldname> + </columnitem> + <columnitem> + <fielddescr>Iface</fielddescr> + <fieldname>interface</fieldname> + </columnitem> + <columnitem> + <fielddescr>protocol</fielddescr> + <fieldname>proto</fieldname> + </columnitem> + <columnitem> + <fielddescr>Server name(s)</fielddescr> + <fieldname>primarysitehostname</fieldname> + <encoding>base64</encoding> + </columnitem> + <columnitem> + <fielddescr>port</fielddescr> + <fieldname>port</fieldname> + </columnitem> + <columnitem> + <fielddescr>Description</fielddescr> + <fieldname>description</fieldname> + </columnitem> + </adddeleteeditpagefields> + <fields> + <field> + <name>Listening Options</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Enable</fielddescr> + <fieldname>enable</fieldname> + <description>Enable this virtual host</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Protocol(s)</fielddescr> + <fieldname>proto</fieldname> + <description>Select protocols that this virtual host will accept connections</description> + <type>select</type> + <options> + <option><name>HTTP</name><value>http</value></option> + <option><name>HTTPS</name><value>https</value></option> + </options> + </field> + <field> + <fielddescr>Server Name(s)</fielddescr> + <fieldname>primarysitehostname</fieldname> + <description> + <![CDATA[Enter hostnames one per line in FQDN format for this website (e.g. www.example.com)<br/> + Leave blank and define the IP Address / port above for IP site proxy (i.e. not named site proxy)]]> + </description> + <cols>40</cols> + <rows>2</rows> + <type>textarea</type> + <encoding>base64</encoding> + </field> + <field> + <fielddescr>Inbound Interface(s)</fielddescr> + <fieldname>interface</fieldname> + <description><![CDATA[Default: <strong>WAN</strong><br>Select interface(s) that this virtualhost will listen on.]]></description> + <type>interfaces_selection</type> + <showlistenall/> + <showvirtualips/> + <showips/> + <required/> + </field> + <field> + <fielddescr>Port</fielddescr> + <fieldname>port</fieldname> + <description>Leave blank to use the default global port.</description> + <size>10</size> + <type>input</type> + </field> + <field> + <fielddescr>Site Webmaster E-Mail address</fielddescr> + <fieldname>siteemail</fieldname> + <size>50</size> + <description> + <![CDATA[ + Enter the Webmaster E-Mail address for this site. + ]]> + </description> + <type>input</type> + </field> + <field> + <fielddescr>Site description</fielddescr> + <fieldname>description</fieldname> + <size>50</size> + <description> + <![CDATA[Enter a site description]]> + </description> + <type>input</type> + </field> + <field> + <fielddescr>HTTPS SSL certificate</fielddescr> + <fieldname>ssl_cert</fieldname> + <description>Choose the SSL Server Certificate here.</description> + <type>select_source</type> + <source><![CDATA[$config['cert']]]></source> + <source_name>descr</source_name> + <source_value>refid</source_value> + <show_disable_value>none</show_disable_value> + </field> + <field> + <fielddescr>intermediate CA certificate(optional)</fielddescr> + <fieldname>reverse_int_ca</fieldname> + <description>Select intermediate CA assigned to certificate. Not all certificates require this.</description> + <type>select_source</type> + <source><![CDATA[$config['ca']]]></source> + <source_name>descr</source_name> + <source_value>refid</source_value> + <show_disable_value>none</show_disable_value> + </field> + <field> + <fielddescr> + <![CDATA[Location(s)]]> + </fielddescr> + <fieldname>locations</fieldname> + <type>rowhelper</type> + <rowhelper> + <rowhelperfield> + <fielddescr><![CDATA[gzip?]]></fielddescr> + <fieldname>compress</fieldname> + <description>Compress data to save bandwidth?</description> + <type>select</type> + <options> + <option><name>yes</name><value>yes</value></option> + <option><name>no</name><value>no</value></option> + </options> + </rowhelperfield> + <rowhelperfield> + <fielddescr><![CDATA[site path]]></fielddescr> + <fieldname>sitepath</fieldname> + <description><![CDATA[Site path to publish.<br>leave blank to use /]]></description> + <type>input</type> + <size>5</size> + </rowhelperfield> + <rowhelperfield> + <fielddescr><![CDATA[Balancer]]></fielddescr> + <fieldname>balancer</fieldname> + <description>Server balancer / pool</description> + <source><![CDATA[$config['installedpackages']['apachebalancer']['config']]]></source> + <source_name>name</source_name> + <source_value>name</source_value> + <show_disable_value>none</show_disable_value> + <type>select_source</type> + <size>5</size> + </rowhelperfield> + <rowhelperfield> + <fielddescr><![CDATA[<a href='https://httpd.apache.org/docs/2.2/mod/mod_proxy.html#proxypass'>LbMethod</a>]]></fielddescr> + <fieldname>lbmethod</fieldname> + <description>Server balance method</description> + <type>select</type> + <options> + <option><name>byrequests</name><value>byrequests</value></option> + <option><name>bytraffic</name><value>bytraffic</value></option> + <option><name>bybusyness</name><value>bybusyness</value></option> + </options> + </rowhelperfield> + <rowhelperfield> + <fielddescr>Backend path</fielddescr> + <fieldname>backendpath</fieldname> + <description><![CDATA[Backend redirect path.<br>Leave blank to use /]]></description> + <type>input</type> + <size>5</size> + </rowhelperfield> + <rowhelperfield> + <fielddescr><![CDATA[ModSecurity]]></fielddescr> + <fieldname>modsecgroup</fieldname> + <description>Choose Modsecurity group to use on this virtual host.</description> + <type>select_source</type> + <source><![CDATA[$config['installedpackages']['apachemodsecuritygroups']['config']]]></source> + <source_name>name</source_name> + <source_value>name</source_value> + <show_disable_value>none</show_disable_value> + </rowhelperfield> + <rowhelperfield> + <fielddescr><![CDATA[Manipulations]]></fielddescr> + <fieldname>modsecmanipulation</fieldname> + <description>Choose Modsecurity group to use on this virtual host.</description> + <type>select_source</type> + <source><![CDATA[$config['installedpackages']['apachemodsecuritymanipulation']['config']]]></source> + <source_name>name</source_name> + <source_value>name</source_value> + <show_disable_value>none</show_disable_value> + </rowhelperfield> + <rowhelperfield> + <fielddescr><![CDATA[<a href='https://httpd.apache.org/docs/2.2/mod/mod_proxy.html#proxypass'> Balancer options</a>]]></fielddescr> + <fieldname>options</fieldname> + <description><![CDATA[Additional proxypass options for this path.<br>ex: ttl=60 stickysession='JSESSIONID']]></description> + <type>input</type> + <size>5</size> + </rowhelperfield> + </rowhelper> + </field> + <field> + <name>Logging</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Preserve Proxy hostname</fielddescr> + <fieldname>preserveproxyhostname</fieldname> + <description> + <![CDATA[ + When enabled, this option will pass the Host: line from the incoming request to the proxied host, instead of the backend IP address. + ]]> + </description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Log file</fielddescr> + <fieldname>logfile</fieldname> + <description> + <![CDATA[Enable access and error log for this virtual host.]]> + </description> + <type>select</type> + <options> + <option><name>Log to default apache log file</name><value>default</value></option> + <option><name>Create a log file for this site</name><value>create</value></option> + <option><name>Do not not this website</name><value>disabled</value></option> + </options> + </field> + <field> + <name>Custom Options</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Custom Options</fielddescr> + <fieldname>custom</fieldname> + <description>Paste extra apache config for this virtualhost. This is usefull for rewrite rules for example.</description> + <type>textarea</type> + <cols>65</cols> + <rows>10</rows> + <encoding>base64</encoding> + </field> + + </fields> + <service> + <name>apache_mod_security</name> + <rcfile>/usr/local/etc/rc.d/apache_mod_security.sh</rcfile> + <executable>httpd</executable> + </service> + <custom_php_resync_config_command> + apache_mod_security_resync(); + </custom_php_resync_config_command> + <include_file>/usr/local/pkg/apache_mod_security.inc</include_file> +</packagegui>
\ No newline at end of file diff --git a/config/arpwatch.xml b/config/arpwatch.xml index 0553eb58..c9434075 100644 --- a/config/arpwatch.xml +++ b/config/arpwatch.xml @@ -89,11 +89,17 @@ <custom_php_global_functions> function sync_package_arpwatch() { global $config; - conf_mount_rw(); - config_lock(); - $int = $config['installedpackages']['arpwatch']['config'][0]['interface']; + conf_mount_rw(); + config_lock(); + $log_file = "/var/log/arp.dat"; + if($_POST['interface'] != "") { + $int = $_POST['interface']; + } else { + $int = $config['installedpackages']['arpwatch']['config'][0]['interface']; + } $int = convert_friendly_interface_to_real_interface_name($int); - $start = "/usr/local/sbin/arpwatch -d -i {$int} > /var/log/arpwatch.reports 2>&1 &"; + $start = "touch {$log_file}\n"; + $start .= "/usr/local/sbin/arpwatch -d -f {$log_file} -i {$int} > /var/log/arpwatch.reports 2>&1 &"; $stop = "/usr/bin/killall arpwatch"; write_rcfile(array( "file" => "arpwatch.sh", @@ -102,9 +108,9 @@ ) ); restart_service("arpwatch"); - conf_mount_ro(); - config_unlock(); - } + conf_mount_ro(); + config_unlock(); + } </custom_php_global_functions> <custom_add_php_command> sync_package_arpwatch(); diff --git a/config/arpwatch_reports.php b/config/arpwatch_reports.php index 1bdb5233..d66b1a46 100755 --- a/config/arpwatch_reports.php +++ b/config/arpwatch_reports.php @@ -3,7 +3,7 @@ /* $Id$ - diag_logs.php + arpwatch_reports.php Copyright (C) 2005 Colin Smith All rights reserved. @@ -31,7 +31,7 @@ require("guiconfig.inc"); -$logfile = "/usr/local/arpwatch/arp.dat"; +$logfile = "/var/log/arp.dat"; if ($_POST['clear']) { stop_service("arpwatch"); diff --git a/config/autoconfigbackup/autoconfigbackup.inc b/config/autoconfigbackup/autoconfigbackup.inc index fc9fb98d..0286ffec 100644 --- a/config/autoconfigbackup/autoconfigbackup.inc +++ b/config/autoconfigbackup/autoconfigbackup.inc @@ -82,10 +82,11 @@ function test_connection($post) { $hostname = $config['system']['hostname'] . "." . $config['system']['domain']; // URL to restore.php - $get_url = "https://{$username}:{$password}@portal.pfsense.org/pfSconfigbackups/restore.php"; + $get_url = "https://portal.pfsense.org/pfSconfigbackups/restore.php"; // Populate available backups $curl_session = curl_init(); + curl_setopt($curl_session, CURLOPT_USERPWD, "{$username}:{$password}"); curl_setopt($curl_session, CURLOPT_URL, $get_url); curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curl_session, CURLOPT_POST, 1); diff --git a/config/autoconfigbackup/autoconfigbackup.xml b/config/autoconfigbackup/autoconfigbackup.xml index 406221bf..a7640f7e 100644 --- a/config/autoconfigbackup/autoconfigbackup.xml +++ b/config/autoconfigbackup/autoconfigbackup.xml @@ -37,7 +37,7 @@ <description>Automatically backs up your pfSense configuration. All contents are encrypted on the server. Requires pfSense Premium Support Portal Subscription from https://portal.pfsense.org</description> <requirements>pfSense Premium Support Portal</requirements> <name>AutoConfigBackup</name> - <version>1.0</version> + <version>1.20</version> <title>Diagnostics: Auto Configuration Backup</title> <savetext>Change</savetext> <include_file>/usr/local/pkg/autoconfigbackup.inc</include_file> diff --git a/config/avahi/avahi.inc b/config/avahi/avahi.inc index 217d2aa1..7b093276 100644 --- a/config/avahi/avahi.inc +++ b/config/avahi/avahi.inc @@ -4,7 +4,7 @@ $Id$ avahi.inc part of pfSense (http://www.pfSense.com) - Copyright (C) 2009 Scott Ullrich, Jim Pingle + Copyright (C) 2009-2012 Scott Ullrich, Jim Pingle All rights reserved. Redistribution and use in source and binary forms, with or without @@ -29,6 +29,16 @@ POSSIBILITY OF SUCH DAMAGE. */ +$pfs_version = substr(trim(file_get_contents("/etc/version")),0,3); +switch ($pfs_version) { + case "1.2": + case "2.0": + define('AVAHI_BASE','/usr/local'); + break; + default: + define('AVAHI_BASE', '/usr/pbi/avahi-' . php_uname("m")); +} + function avahi_start() { mwexec_bg("/usr/local/etc/rc.d/avahi-daemon.sh start"); } @@ -41,17 +51,17 @@ function avahi_install() { global $g, $config; conf_mount_rw(); + // This old hacky install code should only happen on 1.x if (php_uname("m") == "i386") - $archive = (substr(trim(file_get_contents("/etc/version")),0,1) == "2") ? "avahi8.tar.gz" : "avahi.tar.gz"; - + $archive = (substr(trim(file_get_contents("/etc/version")),0,1) == "1") ? "avahi.tar.gz" : ""; // Extract out libraries and avahi-daemon if(!empty($archive) && file_exists("/root/{$archive}")) { - exec("mkdir -p /usr/local/etc/avahi/services/"); - exec("mv /usr/local/etc/avahi/*.service /usr/local/etc/avahi/services/"); + exec("mkdir -p " . AVAHI_BASE . "/etc/avahi/services/"); + exec("mv " . AVAHI_BASE . "/etc/avahi/*.service " . AVAHI_BASE . "/etc/avahi/services/"); exec("/usr/bin/tar xzPUf /root/{$archive} -C /"); unlink("/root/{$archive}"); // Make sure everthing was extracted - if(!file_exists("/usr/local/sbin/avahi-daemon")) { + if(!file_exists(AVAHI_BASE . "/sbin/avahi-daemon")) { log_error("Sorry, something went wrong while extract avahi binaries. Please try the operation again"); return; } @@ -76,6 +86,8 @@ function avahi_write_config() { $enable = $config['installedpackages']['avahi']['config'][0]['enable']; $browsedomains = $config['installedpackages']['avahi']['config'][0]['browsedomains']; $denyif = $config['installedpackages']['avahi']['config'][0]['denyinterfaces']; + $useipv4 = ($config['installedpackages']['avahi']['config'][0]['disable_ipv4']) ? "no" : "yes"; + $useipv6 = ($config['installedpackages']['avahi']['config'][0]['disable_ipv6']) ? "no" : "yes"; // No supplied domains? Use the defaults. if(!$browsedomains) @@ -86,7 +98,7 @@ function avahi_write_config() { // Process interfaces defined by user to deny. if($denyif) { - $if = split(",", $denyif); + $if = explode(",", $denyif); foreach($if as $i) { $ifreal = convert_friendly_interface_to_real_interface_name($i); if($ifreal) @@ -106,13 +118,13 @@ host-name={$hostname} domain-name={$domain} browse-domains="{$browsedomains}" deny-interfaces={$denyinterfaces} -use-ipv4=yes -use-ipv6=no +use-ipv4={$useipv4} +use-ipv6={$useipv6} enable-dbus=no #check-response-ttl=no #use-iff-running=no #disallow-other-stacks=no -#allow-point-to-point=no +allow-point-to-point=yes [wide-area] enable-wide-area=yes @@ -146,8 +158,8 @@ rlimit-nproc=3 EOF; /* Write out .conf file */ - safe_mkdir("/usr/local/etc/avahi"); - $fd = fopen("/usr/local/etc/avahi/avahi-daemon.conf", "w"); + safe_mkdir(AVAHI_BASE . "/etc/avahi"); + $fd = fopen(AVAHI_BASE . "/etc/avahi/avahi-daemon.conf", "w"); fwrite($fd, $avahiconfig); fclose($fd); /* Write out rc.d startup file */ @@ -156,9 +168,22 @@ EOF; $start .= " mkdir -p /proc\n"; $start .= " mount -t procfs procfs /proc\n"; $start .= "fi\n"; - $start .= "/usr/local/sbin/avahi-daemon -D\n"; + $start .= "/usr/bin/killall avahi-daemon\n"; + if (file_exists(AVAHI_BASE . "/etc/rc.d/dbus")) { + $start .= "/usr/bin/killall dbus-daemon\n"; + $start .= "rm /var/run/dbus/dbus.pid\n"; + $start .= AVAHI_BASE . "/etc/rc.d/dbus onestart\n"; + } + $start .= "sleep 5\n"; + $start .= AVAHI_BASE . "/sbin/avahi-daemon -D\n"; $start .= "/etc/rc.conf_mount_ro\n"; - $stop = "/usr/bin/killall avahi-daemon"; + + $stop = "/usr/bin/killall avahi-daemon\n"; + if (file_exists(AVAHI_BASE . "/etc/rc.d/dbus")) { + $stop .= AVAHI_BASE . "/etc/rc.d/dbus onestop\n"; + $stop .= "rm /var/run/dbus/dbus.pid\n"; + } + write_rcfile(array( "file" => "avahi-daemon.sh", "start" => $start, diff --git a/config/avahi/avahi.xml b/config/avahi/avahi.xml index dc77c659..ef229af1 100644 --- a/config/avahi/avahi.xml +++ b/config/avahi/avahi.xml @@ -34,7 +34,7 @@ </copyright> <title>Services: Avahi</title> <name>avahi</name> - <version>1.0</version> + <version>0.6.29 pkg v1.01</version> <savetext>Save</savetext> <include_file>/usr/local/pkg/avahi.inc</include_file> <menu> @@ -68,6 +68,18 @@ <type>interfaces_selection</type> <multiple>true</multiple> </field> + <field> + <fielddescr>Disable IPv6</fielddescr> + <fieldname>disable_ipv6</fieldname> + <description>Disable IPv6 support in Avahi</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Disable IPv4</fielddescr> + <fieldname>disable_ipv4</fieldname> + <description>Disable IPv4 support in Avahi</description> + <type>checkbox</type> + </field> </fields> <additional_files_needed> <prefix>/root/</prefix> @@ -102,6 +114,7 @@ </custom_php_install_command> <custom_php_deinstall_command> unlink_if_exists("/usr/local/etc/rc.d/avahi-daemon.sh"); - exec("killall avahi-daemon"); + exec("killall -9 avahi-daemon"); + exec("killall -9 dbus-daemon"); </custom_php_deinstall_command> </packagegui> diff --git a/config/bacula-client/bacula-client.inc b/config/bacula-client/bacula-client.inc new file mode 100644 index 00000000..156b3763 --- /dev/null +++ b/config/bacula-client/bacula-client.inc @@ -0,0 +1,113 @@ +<?php
+
+/* ========================================================================== */
+/*
+ bacula-client.inc
+ part of pfSense (http://www.pfSense.com)
+ Copyright (C) 2012 Marcio Carlos Braga Antao
+ Copyright (C) 2012 Marcello Coutinho
+ All rights reserved.
+
+ Based on m0n0wall (http://m0n0.ch/wall)
+ Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>.
+ All rights reserved.
+ */
+/* ========================================================================== */
+/*
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+/* ========================================================================== */
+ require_once("config.inc");
+ require_once("util.inc");
+
+function baculaclient_custom_php_install_command(){
+ global $g, $config;
+ baculaclient_custom_php_write_config();
+}
+
+function baculaclient_custom_php_deinstall_command(){
+ global $g, $config;
+
+ conf_mount_rw();
+
+ // 1. Delete our config file
+ unlink_if_exists("/usr/local/etc/bacula-fd.conf");
+
+ // 2. Re-run sshd config generation script
+ exec("/usr/local/etc/rc.d/bacula-fd.sh stop");
+ conf_mount_ro();
+}
+
+function baculaclient_custom_php_write_config(){
+ global $g, $config;
+ conf_mount_rw();
+ //check config_file
+ $startup_file="/usr/local/etc/rc.d/bacula-fd";
+ if (file_exists($startup_file)){
+ $startup_script=file_get_contents($startup_file);
+ $startup_script=preg_replace("/NO/","YES",$startup_script);
+ file_put_contents("{$startup_file}.sh",$startup_script,LOCK_EX);
+ // Ensure bacula-fd has a+rx
+ exec("chmod a+rx {$startup_file}.sh");
+ }
+
+ //check config
+ if (is_array($config['installedpackages']['baculaclient']['config'])){
+ $baculaclient_conf="";
+ foreach ($config['installedpackages']['baculaclient']['config'] as $bc) {
+ // create Director
+ switch ($bc['type']){
+ case "Director":
+ $baculaclient_conf .= "Director { \n\t Name = {$bc['director']}-dir #{$bc['description']}\n\t Password = \"{$bc['password']}\"\n\t}\n";
+ Break;
+ case "Monitor":
+ $baculaclient_conf .= "Director { \n\t Name = {$bc['director']}-mon #{$bc['description']}\n\t Password = \"{$bc['password']}\"\n\t Monitor = yes\n\t}\n";
+ break;
+ case "Local":
+ $baculaclient_conf .= "Director { \n\t Name = {$bc['director']}-dir #{$bc['description']}\n\t Password = \"{$bc['password']}\"\n\t}\n";
+ $baculaclient_conf .= "Director { \n\t Name = {$bc['director']}-mon #{$bc['description']}\n\t Password = \"{$bc['password']}\"\n\t Monitor = yes\n\t}\n";
+ $LocalDirector = $bc['director'];
+ }
+
+ }
+
+ // create Messages
+ $baculaclient_conf .= "Messages { \n\t Name = Standard \n\t director = {$LocalDirector}-dir = all, !skipped, !restored\n\t}\n";
+ // create FielDaemon
+
+ if (is_array($config['installedpackages']['baculaclientfd']['config'])){
+ $port = $config['installedpackages']['baculaclientfd']['config'][0]['port'];
+ $jobs = $config['installedpackages']['baculaclientfd']['config'][0]['jobs'];
+ }
+ else{
+ $port="9102";
+ $jobs="20";
+ }
+ $baculaclient_conf .= "FileDaemon { \n\t Name = {$LocalDirector}-fd #\n\t FDport = {$port}\n\t WorkingDirectory = /var/db/bacula\n\t Pid Directory = /var/run\n\tMaximum Concurrent Jobs = {$jobs}\n\t}\n";
+ file_put_contents("/usr/local/etc/bacula-fd.conf",$baculaclient_conf,LOCK_EX);
+ exec("/usr/local/etc/rc.d/bacula-fd.sh restart");
+ // Mount Read-only
+ conf_mount_ro();
+ }
+ }
+
+ ?>
\ No newline at end of file diff --git a/config/bacula-client/bacula-client.xml b/config/bacula-client/bacula-client.xml new file mode 100644 index 00000000..c79a5a0c --- /dev/null +++ b/config/bacula-client/bacula-client.xml @@ -0,0 +1,163 @@ +<?xml version="1.0" encoding="utf-8" ?> +<packagegui> +<copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + bacula-client.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) Marcio Carlos Braga Antao + Copyright (C) 2012 Marcello Coutinho + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Client Install for Bacula 5.2.6 Backup</description> + <requirements>Bacula Server Installed in or network</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>baculaclient</name> + <version>5.2.6</version> + <title>Bacula-Client: Setting</title> + <aftersaveredirect>/pkg.php?xml=bacula-client.xml</aftersaveredirect> + <include_file>/usr/local/pkg/bacula-client.inc</include_file> + <configpath>installedpackages->package->baculaclient</configpath> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.com/packages/config/bacula-client/bacula-client.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.com/packages/config/bacula-client/bacula-client_fd.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.com/packages/config/bacula-client/bacula-client_view_config.php</item> + </additional_files_needed> + <menu> + <name>Bacula-client</name> + <tooltiptext>bacula backup client</tooltiptext> + <section>Services</section> + <configfile>bacula-client.xml</configfile> + </menu> + <service> + <rcfile>bacula-fd.sh</rcfile> + <name>Bacula-client</name> + <executable>bacula-fd</executable> + <description>bacula backup client</description> + </service> + <tabs> + <tab> + <text>Directors</text> + <url>/pkg.php?xml=bacula-client.xml</url> + <active/> + </tab> + <tab> + <text>FileDaemon</text> + <url>/pkg_edit.php?xml=bacula-client_fd.xml</url> + </tab> + <tab> + <text>View Configuration</text> + <url>/bacula-client_view_config.php</url> + </tab> + </tabs> + <adddeleteeditpagefields> + <columnitem> + <fielddescr>Server Director</fielddescr> + <fieldname>director</fieldname> + </columnitem> + <columnitem> + <fielddescr>Type</fielddescr> + <fieldname>type</fieldname> + </columnitem> + <columnitem> + <fielddescr>Description</fielddescr> + <fieldname>description</fieldname> + </columnitem> + </adddeleteeditpagefields> + <fields> + <field> + <type>listtopic</type> + <fieldname>directors</fieldname> + <name>Directors</name> + </field> + <field> + <fielddescr>Director Name</fielddescr> + <fieldname>director</fieldname> + <type>input</type> + <size>60</size> + <description>Name of director</description> + <required/> + </field> + <field> + <fielddescr>Description</fielddescr> + <fieldname>description</fieldname> + <description>Enter a description for this file.</description> + <type>input</type> + <size>60</size> + </field> + <field> + <fielddescr>Password</fielddescr> + <fieldname>password</fieldname> + <type>password</type> + <size>30</size> + <description><![CDATA[Enter password for Diector use to Access.]]></description> + </field> + <field> + <fielddescr>Director type</fielddescr> + <fieldname>type</fieldname> + <type>select</type> + <options> + <option><name>Director</name><value>Director</value></option> + <option><name>Local</name><value>Local</value></option> + <option><name>Monitor</name><value>Monitor</value></option> + </options> + <description>Director Type. You need at least one local director.</description> + </field> + </fields> + <custom_php_install_command> + baculaclient_custom_php_install_command(); + </custom_php_install_command> + <custom_php_command_before_form> + </custom_php_command_before_form> + <custom_php_validation_command> + </custom_php_validation_command> + <custom_delete_php_command> + </custom_delete_php_command> + <custom_add_php_command> + </custom_add_php_command> + <custom_php_resync_config_command> + baculaclient_custom_php_write_config(); + </custom_php_resync_config_command> +</packagegui>
\ No newline at end of file diff --git a/config/bacula-client/bacula-client_fd.xml b/config/bacula-client/bacula-client_fd.xml new file mode 100644 index 00000000..d6a6a8f0 --- /dev/null +++ b/config/bacula-client/bacula-client_fd.xml @@ -0,0 +1,107 @@ +<?xml version="1.0" encoding="utf-8" ?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + bacula-client_df.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Marcio Carlos Braga Antao + Copyright (C) 2012 Marcello Coutinho + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Client Install for Bacula 5.2.6 Backup</description> + <requirements>Bacula Server Installed in or network</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>baculaclientfd</name> + <version>5.2.6</version> + <title>Bacula-Client: FileDaemon Setting</title> + <aftersaveredirect>/pkg_edit.php?xml=bacula-client_fd.xml</aftersaveredirect> + <include_file>/usr/local/pkg/bacula-client.inc</include_file> + <configpath>installedpackages->package->baculaclient</configpath> + <tabs> + <tab> + <text>Directors</text> + <url>/pkg.php?xml=bacula-client.xml</url> + </tab> + <tab> + <text>FileDaemon</text> + <url>/pkg_edit.php?xml=bacula-client_fd.xml</url> + <active/> + </tab> + <tab> + <text>View Configuration</text> + <url>/bacula-client_view_config.php</url> + </tab> + </tabs> + <fields> + <field> + <type>listtopic</type> + <fieldname>Daemon</fieldname> + <name>daemon</name> + </field> + <field> + <fielddescr>File Daemon Port</fielddescr> + <fieldname>port</fieldname> + <type>input</type> + <size>4</size> + <description>Port for a File Daemon. Default : 9102 </description> + <required/> + </field> + <field> + <fielddescr>Maximun Concurrent Jobs</fielddescr> + <fieldname>jobs</fieldname> + <type>input</type> + <size>3</size> + <required/> + <description>Maximun Concurrent Jobs. Default : 20</description> + </field> + + </fields> + + <custom_php_install_command> + baculaclient_custom_php_install_command(); + </custom_php_install_command> + <custom_php_command_before_form> + </custom_php_command_before_form> + <custom_php_validation_command> + </custom_php_validation_command> + <custom_delete_php_command> + </custom_delete_php_command> + <custom_add_php_command> + </custom_add_php_command> + <custom_php_resync_config_command> + baculaclient_custom_php_write_config(); + </custom_php_resync_config_command> +</packagegui>
\ No newline at end of file diff --git a/config/bacula-client/bacula-client_view_config.php b/config/bacula-client/bacula-client_view_config.php new file mode 100644 index 00000000..7fa64cf4 --- /dev/null +++ b/config/bacula-client/bacula-client_view_config.php @@ -0,0 +1,86 @@ +<?php +/* + bacula-client_view_config.php + part of pfSense (http://www.pfsense.com/) + Copyright (C) 2010 Scott Ullrich <sullrich@gmail.com> + Copyright (C) 2012 M�rcio Carlos Ant�o + 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("guiconfig.inc"); + +$pfSversion = str_replace("\n", "", file_get_contents("/etc/version")); +if(strstr($pfSversion, "1.2")) + $one_two = true; + +$pgtitle = "Bacula-Client: View Configuration"; +include("head.inc"); + +?> +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> +<?php include("fbegin.inc"); ?> + +<?php if($one_two): ?> +<p class="pgtitle"><?=$pgtitle?></font></p> +<?php endif; ?> + +<?php if ($savemsg) print_info_box($savemsg); ?> + +<form action="bacula-client_view_config.php" method="post"> + +<div id="mainlevel"> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr><td> +<?php + $tab_array = array(); + $tab_array[] = array(gettext("Directors"), false, "/pkg.php?xml=bacula-client.xml"); + $tab_array[] = array(gettext("FileDaemon"), false, "/pkg_edit.php?xml=bacula-client_fd.xml"); + $tab_array[] = array(gettext("View Configuration"), true, "/bacula-client_view_config.php"); + display_top_tabs($tab_array); +?> + </td></tr> + <tr> + <td> + <div id="mainarea"> + <table class="tabcont" width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td class="tabcont" > + <textarea id="varnishlogs" rows="50" cols="87%"> +<?php + $config_file = file_get_contents("/usr/local/etc/bacula-fd.conf"); + echo $config_file; +?> + </textarea> + </td> + </tr> + </table> + </div> + </td> + </tr> + </table> +</div> +</form> +<?php include("fend.inc"); ?> +</body> +</html>
\ No newline at end of file diff --git a/config/bandwidthd/bandwidthd.inc b/config/bandwidthd/bandwidthd.inc index 3aa53694..69724a96 100644 --- a/config/bandwidthd/bandwidthd.inc +++ b/config/bandwidthd/bandwidthd.inc @@ -28,12 +28,24 @@ POSSIBILITY OF SUCH DAMAGE. */ +// Check pfSense version +$pfs_version = substr(trim(file_get_contents("/etc/version")),0,3); +switch ($pfs_version) { + case "1.2": + case "2.0": + define('PKG_BANDWIDTHD_BASE', '/usr/local/bandwidthd'); + break; + default: + define('PKG_BANDWIDTHD_BASE', '/usr/pbi/bandwidthd-' . php_uname("m") . '/bandwidthd'); + } +// End: Check pfSense version + function bandwidthd_install_deinstall() { conf_mount_rw(); config_lock(); - exec("rm /usr/local/etc/rc.d/bandwidthd*"); - exec("rm -rf /usr/local/bandwidthd*"); - exec("rm /usr/local/www/bandwidthd"); + exec("rm -f /usr/local/etc/rc.d/bandwidthd*"); + exec("rm -rf " . PKG_BANDWIDTHD_BASE . "/htdocs"); + exec("rm -f /usr/local/www/bandwidthd"); conf_mount_ro(); config_unlock(); } @@ -41,16 +53,22 @@ function bandwidthd_install_deinstall() { function bandwidthd_install_config() { global $config, $g; + /* bandwidthd doesn't have a way to pass a custom config path, unfortunately */ + $bandwidthd_config_dir = PKG_BANDWIDTHD_BASE . "/etc"; + conf_mount_rw(); config_lock(); /* user defined values */ - $meta_refresh = $config['installedpackages']['bandwidthd']['config'][0]['metarefresh']; + $meta_refresh = $config['installedpackages']['bandwidthd']['config'][0]['meta_refresh']; if($meta_refresh) $meta_refresh = "meta_refresh $meta_refresh\n"; - $graph = $config['installedpackages']['bandwidthd']['config'][0]['graph']; + $graph = $config['installedpackages']['bandwidthd']['config'][0]['drawgraphs']; if($graph) $graph = "graph true\n"; + else + $graph = "graph false\n"; + $filter_text = $config['installedpackages']['bandwidthd']['config'][0]['filter']; if($filter_text) $filter_text = "filter $filter_text\n"; @@ -63,6 +81,9 @@ function bandwidthd_install_config() { $promiscuous = $config['installedpackages']['bandwidthd']['config'][0]['promiscuous']; if($promiscuous) $promiscuous = "promiscuous true\n"; + else + $promiscuous = "promiscuous false\n"; + $graph_cutoff = $config['installedpackages']['bandwidthd']['config'][0]['graphcutoff']; if($graph_cutoff) $graph_cutoff = "graph_cutoff $graph_cutoff\n"; @@ -73,7 +94,7 @@ function bandwidthd_install_config() { if($config['installedpackages']['bandwidthd']['config'][0]['active_interface']){ $ifdescrs = array($config['installedpackages']['bandwidthd']['config'][0]['active_interface']); } else { - log_error("You should specify a interface for bandwidthd to listen on. exiting."); + log_error("You should specify an interface for bandwidthd to listen on. Exiting."); } $subnets_custom = split(';',str_replace(' ','',$config['installedpackages']['bandwidthd']['config'][0]['subnets_custom'])); @@ -146,7 +167,7 @@ $dev # An interval is 2.5 minutes, this is how many # intervals to skip before doing a graphing run -$skip_inervals +$skip_intervals # Graph cutoff is how many k must be transfered by an # ip before we bother to graph it @@ -177,9 +198,9 @@ $meta_refresh EOF; - $fd = fopen("/usr/local/bandwidthd/etc/bandwidthd.conf","w"); + $fd = fopen("{$bandwidthd_config_dir}/bandwidthd.conf","w"); if(!$fd) { - log_error("could not open /usr/local/bandwidthd/etc/bandwidthd.conf for writing"); + log_error("could not open {$bandwidthd_config_dir}/bandwidthd.conf for writing"); exit; } fwrite($fd, $config_file); @@ -188,15 +209,15 @@ EOF; /* write out rc.d start/stop file */ write_rcfile(array( "file" => "bandwidthd.sh", - "start" => "/usr/local/bandwidthd/bandwidthd /usr/local/bandwidthd/etc/bandwidthd.conf", + "start" => "/usr/local/bandwidthd/bandwidthd {$bandwidthd_config_dir}/bandwidthd.conf", "stop" => "/usr/bin/killall bandwidthd" ) ); exec("rm /usr/local/www/bandwidthd"); - exec("/bin/ln -s /usr/local/bandwidthd/htdocs /usr/local/www/bandwidthd"); + exec("/bin/ln -s " . PKG_BANDWIDTHD_BASE . "/htdocs /usr/local/www/bandwidthd"); - exec("echo \"Please start bandwidthd to populate this directory.\" > /usr/local/bandwidthd/htdocs/index.html"); + exec("echo \"Please start bandwidthd to populate this directory.\" > " . PKG_BANDWIDTHD_BASE . "/htdocs/index.html"); conf_mount_ro(); config_unlock(); @@ -206,4 +227,4 @@ EOF; } -?> +?>
\ No newline at end of file diff --git a/config/bandwidthd/bandwidthd.xml b/config/bandwidthd/bandwidthd.xml index 6a3dab35..258772a7 100644 --- a/config/bandwidthd/bandwidthd.xml +++ b/config/bandwidthd/bandwidthd.xml @@ -80,7 +80,7 @@ </additional_files_needed> <fields> <field> - <fielddescr>interface</fielddescr> + <fielddescr>Interface</fielddescr> <fieldname>active_interface</fieldname> <description>The interface that bandwidthd will bind to.</description> <type>interfaces_selection</type> @@ -88,27 +88,25 @@ <default_value>lan</default_value> </field> <field> - <fielddescr>Subnet</fielddescr> - <fieldname>subnets_custom</fieldname> - <description>The subnet(s) on which bandwidthd will report. (separate with ';' for multiple subnets, e.g. 192.168.1.0/24;10.0.0.0/24)</description> - <type>input</type> + <fielddescr>Subnet</fielddescr> + <fieldname>subnets_custom</fieldname> + <description>The subnet(s) on which bandwidthd will report. (separate with ';' for multiple subnets, e.g. 192.168.1.0/24;10.0.0.0/24) The ordinary subnet for the selected interface/s is automatically put in the config, do not specify it here.</description> + <type>input</type> </field> <field> <fielddescr>Skip intervals</fielddescr> <fieldname>skipintervals</fieldname> - <description></description> + <description>Number of intervals (2.5 minute) to skip between graphing. Default 0.</description> <type>input</type> - <value>1024</value> </field> <field> <fielddescr>Graph cutoff</fielddescr> <fieldname>graphcutoff</fieldname> - <description>Graph cutoff is how many KB must be transferred by an IP before it is graphed</description> + <description>Graph cutoff is how many KB must be transferred by an IP before it is graphed. Default 1024.</description> <type>input</type> - <value>1024</value> </field> <field> - <fielddescr>promiscuous</fielddescr> + <fielddescr>Promiscuous</fielddescr> <fieldname>promiscuous</fieldname> <description>Put interface in promiscuous mode to score to traffic that may not be routing through the host machine.</description> <type>checkbox</type> @@ -126,25 +124,23 @@ <type>checkbox</type> </field> <field> - <fielddescr>filter</fielddescr> + <fielddescr>Filter</fielddescr> <fieldname>filter</fieldname> <description>Libpcap format filter string used to control what bandwidthd sees. Please always include "ip" in the string to avoid strange problems.</description> <type>input</type> - <value>ip</value> </field> <field> <fielddescr>Draw Graphs</fielddescr> <fieldname>drawgraphs</fieldname> <description>This defaults to true to graph the traffic bandwidthd is recording. Set this to false if you only want cdf output or you are using the database output option. Bandwidthd will use very little RAM and CPU if this is set to false.</description> <type>checkbox</type> - <value>checked</value> + <default_value>on</default_value> </field> <field> <fielddescr>Meta Refresh</fielddescr> <fieldname>meta_refresh</fieldname> <description>Set META REFRESH seconds (default 150, use 0 to disable).</description> <type>input</type> - <value>150</value> </field> </fields> <custom_php_resync_config_command> diff --git a/config/blinkled/blinkled.xml b/config/blinkled/blinkled.xml index c750e80b..b23c4dfc 100644 --- a/config/blinkled/blinkled.xml +++ b/config/blinkled/blinkled.xml @@ -16,11 +16,6 @@ <prefix>/usr/local/pkg/</prefix> <chmod>0755</chmod> </additional_files_needed> - <additional_files_needed> - <prefix>/usr/local/bin/</prefix> - <chmod>0755</chmod> - <item>http://www.pfsense.com/packages/config/blinkled/binaries/blinkled</item> - </additional_files_needed> <service> <name>blinkled</name> <rcfile>blinkled.sh</rcfile> diff --git a/config/dansguardian/dansguardian.conf.template b/config/dansguardian/dansguardian.conf.template index 27099332..ab30527a 100755 --- a/config/dansguardian/dansguardian.conf.template +++ b/config/dansguardian/dansguardian.conf.template @@ -157,7 +157,8 @@ proxyport = {$proxyport} # # Individual filter groups can override this setting in their own configuration. # -accessdeniedaddress = 'http://YOURSERVER.YOURDOMAIN/cgi-bin/dansguardian.pl' +#accessdeniedaddress = 'http://YOURSERVER.YOURDOMAIN/cgi-bin/dansguardian.pl' +{$accessdeniedaddress} # Non standard delimiter (only used with accessdeniedaddress) # To help preserve the full banned URL, including parameters, the variables diff --git a/config/dansguardian/dansguardian.inc b/config/dansguardian/dansguardian.inc index 56acfc5e..c897f944 100755 --- a/config/dansguardian/dansguardian.inc +++ b/config/dansguardian/dansguardian.inc @@ -29,9 +29,18 @@ */ require_once("util.inc"); -require("globals.inc"); +require_once("globals.inc"); #require("guiconfig.inc"); +$pf_version=substr(trim(file_get_contents("/etc/version")),0,3); +if ($pf_version > 2.0) + define('DANSGUARDIAN_DIR', '/usr/pbi/dansguardian-' . php_uname("m")); +else + define('DANSGUARDIAN_DIR', '/usr/local'); + + $uname=posix_uname(); +if ($uname['machine']=='amd64') + ini_set('memory_limit', '250M'); function dg_text_area_decode($text){ return preg_replace('/\r\n/', "\n",base64_decode($text)); @@ -81,7 +90,7 @@ function check_ca_hashes(){ } } -function sync_package_dansguardian() { +function sync_package_dansguardian($via_rpc=false) { global $config,$g; # detect boot process @@ -92,6 +101,9 @@ function sync_package_dansguardian() { $boot_process="on"; } + if (is_process_running('dansguardian') && isset($boot_process) && $via_rpc==false) + return; + #assign xml arrays if (!is_array($config['installedpackages']['dansguardian'])) $config['installedpackages']['dansguardian']['config'][0]=array('interface'=>'lo0', @@ -126,14 +138,22 @@ function sync_package_dansguardian() { $filterport=($dansguardian['filterports']?$dansguardian['filterports']:"8080"); $softrestart=(preg_match('/softrestart/',$dansguardian['daemon_options'])?"yes":"no"); $nodaemon=(preg_match('/nodaemon/',$dansguardian['daemon_options'])?"yes":"off"); - if (preg_match("/\d+\/\d+/",$dansguardian['children'])) - list($minchildren,$maxchildren) = split ("/", $dansguardian['children'], 2); - else - list($minchildren,$maxchildren) = split ("/", "8/120", 2); - if (preg_match("/\d+\/\d+/",$dansguardian['sparechildren'])) - list($minsparechildren,$maxsparechildren) = split ("/", $dansguardian['sparechildren'], 2); - else - list($minsparechildren,$maxsparechildren) = split ("/", "8/64", 2); + if (preg_match("/(\d+)\/(\d+)/",$dansguardian['children'],$matches)){ + $minchildren=$matches[1]; + $maxchildren=$matches[2]; + } + else{ + $minchildren=8; + $maxchildren=120; + } + if (preg_match("/(\d+)\/(\d+)/",$dansguardian['sparechildren'],$matches)){ + $minsparechildren=$matches[1]; + $maxsparechildren=$matches[2]; + } + else{ + $minsparechildren=8; + $maxsparechildren=64; + } $maxagechildren=($dansguardian['maxagechildren']?$dansguardian['maxagechildren']:"500"); $maxips=($dansguardian['maxips']?$dansguardian['maxips']:"0"); $preforkchildren=($dansguardian['preforkchildren']?$dansguardian['preforkchildren']:"10"); @@ -181,6 +201,16 @@ function sync_package_dansguardian() { #report and log $reportlevel=($dansguardian_log['report_level']?$dansguardian_log['report_level']:"3"); + if ($reportlevel == 1 || $reportlevel== 2){ + if (preg_match("@(\w+://[a-zA-Z0-9.:/\-]+)@",$dansguardian_log['reportingcgi'],$cgimatches)){ + $accessdeniedaddress="accessdeniedaddress = '".$cgimatches[1]."'"; + } + else{ + log_error("dansguardian - " . $dansguardian_log['reportingcgi'] . " is not a valid access denied cgi url"); + file_notice("dansguardian - " . $dansguardian_log['reportingcgi'] . " is not a valid access denied cgi url",""); + } + } + $accessdenied=($dansguardian_log['reportingcgi']?$dansguardian_log['report_level']:"3"); $reportlanguage=($dansguardian_log['report_language']?$dansguardian_log['report_language']:"ukenglish"); $showweightedfound=(preg_match('/showweightedfound/',$dansguardian_log['report_options'])?"on":"off"); $usecustombannedflash=(preg_match('/usecustombannedflash/',$dansguardian_log['report_options'])?"on":"off"); @@ -236,10 +266,10 @@ function sync_package_dansguardian() { "/lists/contentscanners/exceptionvirusmimetypelist", "/lists/contentscanners/exceptionvirussitelist", "/lists/contentscanners/exceptionvirusurllist", + "/lists/exceptioniplist", "/lists/pics"); - - $dansguardian_dir="/usr/local/etc/dansguardian"; + $dansguardian_dir= DANSGUARDIAN_DIR . "/etc/dansguardian"; foreach ($files as $file) if (! file_exists($dansguardian_dir.$file.'.sample')){ $new_file=""; @@ -303,12 +333,12 @@ function sync_package_dansguardian() { #phrase ACL #create a default setup if not exists if (!is_array($config['installedpackages']['dansguardianphraseacl']['config'])){ - $banned_file=file("/usr/local/etc/dansguardian/lists/bannedphraselist"); + $banned_file=file(DANSGUARDIAN_DIR . "/etc/dansguardian/lists/bannedphraselist"); foreach($banned_file as $file_line) if (preg_match ("/^.Include<(\S+)>/",$file_line,$matches)) $banned_includes .= $matches[1].","; - $weighted_file=file("/usr/local/etc/dansguardian/lists/weightedphraselist"); + $weighted_file=file(DANSGUARDIAN_DIR . "/etc/dansguardian/lists/weightedphraselist"); foreach($weighted_file as $file_line) if (preg_match ("/^.Include<(\S+)>/",$file_line,$matches)) $weighted_includes .= $matches[1].","; @@ -399,7 +429,7 @@ function sync_package_dansguardian() { file_put_contents($dansguardian_dir."/lists/logsitelist.".$dansguardian_site['name'],($dansguardian_site['urlsite_enabled']?dg_text_area_decode($config['installedpackages']['dansguardiansiteacl']['config'][$count]['log_sitelist']):""),LOCK_EX); $count++; } - + #URL ACL #create a default setup if not exists if (!is_array($config['installedpackages']['dansguardianurlacl']['config'])) @@ -647,7 +677,7 @@ function sync_package_dansguardian() { if($dansguardian_antivirus['extension_list'] == "" && file_exists ($dansguardian_dir.'/lists/contentscanners/exceptionvirusextensionlist.sample')){ $config['installedpackages']['dansguardianantivirusacl']['config'][0]['extension_list']=base64_encode(file_get_contents($dansguardian_dir.'/lists/contentscanners/exceptionvirusextensionlist.sample')); $load_samples++; - } + } file_put_contents($dansguardian_dir."/lists/contentscanners/exceptionvirusextensionlist",($dansguardian_antivirus['extension_enabled']?dg_text_area_decode($config['installedpackages']['dansguardianantivirusacl']['config'][0]['extension_list']):""),LOCK_EX); #log report @@ -657,7 +687,17 @@ function sync_package_dansguardian() { $config['installedpackages']['dansguardianlog']['config'][0]['report_file']=base64_encode($report_file); $dansguardian_log['report_file']=base64_encode($report_file); $load_samples++; - } + } + + #exception ip list + #create a default setup if not exists + if (!is_array($config['installedpackages']['dansguardianips']['config'])) + $config['installedpackages']['dansguardianips']['config'][0]=array("exceptioniplist" => ""); + if($config['installedpackages']['dansguardianips']['config'][0]['exceptioniplist'] == "" && file_exists ($dansguardian_dir.'/lists/exceptioniplist.sample')){ + $config['installedpackages']['dansguardianips']['config'][0]['exceptioniplist']=base64_encode(file_get_contents($dansguardian_dir.'/lists/exceptioniplist.sample')); + $load_samples++; + } + file_put_contents($dansguardian_dir."/lists/exceptioniplist",dg_text_area_decode($config['installedpackages']['dansguardianips']['config'][0]['exceptioniplist']),LOCK_EX); if($load_samples > 0) write_config(); @@ -676,7 +716,8 @@ function sync_package_dansguardian() { 'urlacl'=> "Default", 'group_options' => "scancleancache,infectionbypasserrorsonly", 'reportinglevel'=>'3', - 'mode'=> "1"); + 'mode'=> "1", + 'report_level'=>"global"); $groups=array("scancleancache","hexdecodecontent","blockdownloads","enablepics","deepurlanalysis","infectionbypasserrorsonly","disablecontentscan","sslcertcheck","sslmitm"); #loop on array @@ -695,8 +736,87 @@ function sync_package_dansguardian() { $dansguardian_groups['bypass']=($dansguardian_groups['bypass']?$dansguardian_groups['bypass']:"0"); $dansguardian_groups['infectionbypass']=($dansguardian_groups['infectionbypass']?$dansguardian_groups['infectionbypass']:"0"); $dansguardian_groups['mitmkey']=($dansguardian_groups['mitmkey']?$dansguardian_groups['mitmkey']:"dgs3dD3da"); + switch ($dansguardian_groups['reportinglevel']){ + case "1": + case "2": + $groupreportinglevel="reportinglevel = ".$dansguardian_groups['reportinglevel']; + if (preg_match("@(\w+://[a-zA-Z0-9.:/\-]+)@",$dansguardian_groups['reportingcgi'],$cgimatches)){ + $groupaccessdeniedaddress="accessdeniedaddress = '".$cgimatches[1]."'"; + } + else{ + log_error('Dansguardian - Group '.$dansguardian_groups['name']. ' does not has a valid access denied cgi url.'); + file_notice('Dansguardian - Group '.$dansguardian_groups['name']. ' does not has a valid access denied cgi url.',""); + } + break; + case "-1": + case "0": + case "3": + $groupreportinglevel="reportinglevel = ".$dansguardian_groups['reportinglevel']; + $groupaccessdeniedaddress=""; + break; + default: + $groupreportinglevel=""; + $groupaccessdeniedaddress=""; + } + foreach ($groups as $group) $dansguardian_groups[$group]=(preg_match("/$group/",$dansguardian_groups['group_options'])?"on":"off"); + #create group list files + $lists=array("phraseacl" => array("bannedphrase","weightedphrase","exceptionphrase"), + "siteacl" => array("bannedsite","greysite","exceptionsite","exceptionfilesite","logsite"), + "urlacl" => array("bannedurl","greyurl","exceptionurl","exceptionregexpurl","bannedregexpurl","urlregexp","exceptionfileurl","logurl","logregexpurl"), + "contentacl" => array("contentregexp"), + "extensionacl"=> array("exceptionextension","exceptionmimetype","bannedextension","bannedmimetype"), + "headeracl" => array("headerregexp","bannedregexpheader"), + "searchacl" => array("searchengineregexp","bannedsearchterm","weightedsearchterm","exceptionsearchterm") + ); + foreach ($lists as $list_key => $list_array){ + foreach ($list_array as $list_value){ + #read all access lists applied tho this group option + foreach (explode(",",$dansguardian_groups[$list_key]) as $dacl){ + if (! is_array(${$list_value})) + ${$list_value}=array(); + $file_temp=file_get_contents(DANSGUARDIAN_DIR . "/etc/dansguardian/lists/{$list_value}list.{$dacl}")."\n"; + ${$list_value}=array_merge(explode("\n",$file_temp),${$list_value}); + } + #add a package warning + array_unshift(${$list_value},"#Do not edit this file.","#It's created by dansguardian package and overwrited every config save."); + #save group file and unset array + file_put_contents(DANSGUARDIAN_DIR . "/etc/dansguardian/lists/{$list_value}list.g_{$dansguardian_groups['name']}",implode("\n",array_unique(${$list_value}))."\n",LOCK_EX); + unset(${$list_value}); + } + } + /* + bannedphraselist = '/usr/local/etc/dansguardian/lists/bannedphraselist.{$dansguardian_groups['phraseacl']}' + weightedphraselist = '/usr/local/etc/dansguardian/lists/weightedphraselist.{$dansguardian_groups['phraseacl']}' + exceptionphraselist = '/usr/local/etc/dansguardian/lists/exceptionphraselist.{$dansguardian_groups['phraseacl']}' + bannedsitelist = '/usr/local/etc/dansguardian/lists/bannedsitelist.{$dansguardian_groups['siteacl']}' + greysitelist = '/usr/local/etc/dansguardian/lists/greysitelist.{$dansguardian_groups['siteacl']}' + exceptionsitelist = '/usr/local/etc/dansguardian/lists/exceptionsitelist.{$dansguardian_groups['siteacl']}' + bannedurllist = '/usr/local/etc/dansguardian/lists/bannedurllist.{$dansguardian_groups['urlacl']}' + greyurllist = '/usr/local/etc/dansguardian/lists/greyurllist.{$dansguardian_groups['urlacl']}' + exceptionurllist = '/usr/local/etc/dansguardian/lists/exceptionurllist.{$dansguardian_groups['urlacl']}' + exceptionregexpurllist = '/usr/local/etc/dansguardian/lists/exceptionregexpurllist.{$dansguardian_groups['urlacl']}' + bannedregexpurllist = '/usr/local/etc/dansguardian/lists/bannedregexpurllist.{$dansguardian_groups['urlacl']}' + contentregexplist = '/usr/local/etc/dansguardian/lists/contentregexplist.{$dansguardian_groups['contentacl']}' + urlregexplist = '/usr/local/etc/dansguardian/lists/urlregexplist.{$dansguardian_groups['urlacl']}' + exceptionextensionlist = '/usr/local/etc/dansguardian/lists/exceptionextensionlist.{$dansguardian_groups['extensionacl']}' + exceptionmimetypelist = '/usr/local/etc/dansguardian/lists/exceptionmimetypelist.{$dansguardian_groups['extensionacl']}' + bannedextensionlist = '/usr/local/etc/dansguardian/lists/bannedextensionlist.{$dansguardian_groups['extensionacl']}' + bannedmimetypelist = '/usr/local/etc/dansguardian/lists/bannedmimetypelist.{$dansguardian_groups['extensionacl']}' + exceptionfilesitelist = '/usr/local/etc/dansguardian/lists/exceptionfilesitelist.{$dansguardian_groups['siteacl']}' + exceptionfileurllist = '/usr/local/etc/dansguardian/lists/exceptionfileurllist.{$dansguardian_groups['urlacl']}' + logsitelist = '/usr/local/etc/dansguardian/lists/logsitelist.{$dansguardian_groups['siteacl']}' + logurllist = '/usr/local/etc/dansguardian/lists/logurllist.{$dansguardian_groups['urlacl']}' + logregexpurllist = '/usr/local/etc/dansguardian/lists/logregexpurllist.{$dansguardian_groups['urlacl']}' + headerregexplist = '/usr/local/etc/dansguardian/lists/headerregexplist.{$dansguardian_groups['headeracl']}' + bannedregexpheaderlist = '/usr/local/etc/dansguardian/lists/bannedregexpheaderlist.{$dansguardian_groups['headeracl']}' + searchengineregexplist = '/usr/local/etc/dansguardian/lists/searchengineregexplist.{$dansguardian_groups['searchacl']}' + bannedsearchtermlist = '/usr/local/etc/dansguardian/lists/bannedsearchtermlist.{$dansguardian_groups['searchacl']}' + weightedsearchtermlist = '/usr/local/etc/dansguardian/lists/weightedsearchtermlist.{$dansguardian_groups['searchacl']}' + exceptionsearchtermlist = '/usr/local/etc/dansguardian/lists/exceptionsearchtermlist.{$dansguardian_groups['searchacl']}' + */ + $dg_dir=DANSGUARDIAN_DIR; include("/usr/local/pkg/dansguardianfx.conf.template"); file_put_contents($dansguardian_dir."/dansguardianf".$count.".conf", $dgf, LOCK_EX); @@ -769,7 +889,7 @@ EOF; <fielddescr>Users</fielddescr> <fieldname>info_checkbox</fieldname> <type>checkbox</type> - <description><![CDATA[Dansguardian users are required only when you have more then one group.<br>All unauthenticated users or unlisted uses will match first filter group.]]></description> + <description><![CDATA[Dansguardian users are required only when you have more then one group.<br>All unauthenticated users or unlisted users will match first filter group.]]></description> </field> EOF; } @@ -986,7 +1106,7 @@ EOF; $replace[0]='YES'; #clamdscan.conf dansguardian file - $cconf="/usr/local/etc/dansguardian/contentscanners/clamdscan.conf"; + $cconf=DANSGUARDIAN_DIR . "/etc/dansguardian/contentscanners/clamdscan.conf"; $cconf_file=file_get_contents($cconf); if (preg_match('/#clamdudsfile/',$cconf_file)){ $cconf_file=preg_replace('/#clamdudsfile/','clamdudsfile',$cconf_file); @@ -1013,7 +1133,7 @@ EOF; } file_put_contents($script, $new_clamav_startup, LOCK_EX); chmod ($script,0755); - if (file_exists('/var/run/dansguardian.pid') && is_process_running('clamd') && !isset($boot_process)){ + if (file_exists('/var/run/dansguardian.pid') && is_process_running('clamd')){ log_error('Stopping clamav-clamd'); mwexec("$script stop"); } @@ -1028,17 +1148,14 @@ EOF; #check certificate hashed - $script='/usr/local/etc/rc.d/dansguardian'; - - if($config['installedpackages']['dansguardian']['config'][0]['enable']){ - copy('/usr/local/pkg/dansguardian_rc.template','/usr/local/etc/rc.d/dansguardian'); + $script='/usr/local/etc/rc.d/dansguardian.sh'; + unlink_if_exists('/usr/local/etc/rc.d/dansguardian'); + if($config['installedpackages']['dansguardian']['config'][0]['enable']=="on"){ + copy('/usr/local/pkg/dansguardian_rc.template',$script); chmod ($script,0755); if (is_process_running('dansguardian')){ - #prevent multiple reloads during boot process - if (!isset($boot_process)){ - log_error('Reloading Dansguardian'); - exec("/usr/local/sbin/dansguardian -r"); - } + log_error('Reloading Dansguardian'); + exec("/usr/local/sbin/dansguardian -r"); } else{ log_error('Starting Dansguardian'); @@ -1047,15 +1164,15 @@ EOF; } else{ if (is_process_running('dansguardian')){ - log_error('Stopping Dansguardian'); + log_error('Dansguardian is disabled, stopping process...'); mwexec("$script stop"); } if (file_exists($script)) chmod ($script,444); } - if (!file_exists('/usr/local/etc/dansguardian/lists/phraselists/pornography/weighted_russian_utf8')) - file_put_contents('/usr/local/etc/dansguardian/lists/phraselists/pornography/weighted_russian_utf8',"",LOCK_EX); + if (!file_exists(DANSGUARDIAN_DIR . '/etc/dansguardian/lists/phraselists/pornography/weighted_russian_utf8')) + file_put_contents(DANSGUARDIAN_DIR . '/etc/dansguardian/lists/phraselists/pornography/weighted_russian_utf8',"",LOCK_EX); #check ca certs hashes check_ca_hashes(); @@ -1103,11 +1220,17 @@ function dansguardian_php_install_command() { function dansguardian_php_deinstall_command() { global $config,$g; - mwexec("/usr/local/etc/rc.d/dansguardian stop"); - sleep(1); - conf_mount_rw(); - chmod ("/usr/local/etc/rc.d/dansguardian",0444); - conf_mount_ro(); + if(is_process_running('dansguardian')){ + log_error("stopping dansguardian.."); + mwexec("/usr/local/etc/rc.d/dansguardian.sh stop"); + sleep(1); + } + + if (file_exists("/usr/local/etc/rc.d/dansguardian.sh")){ + conf_mount_rw(); + chmod ("/usr/local/etc/rc.d/dansguardian.sh",0444); + conf_mount_ro(); + } } function dansguardian_do_xmlrpc_sync($sync_to_ip, $password,$sync_type) { @@ -1174,15 +1297,15 @@ function dansguardian_do_xmlrpc_sync($sync_to_ip, $password,$sync_type) { $cli->setCredentials('admin', $password); if($g['debug']) $cli->setDebug(1); - /* send our XMLRPC message and timeout after 250 seconds */ - $resp = $cli->send($msg, "250"); + /* send our XMLRPC message and timeout after 30 seconds */ + $resp = $cli->send($msg, "30"); if(!$resp) { $error = "A communications error occurred while attempting dansguardian XMLRPC sync with {$url}:{$port}."; log_error($error); file_notice("sync_settings", $error, "dansguardian Settings Sync", ""); } elseif($resp->faultCode()) { $cli->setDebug(1); - $resp = $cli->send($msg, "250"); + $resp = $cli->send($msg, "30"); $error = "An error code was received while attempting dansguardian XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("sync_settings", $error, "dansguardian Settings Sync", ""); @@ -1193,7 +1316,7 @@ function dansguardian_do_xmlrpc_sync($sync_to_ip, $password,$sync_type) { /* tell dansguardian to reload our settings on the destionation sync host. */ $method = 'pfsense.exec_php'; $execcmd = "require_once('/usr/local/pkg/dansguardian.inc');\n"; - $execcmd .= "sync_package_dansguardian();"; + $execcmd .= "sync_package_dansguardian(true);"; /* assemble xmlrpc payload */ $params = array( @@ -1205,14 +1328,14 @@ function dansguardian_do_xmlrpc_sync($sync_to_ip, $password,$sync_type) { $msg = new XML_RPC_Message($method, $params); $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); $cli->setCredentials('admin', $password); - $resp = $cli->send($msg, "250"); + $resp = $cli->send($msg, "30"); if(!$resp) { $error = "A communications error occurred while attempting dansguardian XMLRPC sync with {$url}:{$port} (pfsense.exec_php)."; log_error($error); file_notice("sync_settings", $error, "dansguardian Settings Sync", ""); } elseif($resp->faultCode()) { $cli->setDebug(1); - $resp = $cli->send($msg, "250"); + $resp = $cli->send($msg, "30"); $error = "An error code was received while attempting dansguardian XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("sync_settings", $error, "dansguardian Settings Sync", ""); diff --git a/config/dansguardian/dansguardian_about.php b/config/dansguardian/dansguardian_about.php index 49359472..07b5768e 100755 --- a/config/dansguardian/dansguardian_about.php +++ b/config/dansguardian/dansguardian_about.php @@ -1,6 +1,6 @@ <?php /* - mailscanner_about.php + dansguardian_about.php part of pfSense (http://www.pfsense.com/) Copyright (C) 2011 Marcello Coutinho <marcellocoutinho@gmail.com> All rights reserved. @@ -27,7 +27,7 @@ POSSIBILITY OF SUCH DAMAGE. */ -require("guiconfig.inc"); +require_once("guiconfig.inc"); $pfSversion = str_replace("\n", "", file_get_contents("/etc/version")); if(strstr($pfSversion, "1.2")) @@ -96,9 +96,9 @@ include("head.inc"); <td width="78%" class="vtable"><?=gettext("Package Created by <a target=_new href='http://forum.pfsense.org/index.php?action=profile;u=4710'>Marcello Coutinho</a><br><br>");?></td> </tr> <tr> - <td width="22%" valign="top" class="vncell"><?=gettext("Donatios ");?></td> - <td width="78%" class="vtable"><?=gettext("If you like this package, please <a target=_new href='http://www.pfsense.org/index.php?option=com_content&task=view&id=47&Itemid=77'>donate to pfSense project</a>.<br><br> - If you want that your donation goes to this package developer, make a note on donation forwarding it to me.<br><br>");?></td> + <td width="22%" valign="top" class="vncell"><?=gettext("Donations ");?></td> + <td width="78%" class="vtable"><?=gettext("If you like this package, please <a target=_new href='http://www.pfsense.org/index.php?option=com_content&task=view&id=47&Itemid=77'>donate to the pfSense project</a>.<br><br> + If you want your donation to go to this package developer, make a note on the donation forwarding it to me.<br><br>");?></td> </tr> </table> diff --git a/config/dansguardian/dansguardian_groups.xml b/config/dansguardian/dansguardian_groups.xml index baa9b44a..9498ef4c 100755 --- a/config/dansguardian/dansguardian_groups.xml +++ b/config/dansguardian/dansguardian_groups.xml @@ -105,7 +105,10 @@ <fielddescr>Group mode</fielddescr> <fieldname>mode</fieldname> </columnitem> - + <columnitem> + <fielddescr>Reporting level</fielddescr> + <fieldname>reportinglevel</fieldname> + </columnitem> <columnitem> <fielddescr>Description</fielddescr> <fieldname>description</fieldname> @@ -160,6 +163,8 @@ <source><![CDATA[$config['installedpackages']['dansguardianpicsacl']['config']]]></source> <source_name>name</source_name> <source_value>name</source_value> + <multiple/> + <size>5</size> </field> <field> <fielddescr>Phrase</fielddescr> @@ -169,60 +174,74 @@ <source><![CDATA[$config['installedpackages']['dansguardianphraseacl']['config']]]></source> <source_name>name</source_name> <source_value>name</source_value> + <multiple/> + <size>5</size> </field> <field> <fielddescr>Site</fielddescr> <fieldname>siteacl</fieldname> - <description><![CDATA[Select Site Access List to apply on this group.]]></description> + <description><![CDATA[Select Site Access Lists to apply on this group.]]></description> <type>select_source</type> <source><![CDATA[$config['installedpackages']['dansguardiansiteacl']['config']]]></source> <source_name>name</source_name> <source_value>name</source_value> + <multiple/> + <size>5</size> </field> <field> <fielddescr>URL</fielddescr> <fieldname>urlacl</fieldname> - <description><![CDATA[Select URL Access List to apply on this group.]]></description> + <description><![CDATA[Select URL Access Lists to apply on this group.]]></description> <type>select_source</type> <source><![CDATA[$config['installedpackages']['dansguardianurlacl']['config']]]></source> <source_name>name</source_name> <source_value>name</source_value> + <multiple/> + <size>5</size> </field> <field> <fielddescr>Extension</fielddescr> <fieldname>extensionacl</fieldname> - <description><![CDATA[Select Extension Access List to apply on this group.]]></description> + <description><![CDATA[Select Extension Access Lists to apply on this group.]]></description> <type>select_source</type> <source><![CDATA[$config['installedpackages']['dansguardianfileacl']['config']]]></source> <source_name>name</source_name> <source_value>name</source_value> + <multiple/> + <size>5</size> </field> <field> <fielddescr>Header</fielddescr> <fieldname>headeracl</fieldname> - <description><![CDATA[Select Header Access List to apply on this group.]]></description> + <description><![CDATA[Select Header Access Lists to apply on this group.]]></description> <type>select_source</type> <source><![CDATA[$config['installedpackages']['dansguardianheaderacl']['config']]]></source> <source_name>name</source_name> <source_value>name</source_value> + <multiple/> + <size>5</size> </field> <field> <fielddescr>Content</fielddescr> <fieldname>contentacl</fieldname> - <description><![CDATA[Select Content Access List to apply on this group.]]></description> + <description><![CDATA[Select Content Access Lists to apply on this group.]]></description> <type>select_source</type> <source><![CDATA[$config['installedpackages']['dansguardiancontentacl']['config']]]></source> <source_name>name</source_name> <source_value>name</source_value> + <multiple/> + <size>5</size> </field> <field> <fielddescr>Search</fielddescr> <fieldname>searchacl</fieldname> - <description><![CDATA[Select Search Access list to apply on this group.]]></description> + <description><![CDATA[Select Search Access lists to apply on this group.]]></description> <type>select_source</type> <source><![CDATA[$config['installedpackages']['dansguardiansearchacl']['config']]]></source> <source_name>name</source_name> <source_value>name</source_value> + <multiple/> + <size>5</size> </field> <field> <name>Values</name> @@ -247,7 +266,8 @@ If defined, this overrides the global setting in dansguardian.conf for members of this filter group.]]></description> <type>select</type> <options> - <option><name>Use HTML template file (accessdeniedaddress ignored) - recommended</name><value>3</value></option> + <option><name>Use General log option selected on Report and log - recommended</name><value>global</value></option> + <option><name>Use HTML template file (accessdeniedaddress ignored)</name><value>3</value></option> <option><name>Report fully</name><value>2</value></option> <option><name>Report why but not what denied phrase</name><value>1</value></option> <option><name>Just say 'Access Denied'</name><value>0</value></option> @@ -255,6 +275,15 @@ </options> </field> <field> + <fielddescr>Access Denied cgi</fielddescr> + <fieldname>reportingcgi</fieldname> + <description><![CDATA[While using Report Level (report fully) or (Report why but not what denied phrase), specify here the url link to your access denied cgi script + ex:http://YOURSERVER.YOURDOMAIN/cgi-bin/dansguardian.pl]]></description> + <type>input</type> + <size>70</size> + </field> + + <field> <fielddescr>Weighted phrase mode</fielddescr> <fieldname>weightedphrasemode</fieldname> <description><![CDATA[IMPORTANT: Note that setting this to "0" turns off all features which extract phrases from page content, @@ -321,6 +350,15 @@ <type>input</type> <size>10</size> </field> + <field> + <fielddescr>Temporary Denied Page Bypass Secret Key</fielddescr> + <fieldname>bypasskey</fieldname> + <description><![CDATA[If not empty, rather than generating a random key you can specify one. It must be more than 8 chars.<br> + Ex1:Mary had a little lamb.<br> + Ex2:76b42abc1cd0fdcaf6e943dcbc93b826]]></description> + <type>input</type> + <size>70</size> + </field> <field> <fielddescr>Infection/Scan Error Bypass</fielddescr> <fieldname>infectionbypass</fieldname> diff --git a/config/dansguardian/dansguardian_ips_header.xml b/config/dansguardian/dansguardian_ips_header.xml index 33e50332..c15e31da 100644 --- a/config/dansguardian/dansguardian_ips_header.xml +++ b/config/dansguardian/dansguardian_ips_header.xml @@ -97,4 +97,18 @@ </tab> </tabs> <fields> -
\ No newline at end of file + <field> + <name>Exception IP list</name> + <type>listtopic</type> + </field> + <field> + <fieldname>exceptioniplist</fieldname> + <fielddescr>Exception Ip List</fielddescr> + <description><![CDATA[Include ip addresses and or ipadresses/netmask of computers from which web access should not be filtered.<br> + Leave empty to load dansguardian defaults.]]></description> + <type>textarea</type> + <cols>80</cols> + <rows>12</rows> + <encoding>base64</encoding> + </field> +
\ No newline at end of file diff --git a/config/dansguardian/dansguardian_log.xml b/config/dansguardian/dansguardian_log.xml index a3448d44..a9b9d0e9 100644 --- a/config/dansguardian/dansguardian_log.xml +++ b/config/dansguardian/dansguardian_log.xml @@ -114,6 +114,14 @@ <option><name>Just say 'Access Denied'</name><value>0</value></option> <option><name>Log but do not block - Stealth mode</name><value>-1</value></option> </options> + </field> + <field> + <fielddescr>Access Denied cgi</fielddescr> + <fieldname>reportingcgi</fieldname> + <description><![CDATA[While using Report Level (report fully) or (Report why but not what denied phrase), specify here the url link to your access denied cgi script + ex:http://YOURSERVER.YOURDOMAIN/cgi-bin/dansguardian.pl]]></description> + <type>input</type> + <size>70</size> </field> <field> <fielddescr>Report Language</fielddescr> diff --git a/config/dansguardian/dansguardian_site_acl.xml b/config/dansguardian/dansguardian_site_acl.xml index 163c94c9..fcddfea6 100755 --- a/config/dansguardian/dansguardian_site_acl.xml +++ b/config/dansguardian/dansguardian_site_acl.xml @@ -161,7 +161,7 @@ </field> <field> <fielddescr>Enable</fielddescr> - <fieldname>greysite_enable</fieldname> + <fieldname>greysite_enabled</fieldname> <type>checkbox</type> <description></description> </field> diff --git a/config/dansguardian/dansguardian_url_acl.xml b/config/dansguardian/dansguardian_url_acl.xml index 28497e57..556e0bab 100755 --- a/config/dansguardian/dansguardian_url_acl.xml +++ b/config/dansguardian/dansguardian_url_acl.xml @@ -77,7 +77,7 @@ </tab> <tab> <text>Content</text> - <url>/pkg.php?xml=dansguardian_file_acl.xml</url> + <url>/pkg.php?xml=dansguardian_content_acl.xml</url> </tab> <tab> <text>Header</text> diff --git a/config/dansguardian/dansguardianfx.conf.template b/config/dansguardian/dansguardianfx.conf.template index ccc24f19..cfc9645e 100644 --- a/config/dansguardian/dansguardianfx.conf.template +++ b/config/dansguardian/dansguardianfx.conf.template @@ -56,20 +56,20 @@ groupmode = {$dansguardian_groups['mode']} groupname = '{$dansguardian_groups['name']}' # Content filtering files location -bannedphraselist = '/usr/local/etc/dansguardian/lists/weightedphraselist.{$dansguardian_groups['phraseacl']}' -weightedphraselist = '/usr/local/etc/dansguardian/lists/weightedphraselist.{$dansguardian_groups['phraseacl']}' -exceptionphraselist = '/usr/local/etc/dansguardian/lists/exceptionphraselist.{$dansguardian_groups['phraseacl']}' -bannedsitelist = '/usr/local/etc/dansguardian/lists/bannedsitelist.{$dansguardian_groups['siteacl']}' -greysitelist = '/usr/local/etc/dansguardian/lists/greysitelist.{$dansguardian_groups['siteacl']}' -exceptionsitelist = '/usr/local/etc/dansguardian/lists/exceptionsitelist.{$dansguardian_groups['siteacl']}' -bannedurllist = '/usr/local/etc/dansguardian/lists/bannedurllist.{$dansguardian_groups['urlacl']}' -greyurllist = '/usr/local/etc/dansguardian/lists/greyurllist.{$dansguardian_groups['urlacl']}' -exceptionurllist = '/usr/local/etc/dansguardian/lists/exceptionurllist.{$dansguardian_groups['urlacl']}' -exceptionregexpurllist = '/usr/local/etc/dansguardian/lists/exceptionregexpurllist.{$dansguardian_groups['urlacl']}' -bannedregexpurllist = '/usr/local/etc/dansguardian/lists/bannedregexpurllist.{$dansguardian_groups['urlacl']}' -picsfile = '/usr/local/etc/dansguardian/lists/{$dansguardian_groups['picsacl']}' -contentregexplist = '/usr/local/etc/dansguardian/lists/contentregexplist.{$dansguardian_groups['contentacl']}' -urlregexplist = '/usr/local/etc/dansguardian/lists/urlregexplist.{$dansguardian_groups['urlacl']}' +bannedphraselist = '{$dg_dir}/etc/dansguardian/lists/bannedphraselist.g_{$dansguardian_groups['name']}' +weightedphraselist = '{$dg_dir}/etc/dansguardian/lists/weightedphraselist.g_{$dansguardian_groups['name']}' +exceptionphraselist = '{$dg_dir}/etc/dansguardian/lists/exceptionphraselist.g_{$dansguardian_groups['name']}' +bannedsitelist = '{$dg_dir}/etc/dansguardian/lists/bannedsitelist.g_{$dansguardian_groups['name']}' +greysitelist = '{$dg_dir}/etc/dansguardian/lists/greysitelist.g_{$dansguardian_groups['name']}' +exceptionsitelist = '{$dg_dir}/etc/dansguardian/lists/exceptionsitelist.g_{$dansguardian_groups['name']}' +bannedurllist = '{$dg_dir}/etc/dansguardian/lists/bannedurllist.g_{$dansguardian_groups['name']}' +greyurllist = '{$dg_dir}/etc/dansguardian/lists/greyurllist.g_{$dansguardian_groups['name']}' +exceptionurllist = '{$dg_dir}/etc/dansguardian/lists/exceptionurllist.g_{$dansguardian_groups['name']}' +exceptionregexpurllist = '{$dg_dir}/etc/dansguardian/lists/exceptionregexpurllist.g_{$dansguardian_groups['name']}' +bannedregexpurllist = '{$dg_dir}/etc/dansguardian/lists/bannedregexpurllist.g_{$dansguardian_groups['name']}' +picsfile = '{$dg_dir}/etc/dansguardian/lists/g_{$dansguardian_groups['name']}' +contentregexplist = '{$dg_dir}/etc/dansguardian/lists/contentregexplist.g_{$dansguardian_groups['name']}' +urlregexplist = '{$dg_dir}/etc/dansguardian/lists/urlregexplist.g_{$dansguardian_groups['name']}' # Filetype filtering # @@ -83,28 +83,28 @@ urlregexplist = '/usr/local/etc/dansguardian/lists/urlregexplist.{$dansguardian_ # (on | off) # blockdownloads = {$dansguardian_groups['blockdownloads']} -exceptionextensionlist = '/usr/local/etc/dansguardian/lists/exceptionextensionlist.{$dansguardian_groups['extensionacl']}' -exceptionmimetypelist = '/usr/local/etc/dansguardian/lists/exceptionmimetypelist.{$dansguardian_groups['extensionacl']}' +exceptionextensionlist = '{$dg_dir}/etc/dansguardian/lists/exceptionextensionlist.g_{$dansguardian_groups['name']}' +exceptionmimetypelist = '{$dg_dir}/etc/dansguardian/lists/exceptionmimetypelist.g_{$dansguardian_groups['name']}' # # Use the following lists to block specific kinds of file downloads. # The two exception lists above can be used to override these. # -bannedextensionlist = '/usr/local/etc/dansguardian/lists/bannedextensionlist.{$dansguardian_groups['extensionacl']}' -bannedmimetypelist = '/usr/local/etc/dansguardian/lists/bannedmimetypelist.{$dansguardian_groups['extensionacl']}' +bannedextensionlist = '{$dg_dir}/etc/dansguardian/lists/bannedextensionlist.g_{$dansguardian_groups['name']}' +bannedmimetypelist = '{$dg_dir}/etc/dansguardian/lists/bannedmimetypelist.g_{$dansguardian_groups['name']}' # # In either file filtering mode, the following list can be used to override # MIME type & extension blocks for particular domains & URLs (trusted download sites). # -exceptionfilesitelist = '/usr/local/etc/dansguardian/lists/exceptionfilesitelist.{$dansguardian_groups['siteacl']}' -exceptionfileurllist = '/usr/local/etc/dansguardian/lists/exceptionfileurllist.{$dansguardian_groups['urlacl']}' +exceptionfilesitelist = '{$dg_dir}/etc/dansguardian/lists/exceptionfilesitelist.g_{$dansguardian_groups['name']}' +exceptionfileurllist = '{$dg_dir}/etc/dansguardian/lists/exceptionfileurllist.g_{$dansguardian_groups['name']}' # Categorise without blocking: # Supply categorised lists here and the category string shall be logged against # matching requests, but matching these lists does not perform any filtering # action. -logsitelist = '/usr/local/etc/dansguardian/lists/logsitelist.{$dansguardian_groups['siteacl']}' -logurllist = '/usr/local/etc/dansguardian/lists/logurllist.{$dansguardian_groups['urlacl']}' -logregexpurllist = '/usr/local/etc/dansguardian/lists/logregexpurllist.{$dansguardian_groups['urlacl']}' +logsitelist = '{$dg_dir}/etc/dansguardian/lists/logsitelist.g_{$dansguardian_groups['name']}' +logurllist = '{$dg_dir}/etc/dansguardian/lists/logurllist.g_{$dansguardian_groups['name']}' +logregexpurllist = '{$dg_dir}/etc/dansguardian/lists/logregexpurllist.g_{$dansguardian_groups['name']}' # Outgoing HTTP header rules: # Optional lists for blocking based on, and modification of, outgoing HTTP @@ -115,8 +115,8 @@ logregexpurllist = '/usr/local/etc/dansguardian/lists/logregexpurllist.{$dansgua # Headers are matched/replaced on a line-by-line basis, not as a contiguous # block. # Use for example, to remove cookies or prevent certain user-agents. -headerregexplist = '/usr/local/etc/dansguardian/lists/headerregexplist.{$dansguardian_groups['headeracl']}' -bannedregexpheaderlist = '/usr/local/etc/dansguardian/lists/bannedregexpheaderlist.{$dansguardian_groups['headeracl']}' +headerregexplist = '{$dg_dir}/etc/dansguardian/lists/headerregexplist.g_{$dansguardian_groups['name']}' +bannedregexpheaderlist = '{$dg_dir}/etc/dansguardian/lists/bannedregexpheaderlist.g_{$dansguardian_groups['name']}' # Weighted phrase mode # Optional; overrides the weightedphrasemode option in dansguardian.conf @@ -143,7 +143,7 @@ naughtynesslimit = {$dansguardian_groups['naughtynesslimit']} # List of regular expressions for matching search engine URLs. It is assumed # that the search terms themselves will be contained within the first submatch # of each expression. -searchengineregexplist = '/usr/local/etc/dansguardian/lists/searchengineregexplist.{$dansguardian_groups['searchacl']}' +searchengineregexplist = '{$dg_dir}/etc/dansguardian/lists/searchengineregexplist.g_{$dansguardian_groups['name']}' # # Search term limit # The limit over which requests will be blocked for containing search terms @@ -165,9 +165,9 @@ searchtermlimit = {$dansguardian_groups['searchtermlimit']} # of text. # Please note that all or none of the below should be uncommented, not a # mixture. -bannedsearchtermlist = '/usr/local/etc/dansguardian/lists/bannedsearchtermlist.{$dansguardian_groups['searchacl']}' -weightedsearchtermlist = '/usr/local/etc/dansguardian/lists/weightedsearchtermlist.{$dansguardian_groups['searchacl']}' -exceptionsearchtermlist = '/usr/local/etc/dansguardian/lists/exceptionsearchtermlist.{$dansguardian_groups['searchacl']}' +bannedsearchtermlist = '{$dg_dir}/etc/dansguardian/lists/bannedsearchtermlist.g_{$dansguardian_groups['name']}' +weightedsearchtermlist = '{$dg_dir}/etc/dansguardian/lists/weightedsearchtermlist.g_{$dansguardian_groups['name']}' +exceptionsearchtermlist = '{$dg_dir}/etc/dansguardian/lists/exceptionsearchtermlist.g_{$dansguardian_groups['name']}' # Category display threshold # This option only applies to pages blocked by weighted phrase filtering. @@ -268,8 +268,8 @@ deepurlanalysis = {$dansguardian_groups['deepurlanalysis']} # # If defined, this overrides the global setting in dansguardian.conf for # members of this filter group. -# -#reportinglevel = {$dansguardian_groups['reportinglevel']} +# reportinglevel = 3 +{$groupreportinglevel} # accessdeniedaddress is the address of your web server to which the cgi # dansguardian reporting script was copied. Only used in reporting levels @@ -284,8 +284,8 @@ deepurlanalysis = {$dansguardian_groups['deepurlanalysis']} # # If defined, this overrides the global setting in dansguardian.conf for # members of this filter group. -# -#accessdeniedaddress = 'http://YOURSERVER.YOURDOMAIN/cgi-bin/dansguardian.pl' +# accessdeniedaddress = 'http://YOURSERVER.YOURDOMAIN/cgi-bin/dansguardian.pl' +{$groupaccessdeniedaddress} # HTML Template override # If defined, this specifies a custom HTML template file for members of this @@ -293,12 +293,12 @@ deepurlanalysis = {$dansguardian_groups['deepurlanalysis']} # only used in reporting level 3. # # The default template file path is <languagedir>/<language>/template.html -# e.g. /usr/local/share/dansguardian/languages/ukenglish/template.html when using 'ukenglish' +# e.g. {$dg_dir}/share/dansguardian/languages/ukenglish/template.html when using 'ukenglish' # language. # # This option generates a file path of the form: # <languagedir>/<language>/<htmltemplate> -# e.g. /usr/local/share/dansguardian/languages/ukenglish/custom.html +# e.g. {$dg_dir}/share/dansguardian/languages/ukenglish/custom.html # #htmltemplate = 'custom.html' diff --git a/config/freeradius2/freeradius.inc b/config/freeradius2/freeradius.inc index 35566e22..2a6594f7 100644 --- a/config/freeradius2/freeradius.inc +++ b/config/freeradius2/freeradius.inc @@ -45,76 +45,58 @@ require_once("globals.inc"); require_once("filter.inc"); require_once("services.inc"); -define('RADDB', '/usr/local/etc/raddb'); +// Check pfSense version +$pfs_version = substr(trim(file_get_contents("/etc/version")),0,3); +switch ($pfs_version) { + case "1.2": + case "2.0": + define('FREERADIUS_BASE', '/usr/local'); + break; + default: + define('FREERADIUS_BASE', '/usr/pbi/freeradius-' . php_uname("m")); +} +// End: Check pfSense version function freeradius_deinstall_command() { - exec("cd /var/db/pkg && pkg_delete `ls | grep freeradius`"); - exec("rm -rf /usr/local/etc/raddb/"); - exec("rm -rf /var/run/radiusd/"); + if (substr(trim(file_get_contents("/etc/version")),0,3) == "2.0") { + exec("cd /var/db/pkg && pkg_delete `ls | grep freeradius`"); + exec("rm -rf " . FREERADIUS_BASE . "/etc/raddb"); + exec("rm -rf /var/run/radiusd/"); + } } function freeradius_install_command() { global $config; conf_mount_rw(); + // put the constant to a variable + $varFREERADIUS_BASE = FREERADIUS_BASE; + // We create here different folders for different counters. if (!file_exists("/var/log/radacct/datacounter/")) { exec("mkdir /var/log/radacct/datacounter && mkdir /var/log/radacct/datacounter/daily && mkdir /var/log/radacct/datacounter/weekly && mkdir /var/log/radacct/datacounter/monthly && mkdir /var/log/radacct/datacounter/forever"); } if (!file_exists("/var/log/radacct/timecounter/")) { exec("mkdir /var/log/radacct/timecounter"); } - exec("mkdir /usr/local/etc/raddb/scripts"); + exec("mkdir " . FREERADIUS_BASE . "/etc/raddb/scripts"); if (!file_exists("/var/log/radutmp")) { exec("touch /var/log/radutmp"); } if (!file_exists("/var/log/radwtmp")) { exec("touch /var/log/radwtmp"); } - exec("chown -R root:wheel /usr/local/etc/raddb && chown -R root:wheel /usr/local/lib/freeradius-2.1.12 && chown -R root:wheel /var/log/radacct"); + exec("chown -R root:wheel " . FREERADIUS_BASE . "/etc/raddb && chown -R root:wheel " . FREERADIUS_BASE . "/lib/freeradius-2.1.12 && chown -R root:wheel /var/log/radacct"); // creating a backup file of the original policy.conf no matter if user checked this or not - if (!file_exists("/usr/local/etc/raddb/policy.conf.backup")) { - log_error("FreeRADIUS: Creating backup of the original file to /usr/local/etc/raddb/policy.conf.backup"); - copy("/usr/local/etc/raddb/policy.conf", "/usr/local/etc/raddb/policy.conf.backup"); + if (!file_exists(FREERADIUS_BASE . "/etc/raddb/policy.conf.backup")) { + log_error("FreeRADIUS: Creating backup of the original file to " . FREERADIUS_BASE . "/etc/raddb/policy.conf.backup"); + copy(FREERADIUS_BASE . "/etc/raddb/policy.conf", FREERADIUS_BASE . "/etc/raddb/policy.conf.backup"); } // creating a backup file of the original /modules/files no matter if user checked this or not - if (!file_exists("/usr/local/etc/raddb/files.backup")) { - log_error("FreeRADIUS: Creating backup of the original file to /usr/local/etc/raddb/files.backup"); - copy("/usr/local/etc/raddb/modules/files", "/usr/local/etc/raddb/files.backup"); + if (!file_exists(FREERADIUS_BASE . "/etc/raddb/files.backup")) { + log_error("FreeRADIUS: Creating backup of the original file to " . FREERADIUS_BASE . "/etc/raddb/files.backup"); + copy(FREERADIUS_BASE . "/etc/raddb/modules/files", FREERADIUS_BASE . "/etc/raddb/files.backup"); } // Disable virtual-server we do not need by default - if (file_exists("/usr/local/etc/raddb/sites-enabled/control-socket")) { unlink("/usr/local/etc/raddb/sites-enabled/control-socket"); } - if (file_exists("/usr/local/etc/raddb/sites-enabled/inner-tunnel")) { unlink("/usr/local/etc/raddb/sites-enabled/inner-tunnel"); } - - // We need some additional files in /usr/local/lib for the LDAP module. We fetch these files dependent on the architecture. - if (!file_exists("/usr/local/lib/libasn1.so.10") || !file_exists("/usr/local/lib/libgssapi.so.10") || !file_exists("/usr/local/lib/libheimntlm.so.10") || !file_exists("/usr/local/lib/libhx509.so.10") || !file_exists("/usr/local/lib/ldd/libkrb5.so.10") || !file_exists("/usr/local/lib/libroken.so.10")) { - // For i386 systems - if (exec("uname -m") == "i386") { - exec("cd /usr/local/lib/ && fetch http://e-sac.siteseguro.ws/pfsense/8/All/ldd/libasn1.so.10"); - exec("cd /usr/local/lib/ && fetch http://e-sac.siteseguro.ws/pfsense/8/All/ldd/libgssapi.so.10"); - exec("cd /usr/local/lib/ && fetch http://e-sac.siteseguro.ws/pfsense/8/All/ldd/libheimntlm.so.10"); - exec("cd /usr/local/lib/ && fetch http://e-sac.siteseguro.ws/pfsense/8/All/ldd/libhx509.so.10"); - exec("cd /usr/local/lib/ && fetch http://e-sac.siteseguro.ws/pfsense/8/All/ldd/libkrb5.so.10"); - exec("cd /usr/local/lib/ && fetch http://e-sac.siteseguro.ws/pfsense/8/All/ldd/libroken.so.10"); - exec("chmod 0755 /usr/local/lib/libasn1.so.10"); - exec("chmod 0755 /usr/local/lib/libgssapi.so.10"); - exec("chmod 0755 /usr/local/lib/libheimntlm.so.10"); - exec("chmod 0755 /usr/local/lib/libhx509.so.10"); - exec("chmod 0755 /usr/local/lib/ldd/libkrb5.so.10"); - exec("chmod 0755 /usr/local/lib/libroken.so.10"); - } - // For amd64 systems - else { - exec("cd /usr/local/lib/ && fetch http://e-sac.siteseguro.ws/pfsense/8/amd64/All/ldd/libasn1.so.10"); - exec("cd /usr/local/lib/ && fetch http://e-sac.siteseguro.ws/pfsense/8/amd64/All/ldd/libgssapi.so.10"); - exec("cd /usr/local/lib/ && fetch http://e-sac.siteseguro.ws/pfsense/8/amd64/All/ldd/libheimntlm.so.10"); - exec("cd /usr/local/lib/ && fetch http://e-sac.siteseguro.ws/pfsense/8/amd64/All/ldd/libhx509.so.10"); - exec("cd /usr/local/lib/ && fetch http://e-sac.siteseguro.ws/pfsense/8/amd64/All/ldd/libkrb5.so.10"); - exec("cd /usr/local/lib/ && fetch http://e-sac.siteseguro.ws/pfsense/8/amd64/All/ldd/libroken.so.10"); - exec("chmod 0755 /usr/local/lib/libasn1.so.10"); - exec("chmod 0755 /usr/local/lib/libgssapi.so.10"); - exec("chmod 0755 /usr/local/lib/libheimntlm.so.10"); - exec("chmod 0755 /usr/local/lib/libhx509.so.10"); - exec("chmod 0755 /usr/local/lib/ldd/libkrb5.so.10"); - exec("chmod 0755 /usr/local/lib/libroken.so.10"); - } - } + if (file_exists(FREERADIUS_BASE . "/etc/raddb/sites-enabled/control-socket")) { unlink(FREERADIUS_BASE . "/etc/raddb/sites-enabled/control-socket"); } + if (file_exists(FREERADIUS_BASE . "/etc/raddb/sites-enabled/inner-tunnel")) { unlink(FREERADIUS_BASE . "/etc/raddb/sites-enabled/inner-tunnel"); } + // We run this here just to suppress some warnings on syslog if file doesn't exist freeradius_authorizedmacs_resync(); @@ -139,8 +121,8 @@ function freeradius_install_command() { $rcfile = array(); $rcfile['file'] = 'radiusd.sh'; - $rcfile['start'] = '/usr/local/etc/rc.d/radiusd onestart'; - $rcfile['stop'] = '/usr/local/etc/rc.d/radiusd onestop'; + $rcfile['start'] = "$varFREERADIUS_BASE" . '/etc/rc.d/radiusd onestart'; + $rcfile['stop'] = "$varFREERADIUS_BASE" . '/etc/rc.d/radiusd onestop'; write_rcfile($rcfile); conf_mount_ro(); start_service("radiusd"); @@ -150,6 +132,9 @@ function freeradius_settings_resync() { global $config; $conf = ''; + // put the constant to a variable + $varFREERADIUS_BASE = FREERADIUS_BASE; + // We do some checks of some folders which will be deleted after reboot on nanobsd systems if (!file_exists("/var/log/radacct/")) { exec("mkdir /var/log/radacct"); } if (!file_exists("/var/log/radacct/datacounter/")) { exec("mkdir /var/log/radacct/datacounter && mkdir /var/log/radacct/datacounter/daily && mkdir /var/log/radacct/datacounter/weekly && mkdir /var/log/radacct/datacounter/monthly && mkdir /var/log/radacct/datacounter/forever"); } @@ -218,7 +203,7 @@ function freeradius_settings_resync() { $conf .= <<<EOD -prefix = /usr/local +prefix = $varFREERADIUS_BASE exec_prefix = \${prefix} sysconfdir = \${prefix}/etc localstatedir = /var @@ -257,7 +242,7 @@ extended_expressions = $varsettingsextendedexpressions EOD; // Deletes virtual-server coa by default. Will be re-enabled if there is an interface-type "coa" -exec("rm -f /usr/local/etc/raddb/sites-enabled/coa"); +exec("rm -f " . FREERADIUS_BASE . "/etc/raddb/sites-enabled/coa"); $arrinterfaces = $config['installedpackages']['freeradiusinterfaces']['config']; if (is_array($arrinterfaces) && !empty($arrinterfaces)) { @@ -284,7 +269,7 @@ EOD; // Begin "if" for interface-type = coa if ($item['varinterfacetype'] == 'coa') { // Enables virtual-server coa because interface-type is coa - exec("ln -s /usr/local/etc/raddb/sites-available/coa /usr/local/etc/raddb/sites-enabled/"); + exec("ln -s " . FREERADIUS_BASE . "/etc/raddb/sites-available/coa " . FREERADIUS_BASE . "/etc/raddb/sites-enabled/"); $conf .= <<<EOD listen { type = $varinterfacetype @@ -375,7 +360,7 @@ instantiate { EOD; conf_mount_rw(); - file_put_contents(RADDB . '/radiusd.conf', $conf); + file_put_contents(FREERADIUS_BASE . '/etc/raddb/radiusd.conf', $conf); conf_mount_ro(); // "freeradius_sqlconf_resync" is pointing to this function because we need to run "freeradius_serverdefault_resync" and after that restart freeradius. @@ -553,7 +538,7 @@ if (is_array($arrusers) && !empty($arrusers)) { if ($varusersmaxtotaloctets != '') { if ($varusersreplyitem != '') { $varusersreplyitem .=","; } //create exec script - $varusersreplyitem .= "\n\tExec-Program-Wait = " . '"/bin/sh /usr/local/etc/raddb/scripts/datacounter_auth.sh ' . "$varusersusername $varusersmaxtotaloctetstimerange" . '"'; + $varusersreplyitem .= "\n\tExec-Program-Wait = " . '"/bin/sh ' . FREERADIUS_BASE . '/etc/raddb/scripts/datacounter_auth.sh ' . "$varusersusername $varusersmaxtotaloctetstimerange" . '"'; // create limit file - will be always overwritten so we can increase limit from GUI exec("`echo $varusersmaxtotaloctets > /var/log/radacct/datacounter/$varusersmaxtotaloctetstimerange/max-octets-$varusersusername`"); // if used-octets file exist we do NOT overwrite this file!!! @@ -581,7 +566,7 @@ EOD; } //end foreach } // end if - $filename = RADDB . '/users'; + $filename = FREERADIUS_BASE . '/etc/raddb/users'; conf_mount_rw(); file_put_contents($filename, $conf); chmod($filename, 0640); @@ -734,7 +719,7 @@ if (is_array($arrmacs) && !empty($arrmacs)) { if ($varmacsmaxtotaloctets != '') { if ($varmacsreplyitem != '') { $varmacsreplyitem .=","; } //create exec script - $varmacsreplyitem .= "\n\tExec-Program-Wait = " . '"/bin/sh /usr/local/etc/raddb/scripts/datacounter_auth.sh ' . "$varmacsaddress $varmacsmaxtotaloctetstimerange" . '"'; + $varmacsreplyitem .= "\n\tExec-Program-Wait = " . '"/bin/sh ' . FREERADIUS_BASE . '/etc/raddb/scripts/datacounter_auth.sh ' . "$varmacsaddress $varmacsmaxtotaloctetstimerange" . '"'; // create limit file - will be always overwritten so we can increase limit from GUI exec("`echo $varmacsmaxtotaloctets > /var/log/radacct/datacounter/$varmacsmaxtotaloctetstimerange/max-octets-$varmacsaddress`"); // if used-octets file exist we do NOT overwrite this file!!! @@ -762,7 +747,7 @@ EOD; } //end foreach } // end if - $filename = RADDB . '/authorized_macs'; + $filename = FREERADIUS_BASE . '/etc/raddb/authorized_macs'; conf_mount_rw(); file_put_contents($filename, $conf); chmod($filename, 0640); @@ -833,7 +818,7 @@ EOD; } conf_mount_rw(); - file_put_contents(RADDB . '/clients.conf', $conf); + file_put_contents(FREERADIUS_BASE . '/etc/raddb/clients.conf', $conf); conf_mount_ro(); freeradius_sync_on_changes(); @@ -901,12 +886,12 @@ function freeradius_eapconf_resync() { // This is for enable/disbable MS SoH in EAP-PEAP and the virtuial-server "soh-server" if ($eapconf['vareapconfpeapsohenable'] == 'Enable') { $vareapconfpeapsoh = 'soh = yes' . "\n\t\t\tsoh_virtual_server = " . '"' . "soh-server" . '"'; - exec("ln -s /usr/local/etc/raddb/sites-available/soh /usr/local/etc/raddb/sites-enabled/"); + exec("ln -s " . FREERADIUS_BASE . "/etc/raddb/sites-available/soh " . FREERADIUS_BASE . "/etc/raddb/sites-enabled/"); } else { $vareapconfpeapsoh = '### MS SoH Server is disabled ###'; - if (file_exists("/usr/local/etc/raddb/sites-enabled/soh")) { - exec("rm -f /usr/local/etc/raddb/sites-enabled/soh"); + if (file_exists(FREERADIUS_BASE . "/etc/raddb/sites-enabled/soh")) { + exec("rm -f " . FREERADIUS_BASE . "/etc/raddb/sites-enabled/soh"); } } @@ -920,33 +905,33 @@ if ($eapconf['vareapconfchoosecertmanager'] == 'on') { $ca_cert = lookup_ca($eapconf["ssl_ca_cert"]); if ($ca_cert != false) { if(base64_decode($ca_cert['prv'])) { - file_put_contents(RADDB . "/certs/ca_key.pem", + file_put_contents(FREERADIUS_BASE . "/etc/raddb/certs/ca_key.pem", base64_decode($ca_cert['prv'])); - $conf['ssl_ca_key'] = RADDB . '/certs/ca_key.pem'; + $conf['ssl_ca_key'] = FREERADIUS_BASE . '/etc/raddb/certs/ca_key.pem'; } if(base64_decode($ca_cert['crt'])) { - file_put_contents(RADDB . "/certs/ca_cert.pem", + file_put_contents(FREERADIUS_BASE . "/etc/raddb/certs/ca_cert.pem", base64_decode($ca_cert['crt'])); - $conf['ssl_ca_cert'] = RADDB . "/certs/ca_cert.pem"; + $conf['ssl_ca_cert'] = FREERADIUS_BASE . "/etc/raddb/certs/ca_cert.pem"; } $svr_cert = lookup_cert($eapconf["ssl_server_cert"]); if ($svr_cert != false) { if(base64_decode($svr_cert['prv'])) { - file_put_contents(RADDB . "/certs/server_key.pem", + file_put_contents(FREERADIUS_BASE . "/etc/raddb/certs/server_key.pem", base64_decode($svr_cert['prv'])); - $conf['ssl_key'] = RADDB . '/certs/server_key.pem'; + $conf['ssl_key'] = FREERADIUS_BASE . '/etc/raddb/certs/server_key.pem'; } } if(base64_decode($svr_cert['crt'])) { - file_put_contents(RADDB . "/certs/server_cert.pem", + file_put_contents(FREERADIUS_BASE . "/etc/raddb/certs/server_cert.pem", base64_decode($svr_cert['crt'])); - $conf['ssl_server_cert'] = RADDB . "/certs/server_cert.pem"; + $conf['ssl_server_cert'] = FREERADIUS_BASE . "/etc/raddb/certs/server_cert.pem"; } @@ -954,23 +939,23 @@ if ($eapconf['vareapconfchoosecertmanager'] == 'on') { $svr_cert = lookup_cert($eapconf["ssl_client_cert"]); if ($svr_cert != false) { if(base64_decode($svr_cert['prv'])) { - file_put_contents(RADDB . "/certs/client_key.pem", + file_put_contents(FREERADIUS_BASE . "/etc/raddb/certs/client_key.pem", base64_decode($svr_cert['prv'])); - $conf['ssl_key'] = RADDB . '/certs/client_key.pem'; + $conf['ssl_key'] = FREERADIUS_BASE . '/etc/raddb/certs/client_key.pem'; } } if(base64_decode($svr_cert['crt'])) { - file_put_contents(RADDB . "/certs/client_cert.pem", + file_put_contents(FREERADIUS_BASE . "/etc/raddb/certs/client_cert.pem", base64_decode($svr_cert['crt'])); - $conf['ssl_client_cert'] = RADDB . "/certs/client_cert.pem"; + $conf['ssl_client_cert'] = FREERADIUS_BASE . "/etc/raddb/certs/client_cert.pem"; } - exec("openssl pkcs12 -export -in /usr/local/etc/raddb/certs/client_cert.pem -inkey /usr/local/etc/raddb/certs/client_key.pem -out /usr/local/etc/raddb/certs/client_cert.p12 -passout pass\:"); + exec("openssl pkcs12 -export -in " . FREERADIUS_BASE . "/etc/raddb/certs/client_cert.pem -inkey " . FREERADIUS_BASE . "/etc/raddb/certs/client_key.pem -out " . FREERADIUS_BASE . "/etc/raddb/certs/client_cert.p12 -passout pass\:"); } - $conf['ssl_cert_dir'] = RADDB . '/certs'; + $conf['ssl_cert_dir'] = FREERADIUS_BASE . '/etc/raddb/certs'; } $vareapconfprivatekeyfile = 'server_key.pem'; @@ -979,11 +964,11 @@ if ($eapconf['vareapconfchoosecertmanager'] == 'on') { // generate new DH and RANDOM file // We create a single empty file just to check if there is really a change from one to another cert manager to avoid building ne DH and random files - if (!file_exists("/usr/local/etc/raddb/certs/pfsense_cert_mgr")) { - log_error("freeRADIUS: Switched to pfSense Cert-Manager. Creating new DH and random file in /usr/local/etc/raddb/certs"); - exec("cd /usr/local/etc/raddb/certs && openssl dhparam -out dh 1024"); - exec("cd /usr/local/etc/raddb/certs && dd if=/dev/urandom of=./random count=10"); - exec("touch /usr/local/etc/raddb/certs/pfsense_cert_mgr"); + if (!file_exists(FREERADIUS_BASE . "/etc/raddb/certs/pfsense_cert_mgr")) { + log_error("freeRADIUS: Switched to pfSense Cert-Manager. Creating new DH and random file in " . FREERADIUS_BASE . "/etc/raddb/certs"); + exec("cd " . FREERADIUS_BASE . "/etc/raddb/certs && openssl dhparam -out dh 1024"); + exec("cd " . FREERADIUS_BASE . "/etc/raddb/certs && dd if=/dev/urandom of=./random count=10"); + exec("touch " . FREERADIUS_BASE . "/etc/raddb/certs/pfsense_cert_mgr"); } } @@ -1078,7 +1063,7 @@ else { } EOD; - $filename = RADDB . '/eap.conf'; + $filename = FREERADIUS_BASE . '/etc/raddb/eap.conf'; file_put_contents($filename, $conf); chmod($filename, 0640); conf_mount_ro(); @@ -1232,7 +1217,7 @@ sql sql2 { } EOD; - $filename = RADDB . '/sql.conf'; + $filename = FREERADIUS_BASE . '/etc/raddb/sql.conf'; conf_mount_rw(); file_put_contents($filename, $conf); chmod($filename, 0640); @@ -2080,7 +2065,7 @@ post-proxy { } EOD; - $filename = RADDB . '/sites-available/default'; + $filename = FREERADIUS_BASE . '/etc/raddb/sites-available/default'; conf_mount_rw(); file_put_contents($filename, $conf); chmod($filename, 0640); @@ -2175,7 +2160,7 @@ authorityKeyIdentifier = keyid:always,issuer:always basicConstraints = CA:true EOD; - $filename = RADDB . '/certs/ca.cnf'; + $filename = FREERADIUS_BASE . '/etc/raddb/certs/ca.cnf'; conf_mount_rw(); file_put_contents($filename, $conf); chmod($filename, 0640); @@ -2260,7 +2245,7 @@ emailAddress = $varcertsserveremailaddress commonName = "$varcertsservercommonname" EOD; - $filename = RADDB . '/certs/server.cnf'; + $filename = FREERADIUS_BASE . '/etc/raddb/certs/server.cnf'; conf_mount_rw(); file_put_contents($filename, $conf); chmod($filename, 0640); @@ -2345,7 +2330,7 @@ emailAddress = $varcertsclientemailaddress commonName = "$varcertsclientcommonname" EOD; - $filename = RADDB . '/certs/client.cnf'; + $filename = FREERADIUS_BASE . '/etc/raddb/certs/client.cnf'; conf_mount_rw(); file_put_contents($filename, $conf); chmod($filename, 0640); @@ -2378,12 +2363,12 @@ if ($eapconf['vareapconfchoosecertmanager'] == '') { if ($arrcerts['varcertscreateclient'] == 'yes') { // delete all old certificates and keys - log_error("freeRADIUS: deleting all client.csr .crt .key .pem .tar in /usr/local/etc/raddb/certs"); - exec("rm -f /usr/local/etc/raddb/certs/client.csr"); - exec("rm -f /usr/local/etc/raddb/certs/client.crt"); - exec("rm -f /usr/local/etc/raddb/certs/client.key"); - exec("rm -f /usr/local/etc/raddb/certs/client.pem"); - exec("rm -f /usr/local/etc/raddb/certs/client.tar"); + log_error("freeRADIUS: deleting all client.csr .crt .key .pem .tar in " . FREERADIUS_BASE . "/etc/raddb/certs"); + exec("rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/client.csr"); + exec("rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/client.crt"); + exec("rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/client.key"); + exec("rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/client.pem"); + exec("rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/client.tar"); // run fuction to create ONLY new client.cnf files based on user input from freeradiuscert.xml @@ -2391,21 +2376,21 @@ if ($eapconf['vareapconfchoosecertmanager'] == '') { // make bootstrap executable and run to create cert based on client.cnf files - exec("chmod 0770 /usr/local/etc/raddb/certs/bootstrap"); - exec("/usr/local/etc/raddb/certs/bootstrap"); + exec("chmod 0770 " . FREERADIUS_BASE . "/etc/raddb/certs/bootstrap"); + exec(FREERADIUS_BASE . "/etc/raddb/certs/bootstrap"); // rename client generated XX.pem to client.pem // use regex to replace spaces and so on. - $varserial = preg_replace("/\s/","",file_get_contents('/usr/local/etc/raddb/certs/serial.old')); - if (file_exists("/usr/local/etc/raddb/certs/$varserial.pem")) - rename("/usr/local/etc/raddb/certs/$varserial.pem","/usr/local/etc/raddb/certs/client.pem"); + $varserial = preg_replace("/\s/","",file_get_contents(FREERADIUS_BASE . '/etc/raddb/certs/serial.old')); + if (file_exists(FREERADIUS_BASE . "/etc/raddb/certs/$varserial.pem")) + rename(FREERADIUS_BASE . "/etc/raddb/certs/$varserial.pem",FREERADIUS_BASE . "/etc/raddb/certs/client.pem"); // tar client-cert files - exec("cd /usr/local/etc/raddb/certs && tar -cf client.tar client.crt client.csr client.key ca.der client.pem"); + exec("cd " . FREERADIUS_BASE . "/etc/raddb/certs && tar -cf client.tar client.crt client.csr client.key ca.der client.pem"); // Make all files in certs folder read/write only for root - exec("chmod -R 0600 /usr/local/etc/raddb/certs/"); - log_error("freeRADIUS: Created new client.csr .crt .key .pem and added them together with ca.der in /usr/local/etc/raddb/certs/client.tar"); + exec("chmod -R 0600 " . FREERADIUS_BASE . "/etc/raddb/certs/"); + log_error("freeRADIUS: Created new client.csr .crt .key .pem and added them together with ca.der in " . FREERADIUS_BASE . "/etc/raddb/certs/client.tar"); } } else { @@ -2413,18 +2398,18 @@ if ($eapconf['vareapconfchoosecertmanager'] == '') { if ($arrcerts['varcertsdeleteall'] == 'yes') { // delete all old certificates and keys - deletes certs from pfsense cert-manager IN THIS FOLDER, too. - log_error("freeRADIUS: deleting all CA, Server and Client certs, DH, random and database files in /usr/local/etc/raddb/certs"); - exec("rm -f /usr/local/etc/raddb/certs/ca.pem && rm -f /usr/local/etc/raddb/certs/server.pem && rm -f /usr/local/etc/raddb/certs/client.pem"); - exec("rm -f /usr/local/etc/raddb/certs/ca.der && rm -f /usr/local/etc/raddb/certs/server.der && rm -f /usr/local/etc/raddb/certs/client.der"); - exec("rm -f /usr/local/etc/raddb/certs/ca.csr && rm -f /usr/local/etc/raddb/certs/server.csr && rm -f /usr/local/etc/raddb/certs/client.csr"); - exec("rm -f /usr/local/etc/raddb/certs/ca.crt && rm -f /usr/local/etc/raddb/certs/server.crt && rm -f /usr/local/etc/raddb/certs/client.crt"); - exec("rm -f /usr/local/etc/raddb/certs/ca.key && rm -f /usr/local/etc/raddb/certs/server.key && rm -f /usr/local/etc/raddb/certs/client.key"); - exec("rm -f /usr/local/etc/raddb/certs/ca.p12 && rm -f /usr/local/etc/raddb/certs/server.p12 && rm -f /usr/local/etc/raddb/certs/client.p12"); - exec("rm -f /usr/local/etc/raddb/certs/serial*"); - exec("rm -f /usr/local/etc/raddb/certs/index*"); - exec("rm -f /usr/local/etc/raddb/certs/dh"); - exec("rm -f /usr/local/etc/raddb/certs/random"); - exec("rm -f /usr/local/etc/raddb/certs/client.tar"); + log_error("freeRADIUS: deleting all CA, Server and Client certs, DH, random and database files in " . FREERADIUS_BASE . "/etc/raddb/certs"); + exec("rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/ca.pem && rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/server.pem && rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/client.pem"); + exec("rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/ca.der && rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/server.der && rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/client.der"); + exec("rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/ca.csr && rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/server.csr && rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/client.csr"); + exec("rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/ca.crt && rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/server.crt && rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/client.crt"); + exec("rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/ca.key && rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/server.key && rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/client.key"); + exec("rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/ca.p12 && rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/server.p12 && rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/client.p12"); + exec("rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/serial*"); + exec("rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/index*"); + exec("rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/dh"); + exec("rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/random"); + exec("rm -f " . FREERADIUS_BASE . "/etc/raddb/certs/client.tar"); // run fuctions to create new .cnf files based on user input from freeradiuscert.xml @@ -2433,28 +2418,28 @@ if ($eapconf['vareapconfchoosecertmanager'] == '') { freeradius_clientcertcnf_resync(); // this command deletes the pfsense_cert_mgr checkfile so when we change back to pfsense cert manager a new DH + random file will be created - if (file_exists("/usr/local/etc/raddb/certs/pfsense_cert_mgr")) { - unlink("/usr/local/etc/raddb/certs/pfsense_cert_mgr"); + if (file_exists(FREERADIUS_BASE . "/etc/raddb/certs/pfsense_cert_mgr")) { + unlink(FREERADIUS_BASE . "/etc/raddb/certs/pfsense_cert_mgr"); } // generate new DH and RANDOM file - log_error("freeRADIUS: Creating new DH and random file in /usr/local/etc/raddb/certs"); - exec("cd /usr/local/etc/raddb/certs && openssl dhparam -out dh 1024"); - exec("cd /usr/local/etc/raddb/certs && dd if=/dev/urandom of=./random count=10"); + log_error("freeRADIUS: Creating new DH and random file in " . FREERADIUS_BASE . "/etc/raddb/certs"); + exec("cd " . FREERADIUS_BASE . "/etc/raddb/certs && openssl dhparam -out dh 1024"); + exec("cd " . FREERADIUS_BASE . "/etc/raddb/certs && dd if=/dev/urandom of=./random count=10"); - log_error("freeRADIUS: Creating new CA, Server and Client certs in /usr/local/etc/raddb/certs"); + log_error("freeRADIUS: Creating new CA, Server and Client certs in " . FREERADIUS_BASE . "/etc/raddb/certs"); // make bootstrap executable and run to create certs based on .cnf files - exec("chmod 0770 /usr/local/etc/raddb/certs/bootstrap"); - exec("/usr/local/etc/raddb/certs/bootstrap"); + exec("chmod 0770 " . FREERADIUS_BASE . "/etc/raddb/certs/bootstrap"); + exec(FREERADIUS_BASE . "/etc/raddb/certs/bootstrap"); // rename client generated 02.pem to client.pem - if (file_exists("/usr/local/etc/raddb/certs/02.pem")) - rename("/usr/local/etc/raddb/certs/02.pem","/usr/local/etc/raddb/certs/client.pem"); + if (file_exists(FREERADIUS_BASE . "/etc/raddb/certs/02.pem")) + rename(FREERADIUS_BASE . "/etc/raddb/certs/02.pem",FREERADIUS_BASE . "/etc/raddb/certs/client.pem"); // tar client-cert files - exec("cd /usr/local/etc/raddb/certs && tar -cf client.tar client.crt client.csr client.key ca.der client.pem"); - exec("chmod -R 0600 /usr/local/etc/raddb/certs/"); - log_error("freeRADIUS: Added client.csr .crt .key .pem together with ca.der in /usr/local/etc/raddb/certs/client.tar"); + exec("cd " . FREERADIUS_BASE . "/etc/raddb/certs && tar -cf client.tar client.crt client.csr client.key ca.der client.pem"); + exec("chmod -R 0600 " . FREERADIUS_BASE . "/etc/raddb/certs/"); + log_error("freeRADIUS: Added client.csr .crt .key .pem together with ca.der in " . FREERADIUS_BASE . "/etc/raddb/certs/client.tar"); // If there were changes on the certificates we need to restart freeradius restart_service('radiusd'); @@ -2473,24 +2458,36 @@ conf_mount_ro(); /* Uses XMLRPC to synchronize the changes to a remote node */ function freeradius_sync_on_changes() { global $config, $g; - $varsyncenablexmlrpc = $config['installedpackages']['freeradiussync']['config'][0]['varsyncenablexmlrpc']; - + $varsyncenablexmlrpc = $config['installedpackages']['freeradiussync']['config'][0]['varsyncenablexmlrpc']; + $varsynctimeout = $config['installedpackages']['freeradiussync']['config'][0]['varsynctimeout']; + // if checkbox is NOT checked do nothing if(!$varsyncenablexmlrpc) { return; } - - log_error("FreeRADIUS: Starting XMLRPC process (freeradius_do_xmlrpc_sync)."); + + log_error("FreeRADIUS: Starting XMLRPC process (freeradius_do_xmlrpc_sync) with timeout {$varsynctimeout} seconds."); // if checkbox is checked get IP and password of the destination hosts foreach ($config['installedpackages']['freeradiussync']['config'] as $rs ){ foreach($rs['row'] as $sh){ - $varsyncprotocol = $sh['varsyncprotocol']; - $sync_to_ip = $sh['varsyncipaddress']; - $password = $sh['varsyncpassword']; - $varsyncport = $sh['varsyncport']; - if($password && $sync_to_ip && $varsyncport && $varsyncprotocol) - freeradius_do_xmlrpc_sync($sync_to_ip, $password, $varsyncport, $varsyncprotocol); + // if checkbox is NOT checked do nothing + if($sh['varsyncdestinenable']) { + $varsyncprotocol = $sh['varsyncprotocol']; + $sync_to_ip = $sh['varsyncipaddress']; + $password = $sh['varsyncpassword']; + $varsyncport = $sh['varsyncport']; + // check if all credentials are complete for this host + if($password && $sync_to_ip && $varsyncport && $varsyncprotocol) { + freeradius_do_xmlrpc_sync($sync_to_ip, $password, $varsyncport, $varsyncprotocol); + } + else { + log_error("FreeRADIUS: XMLRPC Sync with {$sh['varsyncipaddress']} has incomplete credentials. No XMLRPC Sync done!"); + } + } + else { + log_error("FreeRADIUS: XMLRPC Sync with {$sh['varsyncipaddress']} is disabled"); + } } } log_error("FreeRADIUS: Finished XMLRPC process (freeradius_do_xmlrpc_sync)."); @@ -2500,6 +2497,14 @@ function freeradius_sync_on_changes() { function freeradius_do_xmlrpc_sync($sync_to_ip, $password, $varsyncport, $varsyncprotocol) { global $config, $g; + $varsynctimeout = $config['installedpackages']['freeradiussync']['config'][0]['varsynctimeout']; + + if($varsynctimeout == '' || $varsynctimeout == 0) { + $varsynctimeout = 150; + } + + // log_error("FreeRADIUS: Starting XMLRPC process (freeradius_do_xmlrpc_sync) with timeout {$varsynctimeout} seconds."); + if(!$password) return; @@ -2539,15 +2544,15 @@ function freeradius_do_xmlrpc_sync($sync_to_ip, $password, $varsyncport, $varsyn $cli->setCredentials('admin', $password); if($g['debug']) $cli->setDebug(1); - /* send our XMLRPC message and timeout after 150 seconds */ - $resp = $cli->send($msg, "150"); + /* send our XMLRPC message and timeout after $varsynctimeout seconds */ + $resp = $cli->send($msg, $varsynctimeout); if(!$resp) { $error = "A communications error occurred while FreeRADIUS was attempting XMLRPC sync with {$url}:{$port}."; log_error("FreeRADIUS: $error"); file_notice("sync_settings", $error, "freeradius Settings Sync", ""); } elseif($resp->faultCode()) { $cli->setDebug(1); - $resp = $cli->send($msg, "150"); + $resp = $cli->send($msg, $varsynctimeout); $error = "An error code was received while FreeRADIUS XMLRPC was attempting to sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error("FreeRADIUS: $error"); file_notice("sync_settings", $error, "freeradius Settings Sync", ""); @@ -2571,14 +2576,14 @@ function freeradius_do_xmlrpc_sync($sync_to_ip, $password, $varsyncport, $varsyn $msg = new XML_RPC_Message($method, $params); $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); $cli->setCredentials('admin', $password); - $resp = $cli->send($msg, "150"); + $resp = $cli->send($msg, $varsynctimeout); if(!$resp) { $error = "A communications error occurred while FreeRADIUS was attempting XMLRPC sync with {$url}:{$port} (exec_php)."; log_error($error); file_notice("sync_settings", $error, "freeradius Settings Sync", ""); } elseif($resp->faultCode()) { $cli->setDebug(1); - $resp = $cli->send($msg, "150"); + $resp = $cli->send($msg, $varsynctimeout); $error = "An error code was received while FreeRADIUS XMLRPC was attempting to sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); log_error($error); file_notice("sync_settings", $error, "freeradius Settings Sync", ""); @@ -2600,7 +2605,7 @@ function freeradius_all_after_XMLRPC_resync() { log_error("FreeRADIUS: Finished XMLRPC process. It should be OK. For more information look at the host which started sync."); - exec("/usr/local/etc/rc.d/radiusd onerestart"); + exec(FREERADIUS_BASE . "/etc/rc.d/radiusd onerestart"); } function freeradius_modulescounter_resync() { @@ -2723,7 +2728,7 @@ counter forever { } EOD; - $filename = RADDB . '/modules/counter'; + $filename = FREERADIUS_BASE . '/etc/raddb/modules/counter'; conf_mount_rw(); file_put_contents($filename, $conf); chmod($filename, 0640); @@ -2817,7 +2822,7 @@ nt-response=%{%{mschap:NT-Response}:-00}" } EOD; - $filename = RADDB . '/modules/mschap'; + $filename = FREERADIUS_BASE . '/etc/raddb/modules/mschap'; conf_mount_rw(); file_put_contents($filename, $conf); chmod($filename, 0640); @@ -2862,7 +2867,7 @@ realm ntdomain { } EOD; - $filename = RADDB . '/modules/realm'; + $filename = FREERADIUS_BASE . '/etc/raddb/modules/realm'; conf_mount_rw(); file_put_contents($filename, $conf); chmod($filename, 0640); @@ -2913,37 +2918,37 @@ if($arrmodulesldap['varmodulesldapenabletlssupport'] == 'on') { $ca_cert = lookup_ca($arrmodulesldap["ssl_ca_cert1"]); if ($ca_cert != false) { if(base64_decode($ca_cert['prv'])) { - file_put_contents(RADDB . "/certs/ca_ldap1_key.pem", + file_put_contents(FREERADIUS_BASE . "/etc/raddb/certs/ca_ldap1_key.pem", base64_decode($ca_cert['prv'])); - $conf['ssl_ca_key'] = RADDB . '/certs/ca_ldap1_key.pem'; + $conf['ssl_ca_key'] = FREERADIUS_BASE . '/etc/raddb/certs/ca_ldap1_key.pem'; } if(base64_decode($ca_cert['crt'])) { - file_put_contents(RADDB . "/certs/ca_ldap1_cert.pem", + file_put_contents(FREERADIUS_BASE . "/etc/raddb/certs/ca_ldap1_cert.pem", base64_decode($ca_cert['crt'])); - $conf['ssl_ca_cert1'] = RADDB . "/certs/ca_ldap1_cert.pem"; + $conf['ssl_ca_cert1'] = FREERADIUS_BASE . "/etc/raddb/certs/ca_ldap1_cert.pem"; } $svr_cert = lookup_cert($arrmodulesldap["ssl_server_cert1"]); if ($svr_cert != false) { if(base64_decode($svr_cert['prv'])) { - file_put_contents(RADDB . "/certs/radius_ldap1_cert.key", + file_put_contents(FREERADIUS_BASE . "/etc/raddb/certs/radius_ldap1_cert.key", base64_decode($svr_cert['prv'])); - $conf['ssl_key'] = RADDB . '/certs/radius_ldap1_cert.key'; + $conf['ssl_key'] = FREERADIUS_BASE . '/etc/raddb/certs/radius_ldap1_cert.key'; } } if(base64_decode($svr_cert['crt'])) { - file_put_contents(RADDB . "/certs/radius_ldap1_cert.crt", + file_put_contents(FREERADIUS_BASE . "/etc/raddb/certs/radius_ldap1_cert.crt", base64_decode($svr_cert['crt'])); - $conf['ssl_server_cert1'] = RADDB . "/certs/radius_ldap1_cert.crt"; + $conf['ssl_server_cert1'] = FREERADIUS_BASE . "/etc/raddb/certs/radius_ldap1_cert.crt"; } - $conf['ssl_cert_dir'] = RADDB . '/certs'; + $conf['ssl_cert_dir'] = FREERADIUS_BASE . '/etc/raddb/certs'; } $varmodulesldapstarttls = "yes"; } @@ -2960,37 +2965,37 @@ if($arrmodulesldap['varmodulesldap2enabletlssupport'] == 'on') { $ca_cert = lookup_ca($arrmodulesldap["ssl_ca_cert2"]); if ($ca_cert != false) { if(base64_decode($ca_cert['prv'])) { - file_put_contents(RADDB . "/certs/ca_ldap2_key.pem", + file_put_contents(FREERADIUS_BASE . "/etc/raddb/certs/ca_ldap2_key.pem", base64_decode($ca_cert['prv'])); - $conf['ssl_ca_key'] = RADDB . '/certs/ca_ldap2_key.pem'; + $conf['ssl_ca_key'] = FREERADIUS_BASE . '/etc/raddb/certs/ca_ldap2_key.pem'; } if(base64_decode($ca_cert['crt'])) { - file_put_contents(RADDB . "/certs/ca_ldap2_cert.pem", + file_put_contents(FREERADIUS_BASE . "/etc/raddb/certs/ca_ldap2_cert.pem", base64_decode($ca_cert['crt'])); - $conf['ssl_ca_cert2'] = RADDB . "/certs/ca_ldap2_cert.pem"; + $conf['ssl_ca_cert2'] = FREERADIUS_BASE . "/etc/raddb/certs/ca_ldap2_cert.pem"; } $svr_cert = lookup_cert($arrmodulesldap["ssl_server_cert2"]); if ($svr_cert != false) { if(base64_decode($svr_cert['prv'])) { - file_put_contents(RADDB . "/certs/radius_ldap2_cert.key", + file_put_contents(FREERADIUS_BASE . "/etc/raddb/certs/radius_ldap2_cert.key", base64_decode($svr_cert['prv'])); - $conf['ssl_key'] = RADDB . '/certs/radius_ldap2_cert.key'; + $conf['ssl_key'] = FREERADIUS_BASE . '/etc/raddb/certs/radius_ldap2_cert.key'; } } if(base64_decode($svr_cert['crt'])) { - file_put_contents(RADDB . "/certs/radius_ldap2_cert.crt", + file_put_contents(FREERADIUS_BASE . "/etc/raddb/certs/radius_ldap2_cert.crt", base64_decode($svr_cert['crt'])); - $conf['ssl_server_cert2'] = RADDB . "/certs/radius_ldap2_cert.crt"; + $conf['ssl_server_cert2'] = FREERADIUS_BASE . "/etc/raddb/certs/radius_ldap2_cert.crt"; } - $conf['ssl_cert_dir'] = RADDB . '/certs'; + $conf['ssl_cert_dir'] = FREERADIUS_BASE . '/etc/raddb/certs'; } $varmodulesldap2starttls = "yes"; } @@ -3113,7 +3118,7 @@ else { $varmodulesldap2keepaliveidle = ($arrmodulesldap['varmodulesldap2keepaliveidle']?$arrmodulesldap['varmodulesldap2keepaliveidle']:'60'); $varmodulesldap2keepaliveprobes = ($arrmodulesldap['varmodulesldap2keepaliveprobes']?$arrmodulesldap['varmodulesldap2keepaliveprobes']:'3'); $varmodulesldap2keepaliveinterval = ($arrmodulesldap['varmodulesldap2keepaliveinterval']?$arrmodulesldap['varmodulesldap2keepaliveinterval']:'3'); - +$raddb = FREERADIUS_BASE . '/etc/raddb'; $conf .= <<<EOD # -*- text -*- # @@ -3193,11 +3198,11 @@ ldap { # using ldaps (port 689) connections start_tls = $varmodulesldapstarttls - cacertfile = /usr/local/etc/raddb/certs/ca_ldap1_cert.pem - cacertdir = /usr/local/etc/raddb/certs/ - certfile = /usr/local/etc/raddb/certs/radius_ldap1_cert.crt - keyfile = /usr/local/etc/raddb/certs/radius_ldap1_cert.key - randfile = /usr/local/etc/raddb/certs/random + cacertfile = {$raddb}/certs/ca_ldap1_cert.pem + cacertdir = {$raddb}/certs/ + certfile = {$raddb}/certs/radius_ldap1_cert.crt + keyfile = {$raddb}/certs/radius_ldap1_cert.key + randfile = {$raddb}/certs/random # Certificate Verification requirements. Can be: # "never" (don't even bother trying) @@ -3352,11 +3357,11 @@ ldap ldap2{ # using ldaps (port 689) connections start_tls = $varmodulesldap2starttls - cacertfile = /usr/local/etc/raddb/certs/ca_ldap2_cert.pem - cacertdir = /usr/local/etc/raddb/certs/ - certfile = /usr/local/etc/raddb/certs/radius_ldap2_cert.crt - keyfile = /usr/local/etc/raddb/certs/radius_ldap2_cert.key - randfile = /usr/local/etc/raddb/certs/random + cacertfile = {$raddb}/certs/ca_ldap2_cert.pem + cacertdir = {$raddb}/certs/ + certfile = {$raddb}/certs/radius_ldap2_cert.crt + keyfile = {$raddb}/certs/radius_ldap2_cert.key + randfile = {$raddb}/certs/random # Certificate Verification requirements. Can be: # "never" (don't even bother trying) @@ -3462,7 +3467,7 @@ ldap ldap2{ } EOD; - $filename = RADDB . '/modules/ldap'; + $filename = FREERADIUS_BASE . '/etc/raddb/modules/ldap'; conf_mount_rw(); file_put_contents($filename, $conf); chmod($filename, 0640); @@ -3483,29 +3488,29 @@ function freeradius_plainmacauth_resync() { $varsettings = $config['installedpackages']['freeradiussettings']['config'][0]; // defining variables with filename path - $filepolicyconf = '/usr/local/etc/raddb/policy.conf'; - $filepolicyconfbackup = '/usr/local/etc/raddb/policy.conf.backup'; - $filemodulesfiles = '/usr/local/etc/raddb/modules/files'; - $filemodulesfilesbackup = '/usr/local/etc/raddb/files.backup'; + $filepolicyconf = FREERADIUS_BASE . '/etc/raddb/policy.conf'; + $filepolicyconfbackup = FREERADIUS_BASE . '/etc/raddb/policy.conf.backup'; + $filemodulesfiles = FREERADIUS_BASE . '/etc/raddb/modules/files'; + $filemodulesfilesbackup = FREERADIUS_BASE . '/etc/raddb/files.backup'; // If unchecked then plain mac auth is disabled and backups of the original files will be restored if ($varsettings['varsettingsenablemacauth'] == '') { // This is a check - only restore files if they aren't already - if (file_exists("/usr/local/etc/raddb/plain_macauth_enabled")) { + if (file_exists(FREERADIUS_BASE . "/etc/raddb/plain_macauth_enabled")) { log_error("FreeRADIUS: Plain-MAC-Auth disabled. Restoring the original file from {$filepolicyconfbackup} and {$filemodulesfilesbackup}"); copy($filepolicyconfbackup, $filepolicyconf); copy($filemodulesfilesbackup, $filemodulesfiles); - unlink("/usr/local/etc/raddb/plain_macauth_enabled"); + unlink(FREERADIUS_BASE . "/etc/raddb/plain_macauth_enabled"); freeradius_serverdefault_resync(); } } // If checked then plain mac auth is enabled else { // This is a check - only modify files if they aren't already - if (!file_exists("/usr/local/etc/raddb/plain_macauth_enabled")) { + if (!file_exists(FREERADIUS_BASE . "/etc/raddb/plain_macauth_enabled")) { freeradius_modulesfiles_resync(); freeradius_policyconf_resync(); - exec("cd /usr/local/etc/raddb/ && touch /usr/local/etc/raddb/plain_macauth_enabled"); + exec("cd " . FREERADIUS_BASE . "/etc/raddb && touch " . FREERADIUS_BASE . "/etc/raddb/plain_macauth_enabled"); log_error("FreeRADIUS: Plain-MAC-Auth enabled. Modified {$filepolicyconf} and {$filemodulesfiles}"); freeradius_serverdefault_resync(); } @@ -3567,7 +3572,7 @@ files authorized_macs { } EOD; - $filename = RADDB . '/modules/files'; + $filename = FREERADIUS_BASE . '/etc/raddb/modules/files'; conf_mount_rw(); file_put_contents($filename, $conf); chmod($filename, 0640); @@ -3793,7 +3798,7 @@ policy { } EOD; - $filename = RADDB . '/policy.conf'; + $filename = FREERADIUS_BASE . '/etc/raddb/policy.conf'; conf_mount_rw(); file_put_contents($filename, $conf); chmod($filename, 0640); @@ -3816,21 +3821,33 @@ function freeradius_motp_resync() { // check if disabled then we delete bash und otpverify.sh script if ($varsettings['varsettingsmotpenable'] == '') { - if (file_exists("/usr/local/etc/raddb/scripts/otpverify.sh")) { - unlink("/usr/local/etc/raddb/scripts/otpverify.sh"); + if (file_exists(FREERADIUS_BASE . "/etc/raddb/scripts/otpverify.sh")) { + unlink(FREERADIUS_BASE . "/etc/raddb/scripts/otpverify.sh"); } if (exec("cd /var/db/pkg && ls | grep bash") == "bash-4.1.7") { exec("cd /var/db/pkg && pkg_delete `ls | grep bash`"); log_error('FreeRADIUS: Uninstalling package "bash-4.1.7" which comes with Mobile-One-Time-Password (motp).'); } + if (exec("cd /var/db/pkg && ls | grep bash") == "bash-4.2.20") { + exec("cd /var/db/pkg && pkg_delete `ls | grep bash`"); + log_error('FreeRADIUS: Uninstalling package "bash-4.2.20" which comes with Mobile-One-Time-Password (motp).'); + } } // check if enabled then we need to download "bash" else { - if (exec("cd /var/db/pkg && ls | grep bash") != "bash-4.1.7") { - log_error('FreeRADIUS: Downloading and installing package "bash-4.1.7" to use Mobile-One-Time-Password (motp).'); - exec("pkg_add -r http://ftp-archive.freebsd.org/pub/FreeBSD-Archive/ports/`uname -m`/packages-8.1-release/All/bash-4.1.7.tbz"); + if (substr(trim(file_get_contents("/etc/version")),0,3) == "2.0") { + if (exec("cd /var/db/pkg && ls | grep bash") != "bash-4.1.7") { + log_error('FreeRADIUS: Downloading and installing package "bash-4.1.7" to use Mobile-One-Time-Password (motp).'); + exec("pkg_add -r http://ftp-archive.freebsd.org/pub/FreeBSD-Archive/ports/`uname -m`/packages-8.1-release/All/bash-4.1.7.tbz"); + } + } else { + if (exec("cd /var/db/pkg && ls | grep bash") != "bash-4.2.20") { + log_error('FreeRADIUS: Downloading and installing package "bash-4.2.20" to use Mobile-One-Time-Password (motp).'); + exec("pkg_add -r http://ftp-archive.freebsd.org/pub/FreeBSD/ports/`uname -m`/packages-8.3-release/All/bash-4.2.20.tbz"); + } } + $conf .= <<<EOD #!/bin/bash @@ -3950,7 +3967,7 @@ exit 11 EOD; - $filename = RADDB . '/scripts/otpverify.sh'; + $filename = FREERADIUS_BASE . '/etc/raddb/scripts/otpverify.sh'; conf_mount_rw(); file_put_contents($filename, $conf); chmod($filename, 0750); @@ -3965,14 +3982,17 @@ function freeradius_modulesmotp_resync() { global $config; $conf = ''; + // put the constant to a variable + $varFREERADIUS_BASE = FREERADIUS_BASE; + $conf .= <<<EOD exec motp { wait = yes - program = "/usr/local/bin/bash /usr/local/etc/raddb/scripts/otpverify.sh %{request:User-Name} %{request:User-Password} %{reply:MOTP-Init-Secret} %{reply:MOTP-PIN} %{reply:MOTP-Offset}" + program = "/usr/local/bin/bash $varFREERADIUS_BASE/etc/raddb/scripts/otpverify.sh %{request:User-Name} %{request:User-Password} %{reply:MOTP-Init-Secret} %{reply:MOTP-PIN} %{reply:MOTP-Offset}" } EOD; - $filename = RADDB . '/modules/motp'; + $filename = FREERADIUS_BASE . '/etc/raddb/modules/motp'; conf_mount_rw(); file_put_contents($filename, $conf); chmod($filename, 0640); @@ -3984,26 +4004,29 @@ function freeradius_modulesdatacounter_resync() { global $config; $conf = ''; + // put the constant to a variable + $varFREERADIUS_BASE = FREERADIUS_BASE; + $conf .= <<<EOD exec datacounterdaily { wait = yes - program = "/bin/sh /usr/local/etc/raddb/scripts/datacounter_acct.sh %{request:User-Name} daily %{request:Acct-Input-Octets} %{request:Acct-Output-Octets}" + program = "/bin/sh $varFREERADIUS_BASE/etc/raddb/scripts/datacounter_acct.sh %{request:User-Name} daily %{request:Acct-Input-Octets} %{request:Acct-Output-Octets}" } exec datacounterweekly { wait = yes - program = "/bin/sh /usr/local/etc/raddb/scripts/datacounter_acct.sh %{request:User-Name} weekly %{request:Acct-Input-Octets} %{request:Acct-Output-Octets}" + program = "/bin/sh $varFREERADIUS_BASE/etc/raddb/scripts/datacounter_acct.sh %{request:User-Name} weekly %{request:Acct-Input-Octets} %{request:Acct-Output-Octets}" } exec datacountermonthly { wait = yes - program = "/bin/sh /usr/local/etc/raddb/scripts/datacounter_acct.sh %{request:User-Name} monthly %{request:Acct-Input-Octets} %{request:Acct-Output-Octets}" + program = "/bin/sh $varFREERADIUS_BASE/etc/raddb/scripts/datacounter_acct.sh %{request:User-Name} monthly %{request:Acct-Input-Octets} %{request:Acct-Output-Octets}" } exec datacounterforever { wait = yes - program = "/bin/sh /usr/local/etc/raddb/scripts/datacounter_acct.sh %{request:User-Name} forever %{request:Acct-Input-Octets} %{request:Acct-Output-Octets}" + program = "/bin/sh $varFREERADIUS_BASE/etc/raddb/scripts/datacounter_acct.sh %{request:User-Name} forever %{request:Acct-Input-Octets} %{request:Acct-Output-Octets}" } EOD; - $filename = RADDB . '/modules/datacounter_acct'; + $filename = FREERADIUS_BASE . '/etc/raddb/modules/datacounter_acct'; conf_mount_rw(); file_put_contents($filename, $conf); chmod($filename, 0640); @@ -4034,15 +4057,15 @@ USEDOCTETSUSERNAMEMB=$((`cat "/var/log/radacct/datacounter/\$TIMERANGE/used-octe ### We check if MAX-OCTETS-USERNAME is greater than USED-OCTETS-USERNAME and accept or reject the user if [ `cat "/var/log/radacct/datacounter/\$TIMERANGE/max-octets-\$USERNAME"` -gt `cat "/var/log/radacct/datacounter/\$TIMERANGE/used-octets-\$USERNAME"` ]; then - logger -f /var/log/system.log "FreeRADIUS: Used amount of \$TIMERANGE traffic by \$USERNAME is \$USEDOCTETSUSERNAMEMB of \$MAXOCTETSUSERNAMEMB MB! The user was accepted!!!" + logger -f /var/log/system.log "FreeRADIUS: Used amount of \$TIMERANGE traffic by \$USERNAME is \$USEDOCTETSUSERNAMEMB MB of \$MAXOCTETSUSERNAMEMB MB! The user was accepted!!!" exit 0 else - logger -f /var/log/system.log "FreeRADIUS: Credentials are probably correct but the user \$USERNAME has reached the \$TIMERANGE Amount of Upload and Download Traffic which is \$USEDOCTETSUSERNAMEMB of \$MAXOCTETSUSERNAMEMB MB! The user was rejected!!!" + logger -f /var/log/system.log "FreeRADIUS: Credentials are probably correct but the user \$USERNAME has reached the \$TIMERANGE Amount of Upload and Download Traffic which is \$USEDOCTETSUSERNAMEMB MB of \$MAXOCTETSUSERNAMEMB MB! The user was rejected!!!" exit 99 fi EOD; - $filename = RADDB . '/scripts/datacounter_auth.sh'; + $filename = FREERADIUS_BASE . '/etc/raddb/scripts/datacounter_auth.sh'; conf_mount_rw(); file_put_contents($filename, $conf); chmod($filename, 0750); @@ -4090,7 +4113,7 @@ fi EOD; - $filename = RADDB . '/scripts/datacounter_acct.sh'; + $filename = FREERADIUS_BASE . '/etc/raddb/scripts/datacounter_acct.sh'; conf_mount_rw(); file_put_contents($filename, $conf); chmod($filename, 0750); @@ -4158,7 +4181,7 @@ ATTRIBUTE MOTP-Offset 902 string EOD; - $filename = RADDB . '/dictionary'; + $filename = FREERADIUS_BASE . '/etc/raddb/dictionary'; conf_mount_rw(); file_put_contents($filename, $conf); chmod($filename, 0640); diff --git a/config/freeradius2/freeradius.xml b/config/freeradius2/freeradius.xml index 4cdea6c3..39aaf84d 100644 --- a/config/freeradius2/freeradius.xml +++ b/config/freeradius2/freeradius.xml @@ -200,6 +200,7 @@ <fielddescr>Description</fielddescr> <fieldname>description</fieldname> </columnitem> + <movable>on</movable> </adddeleteeditpagefields> <fields> <field> @@ -207,6 +208,24 @@ <type>listtopic</type> </field> <field> + <fielddescr>sortable</fielddescr> + <fieldname>sortable</fieldname> + <display_maximum_rows>0</display_maximum_rows> + <type>sorting</type> + <include_filtering_inputbox/> + <sortablefields> + <item><name>Username</name><fieldname>varusersusername</fieldname><regex>/%FILTERTEXT%/i</regex></item> + <item><name>One-Time-Password</name><fieldname>varusersmotpenable</fieldname><regex>/%FILTERTEXT%/i</regex></item> + <item><name>Simultaneous Connections</name><fieldname>varuserssimultaneousconnect</fieldname><regex>/%FILTERTEXT%/i</regex></item> + <item><name>IP Address</name><fieldname>varusersframedipaddress</fieldname><regex>/%FILTERTEXT%/i</regex></item> + <item><name>Expiration Date</name><fieldname>varusersexpiration</fieldname><regex>/%FILTERTEXT%/i</regex></item> + <item><name>Session Timeout</name><fieldname>varuserssessiontimeout</fieldname><regex>/%FILTERTEXT%/i</regex></item> + <item><name>Possible Login Times</name><fieldname>varuserslogintime</fieldname><regex>/%FILTERTEXT%/i</regex></item> + <item><name>VLAN ID</name><fieldname>varusersvlanid</fieldname><regex>/%FILTERTEXT%/i</regex></item> + <item><name>Description</name><fieldname>description</fieldname><regex>/%FILTERTEXT%/i</regex></item> + </sortablefields> + </field> + <field> <fielddescr>Username</fielddescr> <fieldname>varusersusername</fieldname> <description><![CDATA[Enter the username. Whitespace is possible. If you do not want to use username/password but custom options then leave this field empty.]]></description> @@ -360,7 +379,7 @@ <field> <fielddescr>Amount of Download and Upload Traffic</fielddescr> <fieldname>varusersmaxtotaloctets</fieldname> - <description><![CDATA[Enter the amount of download and upload traffic (summarized) for this user in <b>MegaByte (MB)</b>. There is a bug in CP which counts the real traffic six times faster. To set a real limit of 100MB you have to enter 600MB here.]]></description> + <description><![CDATA[Enter the amount of download and upload traffic (summarized) for this user in <b>MegaByte (MB)</b>. There is a bug in CP (pfSense v2.0.x) which counts the real traffic many times faster and incorrect.]]></description> <type>input</type> </field> <field> diff --git a/config/freeradius2/freeradius_view_config.php b/config/freeradius2/freeradius_view_config.php index 6bda5f3e..a29e1a55 100644 --- a/config/freeradius2/freeradius_view_config.php +++ b/config/freeradius2/freeradius_view_config.php @@ -31,19 +31,29 @@ */ require("guiconfig.inc"); + +// Check to find out on which system the package is running +if (substr(trim(file_get_contents("/etc/version")),0,3) == "2.0") { + define('RADDB', '/usr/local/etc/raddb'); +} else { + define('RADDB', '/usr/pbi/freeradius-' . php_uname("m") . '/etc/raddb'); +} +// End of system check + + function get_file($file){ - $files['radiusd']="/usr/local/etc/raddb/radiusd.conf"; - $files['eap']="/usr/local/etc/raddb/eap.conf"; - $files['sql']="/usr/local/etc/raddb/sql.conf"; - $files['clients']="/usr/local/etc/raddb/clients.conf"; - $files['users']="/usr/local/etc/raddb/users"; - $files['macs']="/usr/local/etc/raddb/authorized_macs"; - $files['virtual-server-default']="/usr/local/etc/raddb/sites-enabled/default"; - $files['ca']="/usr/local/etc/raddb/certs/ca.cnf"; - $files['server']="/usr/local/etc/raddb/certs/server.cnf"; - $files['client']="/usr/local/etc/raddb/certs/client.cnf"; - $files['index']="/usr/local/etc/raddb/certs/index.txt"; - $files['ldap']="/usr/local/etc/raddb/modules/ldap"; + $files['radiusd']=RADDB . "/radiusd.conf"; + $files['eap']=RADDB . "/eap.conf"; + $files['sql']=RADDB . "/sql.conf"; + $files['clients']=RADDB . "/clients.conf"; + $files['users']=RADDB . "/users"; + $files['macs']=RADDB . "/authorized_macs"; + $files['virtual-server-default']=RADDB . "/sites-enabled/default"; + $files['ca']=RADDB . "/certs/ca.cnf"; + $files['server']=RADDB . "/certs/server.cnf"; + $files['client']=RADDB . "/certs/client.cnf"; + $files['index']=RADDB . "/certs/index.txt"; + $files['ldap']=RADDB . "/modules/ldap"; if ($files[$file]!="" && file_exists($files[$file])){ diff --git a/config/freeradius2/freeradiusauthorizedmacs.xml b/config/freeradius2/freeradiusauthorizedmacs.xml index 02bf2d2b..1903c375 100644 --- a/config/freeradius2/freeradiusauthorizedmacs.xml +++ b/config/freeradius2/freeradiusauthorizedmacs.xml @@ -196,12 +196,30 @@ <fielddescr>Description</fielddescr> <fieldname>description</fieldname> </columnitem> + <movable>on</movable> </adddeleteeditpagefields> <fields> <field> <name>GENERAL CONFIGURATION</name> <type>listtopic</type> - </field> + </field> + <field> + <fielddescr>sortable</fielddescr> + <fieldname>sortable</fieldname> + <display_maximum_rows>0</display_maximum_rows> + <type>sorting</type> + <include_filtering_inputbox/> + <sortablefields> + <item><name>MAC Address</name><fieldname>varmacsaddress</fieldname><regex>/%FILTERTEXT%/i</regex></item> + <item><name>Simultaneous Connections</name><fieldname>varmacssimultaneousconnect</fieldname><regex>/%FILTERTEXT%/i</regex></item> + <item><name>IP Address</name><fieldname>varmacsframedipaddress</fieldname><regex>/%FILTERTEXT%/i</regex></item> + <item><name>Expiration Date</name><fieldname>varmacsexpiration</fieldname><regex>/%FILTERTEXT%/i</regex></item> + <item><name>Session Timeout</name><fieldname>varmacssessiontimeout</fieldname><regex>/%FILTERTEXT%/i</regex></item> + <item><name>Possible Login Times</name><fieldname>varmacslogintime</fieldname><regex>/%FILTERTEXT%/i</regex></item> + <item><name>VLAN ID</name><fieldname>varmacsvlanid</fieldname><regex>/%FILTERTEXT%/i</regex></item> + <item><name>Description</name><fieldname>description</fieldname><regex>/%FILTERTEXT%/i</regex></item> + </sortablefields> + </field> <field> <fielddescr>MAC Address</fielddescr> <fieldname>varmacsaddress</fieldname> @@ -319,7 +337,7 @@ <field> <fielddescr>Amount of Download and Upload Traffic</fielddescr> <fieldname>varmacsmaxtotaloctets</fieldname> - <description><![CDATA[Enter the amount of download and upload traffic (summarized) for this MAC in <b>MegaByte (MB)</b>. There is a bug in CP which counts the real traffic six times faster. To set a real limit of 100MB you have to enter 600MB here.]]></description> + <description><![CDATA[Enter the amount of download and upload traffic (summarized) for this MAC in <b>MegaByte (MB)</b>. There is a bug in CP (pfSense v2.0.x) which counts the real traffic many times faster and incorrect.]]></description> <type>input</type> </field> <field> diff --git a/config/freeradius2/freeradiusclients.xml b/config/freeradius2/freeradiusclients.xml index 2bf24ecc..87d8a11f 100644 --- a/config/freeradius2/freeradiusclients.xml +++ b/config/freeradius2/freeradiusclients.xml @@ -128,6 +128,7 @@ <fielddescr>Description</fielddescr> <fieldname>description</fieldname> </columnitem> + <movable>text</movable> </adddeleteeditpagefields> <fields> <field> diff --git a/config/freeradius2/freeradiusinterfaces.xml b/config/freeradius2/freeradiusinterfaces.xml index 5ec634f1..c944ac17 100644 --- a/config/freeradius2/freeradiusinterfaces.xml +++ b/config/freeradius2/freeradiusinterfaces.xml @@ -116,6 +116,7 @@ <fielddescr>Description</fielddescr> <fieldname>description</fieldname> </columnitem> + <movable>text</movable> </adddeleteeditpagefields> <fields> <field> diff --git a/config/freeradius2/freeradiussync.xml b/config/freeradius2/freeradiussync.xml index 334a98f3..5f1acc74 100644 --- a/config/freeradius2/freeradiussync.xml +++ b/config/freeradius2/freeradiussync.xml @@ -123,11 +123,25 @@ POSSIBILITY OF SUCH DAMAGE. <type>checkbox</type> </field> <field> + <fielddescr>XMLRPC timeout</fielddescr> + <fieldname>varsynctimeout</fieldname> + <description><![CDATA[Timeout in seconds for the XMLRPC timeout. Default: 150]]></description> + <type>input</type> + <default_value>150</default_value> + <size>5</size> + </field> + + <field> <fielddescr>Destination Server</fielddescr> <fieldname>none</fieldname> <type>rowhelper</type> <rowhelper> <rowhelperfield> + <fielddescr>Enable</fielddescr> + <fieldname>varsyncdestinenable</fieldname> + <type>checkbox</type> + </rowhelperfield> + <rowhelperfield> <fielddescr>GUI Protocol</fielddescr> <fieldname>varsyncprotocol</fieldname> <description><![CDATA[Choose the protocol of the destination host. Probably <b>http</b> or <b>https</b>]]></description> @@ -152,7 +166,7 @@ POSSIBILITY OF SUCH DAMAGE. <type>input</type> <size>3</size> </rowhelperfield> - <rowhelperfield> + <rowhelperfield> <fielddescr>GUI Admin Password</fielddescr> <fieldname>varsyncpassword</fieldname> <description><![CDATA[Password of the user "admin" on the destination host.]]></description> diff --git a/config/haproxy/haproxy.inc b/config/haproxy/haproxy.inc index 4ed5f393..1e29f358 100644 --- a/config/haproxy/haproxy.inc +++ b/config/haproxy/haproxy.inc @@ -156,17 +156,6 @@ EOD; fclose($fd); exec("/etc/rc.d/devd restart"); - /* Workaround for the old package deleting the binary on unload instead of the package */ - if (!file_exists("/usr/local/sbin/haproxy")) { - if (substr(trim(`uname -r`), 0, 1) == "8") { - exec("cd /var/db/pkg && pkg_delete `ls | grep haproxy`"); - if (trim(`uname -m`) == 'i386') - exec("pkg_add -r http://e-sac.siteseguro.ws/pfsense/8/All/haproxy-1.4.18.tbz"); - else - exec("pkg_add -r http://e-sac.siteseguro.ws/pfsense/8/amd64/All/haproxy-1.4.18.tbz"); - } - } - /* Do XML upgrade from haproxy 0.31 to haproxy-dev */ if (is_array($config['installedpackages']['haproxy']['ha_servers'])) { /* We have an old config */ diff --git a/config/havp/havp.inc b/config/havp/havp.inc index 7b4f08a5..36c053c9 100644 --- a/config/havp/havp.inc +++ b/config/havp/havp.inc @@ -77,7 +77,13 @@ define('HVDEF_MAXSCANSIZE', '5000000'); # [bytes] ! do not enter 0 o define('HVDEF_MAXARCSCANSIZE', '5000000'); # [bytes] ! do not enter 0 or big size ! define('HVDEF_PID_FILE', '/var/run/havp.pid'); define('HVDEF_WORK_DIR', '/usr/local/etc/havp'); -define('HVDEF_LOG_DIR', '/var/log/havp'); + +$pfSversion = str_replace("\s", "", file_get_contents("/etc/version")); +if(preg_match("/^2.0/",$pfSversion)) + define('HVDEF_LOG_DIR', '/var/log/havp'); +else + define('HVDEF_LOG_DIR', '/var/log'); + define('HVDEF_TEMP_DIR', '/var/tmp'); define('HVDEF_HAVPTEMP_DIR', HVDEF_TEMP_DIR.'/havp'); define('HVDEF_RAMTEMP_DIR', HVDEF_TEMP_DIR.'/havpRAM'); @@ -97,7 +103,12 @@ define('HVDEF_HAVP_MAXSRV', '100'); # Clam #define('HVDEF_CLAM_RUNDIR', '/var/run/clamav'); define('HVDEF_CLAM_RUNDIR', '/var/run'); -define('HVDEF_AVLOG_DIR', '/var/log/clamav'); +define('HVDEF_CLAM_DBDIR', '/var/db/clamav'); +if(preg_match("/^2./",$pfSversion)) + define('HVDEF_AVLOG_DIR', '/var/log/clamav'); +else + define('HVDEF_AVLOG_DIR', '/var/log'); + define('HVDEF_CLAM_SOCKET', HVDEF_CLAM_RUNDIR.'/clamd.sock'); define('HVDEF_CLAM_PID', HVDEF_CLAM_RUNDIR.'/clamd.pid'); define('HVDEF_CLAM_LOG', HVDEF_AVLOG_DIR . '/clamd.log'); @@ -370,7 +381,12 @@ function havp_check_system() $grp = exec('pw group show ' . HVDEF_GROUP); if (strpos($grp, HVDEF_GROUP) !== 0) { exec('pw group add ' . HVDEF_GROUP); - log_error("Antivirus: Username '" . HVDEF_GROUP . "' was added."); + log_error("Antivirus: Group '" . HVDEF_GROUP . "' was added."); + } + $usr = exec('pw usershow -n ' . HVDEF_USER); + if (strpos($usr, HVDEF_USER) !== 0) { + exec('pw useradd ' . HVDEF_USER . ' -g ' . HVDEF_GROUP . ' -h - -s "/sbin/nologin" -d "/nonexistent" -c "havp daemon"'); + log_error("Antivirus: User '" . HVDEF_USER . "' was added."); } # workdir permissions @@ -381,6 +397,11 @@ function havp_check_system() mwexec("mkdir -p " . HVDEF_HAVPTEMP_DIR); havp_set_file_access(HVDEF_HAVPTEMP_DIR, HVDEF_USER, ''); + # clamav dbdir + if (!file_exists(HVDEF_CLAM_DBDIR)) + mwexec("mkdir -p " . HVDEF_CLAM_DBDIR); + havp_set_file_access(HVDEF_CLAM_DBDIR, HVDEF_AVUSER, ''); + # RAM tempdir if (!file_exists(HVDEF_RAMTEMP_DIR)) mwexec("mkdir -p " . HVDEF_RAMTEMP_DIR); @@ -410,6 +431,8 @@ function havp_check_system() if (!file_exists(HVDEF_CLAM_LOG)) file_put_contents(HVDEF_CLAM_LOG, ''); if (!file_exists(HVDEF_FRESHCLAM_LOG)) file_put_contents(HVDEF_FRESHCLAM_LOG, ''); # log dir permissions + if (!file_exists(HVDEF_AVLOG_DIR)) + mwexec("mkdir -p " . HVDEF_AVLOG_DIR); havp_set_file_access(HVDEF_AVLOG_DIR, HVDEF_USER, '0777'); # =-= ClamAV =-= @@ -836,7 +859,7 @@ function havp_config_freshclam() $conf[] = "PidFile /var/run/clamav/freshclam.pid"; $conf[] = "\n# db"; - $conf[] = "DatabaseOwner clamav"; + $conf[] = "DatabaseOwner havp"; $conf[] = "AllowSupplementaryGroups yes"; $conf[] = "DNSDatabaseInfo current.cvd.clamav.net"; @@ -863,7 +886,7 @@ function havp_config_freshclam() case 'sa': $conf[] = "DatabaseMirror clamav.dial-up.net"; break; # south africa case 'tw': $conf[] = "DatabaseMirror clamav.cs.pu.edu.tw"; break; # taiwan case 'uk': $conf[] = "DatabaseMirror clamav.oucs.ox.ac.uk"; break; # united kingdom - case 'us': $conf[] = "DatabaseMirror clamav.catt.com "; break; # united states + case 'us': $conf[] = "DatabaseMirror db.us.clamav.net "; break; # united states default: break; } } @@ -1564,7 +1587,7 @@ function havp_fscan_html() <hr> <span onClick="document.getElementById('scanfilepath').value = '/var/squid';" style="cursor: pointer;"> <img src='./themes/{$g['theme']}/images/icons/icon_pass.gif' title='Click here'> - <font size='-1'><u> Squid cache path (scan you squid cache now).</u></font> + <font size='-1'><u> Squid cache path (scan your squid cache now).</u></font> </img> </span> <br> diff --git a/config/havp/havp.xml b/config/havp/havp.xml index df03fca9..6d991a81 100644 --- a/config/havp/havp.xml +++ b/config/havp/havp.xml @@ -70,8 +70,8 @@ Select interface mode: <br> <b> standard </b> - client(s) bind to the 'proxy port' on selected interface(s); <br> <b> parent for squid </b> - configure HAVP as parent for Squid proxy;<br> - <b> transparent </b> - all 'http' requests on interface(s) will be translated to the HAVP proxy server without any client(s) additional configuration necessary (worked as 'parent for squid' with 'transparent' Squid proxy); <br> - <b> internal </b> - HAVP listen internal interface (127.0.0.1) on 'proxy port', use you own traffic forwarding rules.<br> + <b> transparent </b> - all HTTP requests on interface(s) will be directed to the HAVP proxy server without any client configuration necessary (works as parent for squid with transparent Squid proxy); <br> + <b> internal </b> - HAVP will listen on the loopback (127.0.0.1) on configured 'proxy port.' Use you own traffic forwarding rules.<br> </description> <type>select</type> <default_value>standard</default_value> @@ -85,7 +85,7 @@ <field> <fielddescr>Proxy interface(s)</fielddescr> <fieldname>proxyinterface</fieldname> - <description>The interface(s) for client connections to the proxy. Use 'Ctrl' + L.Click for multiple selection.</description> + <description>The interface(s) for client connections to the proxy. Use 'Ctrl' + L. Click for multiple selection.</description> <type>interfaces_selection</type> <required/> <multiple/> @@ -125,7 +125,7 @@ <fielddescr>Enable Forwarded IP</fielddescr> <fieldname>enableforwardedip</fieldname> <description> - If HAVP is used as parent proxy by some other proxy, this allows to write the real users IP to log, instead of proxy IP. + If HAVP is used as a parent proxy for some other proxy, this allows writing the real user's IP to log, instead of the proxy IP. </description> <type>checkbox</type> </field> @@ -150,7 +150,7 @@ <field> <fielddescr>Max download size, Bytes</fielddescr> <fieldname>maxdownloadsize</fieldname> - <description>Enter value (in Bytes) or leave empty. Downloads larger, than 'Max download size' will be blocked. Only if not Whitelisted!</description> + <description>Enter value (in Bytes) or leave empty. Downloads larger than 'Max download size' will be blocked if not whitelisted.</description> <type>input</type> <size>10</size> <default_value></default_value> @@ -169,7 +169,7 @@ <fielddescr>Whitelist</fielddescr> <fieldname>whitelist</fieldname> <description> - Enter each destination url on a new line that will be accessable to the users without scanning. + Enter each destination URL on a new line that will be accessable to the users without scanning. Use '*' symbol for mask. Example: *.github.com/*, *sourceforge.net/*clamav-*, */*.xml, */*.inc </description> <type>textarea</type> @@ -196,10 +196,10 @@ <fielddescr>Enable RAM Disk</fielddescr> <fieldname>enableramdisk</fieldname> <description> - This option allow use RAM Disk for HAVP temp files for more quick traffic scan. - Ram Disc size depend from 'ScanMax file size and avialable memory. - This option can be ignored in VMVare or on 'low system memory'. - ( RAM Disk size calculated as [1/4 avialable system memory] > [Scan max file size] * 100 ) + This option allow use RAM disk for HAVP temp files for more quick traffic scan. + RAM disk size depends on 'ScanMax' file size and available memory. + This option can be ignored on systems with low memory. + ( RAM disk size calculated as [1/4 available system memory] > [Scan max file size] * 100 ) </description> <type>checkbox</type> </field> @@ -209,7 +209,7 @@ <description> Select this value for limit maximum file size or leave '---(5M)'. Files larger than this limit won't be scanned. - Small values increace scan speed and maximum new connections per second and allow RAM Disk use. + Small values increace scan speed and maximum new connections per second and allow RAM disk use. <br> NOTE: Setting limit is a security risk, because some archives like ZIP need all the data to be scanned properly! Use this only if you diff --git a/config/imspector-dev/imspector.inc b/config/imspector-dev/imspector.inc new file mode 100644 index 00000000..52c7ae1b --- /dev/null +++ b/config/imspector-dev/imspector.inc @@ -0,0 +1,546 @@ +<?php +/* + imspector.inc + part of pfSense (http://www.pfsense.com/) + Copyright (C) 2012 Marcello Coutinho. + Copyright (C) 2011 Scott Ullrich <sullrich@gmail.com>. + Copyright (C) 2011 Bill Marquette <billm@gmail.com>. + Copyright (C) 2007 Ryan Wagoner <rswagoner@gmail.com>. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ + + require_once("config.inc"); + require_once("functions.inc"); + require_once("service-utils.inc"); + + /* IMSpector */ + + define('IMSPECTOR_RCFILE', '/usr/local/etc/rc.d/imspector.sh'); + define('IMSPECTOR_ETC', '/usr/local/etc/imspector'); + define('IMSPECTOR_CONFIG', IMSPECTOR_ETC . '/imspector.conf'); + + function imspector_warn ($msg) { syslog(LOG_WARNING, "imspector: {$msg}"); } + + function ims_text_area_decode($text){ + return preg_replace('/\r\n/', "\n",base64_decode($text)); + } + + function imspector_action ($action) { + if (file_exists(IMSPECTOR_RCFILE)) + mwexec(IMSPECTOR_RCFILE.' '.$action); + } + + function write_imspector_config($file, $text) { + $conf = fopen($file, 'w'); + if(!$conf) { + imspector_warn("Could not open {$file} for writing."); + exit; + } + fwrite($conf, $text); + fclose($conf); + } + + function imspector_pf_rdr($iface, $port) { + return "rdr pass on {$iface} inet proto tcp from any to any port = {$port} -> 127.0.0.1 port 16667\n"; + } + + function imspector_pf_rule($iface, $port) { + return "pass in quick on {$iface} inet proto tcp from any to any port {$port} keep state\n"; + } + + function imspector_proto_to_port ($proto) + { + switch ($proto) { + case 'gadu-gadu': + return 8074; + case 'jabber': + return 5222; + case 'jabber-ssl': + return 5223; + case 'msn': + return 1863; + case 'icq': + return 5190; + case 'yahoo': + return 5050; + case 'irc': + return 6667; + default: + return null; + } + } + + function validate_form_imspector($post, $input_errors) { + if($post['iface_array']) + foreach($post['iface_array'] as $iface) + if($iface == 'wanx') + $input_errors[] = 'It is a security risk to specify WAN in the \'Interface\' field'; + } + + function deinstall_package_imspector() { + imspector_action('stop'); + + unlink_if_exists(IMSPECTOR_RCFILE); + unlink_if_exists(IMSPECTOR_CONFIG); + unlink_if_exists(IMSPECTOR_ETC . '/badwords_custom.txt'); + unlink_if_exists(IMSPECTOR_ETC . '/acl_blacklist.txt'); + unlink_if_exists(IMSPECTOR_ETC . '/acl_whitelist.txt'); + unlink_if_exists('/usr/local/www/imspector_logs.php'); + + //exec('pkg_delete imspector-0.4'); + } + + function imspector_generate_rules($type) { + + $rules = ""; + switch ($type) { + case 'rdr': + case 'nat': + $rules = "# IMSpector rdr anchor\n"; + $rules .= "rdr-anchor \"imspector\"\n"; + break; + case 'rule': + $rules = "# IMSpector \n"; + $rules .= "anchor \"imspector\"\n"; + break; + } + + return $rules; + } + + function sync_package_imspector() { + global $config; + global $input_errors; + + /*detect boot process*/ + if (is_array($_POST)){ + if (preg_match("/\w+/",$_POST['__csrf_magic'])) + unset($boot_process); + else + $boot_process="on"; + } + + if (is_process_running('imspector') && isset($boot_process)) + return; + + /* check default options and sample files*/ + $load_samples=0; + + #bannedphraselist + if (!is_array($config['installedpackages']['imspectoracls'])){ + $config['installedpackages']['imspectoracls']['config'][]=array('enable'=> 'on', + 'description' => 'allow access to all ids', + 'action' => 'allow', + 'localid' => 'all', + 'remoteid' => base64_encode('all')); + $load_samples++; + } + $ims_acls = $config['installedpackages']['imspectoracls']['config']; + + if (is_array($config['installedpackages']['imspectorreplacements'])){ + if ($config['installedpackages']['imspectorreplacements']['config'][0]['badwords_list'] == "" && file_exists(IMSPECTOR_ETC . '/badwords.txt')){ + $config['installedpackages']['imspectorreplacements']['config'][0]['badwords_list'] = base64_encode(file_get_contents(IMSPECTOR_ETC . '/badwords.txt')); + $load_samples++; + } + $ims_replacements = $config['installedpackages']['imspectorreplacements']['config'][0]; + } + + if (is_array($config['installedpackages']['imspector'])) + $ims_config = $config['installedpackages']['imspector']['config'][0]; + + if($load_samples > 0) + write_config(); + + /*continue sync process*/ + log_error("Imspector: Saving changes."); + config_lock(); + + /* remove existing rules */ + exec('/sbin/pfctl -a imspector -Fr > /dev/null'); + exec('/sbin/pfctl -a imspector -Fn > /dev/null'); + + $ifaces_active = ''; + + if($ims_config['enable'] && $ims_config['proto_array']) + $proto_array = explode(',', $ims_config['proto_array']); + + if($ims_config['enable'] && $ims_config['iface_array']) + $iface_array = explode(',', $ims_config['iface_array']); + + if($iface_array && $proto_array) { + foreach($iface_array as $iface) { + $if = convert_friendly_interface_to_real_interface_name($iface); + /* above function returns iface if fail */ + if($if!=$iface) { + $addr = find_interface_ip($if); + /* non enabled interfaces are displayed in list on imspector settings page */ + /* check that the interface has an ip address before adding parameters */ + if($addr) { + foreach($proto_array as $proto) { + if(imspector_proto_to_port($proto)) { + /* we can use rdr pass to auto create the filter rule */ + $pf_rules .= imspector_pf_rdr($if,imspector_proto_to_port($proto)); + } + } + if(!$ifaces_active) + $ifaces_active = "{$iface}"; + else + $ifaces_active .= ", {$iface}"; + } else { + imspector_warn("Interface {$iface} has no ip address, ignoring"); + } + } else { + imspector_warn("Could not resolve real interface for {$iface}"); + } + } + + + /*reload rules*/ + if($pf_rules) { + log_error("Imspector: Reloading rules."); + exec("echo \"{$pf_rules}\" | /sbin/pfctl -a imspector -f -"); + + conf_mount_rw(); + + /* generate configuration files */ + + $conf['plugin_dir'] = '/usr/local/lib/imspector'; + + foreach($proto_array as $proto) + $conf[$proto . '_protocol'] = 'on'; + + if($ims_config['log_file']) { + @mkdir('/var/imspector'); + $conf['file_logging_dir'] = '/var/imspector'; + } + + if($ims_config['log_mysql']) { + $conf['mysql_server'] = $ims_config['mysql_server']; + $conf['mysql_database'] = $ims_config['mysql_database']; + $conf['mysql_username'] = $ims_config['mysql_username']; + $conf['mysql_password'] = $ims_config['mysql_password']; + } + + if($ims_replacements['filter_badwords']) { + write_imspector_config(IMSPECTOR_ETC . '/badwords_custom.txt', ims_text_area_decode($ims_replacements["badwords_list"])); + $conf['badwords_filename'] = IMSPECTOR_ETC . '/badwords_custom.txt'; + } + + if($ims_replacements['block_files']) + $conf['block_files'] = 'on'; + + if($ims_replacements['block_webcams']) + $conf['block_webcams'] = 'on'; + + $acls=""; + $conf['acl_filename'] = IMSPECTOR_ETC . '/acls.txt'; + foreach ($ims_acls as $rule){ + if ($rule['enable']){ + $acls.= "{$rule['action']} {$rule['localid']} ".preg_replace("/\s+/"," ",base64_decode($rule['remoteid']))."\n"; + } + } + write_imspector_config(IMSPECTOR_ETC . '/acls.txt', $acls); + + // Handle Jabber SSL options + if(isset($ims_config["ssl_ca_cert"]) && $ims_config["ssl_ca_cert"] != "none" && + isset($ims_config["ssl_server_cert"]) && $ims_config["ssl_server_cert"] != "none") { + $conf['ssl'] = "on"; + if(!is_dir(IMSPECTOR_ETC . "/ssl")) + mkdir(IMSPECTOR_ETC . "/ssl"); + + $ca_cert = lookup_ca($ims_config["ssl_ca_cert"]); + if ($ca_cert != false) { + if(base64_decode($ca_cert['prv'])) { + file_put_contents(IMSPECTOR_ETC . "/ssl/ssl_ca_key.pem", base64_decode($ca_cert['prv'])); + $conf['ssl_ca_key'] = IMSPECTOR_ETC . '/ssl/ssl_ca_key.pem'; + } + if(base64_decode($ca_cert['crt'])) { + file_put_contents(IMSPECTOR_ETC . "/ssl/ssl_ca_cert.pem", base64_decode($ca_cert['crt'])); + $conf['ssl_ca_cert'] = IMSPECTOR_ETC . "/ssl/ssl_ca_cert.pem"; + } + $svr_cert = lookup_cert($ims_config["ssl_server_cert"]); + if ($svr_cert != false) { + if(base64_decode($svr_cert['prv'])) { + file_put_contents(IMSPECTOR_ETC . "/ssl/ssl_server_key.pem", base64_decode($svr_cert['prv'])); + $conf['ssl_key'] = IMSPECTOR_ETC . '/ssl/ssl_server_key.pem'; + } + + } + $conf['ssl_cert_dir'] = IMSPECTOR_ETC . '/ssl'; + } + } else { + // SSL Not enabled. Make sure Jabber-SSL is not processed. + unset($conf['jabber-ssl']); + unset($conf['ssl']); + } + + if (isset($ims_replacements['responder']) && $ims_replacements['responder'] == 'on') { + $conf['responder_filename'] = IMSPECTOR_ETC . "/responder.db"; + if (isset($ims_replacements['prefix_message']) && $ims_replacements['prefix_message'] != '' ) { + $conf['response_prefix'] = " .={$ims_replacements['prefix_message']}=."; + } + else{ + $conf['response_prefix'] = " .=Your activities are being logged=."; + } + if (isset($ims_replacements['notice_days']) && is_numeric($ims_replacements['notice_days'])) { + if ($ims_replacements['notice_days'] != 0) { + $conf['notice_days'] = $ims_replacements['notice_days']; + } + } else { + $conf['notice_days'] = 1; + } + + /*Custom recorded message response*/ + if(isset($ims_replacements['recorded_message']) && $ims_replacements['recorded_message'] != '' ){ + $conf['notice_response'] = ims_text_area_decode($ims_replacements['recorded_message']); + } + else{ + $conf['notice_response'] = "Your activities are being logged"; + } + + /*Filtered Frequency*/ + if (isset($ims_replacements['filtered_minutes']) && is_numeric($ims_replacements['filtered_minutes'])) { + if ($ims_replacements['filtered_minutes'] != 0) { + $conf['filtered_mins'] = $ims_replacements['filtered_minutes']; + } + } else { + $conf['filtered_mins'] = 15; + } + + /*Custom filtered message response*/ + if(isset($ims_replacements['filtered_message']) && $ims_replacements['filtered_message'] != '' ){ + $conf['filtered_response'] = ims_text_area_decode($ims_replacements['filtered_message']); + } + else{ + $conf['filtered_response'] = "Your message has been filtered"; + } + } + + $conftext = ''; + foreach($conf as $var => $key) + $conftext .= "{$var}={$key}\n"; + write_imspector_config(IMSPECTOR_CONFIG, $conftext); + + /*Check template settings*/ + if ($ims_config['template'] == "") + $template="services_imspector_logs.php"; + else + $template=$ims_config['template']; + + /*link template file*/ + $link="/usr/local/www/imspector_logs.php"; + unlink_if_exists($link); + symlink("/usr/local/www/{$template}", $link); + + /* generate rc file start and stop */ + $stop = <<<EOD +/bin/pkill -x imspector +/bin/sleep 1 +EOD; + $start = $stop."\n\tldconfig -m /usr/local/lib/mysql\n"; + $start .= "\t/usr/local/sbin/imspector -c \"".IMSPECTOR_CONFIG."\""; + + write_rcfile(array( + 'file' => 'imspector.sh', + 'start' => $start, + 'stop' => $stop + ) + ); + + conf_mount_ro(); + } + } + + if(!$iface_array || !$proto_array || !$pf_rules) { + /* no parameters user does not want imspector running */ + /* lets stop the service and remove the rc file */ + + if(file_exists(IMSPECTOR_RCFILE)) { + if(!$ims_config['enable']) + log_error('Impsector: Stopping service: imspector disabled'); + else + log_error('Impsector: Stopping service: no interfaces and/or protocols selected'); + + imspector_action('stop'); + + conf_mount_rw(); + unlink(IMSPECTOR_RCFILE); + unlink(IMSPECTOR_CONFIG); + @unlink(IMSPECTOR_ETC . '/badwords_custom.txt'); + @unlink(IMSPECTOR_ETC . '/acl_blacklist.txt'); + @unlink(IMSPECTOR_ETC . '/acl_whitelist.txt'); + conf_mount_ro(); + } + } + else{ + /* if imspector not running start it */ + if(!is_process_running('imspector')) { + log_error("Impsector: Starting service on interface: {$ifaces_active}"); + imspector_action('start'); + } + /* or restart imspector if settings were changed */ + else{ + log_error("Impsector: Restarting service on interface: {$ifaces_active}"); + imspector_action('restart'); + } + } + config_unlock(); + + /*check xmlrpc sync*/ + imspector_sync_on_changes(); + } + + function imspector_get_ca_certs() { + global $config; + + $ca_arr = array(); + $ca_arr[] = array('refid' => 'none', 'descr' => 'none'); + foreach ($config['ca'] as $ca) { + $ca_arr[] = array('refid' => $ca['refid'], 'descr' => $ca['descr']); + } + return $ca_arr; + } + + function imspector_get_server_certs() { + global $config; + $cert_arr = array(); + $cert_arr[] = array('refid' => 'none', 'descr' => 'none'); + + foreach ($config['cert'] as $cert) { + $cert_arr[] = array('refid' => $cert['refid'], 'descr' => $cert['descr']); + } + return $cert_arr; + } + +/* Uses XMLRPC to synchronize the changes to a remote node */ +function imspector_sync_on_changes() { + global $config, $g; + + $synconchanges = $config['installedpackages']['imspectorsync']['config'][0]['synconchanges']; + if(!$synconchanges) + return; + log_error("Imspector: xmlrpc sync is starting."); + foreach ($config['installedpackages']['imspectorsync']['config'] as $rs ){ + foreach($rs['row'] as $sh){ + $sync_to_ip = $sh['ipaddress']; + $password = $sh['password']; + if($password && $sync_to_ip) + imspector_do_xmlrpc_sync($sync_to_ip, $password); + } + } + log_error("Imspector: xmlrpc sync is ending."); +} +/* Do the actual XMLRPC sync */ +function imspector_do_xmlrpc_sync($sync_to_ip, $password) { + global $config, $g; + + if(!$password) + return; + + if(!$sync_to_ip) + return; + $username="admin"; + + $xmlrpc_sync_neighbor = $sync_to_ip; + if($config['system']['webgui']['protocol'] != "") { + $synchronizetoip = $config['system']['webgui']['protocol']; + $synchronizetoip .= "://"; + } + $port = $config['system']['webgui']['port']; + /* if port is empty lets rely on the protocol selection */ + if($port == "") { + if($config['system']['webgui']['protocol'] == "http") + $port = "80"; + else + $port = "443"; + } + $synchronizetoip .= $sync_to_ip; + + /* xml will hold the sections to sync */ + $xml = array(); + $xml['imspector'] = $config['installedpackages']['imspector']; + $xml['imspectorreplacements'] = $config['installedpackages']['imspectorreplacements']; + $xml['imspectoracls'] = $config['installedpackages']['imspectoracls']; + /* assemble xmlrpc payload */ + $params = array( + XML_RPC_encode($password), + XML_RPC_encode($xml) + ); + + /* set a few variables needed for sync code borrowed from filter.inc */ + $url = $synchronizetoip; + log_error("Imspector: Beginning XMLRPC sync to {$url}:{$port}."); + $method = 'pfsense.merge_installedpackages_section_xmlrpc'; + $msg = new XML_RPC_Message($method, $params); + $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); + $cli->setCredentials($username, $password); + if($g['debug']) + $cli->setDebug(1); + /* send our XMLRPC message and timeout after 250 seconds */ + $resp = $cli->send($msg, "250"); + if(!$resp) { + $error = "A communications error occurred while attempting imspector XMLRPC sync with {$url}:{$port}."; + log_error($error); + file_notice("sync_settings", $error, "imspector Settings Sync", ""); + } elseif($resp->faultCode()) { + $cli->setDebug(1); + $resp = $cli->send($msg, "250"); + $error = "An error code was received while attempting imspector XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); + log_error($error); + file_notice("sync_settings", $error, "imspector Settings Sync", ""); + } else { + log_error("imspector XMLRPC sync successfully completed with {$url}:{$port}."); + } + + /* tell imspector to reload our settings on the destionation sync host. */ + $method = 'pfsense.exec_php'; + $execcmd = "require_once('/usr/local/pkg/imspector.inc');\n"; + $execcmd .= "sync_package_imspector();"; + /* assemble xmlrpc payload */ + $params = array( + XML_RPC_encode($password), + XML_RPC_encode($execcmd) + ); + + log_error("imspector XMLRPC reload data {$url}:{$port}."); + $msg = new XML_RPC_Message($method, $params); + $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); + $cli->setCredentials($username, $password); + $resp = $cli->send($msg, "250"); + if(!$resp) { + $error = "A communications error occurred while attempting imspector XMLRPC sync with {$url}:{$port} (pfsense.exec_php)."; + log_error($error); + file_notice("sync_settings", $error, "imspector Settings Sync", ""); + } elseif($resp->faultCode()) { + $cli->setDebug(1); + $resp = $cli->send($msg, "250"); + $error = "An error code was received while attempting imspector XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); + log_error($error); + file_notice("sync_settings", $error, "imspector Settings Sync", ""); + } else { + log_error("imspector XMLRPC reload data success with {$url}:{$port} (pfsense.exec_php)."); + } + +} +?> diff --git a/config/imspector-dev/imspector.xml b/config/imspector-dev/imspector.xml new file mode 100644 index 00000000..c68fc70e --- /dev/null +++ b/config/imspector-dev/imspector.xml @@ -0,0 +1,251 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* ========================================================================== */ +/* + imspector.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2011 Scott Ullrich <sullrich@gmail.com> + Copyright (C) 2011 Bill Marquette <billm@gmail.com> + Copyright (C) 2007 Ryan Wagoner <rswagoner@gmail.com> + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>imspector</name> + <version>20111108</version> + <title>Services: IMSpector</title> + <savetext>Save</savetext> + <include_file>/usr/local/pkg/imspector.inc</include_file> + <menu> + <name>IMSpector</name> + <tooltiptext>Set IMSpector settings such as protocols to listen on.</tooltiptext> + <section>Services</section> + <url>/services_imspector_logs.php</url> + </menu> + <service> + <name>imspector</name> + <rcfile>imspector.sh</rcfile> + <executable>imspector</executable> + <description><![CDATA[Instant Messenger transparent proxy]]></description> + </service> + <tabs> + <tab> + <text>Settings</text> + <url>/pkg_edit.php?xml=imspector.xml&id=0</url> + <active/> + </tab> + <tab> + <text>Replacements</text> + <url>/pkg_edit.php?xml=imspector_replacements.xml&id=0</url> + </tab> + <tab> + <text>Access Lists</text> + <url>/pkg.php?xml=imspector_acls.xml</url> + </tab> + <tab> + <text>Log</text> + <url>/imspector_logs.php</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=imspector_sync.xml</url> + </tab> + </tabs> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/imspector-dev/imspector_sync.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/imspector-dev/imspector_replacements.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/imspector-dev/imspector_acls.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/imspector-dev/imspector.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/imspector-dev/imspector_logs.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/imspector-dev/services_imspector_logs.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/imspector-dev/services_imspector_logs2.php</item> + </additional_files_needed> + <fields> + <field> + <name>General Settings</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Enable IMSpector</fielddescr> + <fieldname>enable</fieldname> + <type>checkbox</type> + </field> + <field> + <fielddescr>Interfaces</fielddescr> + <fieldname>iface_array</fieldname> + <description><![CDATA[<strong>Generally select internal interface(s) like LAN</strong><br> + You can use the CTRL or COMMAND key to select multiple interfaces.]]></description> + <type>interfaces_selection</type> + <size>3</size> + <required/> + <value>lan</value> + <multiple>true</multiple> + </field> + <field> + <fielddescr>Listen on protocols</fielddescr> + <fieldname>proto_array</fieldname> + <description><![CDATA[<strong>NOTE: Gtalk/Jabber-SSL requires SSL certificates.</strong><br> + You can use the CTRL or COMMAND key to select multiple protocols.]]></description> + <type>select</type> + <size>7</size> + <required/> + <multiple>true</multiple> + <options> + <option><name>MSN</name><value>msn</value></option> + <option><name>ICQ/AIM</name><value>icq</value></option> + <option><name>Yahoo</name><value>yahoo</value></option> + <option><name>IRC</name><value>irc</value></option> + <option><name>Jabber</name><value>jabber</value></option> + <option><name>Gtalk/Jabber-SSL</name><value>jabber-ssl</value></option> + <option><name>Gadu-Gadu</name><value>gadu-gadu</value></option> + </options> + </field> + <field> + <fielddescr>SSL CA Certificate</fielddescr> + <fieldname>ssl_ca_cert</fieldname> + <description> + Choose the SSL CA Certficate here. + </description> + <type>select_source</type> + <source><![CDATA[imspector_get_ca_certs()]]></source> + <source_name>descr</source_name> + <source_value>refid</source_value> + </field> + <field> + <fielddescr>SSL Certificate</fielddescr> + <fieldname>ssl_server_cert</fieldname> + <description> + Choose the SSL Server Certificate here. + </description> + <type>select_source</type> + <source><![CDATA[imspector_get_server_certs()]]></source> + <source_name>descr</source_name> + <source_value>refid</source_value> + </field> + <field> + <name>Logging</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Enable file logging</fielddescr> + <fieldname>log_file</fieldname> + <description>Log files stored in /var/imspector.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Report limit</fielddescr> + <fieldname>reportlimit</fieldname> + <description>Max entries to fetch from log dir(s). Default is 50</description> + <type>input</type> + <size>10</size> + </field> + <field> + <fielddescr>Report template</fielddescr> + <fieldname>template</fieldname> + <description>Template to use on reports</description> + <type>select</type> + <required/> + <options> + <option><name>Default Template</name><value>services_imspector_logs.php</value></option> + <option><name>0guzcan Template</name><value>services_imspector_logs2.php</value></option> + </options> + </field> + <field> + <fielddescr>Enable mySQL logging</fielddescr> + <fieldname>log_mysql</fieldname> + <description>Make sure to specify your MySQL credentials below.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>mySQL server</fielddescr> + <fieldname>mysql_server</fieldname> + <type>input</type> + <size>35</size> + </field> + <field> + <fielddescr>mySQL database</fielddescr> + <fieldname>mysql_database</fieldname> + <type>input</type> + <size>35</size> + </field> + <field> + <fielddescr>mySQL username</fielddescr> + <fieldname>mysql_username</fieldname> + <type>input</type> + <size>35</size> + </field> + <field> + <fielddescr>mySQL password</fielddescr> + <fieldname>mysql_password</fieldname> + <type>password</type> + <size>35</size> + </field> + </fields> + <custom_php_validation_command> + validate_form_imspector($_POST, &$input_errors); + </custom_php_validation_command> + <custom_php_resync_config_command> + sync_package_imspector(); + </custom_php_resync_config_command> + <custom_php_deinstall_command> + deinstall_package_imspector(); + </custom_php_deinstall_command> + <filter_rules_needed>imspector_generate_rules</filter_rules_needed> +</packagegui>
\ No newline at end of file diff --git a/config/imspector-dev/imspector_acls.xml b/config/imspector-dev/imspector_acls.xml new file mode 100644 index 00000000..3176c75f --- /dev/null +++ b/config/imspector-dev/imspector_acls.xml @@ -0,0 +1,173 @@ +<?xml version="1.0" encoding="utf-8" ?> +<packagegui> +<copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + imspector_acls.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Marcello Coutinho + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + + <name>imspectoracls</name> + <version>20111108</version> + <title>Imspector acls</title> + <description>Imspectors Access Lists</description> + <savetext>Save</savetext> + <include_file>/usr/local/pkg/imspector.inc</include_file> + + <menu> + <name>SSH Conditions</name> + <tooltiptext>Configure SSH conditional exceptions</tooltiptext> + <section>Services</section> + <url>/pkg.php?xml=sshdcond.xml</url> + </menu> + <configpath>installedpackages->package->sshdcond</configpath> + + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>755</chmod> + <item>http://www.pfsense.com/packages/config/sshdcond/sshdcond.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>755</chmod> + <item>http://www.pfsense.com/packages/config/sshdcond/sshdcond_sync.xml</item> + </additional_files_needed> + <tabs> + <tab> + <text>Settings</text> + <url>/pkg_edit.php?xml=imspector.xml&id=0</url> + </tab> + <tab> + <text>Replacements</text> + <url>/pkg_edit.php?xml=imspector_replacements.xml&id=0</url> + </tab> + <tab> + <text>Access Lists</text> + <url>/pkg.php?xml=imspector_acls.xml</url> + <active/> + </tab> + <tab> + <text>Log</text> + <url>/imspector_logs.php</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=imspector_sync.xml&id=0</url> + </tab> + </tabs> + <adddeleteeditpagefields> + <columnitem> + <fielddescr>Status</fielddescr> + <fieldname>enable</fieldname> + </columnitem> + <columnitem> + <fielddescr>action</fielddescr> + <fieldname>action</fieldname> + </columnitem> + <columnitem> + <fielddescr>local ID</fielddescr> + <fieldname>localid</fieldname> + </columnitem> + <columnitem> + <fielddescr>Description</fielddescr> + <fieldname>description</fieldname> + </columnitem> + </adddeleteeditpagefields> + <fields> + <field> + <type>listtopic</type> + <name>Imspector Access Lists</name> + <fieldname>temp</fieldname> + </field> + <field> + <fielddescr>Enable</fielddescr> + <fieldname>enable</fieldname> + <type>checkbox</type> + <description><![CDATA[Enable this access list.<br> + Rules are processed in order, from top to bottom.]]></description> + </field> + <field> + <fielddescr>Action</fielddescr> + <fieldname>action</fieldname> + <description>Select action to take on this rule</description> + <type>select</type> + <options> + <option><name>allow</name><value>allow</value></option> + <option><name>deny</name><value>deny</value></option> + </options> + <required/> + </field> + <field> + <fielddescr>Description</fielddescr> + <fieldname>description</fieldname> + <description><![CDATA[Specify a description for this rule.]]></description> + <type>input</type> + <size>50</size> + <required/> + </field> + <field> + <fielddescr>Local ID</fielddescr> + <fieldname>localid</fieldname> + <description><![CDATA[Specify local id for this rule<br> + Local IDs can either be complete, such as <strong>user@company.com</strong>, partial like <strong>company.com</strong> or <strong>all</strong> to match any id.]]></description> + <type>input</type> + <size>50</size> + <required/> + </field> + <field> + <fielddescr>Remote ID</fielddescr> + <fieldname>remoteid</fieldname> + <description><![CDATA[Specify the list of remote ids(one per line) that localid can chat with.<br> + Remote IDs can be complete ids like <strong>user@company.com</strong>, partial <strong>company.com</strong>, <strong>all</strong> to match any id or <strong>groupchat</strong>.]]></description> + <type>textarea</type> + <rows>10</rows> + <cols>60</cols> + <encoding>base64</encoding> + </field> + </fields> + + <custom_php_validation_command> + validate_form_imspector($_POST, &$input_errors); + </custom_php_validation_command> + <custom_php_resync_config_command> + sync_package_imspector(); + </custom_php_resync_config_command> + <custom_php_deinstall_command> + deinstall_package_imspector(); + </custom_php_deinstall_command> + <filter_rules_needed>imspector_generate_rules</filter_rules_needed> +</packagegui>
\ No newline at end of file diff --git a/config/imspector-dev/imspector_logs.php b/config/imspector-dev/imspector_logs.php new file mode 100644 index 00000000..e44ef35f --- /dev/null +++ b/config/imspector-dev/imspector_logs.php @@ -0,0 +1,311 @@ +<?php +/* + services_imspector_logs.php + part of pfSense (http://www.pfsense.com/) + + JavaScript Code is GPL Licensed from SmoothWall Express. + + Copyright (C) 2007 Ryan Wagoner <rswagoner@gmail.com>. + Copyright (C) 2012 Marcello Coutinho + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. +*/ + +require("guiconfig.inc"); + +/* variables */ +$log_dir = '/var/imspector'; +$imspector_config = $config['installedpackages']['imspector']['config'][0]; + +$border_color = '#c0c0c0'; +$default_bgcolor = '#eeeeee'; + +$list_protocol_color = '#000000'; +$list_local_color = '#000000'; +$list_remote_color = '#000000'; +$list_convo_color = '#000000'; + +$list_protocol_bgcolor = '#cccccc'; +$list_local_bgcolor = '#dddddd'; +$list_remote_bgcolor = '#eeeeee'; +$list_end_bgcolor = '#bbbbbb'; + +$convo_title_color = 'black'; +$convo_local_color = 'blue'; +$convo_remote_color = 'red'; + +$convo_title_bgcolor = '#cccccc'; +$convo_local_bgcolor = '#dddddd'; +$convo_remote_bgcolor = '#eeeeee'; + +/* functions */ + +function convert_dir_list ($topdir) { + global $config; + if (!is_dir($topdir)) + return; + $imspector_config = $config['installedpackages']['imspector']['config'][0]; + $limit=(preg_match("/\d+/",$imspector_config['reportlimit'])?$imspector_config['reportlimit']:"50"); + file_put_contents("/tmp/teste.txt",$limit." teste",LOCK_EX); + $count=0; + if ($dh = opendir($topdir)) { + while (($file = readdir($dh)) !== false) { + if(!preg_match('/^\./', $file) == 0) + continue; + if (is_dir("$topdir/$file")) + $list .= convert_dir_list("$topdir/$file"); + else + $list .= "$topdir/$file\n"; + $count ++; + if($count >= $limit){ + closedir($dh); + return $list; + } + } + closedir($dh); + } + return $list; + } + +/* ajax response */ +if ($_POST['mode'] == "render") { + + /* user list */ + print(str_replace(array($log_dir,'/'),array('','|'),convert_dir_list($log_dir))); + print("--END--\n"); + + /* log files */ + if ($_POST['section'] != "none") { + $section = explode('|',$_POST['section']); + $protocol = $section[0]; + $localuser = $section[1]; + $remoteuser = $section[2]; + $conversation = $section[3]; + + /* conversation title */ + print(implode(', ', $section)."\n"); + print("--END--\n"); + + /* conversation content */ + $filename = $log_dir.'/'.implode('/', $section); + if($fd = fopen($filename, 'r')) { + print("<table width='100%' border='0' cellpadding='2' cellspacing='0'>\n"); + while (!feof($fd)) { + $line = fgets($fd); + if(feof($fd)) continue; + $new_format = '([^,]*),([^,]*),([^,]*),([^,]*),([^,]*),([^,]*),(.*)'; + $old_format = '([^,]*),([^,]*),([^,]*),([^,]*),([^,]*),(.*)'; + preg_match("/${new_format}|${old_format}/", $line, $matches); + $address = $matches[1]; + $timestamp = $matches[2]; + $direction = $matches[3]; + $type = $matches[4]; + $filtered = $matches[5]; + if(count($matches) == 8) { + $category = $matches[6]; + $data = $matches[7]; + } else { + $category = ""; + $data = $matches[6]; + } + + if($direction == '0') { + $bgcolor = $convo_remote_bgcolor; + $user = "<<span style='color: $convo_remote_color;'>$remoteuser</span>>"; + } + if($direction == '1') { + $bgcolor = $convo_local_bgcolor; + $user = "<<span style='color: $convo_local_color;'>$localuser</span>>"; + } + + $time = strftime("%H:%M:%S", $timestamp); + + print("<tr bgcolor='$bgcolor'><td style='width: 30px; vertical-align: top;'>[$time]</td>\n + <td style=' width: 60px; vertical-align: top;'>$user</td>\n + <td style=' width: 60px; vertical-align: top;'>$category</td>\n + <td style='vertical-align: top;'>$data</td></tr>\n"); + } + print("</table>\n"); + fclose($fd); + } + } + exit; +} +/* defaults to this page but if no settings are present, redirect to setup page */ +if(!$imspector_config["enable"] || !$imspector_config["iface_array"] || !$imspector_config["proto_array"]) + Header("Location: /pkg_edit.php?xml=imspector.xml&id=0"); + +$pgtitle = "Services: IMSpector Log Viewer"; +include("head.inc"); +/* put your custom HTML head content here */ +/* using some of the $pfSenseHead function calls */ +//$pfSenseHead->addMeta("<meta http-equiv=\"refresh\" content=\"120;url={$_SERVER['SCRIPT_NAME']}\" />"); +//echo $pfSenseHead->getHTML(); +?> +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> +<?php include("fbegin.inc"); ?> +<?php if ($savemsg) print_info_box($savemsg); ?> +<div id="mainlevel"> +<table width="100%" border="0" cellpadding="0" cellspacing="0"> +<?php + $tab_array = array(); + $tab_array[] = array(gettext("Settings "), false, "/pkg_edit.php?xml=imspector.xml&id=0"); + $tab_array[] = array(gettext("Replacements "), false, "/pkg_edit.php?xml=imspector_replacements.xml&id=0"); + $tab_array[] = array(gettext("Access Lists "), false, "/pkg.php?xml=imspector_acls.xml"); + $tab_array[] = array(gettext("Log "), true, "/imspector_logs.php"); + $tab_array[] = array(gettext("Sync "), false, "/pkg_edit.php?xml=imspector_sync.xml&id=0"); + + display_top_tabs($tab_array); +?> +</table> + +<?php +$zz = <<<EOD +<script type="text/javascript"> +var section = 'none'; +var moveit = 1; +var the_timeout; + +function xmlhttpPost() +{ + var xmlHttpReq = false; + var self = this; + + if (window.XMLHttpRequest) + self.xmlHttpReq = new XMLHttpRequest(); + else if (window.ActiveXObject) + self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); + + self.xmlHttpReq.open('POST', 'imspector_logs.php', true); + self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); + + self.xmlHttpReq.onreadystatechange = function() { + if (self.xmlHttpReq && self.xmlHttpReq.readyState == 4) + updatepage(self.xmlHttpReq.responseText); + } + + document.getElementById('im_status').style.display = "inline"; + self.xmlHttpReq.send("mode=render§ion=" + section); +} + +function updatepage(str) +{ + /* update the list of conversations ( if we need to ) */ + var parts = str.split("--END--\\n"); + var lines = parts[0].split("\\n"); + + for (var line = 0 ; line < lines.length ; line ++) { + var a = lines[line].split("|"); + + if (!a[1] || !a[2] || !a[3]) continue; + + /* create titling information if needed */ + if (!document.getElementById(a[1])) { + document.getElementById('im_convos').innerHTML += + "<div id='" + a[1] + "_t' style='width: 100%; background-color: $list_protocol_bgcolor; color: $list_protocol_color;'>" + a[1] + "</div>" + + "<div id='" + a[1] + "' style='width: 100%; background-color: $list_local_bgcolor;'></div>"; + } + if (!document.getElementById(a[1] + "_" + a[2])) { + var imageref = ""; + if (a[0]) imageref = "<img src='" + a[0] + "' alt='" + a[1] + "'/>"; + document.getElementById(a[1]).innerHTML += + "<div id='" + a[1] + "_" + a[2] + "_t' style='width: 100%; color: $list_local_color; padding-left: 5px;'>" + imageref + a[2] + "</div>" + + "<div id='" + a[1] + "_" + a[2] + "' style='width: 100%; background-color: $list_remote_bgcolor; border-bottom: solid 1px $list_end_bgcolor;'></div>"; + } + if (!document.getElementById(a[1] + "_" + a[2] + "_" + a[3])) { + document.getElementById(a[1] + "_" + a[2]).innerHTML += + "<div id='" + a[1] + "_" + a[2] + "_" + a[3] + "_t' style='width: 100%; color: $list_remote_color; padding-left: 10px;'>" + a[3] + "</div>" + + "<div id='" + a[1] + "_" + a[2] + "_" + a[3] + "' style='width: 100%;'></div>"; + } + if (!document.getElementById(a[1] + "_" + a[2] + "_" + a[3] + "_" + a[4])) { + document.getElementById(a[1] + "_" + a[2] + "_" + a[3]).innerHTML += + "<div id='" + a[1] + "_" + a[2] + "_" + a[3] + "_" + a[4] + + "' style='width: 100%; color: $list_convo_color; cursor: pointer; padding-left: 15px;' onClick=" + + '"' + "setsection('" + a[1] + "|" + a[2] + "|" + a[3] + "|" + a[4] + "');" + '"' + "' + >»" + a[4] + "</div>"; + } + } + + /* determine the title of this conversation */ + var details = parts[1].split(","); + var title = details[0] + " conversation between <span style='color: $convo_local_color;'>" + details[ 1 ] + + "</span> and <span style='color: $convo_remote_color;'>" + details[2] + "</span>"; + if (!details[1]) title = " "; + if (!parts[2]) parts[2] = " "; + + document.getElementById('im_status').style.display = "none"; + var bottom = parseInt(document.getElementById('im_content').scrollTop); + var bottom2 = parseInt(document.getElementById('im_content').style.height); + var absheight = parseInt( bottom + bottom2 ); + if (absheight == document.getElementById('im_content').scrollHeight) { + moveit = 1; + } else { + moveit = 0; + } + document.getElementById('im_content').innerHTML = parts[2]; + if (moveit == 1) { + document.getElementById('im_content').scrollTop = 0; + document.getElementById('im_content').scrollTop = document.getElementById('im_content').scrollHeight; + } + document.getElementById('im_content_title').innerHTML = title; + the_timeout = setTimeout( "xmlhttpPost();", 5000 ); +} + +function setsection(value) +{ + section = value; + clearTimeout(the_timeout); + xmlhttpPost(); + document.getElementById('im_content').scrollTop = 0; + document.getElementById('im_content').scrollTop = document.getElementById('im_content').scrollHeight; +} +</script> +EOD; +print($zz); +?> + +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td class="tabcont"> + <div style='width: 100%; text-align: right;'><span id='im_status' style='display: none;'>Updating</span> </div> + <table width="100%"> + <tr> + <td width="15%" bgcolor="<?=$default_bgcolor?>" style="overflow: auto; border: solid 1px <?=$border_color?>;"> + <div id="im_convos" style="height: 400px; overflow: auto; overflow-x: hidden;"></div> + </td> + <td width="75%" bgcolor="<?=$default_bgcolor?>" style="border: solid 1px <?=$border_color?>;"> + <div id="im_content_title" style="height: 20px; overflow: auto; vertical-align: top; + color: <?=$convo_title_color?>; background-color: <?=$convo_title_bgcolor?>;"></div> + <div id="im_content" style="height: 380px; overflow: auto; vertical-align: bottom; overflow-x: hidden;"></div> + </td> + </tr> + </table> + </td> + </tr> +</table> + +<script type="text/javascript">xmlhttpPost();</script> + +</div> +<?php include("fend.inc"); ?> +</body> +</html> diff --git a/config/imspector-dev/imspector_replacements.xml b/config/imspector-dev/imspector_replacements.xml new file mode 100644 index 00000000..7f53bbd4 --- /dev/null +++ b/config/imspector-dev/imspector_replacements.xml @@ -0,0 +1,188 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* ========================================================================== */ +/* + imspector.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2011 Scott Ullrich <sullrich@gmail.com> + Copyright (C) 2011 Bill Marquette <billm@gmail.com> + Copyright (C) 2007 Ryan Wagoner <rswagoner@gmail.com> + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>imspectorreplacements</name> + <version>20111108</version> + <title>Services: IMSpector</title> + <savetext>Save</savetext> + <include_file>/usr/local/pkg/imspector.inc</include_file> + <menu> + <name>IMSpector</name> + <tooltiptext>Set IMSpector settings such as protocols to listen on.</tooltiptext> + <section>Services</section> + <url>/services_imspector_logs.php</url> + </menu> + <service> + <name>imspector</name> + <rcfile>imspector.sh</rcfile> + <executable>imspector</executable> + </service> + <tabs> + <tab> + <text>Settings</text> + <url>/pkg_edit.php?xml=imspector.xml&id=0</url> + </tab> + <tab> + <text>Replacements</text> + <url>/pkg_edit.php?xml=imspector_replacements.xml&id=0</url> + <active/> + </tab> + <tab> + <text>Access Lists</text> + <url>/pkg.php?xml=imspector_acls.xml</url> + </tab> + <tab> + <text>Log</text> + <url>/imspector_logs.php</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=imspector_sync.xml&id=0</url> + </tab> + </tabs> + <fields> + <field> + <name>Response messages</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Enable response messages</fielddescr> + <fieldname>responder</fieldname> + <description> + Inform the users (both local and remote) that the conversation they are having is being recorded. This might be needed for legal reasons. + Inform the sender that a file (or message) was blocked. This is useful because the sender will know a block occured, instead of the transfer simply failing.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Notification frequency</fielddescr> + <fieldname>notice_days</fieldname> + <type>input</type> + <size>10</size> + <description>Frequency in number of days for notifying users they are being logged. Default 1 day if responses are enabled, set to 0 to disable</description> + </field> + <field> + <fielddescr>Filtered frequency</fielddescr> + <fieldname>filtered_minutes</fieldname> + <type>input</type> + <size>10</size> + <description>The time between sending "filtered" in minutes. Default 15 minutes if responses are enabled, set to 0 to disable</description> + </field> + <field> + <fielddescr>Custom message prefix</fielddescr> + <fieldname>prefix_message</fieldname> + <description> + Message to prepend to all IMSpector generated messages. The default is "Message from IMSpector" + </description> + <type>input</type> + <size>60</size> + </field> + <field> + <fielddescr>Custom recorded message response</fielddescr> + <fieldname>recorded_message</fieldname> + <description> + Message to send to users to let them know they are being recorded. The default is "Your activities are being logged" + </description> + <type>textarea</type> + <encoding>base64</encoding> + <rows>5</rows> + <cols>60</cols> + </field> + <field> + <fielddescr>Custom filtered message response</fielddescr> + <fieldname>filtered_message</fieldname> + <description> + Message to send to users to let them know about filtered messages. + </description> + <type>textarea</type> + <encoding>base64</encoding> + <rows>5</rows> + <cols>60</cols> + </field> + <field> + <name>Restrictions</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Block file transfers</fielddescr> + <fieldname>block_files</fieldname> + <description>Block file transfers on supported protocols.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Block web cameras</fielddescr> + <fieldname>block_webcams</fieldname> + <description>This option will block all webcam sessions. Currently IMSpector can only spot webcam sessions on Yahoo.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Enable bad word filtering</fielddescr> + <fieldname>filter_badwords</fieldname> + <description>Replace characters of matched bad word with *.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Bad words list</fielddescr> + <fieldname>badwords_list</fieldname> + <description> + Place one word or phrase to match per line.<br /> + Leave blank to load default list. + </description> + <type>textarea</type> + <encoding>base64</encoding> + <rows>10</rows> + <cols>60</cols> + </field> + </fields> + <custom_php_validation_command> + validate_form_imspector($_POST, &$input_errors); + </custom_php_validation_command> + <custom_php_resync_config_command> + sync_package_imspector(); + </custom_php_resync_config_command> + <custom_php_deinstall_command> + deinstall_package_imspector(); + </custom_php_deinstall_command> + <filter_rules_needed>imspector_generate_rules</filter_rules_needed> + +</packagegui>
\ No newline at end of file diff --git a/config/imspector-dev/imspector_sync.xml b/config/imspector-dev/imspector_sync.xml new file mode 100644 index 00000000..3ff88d41 --- /dev/null +++ b/config/imspector-dev/imspector_sync.xml @@ -0,0 +1,109 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "./schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="./xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + imspector_sync.xml + part of the imspector package for pfSense + Copyright (C) 2012 Marcello Coutinho + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>imspectorsync</name> + <version>1.0</version> + <title>Services: IMSpector</title> + <include_file>/usr/local/pkg/imspector.inc</include_file> +<tabs> + <tab> + <text>Settings</text> + <url>/pkg_edit.php?xml=imspector.xml&id=0</url> + </tab> + <tab> + <text>Replacements</text> + <url>/pkg_edit.php?xml=imspector_replacements.xml&id=0</url> + </tab> + <tab> + <text>Access Lists</text> + <url>/pkg.php?xml=imspector_acls.xml</url> + </tab> + <tab> + <text>Log</text> + <url>/imspector_logs.php</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=imspector_sync.xml&id=0</url> + <active/> + </tab> + </tabs> + <fields> + <field> + <name>XMLRPC Sync</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Automatically sync imspector configuration changes</fielddescr> + <fieldname>synconchanges</fieldname> + <description>Automatically sync imspector(normal and reverse) changes to the hosts defined below.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Remote Server</fielddescr> + <fieldname>none</fieldname> + <type>rowhelper</type> + <rowhelper> + <rowhelperfield> + <fielddescr>IP Address</fielddescr> + <fieldname>ipaddress</fieldname> + <description>IP Address of remote server</description> + <type>input</type> + <size>20</size> + </rowhelperfield> + <rowhelperfield> + <fielddescr>Password</fielddescr> + <fieldname>password</fieldname> + <description>Password for remote server.</description> + <type>password</type> + <size>20</size> + </rowhelperfield> + </rowhelper> + </field> + </fields> + <custom_php_validation_command> + </custom_php_validation_command> + <custom_php_resync_config_command> + sync_package_imspector(); + </custom_php_resync_config_command> +</packagegui> diff --git a/config/imspector-dev/services_imspector_logs.php b/config/imspector-dev/services_imspector_logs.php new file mode 100644 index 00000000..e44ef35f --- /dev/null +++ b/config/imspector-dev/services_imspector_logs.php @@ -0,0 +1,311 @@ +<?php +/* + services_imspector_logs.php + part of pfSense (http://www.pfsense.com/) + + JavaScript Code is GPL Licensed from SmoothWall Express. + + Copyright (C) 2007 Ryan Wagoner <rswagoner@gmail.com>. + Copyright (C) 2012 Marcello Coutinho + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. +*/ + +require("guiconfig.inc"); + +/* variables */ +$log_dir = '/var/imspector'; +$imspector_config = $config['installedpackages']['imspector']['config'][0]; + +$border_color = '#c0c0c0'; +$default_bgcolor = '#eeeeee'; + +$list_protocol_color = '#000000'; +$list_local_color = '#000000'; +$list_remote_color = '#000000'; +$list_convo_color = '#000000'; + +$list_protocol_bgcolor = '#cccccc'; +$list_local_bgcolor = '#dddddd'; +$list_remote_bgcolor = '#eeeeee'; +$list_end_bgcolor = '#bbbbbb'; + +$convo_title_color = 'black'; +$convo_local_color = 'blue'; +$convo_remote_color = 'red'; + +$convo_title_bgcolor = '#cccccc'; +$convo_local_bgcolor = '#dddddd'; +$convo_remote_bgcolor = '#eeeeee'; + +/* functions */ + +function convert_dir_list ($topdir) { + global $config; + if (!is_dir($topdir)) + return; + $imspector_config = $config['installedpackages']['imspector']['config'][0]; + $limit=(preg_match("/\d+/",$imspector_config['reportlimit'])?$imspector_config['reportlimit']:"50"); + file_put_contents("/tmp/teste.txt",$limit." teste",LOCK_EX); + $count=0; + if ($dh = opendir($topdir)) { + while (($file = readdir($dh)) !== false) { + if(!preg_match('/^\./', $file) == 0) + continue; + if (is_dir("$topdir/$file")) + $list .= convert_dir_list("$topdir/$file"); + else + $list .= "$topdir/$file\n"; + $count ++; + if($count >= $limit){ + closedir($dh); + return $list; + } + } + closedir($dh); + } + return $list; + } + +/* ajax response */ +if ($_POST['mode'] == "render") { + + /* user list */ + print(str_replace(array($log_dir,'/'),array('','|'),convert_dir_list($log_dir))); + print("--END--\n"); + + /* log files */ + if ($_POST['section'] != "none") { + $section = explode('|',$_POST['section']); + $protocol = $section[0]; + $localuser = $section[1]; + $remoteuser = $section[2]; + $conversation = $section[3]; + + /* conversation title */ + print(implode(', ', $section)."\n"); + print("--END--\n"); + + /* conversation content */ + $filename = $log_dir.'/'.implode('/', $section); + if($fd = fopen($filename, 'r')) { + print("<table width='100%' border='0' cellpadding='2' cellspacing='0'>\n"); + while (!feof($fd)) { + $line = fgets($fd); + if(feof($fd)) continue; + $new_format = '([^,]*),([^,]*),([^,]*),([^,]*),([^,]*),([^,]*),(.*)'; + $old_format = '([^,]*),([^,]*),([^,]*),([^,]*),([^,]*),(.*)'; + preg_match("/${new_format}|${old_format}/", $line, $matches); + $address = $matches[1]; + $timestamp = $matches[2]; + $direction = $matches[3]; + $type = $matches[4]; + $filtered = $matches[5]; + if(count($matches) == 8) { + $category = $matches[6]; + $data = $matches[7]; + } else { + $category = ""; + $data = $matches[6]; + } + + if($direction == '0') { + $bgcolor = $convo_remote_bgcolor; + $user = "<<span style='color: $convo_remote_color;'>$remoteuser</span>>"; + } + if($direction == '1') { + $bgcolor = $convo_local_bgcolor; + $user = "<<span style='color: $convo_local_color;'>$localuser</span>>"; + } + + $time = strftime("%H:%M:%S", $timestamp); + + print("<tr bgcolor='$bgcolor'><td style='width: 30px; vertical-align: top;'>[$time]</td>\n + <td style=' width: 60px; vertical-align: top;'>$user</td>\n + <td style=' width: 60px; vertical-align: top;'>$category</td>\n + <td style='vertical-align: top;'>$data</td></tr>\n"); + } + print("</table>\n"); + fclose($fd); + } + } + exit; +} +/* defaults to this page but if no settings are present, redirect to setup page */ +if(!$imspector_config["enable"] || !$imspector_config["iface_array"] || !$imspector_config["proto_array"]) + Header("Location: /pkg_edit.php?xml=imspector.xml&id=0"); + +$pgtitle = "Services: IMSpector Log Viewer"; +include("head.inc"); +/* put your custom HTML head content here */ +/* using some of the $pfSenseHead function calls */ +//$pfSenseHead->addMeta("<meta http-equiv=\"refresh\" content=\"120;url={$_SERVER['SCRIPT_NAME']}\" />"); +//echo $pfSenseHead->getHTML(); +?> +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> +<?php include("fbegin.inc"); ?> +<?php if ($savemsg) print_info_box($savemsg); ?> +<div id="mainlevel"> +<table width="100%" border="0" cellpadding="0" cellspacing="0"> +<?php + $tab_array = array(); + $tab_array[] = array(gettext("Settings "), false, "/pkg_edit.php?xml=imspector.xml&id=0"); + $tab_array[] = array(gettext("Replacements "), false, "/pkg_edit.php?xml=imspector_replacements.xml&id=0"); + $tab_array[] = array(gettext("Access Lists "), false, "/pkg.php?xml=imspector_acls.xml"); + $tab_array[] = array(gettext("Log "), true, "/imspector_logs.php"); + $tab_array[] = array(gettext("Sync "), false, "/pkg_edit.php?xml=imspector_sync.xml&id=0"); + + display_top_tabs($tab_array); +?> +</table> + +<?php +$zz = <<<EOD +<script type="text/javascript"> +var section = 'none'; +var moveit = 1; +var the_timeout; + +function xmlhttpPost() +{ + var xmlHttpReq = false; + var self = this; + + if (window.XMLHttpRequest) + self.xmlHttpReq = new XMLHttpRequest(); + else if (window.ActiveXObject) + self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); + + self.xmlHttpReq.open('POST', 'imspector_logs.php', true); + self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); + + self.xmlHttpReq.onreadystatechange = function() { + if (self.xmlHttpReq && self.xmlHttpReq.readyState == 4) + updatepage(self.xmlHttpReq.responseText); + } + + document.getElementById('im_status').style.display = "inline"; + self.xmlHttpReq.send("mode=render§ion=" + section); +} + +function updatepage(str) +{ + /* update the list of conversations ( if we need to ) */ + var parts = str.split("--END--\\n"); + var lines = parts[0].split("\\n"); + + for (var line = 0 ; line < lines.length ; line ++) { + var a = lines[line].split("|"); + + if (!a[1] || !a[2] || !a[3]) continue; + + /* create titling information if needed */ + if (!document.getElementById(a[1])) { + document.getElementById('im_convos').innerHTML += + "<div id='" + a[1] + "_t' style='width: 100%; background-color: $list_protocol_bgcolor; color: $list_protocol_color;'>" + a[1] + "</div>" + + "<div id='" + a[1] + "' style='width: 100%; background-color: $list_local_bgcolor;'></div>"; + } + if (!document.getElementById(a[1] + "_" + a[2])) { + var imageref = ""; + if (a[0]) imageref = "<img src='" + a[0] + "' alt='" + a[1] + "'/>"; + document.getElementById(a[1]).innerHTML += + "<div id='" + a[1] + "_" + a[2] + "_t' style='width: 100%; color: $list_local_color; padding-left: 5px;'>" + imageref + a[2] + "</div>" + + "<div id='" + a[1] + "_" + a[2] + "' style='width: 100%; background-color: $list_remote_bgcolor; border-bottom: solid 1px $list_end_bgcolor;'></div>"; + } + if (!document.getElementById(a[1] + "_" + a[2] + "_" + a[3])) { + document.getElementById(a[1] + "_" + a[2]).innerHTML += + "<div id='" + a[1] + "_" + a[2] + "_" + a[3] + "_t' style='width: 100%; color: $list_remote_color; padding-left: 10px;'>" + a[3] + "</div>" + + "<div id='" + a[1] + "_" + a[2] + "_" + a[3] + "' style='width: 100%;'></div>"; + } + if (!document.getElementById(a[1] + "_" + a[2] + "_" + a[3] + "_" + a[4])) { + document.getElementById(a[1] + "_" + a[2] + "_" + a[3]).innerHTML += + "<div id='" + a[1] + "_" + a[2] + "_" + a[3] + "_" + a[4] + + "' style='width: 100%; color: $list_convo_color; cursor: pointer; padding-left: 15px;' onClick=" + + '"' + "setsection('" + a[1] + "|" + a[2] + "|" + a[3] + "|" + a[4] + "');" + '"' + "' + >»" + a[4] + "</div>"; + } + } + + /* determine the title of this conversation */ + var details = parts[1].split(","); + var title = details[0] + " conversation between <span style='color: $convo_local_color;'>" + details[ 1 ] + + "</span> and <span style='color: $convo_remote_color;'>" + details[2] + "</span>"; + if (!details[1]) title = " "; + if (!parts[2]) parts[2] = " "; + + document.getElementById('im_status').style.display = "none"; + var bottom = parseInt(document.getElementById('im_content').scrollTop); + var bottom2 = parseInt(document.getElementById('im_content').style.height); + var absheight = parseInt( bottom + bottom2 ); + if (absheight == document.getElementById('im_content').scrollHeight) { + moveit = 1; + } else { + moveit = 0; + } + document.getElementById('im_content').innerHTML = parts[2]; + if (moveit == 1) { + document.getElementById('im_content').scrollTop = 0; + document.getElementById('im_content').scrollTop = document.getElementById('im_content').scrollHeight; + } + document.getElementById('im_content_title').innerHTML = title; + the_timeout = setTimeout( "xmlhttpPost();", 5000 ); +} + +function setsection(value) +{ + section = value; + clearTimeout(the_timeout); + xmlhttpPost(); + document.getElementById('im_content').scrollTop = 0; + document.getElementById('im_content').scrollTop = document.getElementById('im_content').scrollHeight; +} +</script> +EOD; +print($zz); +?> + +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td class="tabcont"> + <div style='width: 100%; text-align: right;'><span id='im_status' style='display: none;'>Updating</span> </div> + <table width="100%"> + <tr> + <td width="15%" bgcolor="<?=$default_bgcolor?>" style="overflow: auto; border: solid 1px <?=$border_color?>;"> + <div id="im_convos" style="height: 400px; overflow: auto; overflow-x: hidden;"></div> + </td> + <td width="75%" bgcolor="<?=$default_bgcolor?>" style="border: solid 1px <?=$border_color?>;"> + <div id="im_content_title" style="height: 20px; overflow: auto; vertical-align: top; + color: <?=$convo_title_color?>; background-color: <?=$convo_title_bgcolor?>;"></div> + <div id="im_content" style="height: 380px; overflow: auto; vertical-align: bottom; overflow-x: hidden;"></div> + </td> + </tr> + </table> + </td> + </tr> +</table> + +<script type="text/javascript">xmlhttpPost();</script> + +</div> +<?php include("fend.inc"); ?> +</body> +</html> diff --git a/config/imspector-dev/services_imspector_logs2.php b/config/imspector-dev/services_imspector_logs2.php new file mode 100644 index 00000000..368edeec --- /dev/null +++ b/config/imspector-dev/services_imspector_logs2.php @@ -0,0 +1,318 @@ +<?php +/* + services_imspector_logs.php + part of pfSense (http://www.pfsense.com/) + + JavaScript Code is GPL Licensed from SmoothWall Express. + + Copyright (C) 2007 Ryan Wagoner <rswagoner@gmail.com>. + Copyright (C) 2012 0guzcan at pfsense forum. + Copyright (C) 2012 Marcello Coutinho + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. +*/ +require("guiconfig.inc"); + +/* variables */ +$log_dir = '/var/imspector'; +$imspector_config = $config['installedpackages']['imspector']['config'][0]; + +$border_color = '#c0c0c0'; +$default_bgcolor = '#eeeeee'; + +$list_protocol_color = '#000000'; +$list_local_color = '#ffffff'; +$list_remote_color = '#666666'; +$list_convo_color = '#888888'; + +$list_protocol_bgcolor = '#cccccc'; +$list_local_bgcolor = '#850000'; +$list_remote_bgcolor = '#eeeeee'; +$list_end_bgcolor = '#bbbbbb'; + +$convo_title_color = 'black'; +$convo_local_color = 'blue'; +$convo_remote_color = 'red'; + +$convo_title_bgcolor = '#cccccc'; +$convo_local_bgcolor = '#dddddd'; +$convo_remote_bgcolor = '#eeeeee'; + + +/* functions */ + +function convert_dir_list ($topdir) { + global $config; + if (!is_dir($topdir)) + return; + $imspector_config = $config['installedpackages']['imspector']['config'][0]; + $limit=(preg_match("/\d+/",$imspector_config['reportlimit'])?$imspector_config['reportlimit']:"50"); + file_put_contents("/tmp/teste.txt",$limit." teste",LOCK_EX); + $count=0; + if ($dh = opendir($topdir)) { + while (($file = readdir($dh)) !== false) { + if(!preg_match('/^\./', $file) == 0) + continue; + if (is_dir("$topdir/$file")) + $list .= convert_dir_list("$topdir/$file"); + else + $list .= "$topdir/$file\n"; + $count ++; + if($count >= $limit){ + closedir($dh); + return $list; + } + } + closedir($dh); + } + return $list; + } + +/* ajax response */ +if ($_POST['mode'] == "render") { + + /* user list */ + print(str_replace(array($log_dir,'/'),array('','|'),convert_dir_list($log_dir))); + print("--END--\n"); + + /* log files */ + if ($_POST['section'] != "none") { + $section = explode('|',$_POST['section']); + $protocol = $section[0]; + $localuser = $section[1]; + $remoteuser = $section[2]; + $conversation = $section[3]; + + /* conversation title */ + print(implode(', ', $section)."\n"); + print("--END--\n"); + + /* conversation content */ + $filename = $log_dir.'/'.implode('/', $section); + if($fd = fopen($filename, 'r')) { + $satir_oku = fgets($fd); + $ipsinibulduk = explode(':',$satir_oku); + + print("<table width='100%' border='0' cellpadding='2' cellspacing='1'><tr><td style='color:#fff;' colspan='4' align='center' width='100%' bgcolor='#850000'>user [<span style='font-weight:bold;'>$localuser</span>] at local ip: [<span style='font-weight:bold;'>$ipsinibulduk[0]</span>]</td></tr>\n"); + while (!feof($fd)) { + $line = fgets($fd); + if(feof($fd)) continue; + $new_format = '([^,]*),([^,]*),([^,]*),([^,]*),([^,]*),([^,]*),(.*)'; + $old_format = '([^,]*),([^,]*),([^,]*),([^,]*),([^,]*),(.*)'; + preg_match("/${new_format}|${old_format}/", $line, $matches); + $address = $matches[1]; + $addresbul = explode(':',$address); + $addressnew =$addresbul[0] ; + $timestamp = $matches[2]; + $direction = $matches[3]; + $type = $matches[4]; + $filtered = $matches[5]; + if(count($matches) == 8) { + $category = $matches[6]; + $data = $matches[7]; + } else { + $category = ""; + $data = $matches[6]; + } + + if($direction == '0') { + $bgcolor = $convo_remote_bgcolor; + $user = "<span style='color: $convo_remote_color;'>$remoteuser</span>"; + } + if($direction == '1') { + $bgcolor = $convo_local_bgcolor; + $user = "<span style='color: $convo_local_color;'>$localuser</span>"; + } + + $time = strftime("%H:%M", $timestamp); + + + print("<tr bgcolor='$bgcolor'> + <td style='width: 5%; vertical-align: top;border-bottom:1px solid #ccc;'>[$time]</td>\n + <td style='border-bottom:1px solid #ccc; width: 13%; vertical-align: top;'>$user</td>\n + <td style='border-bottom:1px solid #ccc; width: 1%; vertical-align: top;'>$category</td>\n + <td style='border-bottom:1px solid #ccc; width: 82%; vertical-align: top;'>$data</td></tr>\n"); + } + print("</table>\n"); + fclose($fd); + } + } + exit; +} +/* defaults to this page but if no settings are present, redirect to setup page */ +if(!$imspector_config["enable"] || !$imspector_config["iface_array"] || !$imspector_config["proto_array"]) + Header("Location: /pkg_edit.php?xml=imspector.xml&id=0"); + +$pgtitle = "Services: IMSpector Log Viewer"; +include("head.inc"); +/* put your custom HTML head content here */ +/* using some of the $pfSenseHead function calls */ +//$pfSenseHead->addMeta("<meta http-equiv=\"refresh\" content=\"120;url={$_SERVER['SCRIPT_NAME']}\" />"); +//echo $pfSenseHead->getHTML(); +?> + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> +<?php include("fbegin.inc"); ?> +<?php if ($savemsg) print_info_box($savemsg); ?> +<div id="mainlevel"> +<table width="100%" border="0" cellpadding="0" cellspacing="0"> +<?php + $tab_array = array(); + $tab_array[] = array(gettext("Settings "), false, "/pkg_edit.php?xml=imspector.xml&id=0"); + $tab_array[] = array(gettext("Replacements "), false, "/pkg_edit.php?xml=imspector_replacements.xml&id=0"); + $tab_array[] = array(gettext("Access Lists "), false, "/pkg.php?xml=imspector_acls.xml"); + $tab_array[] = array(gettext("Log "), true, "/imspector_logs.php"); + $tab_array[] = array(gettext("Sync "), false, "/pkg_edit.php?xml=imspector_sync.xml&id=0"); + display_top_tabs($tab_array); +?> +</table> + +<?php +$zz = <<<EOD +<script type="text/javascript"> +var section = 'none'; +var moveit = 1; +var the_timeout; + +function xmlhttpPost() +{ + var xmlHttpReq = false; + var self = this; + + if (window.XMLHttpRequest) + self.xmlHttpReq = new XMLHttpRequest(); + else if (window.ActiveXObject) + self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); + + self.xmlHttpReq.open('POST', 'imspector_logs.php', true); + self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); + + self.xmlHttpReq.onreadystatechange = function() { + if (self.xmlHttpReq && self.xmlHttpReq.readyState == 4) + updatepage(self.xmlHttpReq.responseText); + } + + document.getElementById('im_status').style.display = "inline"; + self.xmlHttpReq.send("mode=render§ion=" + section); +} + +function updatepage(str) +{ + /* update the list of conversations ( if we need to ) */ + var parts = str.split("--END--\\n"); + var lines = parts[0].split("\\n"); + + for (var line = 0 ; line < lines.length ; line ++) { + var a = lines[line].split("|"); + + if (!a[1] || !a[2] || !a[3]) continue; + + /* create titling information if needed */ + if (!document.getElementById(a[1])) { + document.getElementById('im_convos').innerHTML += + "<div id='" + a[1] + "_t' style='width: 100%; background-color: $list_protocol_bgcolor; color: $list_protocol_color;'>" + a[1] + "</div>" + + "<div id='" + a[1] + "' style='width: 100%; background-color: $list_local_bgcolor;'></div>"; + } + if (!document.getElementById(a[1] + "_" + a[2])) { + var imageref = ""; + if (a[0]) imageref = "<img src='" + a[0] + "' alt='" + a[1] + "'/>"; + document.getElementById(a[1]).innerHTML += + "<div id='" + a[1] + "_" + a[2] + "_t' style='width: 100%; color: $list_local_color; padding-left: 5px;'>" + imageref + a[2] + "</div>" + + "<div id='" + a[1] + "_" + a[2] + "' style='width: 100%; background-color: $list_remote_bgcolor; border-bottom: solid 1px $list_end_bgcolor;'></div>"; + } + if (!document.getElementById(a[1] + "_" + a[2] + "_" + a[3])) { + document.getElementById(a[1] + "_" + a[2]).innerHTML += + "<div id='" + a[1] + "_" + a[2] + "_" + a[3] + "_t' style='width: 100%; color: $list_remote_color; padding-left: 10px;'>" + a[3] + "</div>" + + "<div id='" + a[1] + "_" + a[2] + "_" + a[3] + "' style='width: 100%;'></div>"; + } + if (!document.getElementById(a[1] + "_" + a[2] + "_" + a[3] + "_" + a[4])) { + document.getElementById(a[1] + "_" + a[2] + "_" + a[3]).innerHTML += + "<div id='" + a[1] + "_" + a[2] + "_" + a[3] + "_" + a[4] + + "' style='width: 100%; color: $list_convo_color; cursor: pointer; padding-left: 15px;' onClick=" + + '"' + "setsection('" + a[1] + "|" + a[2] + "|" + a[3] + "|" + a[4] + "');" + '"' + "' + >»" + a[4] + "</div>"; + } + } + + /* determine the title of this conversation */ + var details = parts[1].split(","); + var title = "<table border='1' width='100%'><tr><td style='color:#666;' align='center' bgcolor='#eee' valign='top'>"+ details[3]+ " dated " + "[<span style='font-weight:bold;'>" + details[1]+ "</span> ]"+ " with " + "[ <span style='font-weight:bold;'>" + details[2] + " </span> ] " + details[0] + " records</td></tr></table>"; + if (!details[1]) title = " "; + if (!parts[2]) parts[2] = " "; + + document.getElementById('im_status').style.display = "none"; + var bottom = parseInt(document.getElementById('im_content').scrollTop); + var bottom2 = parseInt(document.getElementById('im_content').style.height); + var absheight = parseInt( bottom + bottom2 ); + if (absheight == document.getElementById('im_content').scrollHeight) { + moveit = 1; + } else { + moveit = 0; + } + document.getElementById('im_content').innerHTML = parts[2]; + if (moveit == 1) { + document.getElementById('im_content').scrollTop = 0; + document.getElementById('im_content').scrollTop = document.getElementById('im_content').scrollHeight; + } + document.getElementById('im_content_title').innerHTML = title; + the_timeout = setTimeout( "xmlhttpPost();", 5000 ); +} + +function setsection(value) +{ + section = value; + clearTimeout(the_timeout); + xmlhttpPost(); + document.getElementById('im_content').scrollTop = 0; + document.getElementById('im_content').scrollTop = document.getElementById('im_content').scrollHeight; +} +</script> +EOD; +print($zz); +?> + +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td class="tabcont"> + <div style='width: 100%; text-align: right;'><span id='im_status' style='display: none;'>Updating...</span> </div> + <table width="100%"> + <tr> + <td width="15%" bgcolor="<?=$default_bgcolor?>" style="overflow: auto; border: solid 1px <?=$border_color?>;"> + <div id="im_convos" style="height: 400px; overflow: auto; overflow-x: hidden;"></div> + </td> + <td width="75%" bgcolor="<?=$default_bgcolor?>" style="border: solid 1px <?=$border_color?>;"> + <div id="im_content_title" style="height: 20px; overflow: auto; vertical-align: top; + color: <?=$convo_title_color?>; background-color: <?=$convo_title_bgcolor?>;"></div> + <div id="im_content" style="height: 380px; overflow: auto; vertical-align: bottom; overflow-x: hidden;"></div> + </td> + </tr> + </table> + </td> + </tr> +</table> + +<script type="text/javascript">xmlhttpPost();</script> + +</div> +<?php include("fend.inc"); ?> +</body> +</html>
\ No newline at end of file diff --git a/config/ipguard/ipguard.inc b/config/ipguard/ipguard.inc new file mode 100644 index 00000000..1891b24b --- /dev/null +++ b/config/ipguard/ipguard.inc @@ -0,0 +1,218 @@ +<?php + +/* ========================================================================== */ +/* + ipguard.inc + part of the ipguard package for pfSense (http://www.pfSense.com) + Copyright (C) 2012 Marcello Coutinho + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + require_once("config.inc"); + require_once("util.inc"); + +function ipguard_custom_php_deinstall_command(){ + global $g, $config; + + conf_mount_rw(); + + stop_service('ipguard'); + $ipguard_sh_file = "/usr/local/etc/rc.d/ipguard.sh"; + if (is_file($ipguard_sh_file)) + chmod($ipguard_sh_file,0444); + + conf_mount_ro(); + } + +function ipguard_custom_php_write_config(){ + global $g, $config; + + # detect boot process + if (is_array($_POST)){ + if (!preg_match("/\w+/",$_POST['__csrf_magic'])) + return; + } + + + if (is_array($config['installedpackages']['ipguard']['config'])){ + // Read config + $new_config=array(); + foreach ($config['installedpackages']['ipguard']['config'] as $ipguard){ + if ($ipguard['enable'] && $ipguard['interface'] && $ipguard['mac'] && $ipguard['ip']){ + $new_config[$ipguard['interface']].= "{$ipguard['mac']} {$ipguard['ip']} {$ipguard['description']}\n"; + } + } + } + + //Save /etc/ssh/ipguard_extra + $script="/usr/local/etc/rc.d/ipguard.sh"; + $start=""; + $stop="pkill -anx ipguard"; + conf_mount_rw(); + if (count ($new_config) > 0 && $ipguard['enable']){ + foreach ($new_config as $key => $value){ + $conf_file="/usr/local/etc/ipguard_{$key}.conf"; + file_put_contents($conf_file,$value,LOCK_EX); + $config_file=file_put_contents($conf_file,$new_config[$key],LOCK_EX); + $iface=convert_friendly_interface_to_real_interface_name($key); + $start.="/usr/local/sbin/ipguard -l /var/log/ipguard_{$key}.log -p /var/run/ipguard_{$key}.pid -f {$conf_file} -u 300 -z {$iface}\n\t"; + } + write_rcfile(array( + 'file' => 'ipguard.sh', + 'start' => $start, + 'stop' => $stop + )); + restart_service('ipguard'); + + } + else{ + #remove config files + stop_service('ipguard'); + $ipguard_sh_file = "/usr/local/etc/rc.d/ipguard.sh"; + if (is_file($ipguard_sh_file)) + chmod($ipguard_sh_file,0444); + } + // Mount Read-only + conf_mount_ro(); + + //sync config with other pfsense servers + ipguard_sync_on_changes(); + } + +/* Uses XMLRPC to synchronize the changes to a remote node */ +function ipguard_sync_on_changes() { + global $config, $g; + + if (is_array($config['installedpackages']['ipguardsync'])) { + if ($config['installedpackages']['ipguardsync']['config'][0]['synconchanges']) { + log_error("[ipguard] xmlrpc sync is starting."); + foreach ($config['installedpackages']['ipguardsync']['config'] as $rs ){ + foreach($rs['row'] as $sh){ + $sync_to_ip = $sh['ipaddress']; + $password = $sh['password']; + if($password && $sync_to_ip) + ipguard_do_xmlrpc_sync($sync_to_ip, $password); + } + } + log_error("[ipguard] xmlrpc sync is ending."); + } + } +} + +/* Do the actual XMLRPC sync */ +function ipguard_do_xmlrpc_sync($sync_to_ip, $password) { + global $config, $g; + + if(!$password) + return; + + if(!$sync_to_ip) + return; + + $username='admin'; + $xmlrpc_sync_neighbor = $sync_to_ip; + if($config['system']['webgui']['protocol'] != "") { + $synchronizetoip = $config['system']['webgui']['protocol']; + $synchronizetoip .= "://"; + } + $port = $config['system']['webgui']['port']; + /* if port is empty lets rely on the protocol selection */ + if($port == "") { + if($config['system']['webgui']['protocol'] == "http") + $port = "80"; + else + $port = "443"; + } + $synchronizetoip .= $sync_to_ip; + + /* xml will hold the sections to sync */ + $xml = array(); + $xml['ipguard'] = $config['installedpackages']['ipguard']; + /* assemble xmlrpc payload */ + $params = array( + XML_RPC_encode($password), + XML_RPC_encode($xml) + ); + + /* set a few variables needed for sync code borrowed from filter.inc */ + $url = $synchronizetoip; + log_error("Beginning ipguard XMLRPC sync to {$url}:{$port}."); + $method = 'pfsense.merge_installedpackages_section_xmlrpc'; + $msg = new XML_RPC_Message($method, $params); + $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); + $cli->setCredentials($username, $password); + if($g['debug']) + $cli->setDebug(1); + /* send our XMLRPC message and timeout after 250 seconds */ + $resp = $cli->send($msg, "250"); + if(!$resp) { + $error = "A communications error occurred while attempting ipguard XMLRPC sync with {$url}:{$port}."; + log_error($error); + file_notice("sync_settings", $error, "ipguard Settings Sync", ""); + } elseif($resp->faultCode()) { + $cli->setDebug(1); + $resp = $cli->send($msg, "250"); + $error = "An error code was received while attempting ipguard XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); + log_error($error); + file_notice("sync_settings", $error, "ipguard Settings Sync", ""); + } else { + log_error("ipguard XMLRPC sync successfully completed with {$url}:{$port}."); + } + + /* tell ipguard to reload our settings on the destination sync host. */ + $method = 'pfsense.exec_php'; + $execcmd = "require_once('/usr/local/pkg/ipguard.inc');\n"; + $execcmd .= "ipguard_custom_php_write_config();"; + /* assemble xmlrpc payload */ + $params = array( + XML_RPC_encode($password), + XML_RPC_encode($execcmd) + ); + + log_error("ipguard XMLRPC reload data {$url}:{$port}."); + $msg = new XML_RPC_Message($method, $params); + $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); + $cli->setCredentials($username, $password); + $resp = $cli->send($msg, "250"); + if(!$resp) { + $error = "A communications error occurred while attempting ipguard XMLRPC sync with {$url}:{$port} (pfsense.exec_php)."; + log_error($error); + file_notice("sync_settings", $error, "ipguard Settings Sync", ""); + } elseif($resp->faultCode()) { + $cli->setDebug(1); + $resp = $cli->send($msg, "250"); + $error = "An error code was received while attempting ipguard XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); + log_error($error); + file_notice("sync_settings", $error, "ipguard Settings Sync", ""); + } else { + log_error("ipguard XMLRPC reload data success with {$url}:{$port} (pfsense.exec_php)."); + } +} + ?>
\ No newline at end of file diff --git a/config/ipguard/ipguard.xml b/config/ipguard/ipguard.xml new file mode 100644 index 00000000..cafc6e4e --- /dev/null +++ b/config/ipguard/ipguard.xml @@ -0,0 +1,194 @@ +<?xml version="1.0" encoding="utf-8" ?> +<packagegui> +<copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + ipguard.xml + part of the ipguard package for pfSense (http://www.pfSense.com) + Copyright (C) 2012 Marcello Coutinho + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + + <name>ipguard</name> + <version>1.0</version> + <title>Ipguard</title> + <description>Ipguard macs/ip</description> + <savetext>Save</savetext> + <include_file>/usr/local/pkg/ipguard.inc</include_file> + <menu> + <name>Ipguard</name> + <tooltiptext>Tool designed to protect LAN IP address space by ARP spoofing</tooltiptext> + <section>Firewall</section> + <url>/pkg.php?xml=ipguard.xml</url> + </menu> + <service> + <name>ipguard</name> + <rcfile>ipguard.sh</rcfile> + <executable>ipguard</executable> + <description>Tool designed to protect LAN IP address space by ARP spoofing.</description> + </service> + <configpath>installedpackages->package->ipguard</configpath> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>755</chmod> + <item>http://www.pfsense.com/packages/config/ipguard/ipguard.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>755</chmod> + <item>http://www.pfsense.com/packages/config/ipguard/ipguard_sync.xml</item> + </additional_files_needed> + <tabs> + <tab> + <text>General</text> + <url>/pkg.php?xml=ipguard.xml</url> + <active/> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=ipguard_sync.xml</url> + </tab> + </tabs> + <adddeleteeditpagefields> + <columnitem> + <fielddescr>Enable</fielddescr> + <fieldname>enable</fieldname> + <type>checkbox</type> + </columnitem> + <columnitem> + <fielddescr>Interface</fielddescr> + <fieldname>interface</fieldname> + </columnitem> + <columnitem> + <fielddescr>Mac Address</fielddescr> + <fieldname>mac</fieldname> + </columnitem> + <columnitem> + <fielddescr>Ip Address(es)</fielddescr> + <fieldname>ip</fieldname> + </columnitem> + <columnitem> + <fielddescr>Description</fielddescr> + <fieldname>description</fieldname> + </columnitem> + <movable>on</movable> + <description><![CDATA[If firewall receives traffic with MAC/IP pair not listed here, it will send ARP reply with configured fake address.<br>This will prevent not permitted host from working properly in the specified ethernet segment.]]></description> + </adddeleteeditpagefields> + <fields> + <field> + <type>listtopic</type> + <name>Ipguard Options</name> + <fieldname>temp</fieldname> + </field> + <field> + <fielddescr>sortable</fielddescr> + <fieldname>sortable</fieldname> + <display_maximum_rows>20</display_maximum_rows> + <type>sorting</type> + <include_filtering_inputbox/> + <sortablefields> + <item> + <name>Mac Address</name> + <fieldname>mac</fieldname> + <regex>/%FILTERTEXT%/i</regex> + </item> + <item> + <name>Ip Address</name> + <fieldname>ip</fieldname> + <regex>/%FILTERTEXT%/i</regex> + </item> + </sortablefields> + </field> + <field> + <fielddescr>Enable</fielddescr> + <fieldname>enable</fieldname> + <type>checkbox</type> + <description><![CDATA[Enable this mac rule.<br><strong>Important Note:</strong> Always create rules for pfsense mac and ip address to avoid denying access to pfsense gui.]]></description> + </field> + <field> + <fielddescr>Interface</fielddescr> + <fieldname>interface</fieldname> + <description>The interface on which ipguard server will check this mac</description> + <type>interfaces_selection</type> + <required/> + <default_value>lan</default_value> + </field> + <field> + <fielddescr>Description</fielddescr> + <fieldname>description</fieldname> + <description>Describe this mac rule.</description> + <type>input</type> + <size>50</size> + <required/> + </field> + <field> + <fielddescr>Mac address</fielddescr> + <fieldname>mac</fieldname> + <description><![CDATA[Insert mac address you want to filter.<br> + <strong>To include a permit rule, use mac=00:00:00:00:00:00</strong>]]></description> + <type>input</type> + <size>25</size> + <required/> + </field> + <field> + <fielddescr>Ip address</fielddescr> + <fieldname>ip</fieldname> + <description><![CDATA[Insert ip address, hostname or network cidr you want to apply on this ipguard rule.<br> + <strong>To include a permit rule, use your lan cidr or 0.0.0.0</strong>]]></description> + <type>input</type> + <size>40</size> + <required/> + </field> + </fields> + + <custom_delete_php_command> + ipguard_custom_php_write_config(); + </custom_delete_php_command> + <custom_add_php_command> + ipguard_custom_php_write_config(); + </custom_add_php_command> + <custom_php_install_command> + </custom_php_install_command> + <custom_php_deinstall_command> + ipguard_custom_php_deinstall_command(); + </custom_php_deinstall_command> + <custom_php_resync_config_command> + ipguard_custom_php_write_config(); + </custom_php_resync_config_command> + <custom_php_command_before_form> + unset($_POST['temp']); + </custom_php_command_before_form> + +</packagegui>
\ No newline at end of file diff --git a/config/ipguard/ipguard_sync.xml b/config/ipguard/ipguard_sync.xml new file mode 100755 index 00000000..0b5ffecb --- /dev/null +++ b/config/ipguard/ipguard_sync.xml @@ -0,0 +1,97 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "./schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="./xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + ipguard_sync.xml + part of the ipguard package for pfSense (http://www.pfSense.com) + Copyright (C) 2012 Marcello Coutinho + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>ipguardsync</name> + <version>1.0</version> + <title>Ipguard - Sync</title> + <include_file>/usr/local/pkg/ipguard.inc</include_file> + <tabs> + <tab> + <text>General</text> + <url>/pkg.php?xml=ipguard.xml</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=ipguard_sync.xml</url> + <active/> + </tab> + </tabs> + <fields> + <field> + <name>XMLRPC Sync</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Automatically sync configuration changes</fielddescr> + <fieldname>synconchanges</fieldname> + <description>Automatically sync changes to the hosts defined below.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Remote Server</fielddescr> + <fieldname>none</fieldname> + <type>rowhelper</type> + <rowhelper> + <rowhelperfield> + <fielddescr>IP Address</fielddescr> + <fieldname>ipaddress</fieldname> + <description>IP Address of remote server</description> + <type>input</type> + <size>20</size> + </rowhelperfield> + <rowhelperfield> + <fielddescr>Password</fielddescr> + <fieldname>password</fieldname> + <description>Password for remote server.</description> + <type>password</type> + <size>20</size> + </rowhelperfield> + </rowhelper> + </field> + </fields> + <custom_php_validation_command> + </custom_php_validation_command> + <custom_php_resync_config_command> + ipguard_custom_php_write_config(); + </custom_php_resync_config_command> +</packagegui> diff --git a/config/lcdproc-dev/lcdproc.inc b/config/lcdproc-dev/lcdproc.inc index 6c245058..1436c07d 100644 --- a/config/lcdproc-dev/lcdproc.inc +++ b/config/lcdproc-dev/lcdproc.inc @@ -72,35 +72,15 @@ if($post['comport']) { switch($post['comport']) { case "none": - continue; - break; case "com1": - continue; - break; case "com2": - continue; - break; case "com1a": - continue; - break; case "com2a": - continue; - break; case "ucom1": - continue; - break; case "ucom2": - continue; - break; case "lpt1": - continue; - break; case "ugen0.2": - continue; - break; case "ugen1.2": - continue; - break; case "ugen2.2": continue; break; @@ -112,32 +92,14 @@ if($post['size']) { switch($post['size']) { case "12x1": - continue; - break; case "12x2": - continue; - break; case "12x4": - continue; - break; case "16x1": - continue; - break; case "16x2": - continue; - break; case "16x4": - continue; - break; case "20x1": - continue; - break; case "20x2": - continue; - break; case "20x4": - continue; - break; case "40x2": continue; break; @@ -149,23 +111,11 @@ if($post['port_speed']) { switch($post['port_speed']) { case "0": - continue; - break; case "1200": - continue; - break; case "2400": - continue; - break; case "9600": - continue; - break; case "19200": - continue; - break; case "57600": - continue; - break; case "115200": continue; break; @@ -185,6 +135,14 @@ global $g; global $config; global $input_errors; + + # detect boot process + if (is_array($_POST)){ + if (! preg_match("/\w+/",$_POST['__csrf_magic'])) + return; + } + + #continue sync package lcdproc_notice("Sync: Begin package sync"); config_lock(); $lcdproc_config = $config['installedpackages']['lcdproc']['config'][0]; @@ -500,17 +458,18 @@ } /* generate rc file start and stop */ $stop = <<<EOD -if [ `ps auxw |awk '/lcdproc_client.ph[p]/ {print $2}'| wc -l` != 0 ]; then - ps auxw |awk '/lcdproc_client.ph[p]/ {print $2}'|xargs /bin/kill - sleep 1 +if [ `pgrep -f lcdproc_client.ph` ];then + pkill -f lcdproc_client.ph + sleep 1 fi -if [ `ps auxw |awk '/LCD[d]/ {print $2}'| wc -l` != 0 ]; then - ps auxw |awk '/LCD[d]/ {print $2}'|xargs /bin/kill +if [ `pgrep -anx LCDd` ]; then + pkill -anx LCDd sleep 1 fi + EOD; $start = $stop ."\n"; - $start .= "\t/usr/bin/nice -20 /usr/local/sbin/LCDd -c ". LCDPROC_CONFIG ."\n"; + $start .= "\t/usr/bin/nice -20 /usr/local/sbin/LCDd -c ". LCDPROC_CONFIG ." -u nobody\n"; $start .= "\t/usr/bin/nice -20 /usr/local/bin/php -f /usr/local/pkg/lcdproc_client.php &\n"; /* write out the configuration */ conf_mount_rw(); diff --git a/config/lightsquid/lightsquid.inc b/config/lightsquid/lightsquid.inc index 0519c196..0073877c 100644 --- a/config/lightsquid/lightsquid.inc +++ b/config/lightsquid/lightsquid.inc @@ -35,6 +35,16 @@ require_once('filter.inc'); require_once('service-utils.inc'); require_once('squid.inc'); +$pfs_version = substr(trim(file_get_contents("/etc/version")),0,3); +switch ($pfs_version) { + case "1.2": + case "2.0": + define('LIGHTSQUID_BASE','/usr/local'); + break; + default: + define('LIGHTSQUID_BASE', '/usr/pbi/lightsquid-' . php_uname("m")); +} + define ('CMD_PKGDELETE', 'pkg_delete lightsquid-1.7.1'); // enable GUI debug @@ -42,19 +52,26 @@ define('LS_GUI_DEBUG', 'on'); define('LS_LOG_FILE', '/tmp/lightsquid_gui.log'); // configuration settings !-- CHECK THIS --! -define('LS_CONFIGPATH', '/usr/local/etc/lightsquid'); +define('LS_CONFIGPATH', LIGHTSQUID_BASE . '/etc/lightsquid'); define('LS_CONFIGFILE', 'lightsquid.cfg'); define('LS_CONFIGFILE_DIST', 'lightsquid.cfg.dist'); -define('LS_WWWPATH', '/usr/local/www/lightsquid'); -define('LS_TEMPLATEPATH', '/usr/local/www/lightsquid/tpl'); -define('LS_LANGPATH', '/usr/local/share/lightsquid/lang'); +define('LS_WWWPATH', LIGHTSQUID_BASE . '/www/lightsquid'); +define('LS_TEMPLATEPATH', LIGHTSQUID_BASE . '/www/lightsquid/tpl'); +define('LS_LANGPATH', LIGHTSQUID_BASE . '/share/lightsquid/lang'); define('LS_REPORTPATH', '/var/lightsquid/report'); -define('LS_SQUIDLOGPATH', '/var/squid/logs'); + +global $config; +if (isset($config['installedpackages']['squid']['config'][0])) { + if (!empty($config['installedpackages']['squid']['config'][0]['log_dir'])) + define('LS_SQUIDLOGPATH', $config['installedpackages']['squid']['config'][0]['log_dir']); + else + define('LS_SQUIDLOGPATH', '/var/squid/logs'); +} define('LS_SQUIDLOG', 'access.log'); -define('LS_IP2NAMEPATH', '/usr/local/libexec/lightsquid'); +define('LS_IP2NAMEPATH', LIGHTSQUID_BASE . '/libexec/lightsquid'); define('CRONTAB_FILE', '/var/cron/tabs/root'); -define('CRONTAB_LS_TEMPLATE', '/usr/bin/perl /usr/local/www/lightsquid/lightparser.pl'); +define('CRONTAB_LS_TEMPLATE', '/usr/bin/perl ' . LIGHTSQUID_BASE . '/www/lightsquid/lightparser.pl'); define('CRONTAB_LS_JOBKEY', '/lightparser.pl'); define('CRONTAB_SQUID_TEMPLATE', '/usr/local/sbin/squid -k rotate > /dev/null'); define('CRONTAB_SQUID_JOBKEY', '/squid -k rotate'); @@ -138,7 +155,7 @@ function lightsquid_resync() { mwexec("mkdir -p " . LS_REPORTPATH); } - mwexec("/bin/chmod -R u+w /usr/local/etc/lightsquid"); + mwexec("/bin/chmod -R u+w " . LIGHTSQUID_BASE . "/etc/lightsquid"); // debug $light_test = array(); @@ -208,10 +225,10 @@ function lightsquid_resync() { foreach ($lsconf_var as $key => $val) { for($i = 0; $i < count($lsconf); $i++) { $s = trim($lsconf[$i]); - $e_key = "^[$]" . $key . "[ ]*[=]+"; -# update_log("Regular: eregi(\"$e_key," . "'$s')"); // debug regular template - if (eregi($e_key, $s)) { -# update_log("Regular PASSED: eregi(\"$e_key," . "'$s')"); // debug regular template + $e_key = "/^[$]" . $key . "[ ]*[=]+/i"; +# update_log("Regular: preg_match(\"$e_key," . "'$s')"); // debug regular template + if (preg_match($e_key, $s)) { +# update_log("Regular PASSED: preg_match(\"$e_key," . "'$s')"); // debug regular template $lsconf[$i] = '$' . "$key = $val;"; update_log("Update config: $key=$val"); } @@ -258,8 +275,26 @@ function lightsquid_resync() { // update squid conf if (isset($config['installedpackages']['squid']['config'][0])) { - $config['installedpackages']['squid']['config'][0]['log_enabled'] = 'on'; - $config['installedpackages']['squid']['config'][0]['log_dir'] = LS_SQUIDLOGPATH; + $squid_settings = $config['installedpackages']['squid']['config'][0]; + $squid_settings['log_enabled'] = 'on'; + if (empty($squid_settings['log_dir'])) + $squid_settings['log_dir'] = LS_SQUIDLOGPATH; + + # sqstat + $ifmgr = "127.0.0.1;"; + $iface = ($squid_settings['active_interface'] ? $squid_settings['active_interface'] : 'lan'); + $iface = explode(",", $iface); + foreach ($iface as $i => $if) { + $realif = ls_get_real_interface_address($if); + if ($realif[0]) + $ifmgr = $ifmgr . $realif[0] . ";"; + } + + # ? delete ? + $config['installedpackages']['squidcache']['config'][0]['ext_cachemanager'] = $ifmgr; + # now right + $config['installedpackages']['squidnac']['config'][0]['ext_cachemanager'] = $ifmgr; + write_config(); squid_resync(); } @@ -384,4 +419,15 @@ function refresh_full() { update_log("refresh_full: stop"); } +function ls_get_real_interface_address($iface) +{ + global $config; + + $iface = convert_friendly_interface_to_real_interface_name($iface); + $line = trim(shell_exec("ifconfig $iface | grep inet | grep -v inet6")); + list($dummy, $ip, $dummy2, $netmask) = explode(" ", $line); + + return array($ip, long2ip(hexdec($netmask))); +} + ?>
\ No newline at end of file diff --git a/config/lightsquid/lightsquid.xml b/config/lightsquid/lightsquid.xml index cb481943..b8ce2bc8 100644 --- a/config/lightsquid/lightsquid.xml +++ b/config/lightsquid/lightsquid.xml @@ -47,7 +47,7 @@ <faq>Currently there are no FAQ items provided.</faq> <name>lightsquid</name> <version>1.7.1</version> - <title>Services: Proxy server Report(LightSquid) -> Settings</title> + <title>Services: Proxy Reports (LightSquid, SQStat) -> Settings</title> <category>Status</category> <include_file>/usr/local/pkg/lightsquid.inc</include_file> <menu> @@ -66,6 +66,10 @@ <text>Lightsquid Report</text> <url>/lightsquid/index.cgi</url> </tab> + <tab> + <text>Proxy State</text> + <url>/sqstat/sqstat.php</url> + </tab> </tabs> <additional_files_needed> <prefix>/usr/local/pkg/</prefix> @@ -77,6 +81,26 @@ <chmod>0755</chmod> <item>http://files.pfsense.org/packages/All/lightsquid_tpl.tbz</item> </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/sqstat/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.org/packages/config/lightsquid/sqstat.class.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/sqstat/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.org/packages/config/lightsquid/sqstat.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/sqstat/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.org/packages/config/lightsquid/sqstat.css</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/sqstat/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.org/packages/config/lightsquid/zhabascript.js</item> + </additional_files_needed> <fields> <field> <fielddescr>Language</fielddescr> diff --git a/config/lightsquid/sqstat.class.php b/config/lightsquid/sqstat.class.php new file mode 100644 index 00000000..228aecfe --- /dev/null +++ b/config/lightsquid/sqstat.class.php @@ -0,0 +1,582 @@ +<?php +/* $Id$ */ +/* + sqstat.class.php + Squid Proxy Server realtime stat + + (c) Alex Samorukov, samm@os2.kiev.ua + modification by 2011 Serg Dvoriancev, dv_serg@mail.ru + Squid Proxy Server realtime stat + + part of pfSense (www.pfSense.com) + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + 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. +*/ + +// sqstat class +DEFINE('SQSTAT_VERSION', '1.20'); +DEFINE('SQSTAT_SHOWLEN', 60); + +class squidstat{ + var $fp; + + # conection + var $squidhost; + var $squidport; + + # hosts + var $hosts_file; + var $hosts; + + # versions + var $server_version; + var $sqstat_version; + + # other + var $group_by; + var $resolveip; + var $autorefresh; + var $use_sessions = false; + + # cache manager + var $cachemgr_passwd; + + # errors + var $errno; + var $errstr; + + function squidstat(){ + $this->sqstat_version = SQSTAT_VERSION; + + $this->squidhost = '127.0.0.1'; + $this->squidport = '3128'; + + $This->group_by = 'host'; + $this->resolveip = true; + $this->hosts_file = ''; + $this->autorefresh = 0; + $this->cachemgr_passwd = ''; + + $errno = 0; + $errstr = ''; + + if (!function_exists("preg_match")) { $this->errorMsg(5, 'You need to install <a href="http://www.php.net/pcre/" target="_blank">PHP pcre extension</a> to run this script'); + $this->showError(); + exit(5); + } + + // we need session support to gather avg. speed + if (function_exists("session_start")){ + $this->use_sessions=true; + } + + } + + function formatXHTML($body, $refresh, $use_js = false){ + $text='<?xml version="1.0" encoding="UTF-8"?>'."\n". + '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n" + .'<html>' + .'<head>' + .'<link href="sqstat.css" rel="stylesheet" type="text/css"/>'; + if($refresh) $text.='<META HTTP-EQUIV=Refresh CONTENT="'.$refresh.'; URL='.$_SERVER["PHP_SELF"].'?refresh='.$refresh.'&config='.$GLOBALS["config"].'"/>'; + $text.='<title>SqStat '.SQSTAT_VERSION.'</title>' + .($use_js?'<script src="zhabascript.js" type="text/javascript"></script>':'').'</head>' + .($use_js?'<body onload="jsInit();"><div id="dhtmltooltip"></div><img id="dhtmlpointer" src="arrow.gif">':'<body>') + .$body.'</body></html>'; + return $text; + } + + function showError(){ + $text='<h1>SqStat error</h1>'. + '<h2 style="color:red">Error ('.$this->errno.'): '.$this->errstr.'</span>'; + echo $this->formatXHTML($text,0); + } + + function connect($squidhost, $squidport){ + $this->fp = false; + # connecting to the squidhost + $this->fp = @fsockopen($squidhost, $squidport, $this->errno, $this->errstr, 10); + if (!$this->fp) { + # failed to connect + return false; + } + return true; + } + + # based @ (c) moritz at barafranca dot com + function duration ($seconds) { + $takes_time = array(604800,86400,3600,60,0); + $suffixes = array("w","d","h","m","s"); + $output = ""; + foreach ($takes_time as $key=>$val) { + ${$suffixes[$key]} = ($val == 0) ? $seconds : floor(($seconds/$val)); + $seconds -= ${$suffixes[$key]} * $val; + if (${$suffixes[$key]} > 0) { + $output .= ${$suffixes[$key]}; + $output .= $suffixes[$key]." "; + } + } + return trim($output); + } + + /** + * Format a number of bytes into a human readable format. + * Optionally choose the output format and/or force a particular unit + * + * @param int $bytes The number of bytes to format. Must be positive + * @param string $format Optional. The output format for the string + * @param string $force Optional. Force a certain unit. B|KB|MB|GB|TB + * @return string The formatted file size + */ + function filesize_format($bytes, $format = '', $force = '') + { + $force = strtoupper($force); + $defaultFormat = '%01d %s'; + if (strlen($format) == 0) + $format = $defaultFormat; + $bytes = max(0, (int) $bytes); + $units = array('b', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb'); + $power = array_search($force, $units); + if ($power === false) + $power = $bytes > 0 ? floor(log($bytes)/log(1024)) : 0; + return sprintf($format, $bytes / pow(1024, $power), $units[$power]); + } + + function makeQuery($pass = ""){ + $raw = array(); + # sending request + if(!$this->fp) + die("Please connect to server"); + + $out = "GET cache_object://localhost/active_requests HTTP/1.0\r\n"; + if ($pass != "") + $out .= "Authorization: Basic ".base64_encode("cachemgr:$pass")."\r\n"; + $out .= "\r\n"; + + fwrite($this->fp, $out); + + while (!feof($this->fp)) { + $raw[] = trim(fgets($this->fp, 2048)); + } + fclose($this->fp); + + if ($raw[0]!="HTTP/1.0 200 OK") { $this->errorMsg(1, "Cannot get data. Server answered: $raw[0]"); + return false; + } + + # parsing output; + $header = 1; + $connection = 0; + $parsed["server_version"] = "Unknown"; + foreach($raw as $key=>$v){ + # cutoff http header + if ($header==1 && $v=="") $header=0; + if ($header) { + if(substr(strtolower($v),0,7) == "server:") { # parsing server version + $parsed["server_version"] = substr($v,8); + } + } + else { + if(substr($v,0,11) == "Connection:") { # parsing connection + $connection = substr($v,12); + } + if ($connection) { + # username field is avaible in Squid 2.6 stable + if(substr($v,0,9) == "username ") $parsed["con"][$connection]["username"] = substr($v, 9); + if(substr($v,0,5) == "peer:") $parsed["con"][$connection]["peer"] = substr($v, 6); + if(substr($v,0,3) == "me:") $parsed["con"][$connection]["me"] = substr($v, 4); + if(substr($v,0,4) == "uri ") $parsed["con"][$connection]["uri"] = substr($v, 4); + if(substr($v,0,10) == "delay_pool") $parsed["con"][$connection]["delay_pool"] = substr($v, 11); + + if (preg_match('/out.offset \d+, out.size (\d+)/', $v, $matches)) { + $parsed["con"][$connection]["bytes"] = $matches[1]; + } + if (preg_match('/start \d+\.\d+ \((\d+).\d+ seconds ago\)/', $v, $matches)){ + $parsed["con"][$connection]["seconds"] = $matches[1]; + } + } + } + } + return $parsed; + } + + function implode_with_keys($array, $glue) { + foreach ($array as $key => $v){ + $ret[] = $key . '=' . htmlspecialchars($v); + } + return implode($glue, $ret); + } + + function makeHtmlReport($data, $resolveip = false, $hosts_array = array(), $use_js = true) { + global $group_by; + if($this->use_sessions){ + session_name('SQDATA'); + session_start(); + } + + $total_avg = $total_curr = 0; + // resort data array + $users=array(); + switch($group_by){ + case "host": + $group_by_name="Host"; + $group_by_key='return $ip;'; + break; + case "username": + $group_by_name="User"; + $group_by_key='return $v["username"];'; + break; + default: + die("wrong group_by!"); + } + + foreach($data["con"] as $key => $v){ + if(substr($v["uri"],0,13)=="cache_object:") continue; // skip myself + $ip=substr($v["peer"],0,strpos($v["peer"],":")); + if(isset($hosts_array[$ip])){ + $ip=$hosts_array[$ip]; + } + // i use ip2long() to make ip sorting work correctly + elseif($resolveip){ + $hostname=gethostbyaddr($ip); + if($hostname==$ip) $ip=ip2long($ip);// resolve failed + else $ip=$hostname; + } + else{ + $ip=ip2long(substr($v["peer"],0,strpos($v["peer"],":"))); + } + $v['connection'] = $key; + if(!isset($v["username"])) $v["username"]="N/A"; + $users[eval($group_by_key)][]=$v; + } + ksort($users); + $refresh=0; + if(isset($_GET["refresh"]) && !isset($_GET["stop"])) $refresh=(int)$_GET["refresh"]; + $text=''; + if(count($GLOBALS["configs"])==1) $servers=$GLOBALS["squidhost"].':'.$GLOBALS["squidport"]; + else{ + $servers='<select onchange="this.form.submit();" name="config">'; + foreach ($GLOBALS["configs"] as $key=>$v){ + $servers.='<option '.($GLOBALS["config"]==$key?' selected="selected" ':'').' value="'.$key.'">'.htmlspecialchars($v).'</option>'; + } + $servers.='</select>'; + } + $text.='<div class="header"><form method="get" action="'.$_SERVER["PHP_SELF"].'">'. + 'Squid RealTime stat for the '.$servers.' proxy server ('.$data["server_version"].').<br/>'. + 'Auto refresh: <input name="refresh" type="text" size="4" value="'.$refresh.'"/> sec. <input type="submit" value="Update"/> <input name="stop" type="submit" value="Stop"/> Created at: <tt>'.date("h:i:s d/m/Y").'</tt><br/>'. + '</div>'. + '<table class="result" align="center" width="100%" border="0">'. + '<tr>'. + '<th>'.$group_by_name.'</th><th>URI</th>'. + ($this->use_sessions?'<th>Curr. Speed</th><th>Avg. Speed</th>':''). + '<th>Size</th><th>Time</th>'. + '</tr>'; + $ausers=$acon=0; + unset($session_data); + if (isset($_SESSION['time']) && ((time() - $_SESSION['time']) < 3*60) && isset($_SESSION['sqdata']) && is_array($_SESSION['sqdata'])) { + //only if the latest data was less than 3 minutes ago + $session_data = $_SESSION['sqdata']; + } + $table=''; + foreach($users as $key=>$v){ + $ausers++; + $table.='<tr><td style="border-right:0;" colspan="2"><b>'.(is_int($key)?long2ip($key):$key).'</b></td>'. + '<td style="border-left:0;" colspan="5"> </td></tr>'; + $user_avg = $user_curr = $con_color = 0; + foreach ($v as $con){ + if(substr($con["uri"],0,7)=="http://" || substr($con["uri"],0,6)=="ftp://"){ + if(strlen($con["uri"])>SQSTAT_SHOWLEN) $uritext=htmlspecialchars(substr($con["uri"],0,SQSTAT_SHOWLEN)).'</a> ....'; + else $uritext=htmlspecialchars($con["uri"]).'</a>'; + $uri='<a target="_blank" href="'.htmlspecialchars($con["uri"]).'">'.$uritext; + } + else $uri=htmlspecialchars($con["uri"]); + $acon++; + //speed stuff + $con_id = $con['connection']; + $is_time = time(); + $curr_speed=0; + $avg_speed=0; + if (isset($session_data[$con_id]) && $con_data = $session_data[$con_id] ) { + // if we have info about current connection, we do analyze its data + // current speed + $was_time = $con_data['time']; + $was_size = $con_data['size']; + if ($was_time && $was_size) { + $delta = $is_time - $was_time; + if ($delta == 0) { + $delta = 1; + } + if ($con['bytes'] >= $was_size) { + $curr_speed = ($con['bytes'] - $was_size) / 1024 / $delta; + } + } else { + $curr_speed = $con['bytes'] / 1024; + } + + //avg speed + $avg_speed = $con['bytes'] / 1024; + if ($con['seconds'] > 0) { + $avg_speed /= $con['seconds']; + } + } + + $new_data[$con_id]['time'] = $is_time; + $new_data[$con_id]['size'] = $con['bytes']; + + //sum speeds + $total_avg += $avg_speed; + $user_avg += $avg_speed; + $total_curr += $curr_speed; + $user_curr += $curr_speed; + + if($use_js) $js='onMouseout="hideddrivetip()" onMouseover="ddrivetip(\''.$this->implode_with_keys($con,'<br/>').'\')"'; + else $js=''; + $table.='<tr'.( (++$con_color % 2 == 0) ? ' class="odd"' : '' ).'><td id="white"></td>'. + '<td nowrap '.$js.' width="80%" >'.$uri.'</td>'; + if($this->use_sessions){ + $table .= '<td nowrap align="right">'.( (round($curr_speed, 2) > 0) ? sprintf("%01.2f KB/s", $curr_speed) : '' ).'</td>'. + '<td nowrap align="right">'.( (round($avg_speed, 2) > 0) ? sprintf("%01.2f KB/s", $avg_speed) : '' ). '</td>'; + } + $table .= '<td nowrap align="right">'.$this->filesize_format($con["bytes"]).'</td>'. + '<td nowrap align="right">'.$this->duration($con["seconds"],"short").'</td>'. + '</tr>'; + } + if($this->use_sessions){ + $table.=sprintf("<tr><td colspan=\"2\"></td><td align=\"right\" id=\"highlight\">%01.2f KB/s</td><td align=\"right\" id=\"highlight\">%01.2f KB/s</td><td colspan=\"2\"></td>", + $user_curr, $user_avg); + } + + } + $_SESSION['time'] = time(); + if(isset($new_data)) $_SESSION['sqdata'] = $new_data; + $stat_row=''; + if($this->use_sessions){ + $stat_row.=sprintf("<tr class=\"total\"><td><b>Total:</b></td><td align=\"right\" colspan=\"5\"><b>%d</b> users and <b>%d</b> connections @ <b>%01.2f/%01.2f</b> KB/s (CURR/AVG)</td></tr>", + $ausers, $acon, $total_curr, $total_avg); + } + else { + $stat_row.=sprintf("<tr class=\"total\"><td><b>Total:</b></td><td align=\"right\" colspan=\"5\"><b>%d</b> users and <b>%d</b> connections</td></tr>", + $ausers, $acon); + } + if($ausers==0){ + $text.='<tr><td colspan=6><b>No active connections</b></td></tr>'; + } + else { + $text.=$stat_row.$table.$stat_row; + } + $text .= '</table>'. + '<p class="copyleft">© <a href="mailto:samm@os2.kiev.ua?subject=SqStat '.SQSTAT_VERSION.'">Alex Samorukov</a>, 2006</p>'; + return $this->formatXHTML($text,$refresh,$use_js); + } + + function parseRequest($data, $group_by = 'host', $resolveip = false) { $parsed = array(); + if ($this->use_sessions) { + session_name('SQDATA'); + session_start(); + } + + # resort data array + $users = array(); + switch ($group_by) { + case "username": + $group_by_name = "User"; + $group_by_key = "username"; + break; + case "host": + default: + $group_by_name = "Host"; + $group_by_key = "peer"; + break; + } + + # resolve IP & group + foreach ($data["con"] as $key => $v) { # skip myself + if (substr($v["uri"], 0, 13) == "cache_object:") continue; + + $ip = substr($v["peer"], 0, strpos($v["peer"], ":")); + $v["peer"] = $ip; + + # name from hosts + if (isset($this->hosts[$ip])) { + $ip = $this->hosts[$ip]; + } + else + # i use ip2long() to make ip sorting work correctly + if ($resolveip) { + $hostname = gethostbyaddr($ip); + if ($hostname == $ip) + $ip = ip2long($ip); # resolve failed. use (ip2long) key + else $ip = $hostname; + } + else { + $ip = ip2long(substr($v["peer"], 0, strpos($v["peer"], ":"))); + } + $v['con_id'] = $key; + $v["username"] = isset($v["username"]) ? $v["username"] : "N/A"; + + # users [key => conn_array] + $users[$v[$group_by_key]][] = $v; + } + ksort($users); + + unset($session_data); + if (isset($_SESSION['time']) && ((time() - $_SESSION['time']) < 3*60) && + isset($_SESSION['sqdata']) && is_array($_SESSION['sqdata'])) { + # only if the latest data was less than 3 minutes ago + $session_data = $_SESSION['sqdata']; + } + + # users count & con cont + $ausers = $acon = 0; + $total_avg = $total_curr = 0; + foreach ($users as $key => $v) { $ausers++; + + $user_avg = $user_curr = $con_color = 0; + foreach ($v as $con_key => $con){ $cres = array(); + $acon++; + + $uritext = $con["uri"]; + if (substr($con["uri"], 0, 7) == "http://" || substr($con["uri"], 0, 6) == "ftp://") { + if (strlen($uritext) > SQSTAT_SHOWLEN) + $uritext = htmlspecialchars(substr($uritext, 0, SQSTAT_SHOWLEN)) . ' ....'; + } + else $uritext = htmlspecialchars($uritext); + $cres['uritext'] = $uritext; + $cres['uri'] = $con["uri"]; + + # speed stuff + $con_id = $con['connection']; + $is_time = time(); + $curr_speed = $avg_speed = 0; + if (isset($session_data[$con_id]) && $con_data = $session_data[$con_id] ) { + # if we have info about current connection, we do analyze its data + # current speed + $was_time = $con_data['time']; + $was_size = $con_data['size']; + if ($was_time && $was_size) { + $delta = $is_time - $was_time; + if ($delta == 0) { + $delta = 1; + } + if ($con['bytes'] >= $was_size) { + $curr_speed = ($con['bytes'] - $was_size) / 1024 / $delta; + } + } else { + $curr_speed = $con['bytes'] / 1024; + } + + # avg speed + $avg_speed = $con['bytes'] / 1024; + if ($con['seconds'] > 0) { + $avg_speed /= $con['seconds']; + } + } + $cres['cur_speed'] = $curr_speed; + $cres['avg_speed'] = $avg_speed; + $cres['seconds'] = $con["seconds"]; + $cres['bytes'] = $con["bytes"]; + + # groupped parsed[key => conn_key] + $parsed['users'][$key]['con'][$con_key] = $cres; + + # for sessions + $new_data[$con_id]['time'] = $is_time; + $new_data[$con_id]['size'] = $con['bytes']; + + # sum speeds + $total_avg += $avg_speed; + $user_avg += $avg_speed; + $total_curr += $curr_speed; + $user_curr += $curr_speed; + } + + # total per user + $parsed['users'][$key]['user_curr'] = $user_curr; + $parsed['users'][$key]['user_avg'] = $user_avg; + } + + # total info + $parsed['ausers'] = $ausers; + $parsed['acon'] = $acon; + $parsed['total_avg'] = $total_avg; + $parsed['total_curr'] = $total_curr; + + # update session info + $_SESSION['time'] = time(); + if (isset($new_data)) $_SESSION['sqdata'] = $new_data; + + return $parsed; + } + + function errorMsg($errno, $errstr) + { $this->errno = $errno; + $this->errstr = $errstr; + } + + function load_hosts() + { + # loading hosts file + $hosts_array = array(); + + if (!empty($this->hosts_file)) { + if (is_file($this->hosts_file)) { + $handle = @fopen($this->hosts_file, "r"); + if ($handle) { + while (!feof($handle)) { + $buffer = fgets($handle, 4096); + unset($matches); + if (preg_match('/^([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})[ \t]+(.+)$/i', $buffer, $matches)) { + $hosts_array[$matches[1]]=$matches[2]; + } + } + fclose($handle); + } + $this->hosts = $hosts_array; + } + else { + #error + $this->errorMsg(4, "Hosts file not found. Cant read <tt>'{$this->hosts_file}'</tt>."); + return $this->errno; + } + } + + return 0; + } + + function query_exec() + { + $data = ""; + + $this->server_version = '(unknown)'; + if ($this->connect($this->squidhost, $this->squidport)) { + $data = $this->makeQuery($this->cachemgr_passwd); + if ($this->errno == 0) { + $this->server_version = $data['server_version']; + $data = $this->parseRequest($data, 'host', true); + } + } + + return $data; + } + +} +?>
\ No newline at end of file diff --git a/config/lightsquid/sqstat.css b/config/lightsquid/sqstat.css new file mode 100644 index 00000000..7575933e --- /dev/null +++ b/config/lightsquid/sqstat.css @@ -0,0 +1,68 @@ +/* "connections" table */ +TABLE.result{ + border:1px solid #ccccdd;border-collapse:collapse; +} +TABLE.result TH{ + font-family: Verdana;font-size:14px; +} +TABLE.result TD{ + font-family: Verdana;font-size:11px;border:1px solid #c0c0c0;padding:2px; +} +TABLE.result TR.total TD{ + background-color:#DCDAD5; +} + +TABLE.result TH{ + background-color:#ccccdd; + white-space: nowrap; padding: 0px 2px; +} + +TABLE.result tr.odd td { + background-color: #eef; +} +TABLE.result tr.odd td#white { + background-color: #fff; +} +TABLE.result td#highlight { + background-color: #e9e9e9; +} + + +/* top header */ +DIV.header{ + border:3px solid #ccccdd;margin-bottom:10px;padding:3px; + font-family: Verdana;font-size:12pt; +} +.copyleft,SELECT{ + font-family: Verdana;font-size:10px; +} +.copyleft A{ + text-decoration:none +} +.copyleft A:HOVER{ + text-decoration:underline +} +FORM{ + margin:0;padding:0; +} + +#dhtmltooltip{ + position: absolute; + /* width: 350px; */ + border: 2px solid black; + padding: 2px; + background-color: lightyellow; + visibility: hidden; + z-index: 100; + font-family: Verdana; font-size: 10px; +} + + +#dhtmlpointer{ + position:absolute; + left: -300px; + z-index: 101; + visibility: hidden; +} + + diff --git a/config/lightsquid/sqstat.php b/config/lightsquid/sqstat.php new file mode 100644 index 00000000..a56b604a --- /dev/null +++ b/config/lightsquid/sqstat.php @@ -0,0 +1,417 @@ +<?php +/* $Id$ */ +/* + sqstat.php + Squid Proxy Server realtime stat + + (c) Alex Samorukov, samm@os2.kiev.ua + modification by 2011 Serg Dvoriancev, dv_serg@mail.ru + + part of pfSense (www.pfSense.com) + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + 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. +*/ + +/* +*** sqstat - Squid Proxy Server realtime stat *** +(c) Alex Samorukov, samm@os2.kiev.ua +*/ + +require_once('guiconfig.inc'); +require_once('sqstat.class.php'); + +# init +$squidclass = new squidstat(); + +# ------------------------------------------------------------------------------ +# Requests +# ------------------------------------------------------------------------------ + +# AJAX responce +if ($_REQUEST['getactivity']) +{ + header("Content-type: text/javascript"); + echo sqstat_AJAX_response( $_REQUEST ); + exit; +} + +# ------------------------------------------------------------------------------ +# HTML Page +# ------------------------------------------------------------------------------ + +$pgtitle = "Proxy Squid: Realtime stat (sqstat)"; + +require_once("head.inc"); + +?> + +<link href="sqstat.css" rel="stylesheet" type="text/css"/> +<script type="text/javascript" src="/javascript/scriptaculous/prototype.js"></script> +<script type="text/javascript" src="zhabascript.js"></script> + +<!-- Ajax Script --> +<script type="text/javascript"> + +var intervalID = 0; + +function el(id) { + return document.getElementById(id); +} + +function getactivity(action) { + var url = "<?php echo ($_SERVER["PHP_SELF"]); ?>"; + var pars = "getactivity=yes"; + + var myAjax = new Ajax.Request( url, + { + method: 'post', + parameters: pars, + onComplete: activitycallback + }); +} + +function activitycallback(transport) { + + if (200 == transport.status) { + result = transport.responseText; + } +} + +function update_start() { + var cmax = parseInt(el('refresh').value); + + update_stop(); + + if (cmax > 0) { + intervalID = window.setInterval('getactivity();', cmax * 1000); + } +} + +function update_stop() { + window.clearInterval(intervalID); + intervalID = 0; +} + +// pre-call +window.setTimeout('update_start()', 150); + +</script> + +<!-- HTML --> + +<!-- begin --> +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> +<?php include("fbegin.inc"); ?> + +<?php + # prepare page data + $data = ''; + sqstat_loadconfig(); + if (sqstat_loadconfig() == 0) { + $data = $squidclass->query_exec(); + } + + if ($squidclass->errno == 0) { + $data = sqstat_resultHTML($data); + } + else { + # error + $data = sqstat_errorHTML(); + } +?> + +<!-- form --> +<div id="sqstat_header" class="header" > + <?php echo ( sqstat_headerHTML() ); ?> +</div> + +<!-- result table --> +<div id="sqstat_result" class="result"> + <?php echo ($data); ?> +</div> + +<!-- end --> +<?php include("fend.inc"); ?> +</body> +</html> + +<?php + +# ------------------------------------------------------------------------------ +# Functions +# ------------------------------------------------------------------------------ + +function sqstat_AJAX_response( $request ) +{ + global $squidclass, $data; + $res = ''; + + if (sqstat_loadconfig() != 0) { + return sqstat_AJAX_error(sqstat_errorHTML()); + } + + # Actions + $data = $squidclass->query_exec(); + + $ver = sqstat_serverInfoHTML(); + $res .= "el('sqstat_serverver').innerHTML = '$ver';"; + + $time = date("h:i:s d/m/Y"); + $res .= "el('sqstat_updtime').innerHTML = '$time';"; + + $data = sqstat_resultHTML( $data ); + if ($squidclass->errno == 0) { + $data = sqstat_AJAX_prep($data); + $res .= "el('sqstat_result').innerHTML = '$data';"; + } + else { + # error + $res .= sqstat_AJAX_error(sqstat_errorHTML()); + } + + return $res; +} + +function sqstat_AJAX_prep($text) +{ + $text = str_replace("'", "\'", $text); + $text = str_replace("\n", "\\r\\n", $text); + return $text; +} + +function sqstat_AJAX_error($err) +{ + $err = sqstat_AJAX_prep($err); + $t .= "el('sqstat_result').innerHTML = '$err';"; + return $t; +} + +# ------------------------------------------------------------------------------ +# Reports +# ------------------------------------------------------------------------------ + +function sqstat_headerHTML() +{ + global $squidclass; + + $date = date("h:i:s d/m/Y"); + $squidinfo = sqstat_serverInfoHTML(); + + if (empty($squidclass->autorefresh)) $squidclass->autorefresh = 0; + + return +<<<EOD + <form method="get" action="{$_SERVER["PHP_SELF"]}"> + <input id="counter" name="counter" type="hidden" value=0/> + Squid RealTime stat {$squidclass->sqstat_version} for the {$servers} proxy server <a id='sqstat_serverver'>{$squidinfo}</a>.<br/> + Auto refresh: + <input id="refresh" name="refresh" type="text" size="4" value="{$squidclass->autorefresh}"/> sec. + <input type="button" value="Update" onclick="update_start();"/> + <input type="button" value="Stop" onclick="update_stop();"/> Created at: <tt id='sqstat_updtime'>{$date}</tt><br/> + </form> +EOD; +} + +function sqstat_serverInfoHTML() +{ + global $squidclass; + return $squidclass->server_version . " ({$squidclass->squidhost}:{$squidclass->squidport})"; +} + +function sqstat_resultHTML($data) +{ + global $squidclass; + + $group_by_name = $squidclass->group_by_name; + $use_js = true; + + $t = array(); + + # table header + $t[] = "<table class='result' align='center' width='100%' border='0'>"; + $t[] = "<tr>"; + $t[] = "<th>{$group_by_name}</th><th>URI</th>"; + if ($squidclass->use_sessions) + $t[] = "<th>Curr. Speed</th><th>Avg. Speed</th>"; + $t[] = "<th>Size</th><th>Time</th>"; + $t[] = "</tr>"; + + # table body + if (is_array($data['users'])) { + $tbl = array(); + + $con_color = 0; + foreach($data['users'] as $key => $v) { + # skeep total info + if ($key == 'total') continue; + # group row + $tbl[] = "<tr>"; + $tbl[] = "<td style='border-right:0;' colspan='2'><b>" . (is_int($key) ? long2ip($key) : $key) . "</b></td>"; + $tbl[] = "<td style='border-left:0;' colspan='5'> </td>"; + $tbl[] = "</tr>"; + + # connections row + foreach ($v['con'] as $con) { + if ($use_js) + $js = "onMouseout='hideddrivetip()' onMouseover='ddrivetip(\"" . $squidclass->implode_with_keys($con,"<br/>") . "\")'"; + else $js=''; + + # begin new row + $class = (++$con_color % 2 == 0) ? " class='odd'" : ""; + $tbl[] = "<tr ($class)>"; + + # URL + $uri = "<a target='_blank' href='" . htmlspecialchars($con["uri"]) ."'>{$con['uritext']}</a>"; + $tbl[] = "<td id='white'></td>"; + $tbl[] = "<td nowrap {$js} width='80%'>{$uri}</td>"; + + # speed + if ($squidclass->use_sessions) { + $cur_s = round($con['cur_speed'], 2) > 0 ? sprintf("%01.2f KB/s", $con['cur_speed']) : ''; + $avg_s = round($con['avg_speed'], 2) > 0 ? sprintf("%01.2f KB/s", $con['avg_speed']) : ''; + $tbl[] = "<td nowrap align='right'>{$cur_s}</td>"; + $tbl[] = "<td nowrap align='right'>{$avg_s}</td>"; + } + + # file size + $filesize = $squidclass->filesize_format($con["bytes"]); + $duration = $squidclass->duration($con["seconds"], "short"); + $tbl[] = "<td nowrap align='right'>{$filesize}</td>"; + $tbl[] = "<td nowrap align='right'>{$duration}</td>"; + + # end row + $tbl[] = "</tr>"; + } + + # total user speed + if ($squidclass->use_sessions) { + $user_curr = sprintf("%01.2f KB/s", $v['user_curr']); + $user_avg = sprintf("%01.2f KB/s", $v['user_avg']); + $tbl[] ="<tr>"; + $tbl[] ="<td colspan='2'></td>"; + $tbl[] ="<td align='right' id='highlight'>{$user_curr}</td>"; + $tbl[] ="<td align='right' id='highlight'>{$user_avg}</td>"; + $tbl[] ="<td colspan='2'></td>"; + } + } + + + # status row + $stat = array(); + $ausers = sprintf("%d", $data['ausers']); + $acon = sprintf("%d", $data['acon']); + $stat[] = "<tr class='total'><td><b>Total:</b></td>"; + if ($squidclass->use_sessions) { + $total_curr = sprintf("%01.2f", $data['total_curr']); + $total_avg = sprintf("%01.2f", $data['total_avg']); + $stat[] = "<td align='right' colspan='5'><b>{$ausers}</b> users and <b>{$acon}</b> connections @ <b>{$total_curr}/{$total_avg}</b> KB/s (CURR/AVG)</td>"; + } + else { + $stat[] = "<td align='right' colspan='5'><b>{$ausers}</b> users and <b>{$acon}</b> connections</td>"; + } + $t[] = "</tr>"; + } + + if ($ausers == 0) { + $t[] = "<tr><td colspan=6><b>No active connections</b></td></tr>"; + } + else { + $stat = implode("\n", $stat); + $tbl = implode("\n", $tbl); + $t[] = $stat . $tbl . $stat; + } + + $t[] = "</table>"; + $t[] = "<p class='copyleft'>Report based on SQStat © <a href='mailto:samm@os2.kiev.ua?subject=SqStat '" . SQSTAT_VERSION . "'>Alex Samorukov</a>, 2006</p>"; + + return implode("\n", $t); +} + +function sqstat_errorHTML() +{ + global $squidclass; + $t = array(); + + # table header + $t[] = "<table class='result' align='center' width='100%' border='0'>"; + $t[] = "<tr><th align='left'>SqStat error</th></tr>"; + $t[] = "<tr><td>"; + $t[] = '<p style="color:red">Error (' . $squidclass->errno . '): ' . $squidclass->errstr . '</p>'; + $t[] = "</td></tr>"; + $t[] = "</table>"; + + return implode ("\n", $t); +} + +function sqstat_loadconfig() +{ + global $squidclass, $config; + + $squidclass->errno = 0; + $squidclass->errstr = ''; + + $squidclass->sqstat_version = SQSTAT_VERSION; + + # === load config from pfSense === + $iface = '127.0.0.1'; + $iport = 3128; + $squid_settings = $config['installedpackages']['squid']['config'][0]; + if (!empty($squid_settings)) { + # squid interface IP & port + $realif = array(); + $iface = ($squid_settings['active_interface'] ? $squid_settings['active_interface'] : 'lan'); + $iface = explode(",", $iface); + foreach ($iface as $i => $if) { + $realif[] = sqstat_get_real_interface_address($if); + $iface = $realif[$i][0] ? $realif[$i][0] : '127.0.0.1'; + } + $iport = $squid_settings['proxy_port'] ? $squid_settings['proxy_port'] : 3128; + } + $squidclass->squidhost = $iface; + $squidclass->squidport = $iport; + + $squidclass->group_by = "host"; + $squidclass->resolveip = true; + $squidclass->hosts_file = ''; # hosts file not used + $squidclass->autorefresh = 3; # refresh 3 sec by default + $squidclass->cachemgr_passwd = ''; + + # load hosts file, if defined + if (!empty($squidclass->hosts_file)) { + $squidclass->load_hosts(); + } + + return $squidclass->errno; +} + +function sqstat_get_real_interface_address($iface) +{ + global $config; + + $iface = convert_friendly_interface_to_real_interface_name($iface); + $line = trim(shell_exec("ifconfig $iface | grep inet | grep -v inet6")); + list($dummy, $ip, $dummy2, $netmask) = explode(" ", $line); + + return array($ip, long2ip(hexdec($netmask))); +} + +?>
\ No newline at end of file diff --git a/config/lightsquid/zhabascript.js b/config/lightsquid/zhabascript.js new file mode 100644 index 00000000..311e5fe9 --- /dev/null +++ b/config/lightsquid/zhabascript.js @@ -0,0 +1,118 @@ +/*********************************************** +* Cool DHTML tooltip script- © Dynamic Drive DHTML code library (www.dynamicdrive.com) +* This notice MUST stay intact for legal use +* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code +***********************************************/ + +var offsetxpoint=-60 //Customize x offset of tooltip +var offsetypoint=20 //Customize y offset of tooltip +var ie=document.all +var ns6=document.getElementById && !document.all +var enabletip=false +var tipobj=false; + +function jsInit(){ + + if (ie||ns6) + tipobj=document.all? document.all["dhtmltooltip"] : document.getElementById? document.getElementById("dhtmltooltip") : "" + //alert(tipobj); +} + +/*********************************************** +* Cool DHTML tooltip script II- © Dynamic Drive DHTML code library (www.dynamicdrive.com) +* This notice MUST stay intact for legal use +* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code +***********************************************/ + +var offsetfromcursorX=12 //Customize x offset of tooltip +var offsetfromcursorY=10 //Customize y offset of tooltip + +var offsetdivfrompointerX=10 //Customize x offset of tooltip DIV relative to pointer image +var offsetdivfrompointerY=14 //Customize y offset of tooltip DIV relative to pointer image. Tip: Set it to (height_of_pointer_image-1). + +//document.write('<div id="dhtmltooltip"></div>') //write out tooltip DIV +document.write('<img id="dhtmlpointer" src="arrow.gif">') //write out pointer image + +var ie=document.all +var ns6=document.getElementById && !document.all +var enabletip=false +if (ie||ns6) + var tipobj=document.all? document.all["dhtmltooltip"] : document.getElementById? document.getElementById("dhtmltooltip") : "" + +var pointerobj=document.all? document.all["dhtmlpointer"] : document.getElementById? document.getElementById("dhtmlpointer") : "" + +function ietruebody(){ + return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body +} + +function ddrivetip(thetext, thewidth, thecolor){ + if(!tipobj) return false; + if (ns6||ie){ + if (typeof thewidth!="undefined") tipobj.style.width=thewidth+"px" + if (typeof thecolor!="undefined" && thecolor!="") tipobj.style.backgroundColor=thecolor + tipobj.innerHTML=thetext + enabletip=true + return false + } +} + +function positiontip(e){ + if (enabletip){ + var nondefaultpos=false + var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft; + var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop; + //Find out how close the mouse is to the corner of the window + var winwidth=ie&&!window.opera? ietruebody().clientWidth : window.innerWidth-20 + var winheight=ie&&!window.opera? ietruebody().clientHeight : window.innerHeight-20 + + var rightedge=ie&&!window.opera? winwidth-event.clientX-offsetfromcursorX : winwidth-e.clientX-offsetfromcursorX + var bottomedge=ie&&!window.opera? winheight-event.clientY-offsetfromcursorY : winheight-e.clientY-offsetfromcursorY + + var leftedge=(offsetfromcursorX<0)? offsetfromcursorX*(-1) : -1000 + + //if the horizontal distance isn't enough to accomodate the width of the context menu +/* if (rightedge<tipobj.offsetWidth){ + //move the horizontal position of the menu to the left by it's width + tipobj.style.left=curX-tipobj.offsetWidth+"px" + nondefaultpos=true + alert(1); + } + else */ + if (curX<leftedge) + tipobj.style.left="5px" + else{ + //position the horizontal position of the menu where the mouse is positioned + tipobj.style.left=curX+offsetfromcursorX-offsetdivfrompointerX+"px" + pointerobj.style.left=curX+offsetfromcursorX+"px" + } + + //same concept with the vertical position + if (bottomedge<tipobj.offsetHeight){ + tipobj.style.top=curY-tipobj.offsetHeight-offsetfromcursorY+"px" + nondefaultpos=true + } + else{ + tipobj.style.top=curY+offsetfromcursorY+offsetdivfrompointerY+"px" + pointerobj.style.top=curY+offsetfromcursorY+"px" + } + tipobj.style.visibility="visible" + if (!nondefaultpos) + pointerobj.style.visibility="visible" + else + pointerobj.style.visibility="hidden" + } +} + +function hideddrivetip(){ + if (ns6||ie){ + enabletip=false + tipobj.style.visibility="hidden" + pointerobj.style.visibility="hidden" + tipobj.style.left="-1000px" + tipobj.style.backgroundColor='' + tipobj.style.width='' + } +} + +document.onmousemove=positiontip + diff --git a/config/mailreport/mail_reports.inc b/config/mailreport/mail_reports.inc index 48fbc868..8ab31301 100644 --- a/config/mailreport/mail_reports.inc +++ b/config/mailreport/mail_reports.inc @@ -213,6 +213,7 @@ function mail_report_generate_graph($database, $style, $graph, $start, $end) { require_once("filter.inc"); require_once("shaper.inc"); require_once("rrd.inc"); + global $g; $pgtitle = array(gettext("System"),gettext("RRD Graphs"),gettext("Image viewer")); diff --git a/config/mailscanner/mailscanner.conf.template b/config/mailscanner/mailscanner.conf.template new file mode 100644 index 00000000..06090be3 --- /dev/null +++ b/config/mailscanner/mailscanner.conf.template @@ -0,0 +1,493 @@ +<?php +#create MailScanner.conf +$mc=<<<EOF +{$info} +# Configuration directory containing this file +%etc-dir% = /usr/local/etc/MailScanner + +# Set the directory containing all the reports in the required language +%report-dir% = /usr/local/share/MailScanner/reports/{$report_language} + +# Rulesets directory containing your ".rules" files +%rules-dir% = /usr/local/etc/MailScanner/rules + +# Configuration directory containing files related to MCP +# (Message Content Protection) +%mcp-dir% = /usr/local/etc/MailScanner/mcp + +# +# System settings +# --------------- +# +Max Children = {$max_children} +Run As User = postfix +Run As Group = postfix +Queue Scan Interval = 6 +Incoming Queue Dir = /var/spool/postfix/hold +Outgoing Queue Dir = /var/spool/postfix/incoming +Incoming Work Dir = /var/spool/MailScanner/incoming +Quarantine Dir = /var/spool/MailScanner/quarantine +PID file = /var/run/MailScanner.pid +Restart Every = 14400 +MTA = postfix +Sendmail = /usr/local/sbin/sendmail + +# +# Incoming Work Dir Settings +# -------------------------- +# +Incoming Work User = postix +Incoming Work Group = postix +Incoming Work Permissions = 0600 + +# +# Quarantine and Archive Settings +# ------------------------------- +# +Quarantine User = postifx +Quarantine Group = postfix +Quarantine Permissions = 0600 + +# +# Processing Incoming Mail +# ------------------------ +# +Max Unscanned Bytes Per Scan = 100m +Max Unsafe Bytes Per Scan = 50m +Max Unscanned Messages Per Scan = 30 +Max Unsafe Messages Per Scan = 30 +Max Normal Queue Size = 800 +Scan Messages = {$scan_messages} +Reject Message = {$reject_message} +Maximum Processing Attempts = 10 +Processing Attempts Database = /var/spool/MailScanner/incoming/Processing.db +Maximum Attachments Per Message = 200 +Expand TNEF = {$expand_tnef} +Deliver Unparsable TNEF = {$deliver_tnef} +Use TNEF Contents = {$attachments['tnef_contents']} +TNEF Expander = /usr/local/bin/tnef --maxsize=100000000 +TNEF Timeout = 120 +File Command = /usr/bin/file +File Timeout = 20 +Gunzip Command = /usr/bin/gunzip +Gunzip Timeout = 50 +Unrar Command = /usr/local/bin/unrar +Unrar Timeout = 50 +Find UU-Encoded Files = no +Maximum Message Size = %rules-dir%/max.message.size.rules +Maximum Attachment Size ={$max_size} +Minimum Attachment Size = -1 +Maximum Archive Depth = {$archive_depth} +Find Archives By Content ={$find_archive} +Unpack Microsoft Documents = {$microsoft} +Zip Attachments = {$zip_attachments} +Attachments Zip Filename = {$zip_file} +Attachments Min Total Size To Zip = 100k +Attachment Extensions Not To Zip = {$zip_exclude} +Add Text Of Doc = no +Antiword = /usr/bin/antiword -f +Antiword Timeout = 50 +Unzip Maximum Files Per Archive = {$unzip_max_per_archive} +Unzip Maximum File Size = {$unzip_max} +Unzip Filenames = *.txt *.ini *.log *.csv +Unzip MimeType = text/plain + +# +# Virus Scanning and Vulnerability Testing +# ---------------------------------------- +# +Virus Scanning = {$virus_scanning} +Virus Scanners = {$antivirus['virus_scanner']} +Virus Scanner Timeout = {$antivirus_timeout} +Deliver Disinfected Files = {$deliver_disinfected} +Silent Viruses = {$silent_viruses} +Still Deliver Silent Viruses = {$deliver_silent} +Non-Forging Viruses = Joke/ OF97/ WM97/ W97M/ eicar +Spam-Virus Header = {$spam_virus_header} +Virus Names Which Are Spam = Sane*UNOFFICIAL HTML/* *Phish* +Block Encrypted Messages = {$block_encrypted} +Block Unencrypted Messages = {$block_unencrypted} +Allow Password-Protected Archives = {$allow_password} +Check Filenames In Password-Protected Archives = {$check_filenames} +Monitors for ClamAV Updates = /var/db/clamav/*.cvd +ClamAVmodule Maximum Recursion Level = 8 +ClamAVmodule Maximum Files = 1000 +ClamAVmodule Maximum File Size = 10000000 # (10 Mbytes) +ClamAVmodule Maximum Compression Ratio = 25 +Allowed Sophos Error Messages = +Sophos IDE Dir = /opt/sophos-av/lib/sav +Sophos Lib Dir = /opt/sophos-av/lib +Monitors For Sophos Updates = /opt/sophos-av/lib/sav/*.ide +Clamd Port = 3310 +Clamd Socket = /var/run/clamav/clamd.sock +Clamd Lock File = # /var/lock/subsys/clamd +Clamd Use Threads = no +ClamAV Full Message Scan = yes +Fpscand Port = 10200 +{$custom_antivirus_options} + +# +# Removing/Logging dangerous or potentially offensive content +# ----------------------------------------------------------- +# +Dangerous Content Scanning = {$dangerous_content} +Allow Partial Messages = {$partial_messages} +Allow External Message Bodies = {$external_bodies} +Find Phishing Fraud = {$phishing_fraud} +Also Find Numeric Phishing = {$numeric_phishig} +Use Stricter Phishing Net = ${stricter_phishing_net} +Highlight Phishing Fraud = ${highlight_phishing} +Phishing Safe Sites File = %etc-dir%/phishing.safe.sites.conf +Phishing Bad Sites File = %etc-dir%/phishing.bad.sites.conf +Country Sub-Domains List = %etc-dir%/country.domains.conf +Allow IFrame Tags = {$content['iframe_tags']} +Allow Form Tags = {$content['form_tags']} +Allow Script Tags = {$content['script_tags']} +Allow WebBugs = {$content['web_bugs']} +Ignored Web Bug Filenames = spacer pixel.gif pixel.png gap shim +Known Web Bug Servers = msgtag.com +Web Bug Replacement = http://www.mailscanner.tv/1x1spacer.gif +Allow Object Codebase Tags = {$content['codebase_tags']} +Convert Dangerous HTML To Text = {$dangerous_html} +Convert HTML To Text = {$html_to_text} + +# +# Attachment Filename Checking +# ---------------------------- +# +Archives Are = zip rar ole +Allow Filenames = +Deny Filenames = +Filename Rules = %etc-dir%/filename.rules.conf +Allow Filetypes = +Allow File MIME Types = +Deny Filetypes = +Deny File MIME Types = +Filetype Rules = %etc-dir%/filetype.rules.conf +Archives: Allow Filenames = +Archives: Deny Filenames = +Archives: Filename Rules = %etc-dir%/archives.filename.rules.conf +Archives: Allow Filetypes = +Archives: Allow File MIME Types = +Archives: Deny Filetypes = +Archives: Deny File MIME Types = +Archives: Filetype Rules = %etc-dir%/archives.filetype.rules.conf +Default Rename Pattern = __FILENAME__.disarmed + +# +# Reports and Responses +# --------------------- +# +Quarantine Infections = {$quarantine_infections} +Quarantine Silent Viruses = {$quarantine_silent_virus} +Quarantine Modified Body = {$quarantine_modified_body} +Quarantine Whole Message = {$quarantine_whole_message} +Quarantine Whole Messages As Queue Files = {$quarantine_whole_message_as_queue} +Keep Spam And MCP Archive Clean = {$keep_spam_and_mcp} +Language Strings = %report-dir%/languages.conf +Rejection Report = %report-dir%/rejection.report.txt +Deleted Bad Content Message Report = %report-dir%/deleted.content.message.txt +Deleted Bad Filename Message Report = %report-dir%/deleted.filename.message.txt +Deleted Virus Message Report = %report-dir%/deleted.virus.message.txt +Deleted Size Message Report = %report-dir%/deleted.size.message.txt +Stored Bad Content Message Report = %report-dir%/stored.content.message.txt +Stored Bad Filename Message Report = %report-dir%/stored.filename.message.txt +Stored Virus Message Report = %report-dir%/stored.virus.message.txt +Stored Size Message Report = %report-dir%/stored.size.message.txt +Disinfected Report = %report-dir%/disinfected.report.txt +Inline HTML Signature = %report-dir%/inline.sig.html +Inline Text Signature = %report-dir%/inline.sig.txt +Signature Image Filename = %report-dir%/sig.jpg +Signature Image <img> Filename = signature.jpg +Inline HTML Warning = %report-dir%/inline.warning.html +Inline Text Warning = %report-dir%/inline.warning.txt +Sender Content Report = %report-dir%/sender.content.report.txt +Sender Error Report = %report-dir%/sender.error.report.txt +Sender Bad Filename Report = %report-dir%/sender.filename.report.txt +Sender Virus Report = %report-dir%/sender.virus.report.txt +Sender Size Report = %report-dir%/sender.size.report.txt +Hide Incoming Work Dir = {$hide_incoming_work_dir} +Include Scanner Name In Reports = {$include_scanner_name} +# +# Changes to Message Headers +# -------------------------- +# +Mail Header = X-%org-name%-MailScanner: +Spam Header = X-%org-name%-MailScanner-SpamCheck: +Spam Score Header = X-%org-name%-MailScanner-SpamScore: +Information Header = X-%org-name%-MailScanner-Information: +Add Envelope From Header = yes +Add Envelope To Header = no +Envelope From Header = X-%org-name%-MailScanner-From: +Envelope To Header = X-%org-name%-MailScanner-To: +ID Header = X-%org-name%-MailScanner-ID: +IP Protocol Version Header = # X-%org-name%-MailScanner-IP-Protocol: +Spam Score Character = s +SpamScore Number Instead Of Stars = no +Minimum Stars If On Spam List = 0 +Clean Header Value = Found to be clean +Infected Header Value = Found to be infected +Disinfected Header Value = Disinfected +Information Header Value = Please contact the ISP for more information +Detailed Spam Report = yes +Include Scores In SpamAssassin Report = yes +Always Include SpamAssassin Report = no +Multiple Headers = append +Place New Headers At Top Of Message = no +Hostname = the %org-name% ($HOSTNAME) MailScanner +Sign Messages Already Processed = no +Sign Clean Messages = yes +Attach Image To Signature = no +Attach Image To HTML Message Only = yes +Allow Multiple HTML Signatures = no +Dont Sign HTML If Headers Exist = # In-Reply-To: References: +Mark Infected Messages = yes +Mark Unscanned Messages = yes +Unscanned Header Value = Not scanned: please contact your Internet E-Mail Service Provider for details +Remove These Headers = X-Mozilla-Status: X-Mozilla-Status2: +Deliver Cleaned Messages = yes + +# +# Notifications back to the senders of blocked messages +# ----------------------------------------------------- +# +Notify Senders = {$notify_sender} +Notify Senders Of Viruses = {$notify_sender_viruses} +Notify Senders Of Blocked Filenames Or Filetypes = {$notify_sender_fileytypes} +Notify Senders Of Blocked Size Attachments = {$notify_sender_attachments} +Notify Senders Of Other Blocked Content = {$notify_sender_contents} +Never Notify Senders Of Precedence = list bulk + +# +# Changes to the Subject: line +# ---------------------------- +# +Scanned Modify Subject = no # end +Scanned Subject Text = [Scanned] +Virus Modify Subject = start +Virus Subject Text = [Virus?] +Filename Modify Subject = start +Filename Subject Text = [Filename?] +Content Modify Subject = start +Content Subject Text = [Dangerous Content?] +Size Modify Subject = start +Size Subject Text = [Size] +Disarmed Modify Subject = start +Disarmed Subject Text = [Disarmed] +Phishing Modify Subject = no +Phishing Subject Text = [Fraude?] +Spam Modify Subject = start +Spam Subject Text = [Spam?] +High Scoring Spam Modify Subject = start +High Scoring Spam Subject Text = [Spam?] + +# +# Changes to the Message Body +# --------------------------- +# +Warning Is Attachment = yes +Attachment Warning Filename = %org-name%-Attachment-Warning.txt +Attachment Encoding Charset = ISO-8859-1 + +# +# Mail Archiving and Monitoring +# ----------------------------- +# +Archive Mail = +Missing Mail Archive Is = directory + +# +# Notices to System Administrators +# -------------------------------- +# +Send Notices = {$send_notices} +Notices Include Full Headers = {$notices_include_header} +Hide Incoming Work Dir in Notices = {$hide_incoming_work_dir_notices} +Notice Signature = {$notice_signature} +Notices From = ${$notice_from} +Notices To = ${$notice_to} +Local Postmaster = postmaster + +# +# Spam Detection and Virus Scanner Definitions +# -------------------------------------------- +# +Spam List Definitions = %etc-dir%/spam.lists.conf +Virus Scanner Definitions = %etc-dir%/virus.scanners.conf + +# +# Spam Detection and Spam Lists (DNS blocklists) +# ---------------------------------------------- +# + +Spam Checks = yes +Spam List = # spamhaus-ZEN # You can un-comment this to enable them +Spam Domain List = +Spam Lists To Be Spam = 1 +Spam Lists To Reach High Score = 3 +Spam List Timeout = 10 +Max Spam List Timeouts = 7 +Spam List Timeouts History = 10 +Is Definitely Not Spam = %rules-dir%/spam.whitelist.rules +Is Definitely Spam = no +Definite Spam Is High Scoring = no +Ignore Spam Whitelist If Recipients Exceed = 20 +Max Spam Check Size = 200k + +# +# Watermarking +# ------------ +# +Use Watermarking = no +Add Watermark = yes +Check Watermarks With No Sender = yes +Treat Invalid Watermarks With No Sender as Spam = nothing +Check Watermarks To Skip Spam Checks = yes +Watermark Secret = %org-name%-Secret +Watermark Lifetime = 604800 +Watermark Header = X-%org-name%-MailScanner-Watermark: + +# +# SpamAssassin +# ------------ +# + +Use SpamAssassin = {$use_sa} +Max SpamAssassin Size = {$sa_max} +Required SpamAssassin Score = {$sa_score} +High SpamAssassin Score = {$hi_score} +SpamAssassin Auto Whitelist = {$sa_auto_whitelist} +SpamAssassin Timeout = 75 +Max SpamAssassin Timeouts = 10 +SpamAssassin Timeouts History = 30 +Check SpamAssassin If On Spam List = {$check_sa_if_on_spam_list} +Include Binary Attachments In SpamAssassin = {$include_sa_bin_attachments} +Spam Score = {$spam_score} +Cache SpamAssassin Results = {$cache_spamassassin_results} +SpamAssassin Cache Database File = /var/spool/MailScanner/incoming/SpamAssassin.cache.db +Rebuild Bayes Every = {$rebuild_bayes} +Wait During Bayes Rebuild = {$wait_during_bayes_rebuild} + +# +# Custom Spam Scanner Plugin +# -------------------------- +# +Use Custom Spam Scanner = no +Max Custom Spam Scanner Size = 20k +Custom Spam Scanner Timeout = 20 +Max Custom Spam Scanner Timeouts = 10 +Custom Spam Scanner Timeout History = 20 + +# +# What to do with spam +# -------------------- +# + +Spam Actions = {$spam_actions} header "X-Spam-Status: Yes" +High Scoring Spam Actions = {$hispam_actions} header "X-Spam-Status: Yes" +Non Spam Actions = deliver header "X-Spam-Status: No" +SpamAssassin Rule Actions = +Sender Spam Report = %report-dir%/sender.spam.report.txt +Sender Spam List Report = %report-dir%/sender.spam.rbl.report.txt +Sender SpamAssassin Report = %report-dir%/sender.spam.sa.report.txt +Inline Spam Warning = %report-dir%/inline.spam.warning.txt +Recipient Spam Report = %report-dir%/recipient.spam.report.txt +Enable Spam Bounce = %rules-dir%/bounce.rules +Bounce Spam As Attachment = no +# +# Logging +# ------- +# +Syslog Facility = {$syslog_facility} +Log Speed = {$log_speed} +Log Spam = {$log_spam} +Log Non Spam = {$log_non_spam} +Log Delivery And Non-Delivery = {$log_delivery} +Log Permitted Filenames = {$log_filenames} +Log Permitted Filetypes = {$log_filetypes} +Log Permitted File MIME Types = {$log_mime} +Log Silent Viruses = {$log_silent} +Log Dangerous HTML Tags = {$log_dangerous} +Log SpamAssassin Rule Actions = {$log_sa_rule_action} + +# +# Advanced SpamAssassin Settings +# ------------------------------ +# +SpamAssassin Temporary Dir = /var/spool/MailScanner/incoming/SpamAssassin-Temp +SpamAssassin User State Dir = +SpamAssassin Install Prefix = +SpamAssassin Site Rules Dir = /usr/local/etc/mail/spamassassin +SpamAssassin Local Rules Dir = +SpamAssassin Local State Dir = # /var/lib/spamassassin +SpamAssassin Default Rules Dir = + +# +# MCP (Message Content Protection) +# ----------------------------- +# + +MCP Checks = {$mcp_checks} +First Check = spam +MCP Required SpamAssassin Score = {$mcp_score} +MCP High SpamAssassin Score = {$hi_mcp_score} +MCP Error Score = 1 +MCP Header = X-%org-name%-MailScanner-MCPCheck: +Non MCP Actions = deliver +MCP Actions = {$mcp_action} +High Scoring MCP Actions = {$mcp_hi_action} +Bounce MCP As Attachment = {$bounce_mcp} +MCP Modify Subject = start +MCP Subject Text = [MCP?] +High Scoring MCP Modify Subject = start +High Scoring MCP Subject Text = [MCP?] + +Is Definitely MCP = {$is_mcp} +Is Definitely Not MCP = {$is_not_mcp} +Definite MCP Is High Scoring = {$mcp_is_high_score} +Always Include MCP Report = {$include_mcp_report} +Detailed MCP Report = {$detailled_mcp_report} +Include Scores In MCP Report = {$score_mcp_report} +Log MCP = {$log_mcp} + +MCP Max SpamAssassin Timeouts = 20 +MCP Max SpamAssassin Size = {$mcp_max} +MCP SpamAssassin Timeout = 10 + +MCP SpamAssassin Prefs File = %mcp-dir%/mcp.spam.assassin.prefs.conf +MCP SpamAssassin User State Dir = +MCP SpamAssassin Local Rules Dir = %mcp-dir% +MCP SpamAssassin Default Rules Dir = %mcp-dir% +MCP SpamAssassin Install Prefix = %mcp-dir% +Recipient MCP Report = %report-dir%/recipient.mcp.report.txt +Sender MCP Report = %report-dir%/sender.mcp.report.txt + +# +# Advanced Settings +# ----------------- +# +Use Default Rules With Multiple Recipients = {$default_rule_multiple} +Read IP Address From Received Header = {$read_ipaddress} +Spam Score Number Format = {$spam_score_format} +MailScanner Version Number = 4.83.5 +SpamAssassin Cache Timings = {$cache_timings} +Debug = {$debug} +Debug SpamAssassin = {$debug_spam} +Run In Foreground = {$foreground} +Always Looked Up Last = {$look_up_last} +Always Looked Up Last After Batch = {$look_up_last_batch} +Deliver In Background = {$deliver_background} +Delivery Method = {$mailscanner['deliver_method']} +Split Exim Spool = {$split_exim_spool} +Lockfile Dir = /var/spool/MailScanner/incoming/Locks +Custom Functions Dir = /usr/local/lib/MailScanner/MailScanner/CustomFunctions +Lock Type = +Syslog Socket Type = +Automatic Syntax Check = {$syntax_check} +Minimum Code Status = {$mailscanner['minimum_code']} +include /usr/local/etc/MailScanner/conf.d/* + + + +EOF; +?> diff --git a/config/mailscanner/mailscanner.inc b/config/mailscanner/mailscanner.inc index 1a4f284d..3ff4cd40 100644 --- a/config/mailscanner/mailscanner.inc +++ b/config/mailscanner/mailscanner.inc @@ -32,7 +32,10 @@ require_once("util.inc"); require("globals.inc"); #require("guiconfig.inc"); - +$uname=posix_uname(); +if ($uname['machine']=='amd64') + ini_set('memory_limit', '250M'); + function ms_text_area_decode($text){ return preg_replace('/\r\n/', "\n",base64_decode($text)); } @@ -40,19 +43,84 @@ function ms_text_area_decode($text){ function sync_package_mailscanner() { global $config; + # detect boot process + if (is_array($_POST)){ + if (preg_match("/\w+/",$_POST['__csrf_magic'])) + unset($boot_process); + else + $boot_process="on"; + } + exec('/bin/pgrep -f MailScanner',$pgrep_out); + if (count($pgrep_out) > 0 && isset($boot_process)) + return; + + #check default config + $load_samples=0; + #assign xml arrays - if (is_array($config['installedpackages']['mailscanner'])) - $mailscanner=$config['installedpackages']['mailscanner']['config'][0]; - if (is_array($config['installedpackages']['msattachments'])) - $attachments=$config['installedpackages']['msattachments']['config'][0]; - if (is_array($config['installedpackages']['msantivirus'])) - $antivirus=$config['installedpackages']['msantivirus']['config'][0]; - if (is_array($config['installedpackages']['mscontent'])) - $content=$config['installedpackages']['mscontent']['config'][0]; - if (is_array($config['installedpackages']['msreport'])) - $report=$config['installedpackages']['msreport']['config'][0]; - if (is_array($config['installedpackages']['msantispam'])) - $antispam=$config['installedpackages']['msantispam']['config'][0]; + if (!is_array($config['installedpackages']['mailscanner'])){ + $config['installedpackages']['mailscanner']['config'][0]=array( 'max_children'=> '5', + 'pim'=> 'ScanMessages', + 'syslog_facility'=> 'mail', + 'syslog'=>'LogSpamAssassinRuleActions', + 'advanced'=> 'DeliverInBackground,AutomaticSyntaxCheck', + 'deliver_method'=>'batch', + 'minimum_code'=>'batch', + 'spam_score_format'=>'%d', + 'cache_timings'=> '1800,300,10800,172800,600' ); + $load_samples++; + } + $mailscanner=$config['installedpackages']['mailscanner']['config'][0]; + if (!is_array($config['installedpackages']['msattachments'])){ + $config['installedpackages']['msattachments']['config'][0]=array('features'=>'ExpandTNEF,FindArchiveByContent,UnpackMicrosoftDocuments', + 'tnef_contents'=>'replace', + 'max_sizes'=>'-1', + 'archive_depth'=>'8', + 'attachment_filename'=>'MessageAttachments.zip', + 'attachment_extension_exclude'=>'0', + 'attachment_max_per_archive'=>'0', + 'attachment_max'=>'50k'); + $load_samples++; + } + $attachments=$config['installedpackages']['msattachments']['config'][0]; + if (!is_array($config['installedpackages']['msantivirus'])){ + $config['installedpackages']['msantivirus']['config'][0]=array( 'features'=>'VirusScanning,CheckFilenamesInPassword-ProtectedArchives', + 'virus_scanner'=>'auto', + 'timeout'=>'300', + 'silent_virus'=>'HTML-Iframe,All-viruses'); + $load_samples++; + } + $antivirus=$config['installedpackages']['msantivirus']['config'][0]; + if (!is_array($config['installedpackages']['mscontent'])){ + $config['installedpackages']['mscontent']['config'][0]=array('checks'=>'DangerousContentScanning,UseStricterPhishingNet,HighlightPhishingFraud', + 'iframe_tags'=>'disarm', + 'form_tags'=>'disarm', + 'web_bugs'=>'disarm', + 'codebase_tags'=>'disarm'); + $load_samples++; + } + $content=$config['installedpackages']['mscontent']['config'][0]; + if (!is_array($config['installedpackages']['msreport'])){ + $config['installedpackages']['msreport']['config'][0]=array('features'=>'HideIncomingWorkDir,IncludeScannerNameInReports', + 'notification'=>'NotifySendersofBlockedFilenamesorFiletypes', + 'system'=>'NoticesIncludeFullHeaders', + 'language'=>'en'); + $load_samples++; + } + $report=$config['installedpackages']['msreport']['config'][0]; + if (!is_array($config['installedpackages']['msantispam'])){ + $config['installedpackages']['msantispam']['config'][0]=array( 'rblfeatures'=>'spam_checks', + 'safeatures'=>'use_sa,sa_auto_whitelist,check_sa_if_on_spam_list,spam_score,cache_spamassassin_results,use_pyzor,use_razor,use_dcc,use_bayes,use_auto_learn_bayes', + 'sa_score'=>'6', + 'spam_actions'=>'deliver', + 'hi_score'=>'20', + 'hispam_actions'=>'deliver', + 'rebuild_bayes'=>'86400', + 'mcp_features'=>'detailled_mcp_report', + 'mcp_score'=>'1'); + $load_samples++; + } + $antispam=$config['installedpackages']['msantispam']['config'][0]; if (is_array($config['installedpackages']['msalerts'])) $alert=$config['installedpackages']['msalerts']['config'][0]; @@ -186,7 +254,6 @@ function sync_package_mailscanner() { Language Strings = %report-dir%/languages.conf */ #check files - $load_samples=0; $mailscanner_dir="/usr/local/etc/MailScanner"; if($attachments['filename_rules'] == ""){ @@ -263,9 +330,11 @@ Language Strings = %report-dir%/languages.conf foreach ($report_files as $key_r => $file_r){ if ($report[$key_r] == ""){ #$input_errors[]= $key; - $config['installedpackages']['msreport']['config'][0][$key_r]=base64_encode(file_get_contents($report_dir.'/'.$file_r.'.sample')); - file_put_contents($report_dir.'/'.$file_r,ms_text_area_decode($config['installedpackages']['msreport']['config'][0][$key_r]),LOCK_EX); - $load_samples++; + if (file_exists($report_dir.'/'.$file_r.'.sample')){ + $config['installedpackages']['msreport']['config'][0][$key_r]=base64_encode(file_get_contents($report_dir.'/'.$file_r.'.sample')); + file_put_contents($report_dir.'/'.$file_r,ms_text_area_decode($config['installedpackages']['msreport']['config'][0][$key_r]),LOCK_EX); + $load_samples++; + } } #print $key_r ."X $file_r X". base64_encode(file_get_contents($report_dir.'/'.$file_r.'.sample')) ."<br>"; @@ -296,512 +365,23 @@ Language Strings = %report-dir%/languages.conf #exit; if($load_samples > 0) write_config(); - /* + +/* Phishing Safe Sites File = %etc-dir%/phishing.safe.sites.conf Phishing Bad Sites File = %etc-dir%/phishing.bad.sites.conf Country Sub-Domains List = %etc-dir%/country.domains.conf */ - #create MailScanner.conf$deliver_silent - $mc=<<<EOF -{$info} -# Configuration directory containing this file -%etc-dir% = /usr/local/etc/MailScanner - -# Set the directory containing all the reports in the required language -%report-dir% = /usr/local/share/MailScanner/reports/{$report_language} - -# Rulesets directory containing your ".rules" files -%rules-dir% = /usr/local/etc/MailScanner/rules - -# Configuration directory containing files related to MCP -# (Message Content Protection) -%mcp-dir% = /usr/local/etc/MailScanner/mcp - -# -# System settings -# --------------- -# -Max Children = {$max_children} -Run As User = postfix -Run As Group = postfix -Queue Scan Interval = 6 -Incoming Queue Dir = /var/spool/postfix/hold -Outgoing Queue Dir = /var/spool/postfix/incoming -Incoming Work Dir = /var/spool/MailScanner/incoming -Quarantine Dir = /var/spool/MailScanner/quarantine -PID file = /var/run/MailScanner.pid -Restart Every = 14400 -MTA = postfix -Sendmail = /usr/local/sbin/sendmail - -# -# Incoming Work Dir Settings -# -------------------------- -# -Incoming Work User = postix -Incoming Work Group = postix -Incoming Work Permissions = 0600 - -# -# Quarantine and Archive Settings -# ------------------------------- -# -Quarantine User = postifx -Quarantine Group = postfix -Quarantine Permissions = 0600 - -# -# Processing Incoming Mail -# ------------------------ -# -Max Unscanned Bytes Per Scan = 100m -Max Unsafe Bytes Per Scan = 50m -Max Unscanned Messages Per Scan = 30 -Max Unsafe Messages Per Scan = 30 -Max Normal Queue Size = 800 -Scan Messages = {$scan_messages} -Reject Message = {$reject_message} -Maximum Processing Attempts = 10 -Processing Attempts Database = /var/spool/MailScanner/incoming/Processing.db -Maximum Attachments Per Message = 200 -Expand TNEF = {$expand_tnef} -Deliver Unparsable TNEF = {$deliver_tnef} -Use TNEF Contents = {$attachments['tnef_contents']} -TNEF Expander = /usr/local/bin/tnef --maxsize=100000000 -TNEF Timeout = 120 -File Command = /usr/bin/file -File Timeout = 20 -Gunzip Command = /usr/bin/gunzip -Gunzip Timeout = 50 -Unrar Command = /usr/local/bin/unrar -Unrar Timeout = 50 -Find UU-Encoded Files = no -Maximum Message Size = %rules-dir%/max.message.size.rules -Maximum Attachment Size ={$max_size} -Minimum Attachment Size = -1 -Maximum Archive Depth = {$archive_depth} -Find Archives By Content ={$find_archive} -Unpack Microsoft Documents = {$microsoft} -Zip Attachments = {$zip_attachments} -Attachments Zip Filename = {$zip_file} -Attachments Min Total Size To Zip = 100k -Attachment Extensions Not To Zip = {$zip_exclude} -Add Text Of Doc = no -Antiword = /usr/bin/antiword -f -Antiword Timeout = 50 -Unzip Maximum Files Per Archive = {$unzip_max_per_archive} -Unzip Maximum File Size = {$unzip_max} -Unzip Filenames = *.txt *.ini *.log *.csv -Unzip MimeType = text/plain - -# -# Virus Scanning and Vulnerability Testing -# ---------------------------------------- -# -Virus Scanning = {$virus_scanning} -Virus Scanners = {$antivirus['virus_scanner']} -Virus Scanner Timeout = {$antivirus_timeout} -Deliver Disinfected Files = {$deliver_disinfected} -Silent Viruses = {$silent_viruses} -Still Deliver Silent Viruses = {$deliver_silent} -Non-Forging Viruses = Joke/ OF97/ WM97/ W97M/ eicar -Spam-Virus Header = {$spam_virus_header} -Virus Names Which Are Spam = Sane*UNOFFICIAL HTML/* *Phish* -Block Encrypted Messages = {$block_encrypted} -Block Unencrypted Messages = {$block_unencrypted} -Allow Password-Protected Archives = {$allow_password} -Check Filenames In Password-Protected Archives = {$check_filenames} -Monitors for ClamAV Updates = /var/db/clamav/*.cvd -ClamAVmodule Maximum Recursion Level = 8 -ClamAVmodule Maximum Files = 1000 -ClamAVmodule Maximum File Size = 10000000 # (10 Mbytes) -ClamAVmodule Maximum Compression Ratio = 25 -Allowed Sophos Error Messages = -Sophos IDE Dir = /opt/sophos-av/lib/sav -Sophos Lib Dir = /opt/sophos-av/lib -Monitors For Sophos Updates = /opt/sophos-av/lib/sav/*.ide -Clamd Port = 3310 -Clamd Socket = /var/run/clamav/clamd.sock -Clamd Lock File = # /var/lock/subsys/clamd -Clamd Use Threads = no -ClamAV Full Message Scan = yes -Fpscand Port = 10200 -{$custom_antivirus_options} - -# -# Removing/Logging dangerous or potentially offensive content -# ----------------------------------------------------------- -# -Dangerous Content Scanning = {$dangerous_content} -Allow Partial Messages = {$partial_messages} -Allow External Message Bodies = {$external_bodies} -Find Phishing Fraud = {$phishing_fraud} -Also Find Numeric Phishing = {$numeric_phishig} -Use Stricter Phishing Net = ${stricter_phishing_net} -Highlight Phishing Fraud = ${highlight_phishing} -Phishing Safe Sites File = %etc-dir%/phishing.safe.sites.conf -Phishing Bad Sites File = %etc-dir%/phishing.bad.sites.conf -Country Sub-Domains List = %etc-dir%/country.domains.conf -Allow IFrame Tags = {$content['iframe_tags']} -Allow Form Tags = {$content['form_tags']} -Allow Script Tags = {$content['script_tags']} -Allow WebBugs = {$content['web_bugs']} -Ignored Web Bug Filenames = spacer pixel.gif pixel.png gap shim -Known Web Bug Servers = msgtag.com -Web Bug Replacement = http://www.mailscanner.tv/1x1spacer.gif -Allow Object Codebase Tags = {$content['codebase_tags']} -Convert Dangerous HTML To Text = {$dangerous_html} -Convert HTML To Text = {$html_to_text} - -# -# Attachment Filename Checking -# ---------------------------- -# -Archives Are = zip rar ole -Allow Filenames = -Deny Filenames = -Filename Rules = %etc-dir%/filename.rules.conf -Allow Filetypes = -Allow File MIME Types = -Deny Filetypes = -Deny File MIME Types = -Filetype Rules = %etc-dir%/filetype.rules.conf -Archives: Allow Filenames = -Archives: Deny Filenames = -Archives: Filename Rules = %etc-dir%/archives.filename.rules.conf -Archives: Allow Filetypes = -Archives: Allow File MIME Types = -Archives: Deny Filetypes = -Archives: Deny File MIME Types = -Archives: Filetype Rules = %etc-dir%/archives.filetype.rules.conf -Default Rename Pattern = __FILENAME__.disarmed - -# -# Reports and Responses -# --------------------- -# -Quarantine Infections = {$quarantine_infections} -Quarantine Silent Viruses = {$quarantine_silent_virus} -Quarantine Modified Body = {$quarantine_modified_body} -Quarantine Whole Message = {$quarantine_whole_message} -Quarantine Whole Messages As Queue Files = {$quarantine_whole_message_as_queue} -Keep Spam And MCP Archive Clean = {$keep_spam_and_mcp} -Language Strings = %report-dir%/languages.conf -Rejection Report = %report-dir%/rejection.report.txt -Deleted Bad Content Message Report = %report-dir%/deleted.content.message.txt -Deleted Bad Filename Message Report = %report-dir%/deleted.filename.message.txt -Deleted Virus Message Report = %report-dir%/deleted.virus.message.txt -Deleted Size Message Report = %report-dir%/deleted.size.message.txt -Stored Bad Content Message Report = %report-dir%/stored.content.message.txt -Stored Bad Filename Message Report = %report-dir%/stored.filename.message.txt -Stored Virus Message Report = %report-dir%/stored.virus.message.txt -Stored Size Message Report = %report-dir%/stored.size.message.txt -Disinfected Report = %report-dir%/disinfected.report.txt -Inline HTML Signature = %report-dir%/inline.sig.html -Inline Text Signature = %report-dir%/inline.sig.txt -Signature Image Filename = %report-dir%/sig.jpg -Signature Image <img> Filename = signature.jpg -Inline HTML Warning = %report-dir%/inline.warning.html -Inline Text Warning = %report-dir%/inline.warning.txt -Sender Content Report = %report-dir%/sender.content.report.txt -Sender Error Report = %report-dir%/sender.error.report.txt -Sender Bad Filename Report = %report-dir%/sender.filename.report.txt -Sender Virus Report = %report-dir%/sender.virus.report.txt -Sender Size Report = %report-dir%/sender.size.report.txt -Hide Incoming Work Dir = {$hide_incoming_work_dir} -Include Scanner Name In Reports = {$include_scanner_name} -# -# Changes to Message Headers -# -------------------------- -# -Mail Header = X-%org-name%-MailScanner: -Spam Header = X-%org-name%-MailScanner-SpamCheck: -Spam Score Header = X-%org-name%-MailScanner-SpamScore: -Information Header = X-%org-name%-MailScanner-Information: -Add Envelope From Header = yes -Add Envelope To Header = no -Envelope From Header = X-%org-name%-MailScanner-From: -Envelope To Header = X-%org-name%-MailScanner-To: -ID Header = X-%org-name%-MailScanner-ID: -IP Protocol Version Header = # X-%org-name%-MailScanner-IP-Protocol: -Spam Score Character = s -SpamScore Number Instead Of Stars = no -Minimum Stars If On Spam List = 0 -Clean Header Value = Found to be clean -Infected Header Value = Found to be infected -Disinfected Header Value = Disinfected -Information Header Value = Please contact the ISP for more information -Detailed Spam Report = yes -Include Scores In SpamAssassin Report = yes -Always Include SpamAssassin Report = no -Multiple Headers = append -Place New Headers At Top Of Message = no -Hostname = the %org-name% ($HOSTNAME) MailScanner -Sign Messages Already Processed = no -Sign Clean Messages = yes -Attach Image To Signature = no -Attach Image To HTML Message Only = yes -Allow Multiple HTML Signatures = no -Dont Sign HTML If Headers Exist = # In-Reply-To: References: -Mark Infected Messages = yes -Mark Unscanned Messages = yes -Unscanned Header Value = Not scanned: please contact your Internet E-Mail Service Provider for details -Remove These Headers = X-Mozilla-Status: X-Mozilla-Status2: -Deliver Cleaned Messages = yes - -# -# Notifications back to the senders of blocked messages -# ----------------------------------------------------- -# -Notify Senders = {$notify_sender} -Notify Senders Of Viruses = {$notify_sender_viruses} -Notify Senders Of Blocked Filenames Or Filetypes = {$notify_sender_fileytypes} -Notify Senders Of Blocked Size Attachments = {$notify_sender_attachments} -Notify Senders Of Other Blocked Content = {$notify_sender_contents} -Never Notify Senders Of Precedence = list bulk - -# -# Changes to the Subject: line -# ---------------------------- -# -Scanned Modify Subject = no # end -Scanned Subject Text = [Scanned] -Virus Modify Subject = start -Virus Subject Text = [Virus?] -Filename Modify Subject = start -Filename Subject Text = [Filename?] -Content Modify Subject = start -Content Subject Text = [Dangerous Content?] -Size Modify Subject = start -Size Subject Text = [Size] -Disarmed Modify Subject = start -Disarmed Subject Text = [Disarmed] -Phishing Modify Subject = no -Phishing Subject Text = [Fraude?] -Spam Modify Subject = start -Spam Subject Text = [Spam?] -High Scoring Spam Modify Subject = start -High Scoring Spam Subject Text = [Spam?] - -# -# Changes to the Message Body -# --------------------------- -# -Warning Is Attachment = yes -Attachment Warning Filename = %org-name%-Attachment-Warning.txt -Attachment Encoding Charset = ISO-8859-1 - -# -# Mail Archiving and Monitoring -# ----------------------------- -# -Archive Mail = -Missing Mail Archive Is = directory - -# -# Notices to System Administrators -# -------------------------------- -# -Send Notices = {$send_notices} -Notices Include Full Headers = {$notices_include_header} -Hide Incoming Work Dir in Notices = {$hide_incoming_work_dir_notices} -Notice Signature = {$notice_signature} -Notices From = ${$notice_from} -Notices To = ${$notice_to} -Local Postmaster = postmaster - -# -# Spam Detection and Virus Scanner Definitions -# -------------------------------------------- -# -Spam List Definitions = %etc-dir%/spam.lists.conf -Virus Scanner Definitions = %etc-dir%/virus.scanners.conf - -# -# Spam Detection and Spam Lists (DNS blocklists) -# ---------------------------------------------- -# - -Spam Checks = yes -Spam List = # spamhaus-ZEN # You can un-comment this to enable them -Spam Domain List = -Spam Lists To Be Spam = 1 -Spam Lists To Reach High Score = 3 -Spam List Timeout = 10 -Max Spam List Timeouts = 7 -Spam List Timeouts History = 10 -Is Definitely Not Spam = %rules-dir%/spam.whitelist.rules -Is Definitely Spam = no -Definite Spam Is High Scoring = no -Ignore Spam Whitelist If Recipients Exceed = 20 -Max Spam Check Size = 200k - -# -# Watermarking -# ------------ -# -Use Watermarking = no -Add Watermark = yes -Check Watermarks With No Sender = yes -Treat Invalid Watermarks With No Sender as Spam = nothing -Check Watermarks To Skip Spam Checks = yes -Watermark Secret = %org-name%-Secret -Watermark Lifetime = 604800 -Watermark Header = X-%org-name%-MailScanner-Watermark: - -# -# SpamAssassin -# ------------ -# - -Use SpamAssassin = {$use_sa} -Max SpamAssassin Size = {$sa_max} -Required SpamAssassin Score = {$sa_score} -High SpamAssassin Score = {$hi_score} -SpamAssassin Auto Whitelist = {$sa_auto_whitelist} -SpamAssassin Timeout = 75 -Max SpamAssassin Timeouts = 10 -SpamAssassin Timeouts History = 30 -Check SpamAssassin If On Spam List = {$check_sa_if_on_spam_list} -Include Binary Attachments In SpamAssassin = {$include_sa_bin_attachments} -Spam Score = {$spam_score} -Cache SpamAssassin Results = {$cache_spamassassin_results} -SpamAssassin Cache Database File = /var/spool/MailScanner/incoming/SpamAssassin.cache.db -Rebuild Bayes Every = {$rebuild_bayes} -Wait During Bayes Rebuild = {$wait_during_bayes_rebuild} - -# -# Custom Spam Scanner Plugin -# -------------------------- -# -Use Custom Spam Scanner = no -Max Custom Spam Scanner Size = 20k -Custom Spam Scanner Timeout = 20 -Max Custom Spam Scanner Timeouts = 10 -Custom Spam Scanner Timeout History = 20 - -# -# What to do with spam -# -------------------- -# - -Spam Actions = {$spam_actions} header "X-Spam-Status: Yes" -High Scoring Spam Actions = {$hispam_actions} header "X-Spam-Status: Yes" -Non Spam Actions = deliver header "X-Spam-Status: No" -SpamAssassin Rule Actions = -Sender Spam Report = %report-dir%/sender.spam.report.txt -Sender Spam List Report = %report-dir%/sender.spam.rbl.report.txt -Sender SpamAssassin Report = %report-dir%/sender.spam.sa.report.txt -Inline Spam Warning = %report-dir%/inline.spam.warning.txt -Recipient Spam Report = %report-dir%/recipient.spam.report.txt -Enable Spam Bounce = %rules-dir%/bounce.rules -Bounce Spam As Attachment = no -# -# Logging -# ------- -# -Syslog Facility = {$syslog_facility} -Log Speed = {$log_speed} -Log Spam = {$log_spam} -Log Non Spam = {$log_non_spam} -Log Delivery And Non-Delivery = {$log_delivery} -Log Permitted Filenames = {$log_filenames} -Log Permitted Filetypes = {$log_filetypes} -Log Permitted File MIME Types = {$log_mime} -Log Silent Viruses = {$log_silent} -Log Dangerous HTML Tags = {$log_dangerous} -Log SpamAssassin Rule Actions = {$log_sa_rule_action} - -# -# Advanced SpamAssassin Settings -# ------------------------------ -# -SpamAssassin Temporary Dir = /var/spool/MailScanner/incoming/SpamAssassin-Temp -SpamAssassin User State Dir = -SpamAssassin Install Prefix = -SpamAssassin Site Rules Dir = /usr/local/etc/mail/spamassassin -SpamAssassin Local Rules Dir = -SpamAssassin Local State Dir = # /var/lib/spamassassin -SpamAssassin Default Rules Dir = - -# -# MCP (Message Content Protection) -# ----------------------------- -# - -MCP Checks = {$mcp_checks} -First Check = spam -MCP Required SpamAssassin Score = {$mcp_score} -MCP High SpamAssassin Score = {$hi_mcp_score} -MCP Error Score = 1 -MCP Header = X-%org-name%-MailScanner-MCPCheck: -Non MCP Actions = deliver -MCP Actions = {$mcp_action} -High Scoring MCP Actions = {$mcp_hi_action} -Bounce MCP As Attachment = {$bounce_mcp} -MCP Modify Subject = start -MCP Subject Text = [MCP?] -High Scoring MCP Modify Subject = start -High Scoring MCP Subject Text = [MCP?] - -Is Definitely MCP = {$is_mcp} -Is Definitely Not MCP = {$is_not_mcp} -Definite MCP Is High Scoring = {$mcp_is_high_score} -Always Include MCP Report = {$include_mcp_report} -Detailed MCP Report = {$detailled_mcp_report} -Include Scores In MCP Report = {$score_mcp_report} -Log MCP = {$log_mcp} - -MCP Max SpamAssassin Timeouts = 20 -MCP Max SpamAssassin Size = {$mcp_max} -MCP SpamAssassin Timeout = 10 - -MCP SpamAssassin Prefs File = %mcp-dir%/mcp.spam.assassin.prefs.conf -MCP SpamAssassin User State Dir = -MCP SpamAssassin Local Rules Dir = %mcp-dir% -MCP SpamAssassin Default Rules Dir = %mcp-dir% -MCP SpamAssassin Install Prefix = %mcp-dir% -Recipient MCP Report = %report-dir%/recipient.mcp.report.txt -Sender MCP Report = %report-dir%/sender.mcp.report.txt - -# -# Advanced Settings -# ----------------- -# -Use Default Rules With Multiple Recipients = {$default_rule_multiple} -Read IP Address From Received Header = {$read_ipaddress} -Spam Score Number Format = {$spam_score_format} -MailScanner Version Number = 4.83.5 -SpamAssassin Cache Timings = {$cache_timings} -Debug = {$debug} -Debug SpamAssassin = {$debug_spam} -Run In Foreground = {$foreground} -Always Looked Up Last = {$look_up_last} -Always Looked Up Last After Batch = {$look_up_last_batch} -Deliver In Background = {$deliver_background} -Delivery Method = {$mailscanner['deliver_method']} -Split Exim Spool = {$split_exim_spool} -Lockfile Dir = /var/spool/MailScanner/incoming/Locks -Custom Functions Dir = /usr/local/lib/MailScanner/MailScanner/CustomFunctions -Lock Type = -Syslog Socket Type = -Automatic Syntax Check = {$syntax_check} -Minimum Code Status = {$mailscanner['minimum_code']} -include /usr/local/etc/MailScanner/conf.d/* - - - -EOF; + #create MailScanner.conf + include("mailscanner.conf.template"); #write files conf_mount_rw(); - if (!is_dir("/var/spool/MailScanner/incoming")){ - mkdir("/var/spool/MailScanner/incoming", 0755,true); - chown ('/var/spool/MailScanner/incoming','postfix'); - } - if (!is_dir("/var/spool/MailScanner/quarantine")){ - mkdir("/var/spool/MailScanner/quarantine", 0755,true); - chown ('/var/spool/MailScanner/quarantine','postfix'); + $msc_dirs=array("incoming", "incoming/Locks", "quarantine"); + foreach ($msc_dirs as $msc_dir){ + if (!is_dir("/var/spool/MailScanner/{$msc_dir}")){ + mkdir("/var/spool/MailScanner/{$msc_dir}", 0755,true); + chown ("/var/spool/MailScanner/{$msc_dir}",'postfix'); + } } chown ('/var/spool/postfix','postfix'); @@ -811,7 +391,7 @@ EOF; $mfiles[]="/usr/local/share/MailScanner/reports/{$mlang}/languages.conf"; foreach ($mfiles as $mfile) - if (! file_exists ($mfile)) + if (! file_exists ($mfile) && file_exists($mfile.".sample")) copy($mfile.".sample",$mfile); @@ -965,46 +545,70 @@ EOF; log_error('No clamav database found, running freshclam in background.'); mwexec_bg('/usr/local/bin/freshclam'); } + #clamav-wrapper file $cconf=$libexec_dir."clamav-wrapper"; - $cconf_file=file_get_contents($cconf); - if (preg_match('/"clamav"/',$cconf_file)){ - $cconf_file=preg_replace('/"clamav"/','"postfix"',$cconf_file); - file_put_contents($cconf, $cconf_file, LOCK_EX); + if (file_exists($cconf)){ + $cconf_file=file_get_contents($cconf); + if (preg_match('/"clamav"/',$cconf_file)){ + $cconf_file=preg_replace('/"clamav"/','"postfix"',$cconf_file); + file_put_contents($cconf, $cconf_file, LOCK_EX); + } } #freshclam conf file $cconf="/usr/local/etc/freshclam.conf"; - $cconf_file=file_get_contents($cconf); - if (preg_match('/DatabaseOwner clamav/',$cconf_file)){ - $cconf_file=preg_replace("/DatabaseOwner clamav/","DatabaseOwner postfix",$cconf_file); - file_put_contents($cconf, $cconf_file, LOCK_EX); + if (file_exists($conf)){ + $cconf_file=file_get_contents($cconf); + if (preg_match('/DatabaseOwner clamav/',$cconf_file)){ + $cconf_file=preg_replace("/DatabaseOwner clamav/","DatabaseOwner postfix",$cconf_file); + file_put_contents($cconf, $cconf_file, LOCK_EX); + } } #clamd conf file $cconf="/usr/local/etc/clamd.conf"; - $cconf_file=file_get_contents($cconf); - if (preg_match('/User clamav/',$cconf_file)){ - $cconf_file=preg_replace("/User clamav/","User postfix",$cconf_file); - file_put_contents($cconf, $cconf_file, LOCK_EX); + if (file_exists($conf)){ + $cconf_file=file_get_contents($cconf); + if (preg_match('/User clamav/',$cconf_file)){ + $cconf_file=preg_replace("/User clamav/","User postfix",$cconf_file); + file_put_contents($cconf, $cconf_file, LOCK_EX); + } } #clamd script file $script='/usr/local/etc/rc.d/clamav-clamd'; - $script_file=file($script); - foreach ($script_file as $script_line){ - if(preg_match("/command=/",$script_line)){ - $new_clamav_startup.= "/bin/mkdir /var/run/clamav\n"; - $new_clamav_startup.= "chown postfix /var/run/clamav\n"; - $new_clamav_startup.=$script_line; + if (file_exists($script)){ + $script_file=file($script); + foreach ($script_file as $script_line){ + if(preg_match("/command=/",$script_line)){ + $new_clamav_startup.= "/bin/mkdir -p /var/run/clamav\n"; + $new_clamav_startup.= "chown postfix /var/run/clamav\n"; + $new_clamav_startup.=$script_line; + } + elseif(!preg_match("/(mkdir|chown|sleep|mailscanner)/",$script_line)) { + $new_clamav_startup.=preg_replace("/NO/","YES",$script_line); + } } - elseif(!preg_match("/(mkdir|chown|sleep|mailscanner)/",$script_line)) { - $new_clamav_startup.=preg_replace("/NO/","YES",$script_line); + file_put_contents($script, $new_clamav_startup, LOCK_EX); + + chmod ($script,0755); + if($config['installedpackages']['mailscanner']['config'][0]['enable']){ + if (is_process_running('clamd')){ + log_error("Restarting clamav-clamd daemon"); + mwexec("$script restart"); + } + else{ + log_error("Starting clamav-clamd daemon"); + mwexec_bg("$script start"); + } + } + else{ + if (is_process_running('clamd')){ + log_error("Restarting clamav-clamd daemon"); + mwexec("$script start"); + } } } - file_put_contents($script, $new_clamav_startup, LOCK_EX); - chmod ($script,0755); - mwexec("$script stop"); - mwexec_bg("$script start"); } } else{ @@ -1012,63 +616,105 @@ EOF; unlink_if_exists($libexec_dir.'clamav-wrapper'); } - #check dcc startup script - $script='/usr/local/etc/rc.d/dccifd'; - $script_file=file_get_contents($script); - if (preg_match('/NO/',$script_file)){ - $script_file=preg_replace("/NO/","YES",$script_file); - file_put_contents($script, $script_file, LOCK_EX); - chmod ($script,0755); - } #check dcc config file $script='/usr/local/dcc/dcc_conf'; - $script_file=file_get_contents($script); - if (preg_match('/DCCIFD_ENABLE=off/',$script_file)){ - $script_file=preg_replace("/DCCIFD_ENABLE=off/","DCCIFD_ENABLE=on",$script_file); - file_put_contents($script, $script_file, LOCK_EX); + if (file_exists($script)){ + $script_file=file_get_contents($script); + if (preg_match('/DCCIFD_ENABLE=off/',$script_file)){ + $script_file=preg_replace("/DCCIFD_ENABLE=off/","DCCIFD_ENABLE=on",$script_file); + file_put_contents($script, $script_file, LOCK_EX); + } + } + + #check dcc startup script + $script='/usr/local/etc/rc.d/dccifd'; + if (file_exists($script)){ + $script_file=file_get_contents($script); + if (preg_match('/NO/',$script_file)){ + $script_file=preg_replace("/NO/","YES",$script_file); + file_put_contents($script, $script_file, LOCK_EX); + chmod ($script,0755); + } + + if($config['installedpackages']['mailscanner']['config'][0]['enable']){ + if(is_process_running('dccifd')){ + log_error("Restarting dccifd"); + mwexec("$script restart"); + } + else{ + log_error("Starting dccifd"); + mwexec("$script start"); + } + } + else{ + if(is_process_running('dccifd')){ + log_error("Stopping dccifd"); + mwexec("$script stop"); + } + } } - mwexec("$script stop"); - mwexec_bg("$script start"); $script='/usr/local/etc/rc.d/mailscanner'; #fix MIME::ToolUtils deprecated function and usecure dependency calls in /usr/local/sbin/mailscanner $cconf="/usr/local/sbin/mailscanner"; - $cconf_file=file_get_contents($cconf); - $pattern2[0]='/perl\W+I/'; - $pattern2[1]='/\smy .current = config MIME::ToolUtils/'; - $replacement2[0]='perl -U -I'; - $replacement2[1]=' #my $current = config MIME::ToolUtils'; - if (preg_match('/perl\W+I/',$cconf_file)){ - $cconf_file=preg_replace($pattern2,$replacement2,$cconf_file); - file_put_contents($cconf, $cconf_file, LOCK_EX); - #force old process stop - mwexec("$script stop"); - } - - $script_file=file_get_contents($script); - if (preg_match('/NO/',$script_file)){ - $script_file=preg_replace("/NO/","YES",$script_file); - file_put_contents($script, $script_file, LOCK_EX); - chmod ($script,0755); - } - if($config['installedpackages']['mailscanner']['config'][0]['enable']){ - log_error("Reload mailscanner"); - chmod ($script,0755); - mwexec("$script stop"); - sleep(2); - mwexec_bg("$script start"); - } - else{ - log_error("Stopping mailscanner if running"); - mwexec("$script stop"); - chmod ($script,0444); + if (file_exists($cconf)){ + #check perl's version + exec('find /usr/local/lib/perl5/site_perl -name Df.pm',$find_out); + $perl_bin="perl"; + foreach($find_out as $perl_dir){ + if (preg_match ('@usr/local/lib/perl5/site_perl/([.0-9]+)/mach/Filesys/Df.pm@',$perl_dir,$perl_match)) + $perl_bin.=$perl_match[1]; + } + + $cconf_file=file_get_contents($cconf); + $pattern2[0]='@#!/usr.*bin/perl.*I@'; + $pattern2[1]='/\smy .current = config MIME::ToolUtils/'; + $replacement2[0]='#!/usr/local/bin/'.$perl_bin.' -U -I'; + $replacement2[1]=' #my $current = config MIME::ToolUtils'; + if (preg_match('@#!/usr.*bin/perl.*I@',$cconf_file)){ + $cconf_file=preg_replace($pattern2,$replacement2,$cconf_file); + file_put_contents($cconf, $cconf_file, LOCK_EX); + } } + if (file_exists($script)){ + $script_file=file_get_contents($script); + if (preg_match('/NO/',$script_file)){ + $script_file=preg_replace("/NO/","YES",$script_file); + file_put_contents($script, $script_file, LOCK_EX); + chmod ($script,0755); + } + exec('/bin/pgrep -f MailScanner', $pgrep_out); + if($config['installedpackages']['mailscanner']['config'][0]['enable']){ + chmod ($script,0755); + if (count($pgrep_out) > 0 && file_exists($script)){ + log_error("Restarting MailScanner"); + mwexec_bg("$script restart"); + } + else{ + log_error("Starting MailScanner"); + mwexec("$script start"); + } + } + else{ + if (count($pgrep_out) > 0 && file_exists($script)){ + log_error("Stopping MailScanner"); + mwexec("$script stop"); + chmod ($script,0444); + } + } + } conf_mount_ro(); + + #does not sync during boot process + if (isset($boot_process)) + return; + $synconchanges = $config['installedpackages']['mailscannersync']['config'][0]['synconchanges']; if(!$synconchanges && !$syncondbchanges) return; - log_error("[mailscanner] mailscanner_xmlrpc_sync.php is starting."); + + log_error("[MailScanner] mailscanner_xmlrpc_sync.php is starting."); foreach ($config['installedpackages']['mailscannersync']['config'] as $rs ){ foreach($rs['row'] as $sh){ $sync_to_ip = $sh['ipaddress']; @@ -1103,11 +749,14 @@ function mailscanner_php_install_command() { } function mailscanner_php_deinstall_command() { - mwexec("/usr/local/etc/rc.d/mailscanner.sh stop"); - sleep(1); - conf_mount_rw(); - unlink_if_exists("/usr/local/etc/rc.d/mailscanner.sh"); - conf_mount_ro(); + exec('/bin/pgrep -f MailScanner',$pgrep_out); + if (count($pgreg_out) > 0){ + mwexec("/usr/local/etc/rc.d/mailscanner stop"); + sleep(1); + conf_mount_rw(); + unlink_if_exists("/usr/local/etc/rc.d/mailscanner"); + conf_mount_ro(); + } } function mailscanner_do_xmlrpc_sync($sync_to_ip, $password,$sync_type) { diff --git a/config/mailscanner/mailscanner.xml b/config/mailscanner/mailscanner.xml index cf00023d..0e644196 100644 --- a/config/mailscanner/mailscanner.xml +++ b/config/mailscanner/mailscanner.xml @@ -107,7 +107,11 @@ <prefix>/usr/local/www/</prefix> <chmod>0755</chmod> </additional_files_needed> - + <additional_files_needed> + <item>http://www.pfsense.org/packages/config/mailscanner/mailscanner.conf.template</item> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + </additional_files_needed> <tabs> <tab> <text>General</text> diff --git a/config/nmap/nmap.inc b/config/nmap/nmap.inc index e9093077..552ad01c 100644 --- a/config/nmap/nmap.inc +++ b/config/nmap/nmap.inc @@ -28,8 +28,31 @@ POSSIBILITY OF SUCH DAMAGE. */ +function nmap_custom_php_validation_command($post, $input_errors) { + global $_POST, $savemsg, $config; + if (empty($_POST['hostname'])) { + $input_errors[] = gettext("You must enter an IP address to scan."); + } elseif (!(is_ipaddr($_POST['hostname']) || + is_subnet($_POST['hostname']) || + is_hostname($_POST['hostname']))) { + $input_errors[] = gettext("You must enter a valid IP address to scan."); + } + + if(!empty($_POST['interface'])) { + $interfaces = get_configured_interface_with_descr(); + if (!array_key_exists($_POST['interface'], $interfaces)) { + $input_errors[] = gettext("Invalid interface."); + } + } +} + function nmap_custom_add_php_command() { $nmap_options = ""; + + if (function_exists("is_ipaddrv6") && function_exists("is_subnetv6")) + if (is_ipaddrv6($_POST['hostname']) || is_subnetv6($_POST['hostname'])) + $nmap_options .= " -6"; + switch($_POST['scanmethod']) { case 'syn': $nmap_options .= " -sS"; @@ -43,13 +66,44 @@ function nmap_custom_add_php_command() { case 'udp': $nmap_options .= " -sU"; break; + case 'arp': + $nmap_options .= " -sP -PR"; + break; } - + if($_POST['noping']) $nmap_options .= " -P0"; if($_POST['servicever']) $nmap_options .= " -sV"; if($_POST['osdetect']) $nmap_options .= " -O"; - $nmap_options .= " " . $_POST['hostname']; + if(!empty($_POST['interface'])) $nmap_options .= " -e " . get_real_interface($_POST['interface']); + + $nmap_options .= " " . escapeshellarg($_POST['hostname']); + echo "Running: /usr/local/bin/nmap {$nmap_options}</br>"; system("/usr/local/bin/nmap" . $nmap_options); } +function nmap_get_interfaces() { + global $config; + $interfaces = get_configured_interface_with_descr(); + $nmap_ifs = array(array("name" => "Any", "value" => "")); + foreach ($interfaces as $iface => $ifacename) { + $tmp["name"] = $ifacename; + $tmp["value"] = $iface; + $nmap_ifs[] = $tmp; + } + + foreach (array('server', 'client') as $mode) { + if (is_array($config['openvpn']["openvpn-{$mode}"])) { + foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) { + if (!isset($setting['disable'])) { + $tmp["name"] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']); + $tmp["value"] = 'ovpn' . substr($mode, 0, 1) . $setting['vpnid']; + $nmap_ifs[] = $tmp; + } + } + } + } + + return $nmap_ifs; +} + ?> diff --git a/config/nmap/nmap.xml b/config/nmap/nmap.xml index 7f290ade..cb3980a2 100644 --- a/config/nmap/nmap.xml +++ b/config/nmap/nmap.xml @@ -2,56 +2,56 @@ <!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> <?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> <packagegui> - <copyright> - <![CDATA[ + <copyright> + <![CDATA[ /* $Id$ */ /* ========================================================================== */ /* - authng.xml - part of pfSense (http://www.pfSense.com) - Copyright (C) 2007 to whom it may belong - All rights reserved. + authng.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2007 to whom it may belong + All rights reserved. - Based on m0n0wall (http://m0n0.ch/wall) - Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. - All rights reserved. - */ + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + All rights reserved. +*/ /* ========================================================================== */ /* - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + 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. + 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. + 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 SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. +*/ /* ========================================================================== */ - ]]> - </copyright> - <description>Describe your package here</description> - <requirements>Describe your package requirements here</requirements> - <faq>Currently there are no FAQ items provided.</faq> +]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> <name>nmap</name> - <version>4.76</version> + <version>6.01</version> <title>Diagnostics: NMap</title> <savetext>Scan</savetext> <preoutput>yes</preoutput> <donotsave>true</donotsave> - <include_file>/usr/local/pkg/nmap.inc</include_file> + <include_file>/usr/local/pkg/nmap.inc</include_file> <!-- Menu is where this packages menu will appear --> <menu> <name>NMap</name> @@ -66,47 +66,60 @@ </additional_files_needed> <fields> <field> - <fielddescr>IP or Hostname</fielddescr> - <fieldname>hostname</fieldname> - <description>Enter the IP address or hostname that you would like to scan.</description> - <type>input</type> + <fielddescr>IP or Hostname</fielddescr> + <fieldname>hostname</fieldname> + <description>Enter the IP address or hostname that you would like to scan.</description> + <type>input</type> + </field> + <field> + <fielddescr>Interface</fielddescr> + <fieldname>interface</fieldname> + <description>Enter the source interface here.</description> + <type>select_source</type> + <source><![CDATA[nmap_get_interfaces()]]></source> + <source_name>name</source_name> + <source_value>value</source_value> </field> <field> <fielddescr>Scan Method</fielddescr> <fieldname>scanmethod</fieldname> - <type>select</type> - <default_value>syn</default_value> - <options> - <option><name>SYN</name><value>syn</value></option> - <option><name>TCP connect()</name><value>connect</value></option> - <option><name>Ping</name><value>icmp</value></option> - <option><name>UDP</name><value>udp</value></option> - </options> - <typehint>Scan method</typehint> - </field> - <field> - <fielddescr>-P0</fielddescr> - <fieldname>noping</fieldname> - <description>This allows the scanning of networks that don't allow ICMP echo requests (or responses) through their firewall. microsoft.com is an example of such a network, and thus you should always use -P0 or -PT80 when port scanning microsoft.com. Note the "ping" in this contecx may involve more than the traditional ICMP echo request packet. Nmap supports many such probes, including arbitrary combinations of TCP, UDP, and ICMP probes. By default, Nmap sends an ICMP echo request and a TCP ACK packet to port 80.</description> - <type>checkbox</type> - <typehint>Do not try to ping hosts at all before scanning them.</typehint> - </field> + <type>select</type> + <default_value>syn</default_value> + <options> + <option><name>SYN</name><value>syn</value></option> + <option><name>TCP connect()</name><value>connect</value></option> + <option><name>Ping</name><value>icmp</value></option> + <option><name>UDP</name><value>udp</value></option> + <option><name>ARP (directly connected networks only!)</name><value>arp</value></option> + </options> + <typehint>Scan method</typehint> + </field> + <field> + <fielddescr>-P0</fielddescr> + <fieldname>noping</fieldname> + <description>This allows the scanning of networks that don't allow ICMP echo requests (or responses) through their firewall. microsoft.com is an example of such a network, and thus you should always use -P0 or -PT80 when port scanning microsoft.com. Note the "ping" in this context may involve more than the traditional ICMP echo request packet. Nmap supports many such probes, including arbitrary combinations of TCP, UDP, and ICMP probes. By default, Nmap sends an ICMP echo request and a TCP ACK packet to port 80.</description> + <type>checkbox</type> + <typehint>Do not try to ping hosts at all before scanning them.</typehint> + </field> <field> - <fielddescr>-sV</fielddescr> - <fieldname>servicever</fieldname> - <description>After TCP and/or UDP ports are discovered using one of the other scan methods, version detection communicates with those ports to try and determine more about what is actually running. A file called nmap-service-probes is used to determine the best probes for detecting various services and the match strings to expect. Nmap tries to determine the service protocol (e.g. ftp, ssh, telnet, http), the application name (e.g. ISC Bind, Apache httpd, Solaris telnetd), the version number, and sometimes miscellaneous details like whether an X server is open to connections or the SSH protocol version)</description> - <type>checkbox</type> - <typehint>Try to identify service versions</typehint> + <fielddescr>-sV</fielddescr> + <fieldname>servicever</fieldname> + <description>After TCP and/or UDP ports are discovered using one of the other scan methods, version detection communicates with those ports to try and determine more about what is actually running. A file called nmap-service-probes is used to determine the best probes for detecting various services and the match strings to expect. Nmap tries to determine the service protocol (e.g. ftp, ssh, telnet, http), the application name (e.g. ISC Bind, Apache httpd, Solaris telnetd), the version number, and sometimes miscellaneous details like whether an X server is open to connections or the SSH protocol version)</description> + <type>checkbox</type> + <typehint>Try to identify service versions</typehint> </field> <field> - <fielddescr>-O</fielddescr> - <fieldname>osdetect</fieldname> - <description>This option activates remote host identification via TCP/IP fingerprinting. In other words, it uses a bunch of techniques to detect subtleties in the underlying operating system network stack of the computers you are scanning. It uses this information to create a "fingerprint" which it compares with its database of known OS fingerprints (the nmap-os-fingerprints file) to decide what type of system you are scanning</description> - <type>checkbox</type> - <typehint>Turn on OS detection</typehint> + <fielddescr>-O</fielddescr> + <fieldname>osdetect</fieldname> + <description>This option activates remote host identification via TCP/IP fingerprinting. In other words, it uses a bunch of techniques to detect subtleties in the underlying operating system network stack of the computers you are scanning. It uses this information to create a "fingerprint" which it compares with its database of known OS fingerprints (the nmap-os-fingerprints file) to decide what type of system you are scanning</description> + <type>checkbox</type> + <typehint>Turn on OS detection</typehint> </field> - </fields> - <custom_add_php_command> - nmap_custom_add_php_command(); - </custom_add_php_command> + </fields> + <custom_add_php_command> + nmap_custom_add_php_command(); + </custom_add_php_command> + <custom_php_validation_command> + nmap_custom_php_validation_command($_POST, &$input_errors); + </custom_php_validation_command> </packagegui> diff --git a/config/nrpe2/nrpe2.inc b/config/nrpe2/nrpe2.inc index ca6f00ab..cd3fa013 100644 --- a/config/nrpe2/nrpe2.inc +++ b/config/nrpe2/nrpe2.inc @@ -25,9 +25,20 @@ require_once('filter.inc'); +if (substr(trim(file_get_contents("/etc/version")),0,3) == "2.0") { + define('NRPE_BASE', '/usr/local'); +} else { + define('NRPE_BASE', '/usr/pbi/nrpe-' . php_uname("m")); +} +define('NRPE_CONFIG_DIR', NRPE_BASE . '/etc'); +define('NRPE_RCFILE', '/usr/local/etc/rc.d/nrpe2.sh'); + + function nrpe2_custom_php_install_command() { global $g, $config; conf_mount_rw(); + $NRPE_BASE = NRPE_BASE; + $NRPE_CONFIG_DIR = NRPE_CONFIG_DIR; $ip = $config['interfaces']['lan']['ipaddr']; @@ -81,8 +92,8 @@ function nrpe2_custom_php_install_command() { ) ); } - unlink_if_exists('/usr/local/etc/rc.d/nrpe2'); - $fd = fopen('/usr/local/etc/rc.d/nrpe2.sh', 'w'); + unlink_if_exists(NRPE_CONFIG_DIR . '/rc.d/nrpe2'); + $fd = fopen(NRPE_RCFILE, 'w'); $rc_file = <<<EOD #!/bin/sh # @@ -98,7 +109,7 @@ function nrpe2_custom_php_install_command() { # nrpe2_enable (bool): Set to "NO" by default. # Set it to "YES" to enable nrpe2. # nrpe2_flags (str): Set to "" by default. -# nrpe2_configfile (str): Set to "/usr/local/etc/nrpe.cfg" by default. +# nrpe2_configfile (str): Set to "{$NRPE_CONFIG_DIR}/nrpe.cfg" by default. # nrpe2_pidfile (str): Set to "/var/spool/nagios/nrpe2.pid" by default. # @@ -108,14 +119,14 @@ nrpe2_enable=\${nrpe2_enable-"YES"} name="nrpe2" rcvar=`set_rcvar` -command="/usr/local/sbin/nrpe2" +command="{$NRPE_BASE}/sbin/nrpe2" command_args="-d" extra_commands="reload" sig_reload=HUP [ -z "\${nrpe2_flags}" ] && nrpe2_flags="" -[ -z "\${nrpe2_configfile}" ] && nrpe2_configfile="/usr/local/etc/nrpe.cfg" +[ -z "\${nrpe2_configfile}" ] && nrpe2_configfile="{$NRPE_CONFIG_DIR}/nrpe.cfg" [ -z "\${nrpe2_pidfile}" ] && nrpe2_pidfile="/var/run/nrpe2.pid" load_rc_config "\${name}" @@ -129,7 +140,7 @@ run_rc_command "$1" EOD; fwrite($fd, $rc_file); fclose($fd); - chmod('/usr/local/etc/rc.d/nrpe2.sh', 0755); + chmod(NRPE_RCFILE, 0755); conf_mount_ro(); } @@ -143,7 +154,7 @@ function nrpe2_custom_php_deinstall_command() { function nrpe2_custom_php_write_config() { global $g, $config; - $nagios_check_path = "/usr/local/libexec/nagios"; + $nagios_check_path = NRPE_BASE . "/libexec/nagios"; conf_mount_rw(); $cmds = array(); @@ -157,7 +168,7 @@ function nrpe2_custom_php_write_config() { $server_address = $config['installedpackages']['nrpe2']['config'][0]['server_address']; $allowed_hosts = $config['installedpackages']['nrpe2']['config'][0]['allowed_hosts']; - $fd = fopen('/usr/local/etc/nrpe.cfg', 'w'); + $fd = fopen(NRPE_CONFIG_DIR . '/nrpe.cfg', 'w'); $nrpe_cfg = <<<EOD log_facility=daemon pid_file=/var/run/nrpe2.pid @@ -181,15 +192,15 @@ function nrpe2_custom_php_service() { global $g, $config; if ($config['installedpackages']['nrpe2']['config'][0]['enabled'] == "on") { - exec("/usr/local/etc/rc.d/nrpe2.sh restart"); + exec(NRPE_RCFILE . " restart"); } else { - exec("/usr/local/etc/rc.d/nrpe2.sh stop"); + exec(NRPE_RCFILE . " stop"); } } function nrpe2_get_commands() { - $nagios_check_path = "/usr/local/libexec/nagios"; + $nagios_check_path = NRPE_BASE . "/libexec/nagios"; $commands = glob("{$nagios_check_path}/check_*"); $cmdarr = array(); foreach ($commands as $cmd) diff --git a/config/nrpe2/nrpe2.xml b/config/nrpe2/nrpe2.xml index f08fe50f..cb99aacb 100644 --- a/config/nrpe2/nrpe2.xml +++ b/config/nrpe2/nrpe2.xml @@ -15,7 +15,7 @@ </menu> <service> <name>nrpe2</name> - <rcfile>nrpe2</rcfile> + <rcfile>nrpe2.sh</rcfile> <executable>nrpe2</executable> <description>Nagios NRPE Daemon</description> </service> diff --git a/config/nut/nut.inc b/config/nut/nut.inc index 28ff3999..0c1235dd 100644 --- a/config/nut/nut.inc +++ b/config/nut/nut.inc @@ -34,7 +34,12 @@ /* Nut */ define('NUT_RCFILE', '/usr/local/etc/rc.d/nut.sh'); - define('NUT_DIR','/usr/local/etc/nut'); + + if (substr(trim(file_get_contents("/etc/version")),0,3) == "2.0") { + define('NUT_DIR','/usr/local/etc/nut'); + } else { + define('NUT_DIR', '/usr/pbi/nut-' . php_uname("m") . '/etc/nut'); + } function nut_notice ($msg) { syslog(LOG_NOTICE, "nut: {$msg}"); return; } function nut_warn ($msg) { syslog(LOG_WARNING, "nut: {$msg}"); return; } @@ -158,8 +163,6 @@ $input_errors[] = 'You must select a driver in the \'Local UPS Driver\' field'; if(!$post['port']) $input_errors[] = 'You must select a port in the \'Local UPS Port\' field'; - if($post['allowaddr'] && !nut_validate_ip($post['allowaddr'],true)) - $input_errors[] = 'You must specify a valid address \'Local Remote Access Address\' field'; } } @@ -224,7 +227,6 @@ EOD; $port = nut_config('port'); $upstype = nut_config_sub('upstype', 3); $cable = nut_config_sub('cable', 3); - $allowaddr = nut_config('allowaddr'); $allowuser = nut_config('allowuser'); $allowpass = nut_config('allowpass'); $shutdownflag = (nut_config('powerdown') == 'on') ? '-p' : '-h'; @@ -262,30 +264,23 @@ EOD; $ups_conf .= "upstype={$upstype}\n"; /* upsd.conf */ - $upsd_conf = "ACL all 0.0.0.0/0\n"; - $upsd_conf .= "ACL localhost 127.0.0.1/32\n"; - if($allowaddr && $allowuser) { - $upsd_conf .= "ACL remote {$allowaddr}\n"; - $upsd_conf .= "ACCEPT remote\n"; - } - $upsd_conf .= "ACCEPT localhost\n"; - $upsd_conf .= "REJECT all\n"; + $upsd_conf = "LISTEN 127.0.0.1\n"; + $upsd_conf .= "LISTEN ::1\n"; + $password = uniqid("nut"); /* upsd.users */ $upsd_users = "[monuser]\n"; - $upsd_users .= "password = mypass\n"; - $upsd_users .= "allowfrom = localhost\n"; + $upsd_users .= "password = {$password}\n"; $upsd_users .= "upsmon master\n"; if($allowaddr && $allowuser) { $upsd_users .= "\n[$allowuser]\n"; $upsd_users .= "password = $allowpass\n"; - $upsd_users .= "allowfrom = remote\n"; $upsd_users .= "upsmon master\n"; } /* upsmon.conf */ $upsmon_conf = <<<EOD -MONITOR {$name}@localhost 1 monuser mypass master +MONITOR {$name}@localhost 1 monuser {$password} master MINSUPPLIES 1 SHUTDOWNCMD "/sbin/shutdown {$shutdownflag} +0" POWERDOWNFLAG /etc/killpower @@ -386,30 +381,23 @@ EOD; $ups_conf .= "notransferoids=true\n"; /* upsd.conf */ - $upsd_conf = "ACL all 0.0.0.0/0\n"; - $upsd_conf .= "ACL localhost 127.0.0.1/32\n"; - if($allowaddr && $allowuser) { - $upsd_conf .= "ACL remote {$allowaddr}\n"; - $upsd_conf .= "ACCEPT remote\n"; - } - $upsd_conf .= "ACCEPT localhost\n"; - $upsd_conf .= "REJECT all\n"; + $upsd_conf = "LISTEN 127.0.0.1\n"; + $upsd_conf .= "LISTEN ::1\n"; + $password = uniqid("nut"); /* upsd.users */ $upsd_users = "[monuser]\n"; - $upsd_users .= "password = mypass\n"; - $upsd_users .= "allowfrom = localhost\n"; + $upsd_users .= "password = {$password}\n"; $upsd_users .= "upsmon master\n"; if($allowaddr && $allowuser) { $upsd_users .= "\n[$allowuser]\n"; $upsd_users .= "password = $allowpass\n"; - $upsd_users .= "allowfrom = remote\n"; $upsd_users .= "upsmon master\n"; } /* upsmon.conf */ $upsmon_conf = <<<EOD -MONITOR {$name}@localhost 1 monuser mypass master +MONITOR {$name}@localhost 1 monuser {$password} master MINSUPPLIES 1 SHUTDOWNCMD "/sbin/shutdown {$shutdownflag} +0" POWERDOWNFLAG /etc/killpower diff --git a/config/nut/nut.xml b/config/nut/nut.xml index b1fb705a..75a5c246 100644 --- a/config/nut/nut.xml +++ b/config/nut/nut.xml @@ -7,7 +7,7 @@ /* $Id$ */ /* ========================================================================== */ /* - authng.xml + nut.xml part of pfSense (http://www.pfSense.com) Copyright (C) 2007 to whom it may belong All rights reserved. @@ -46,7 +46,7 @@ <requirements>Describe your package requirements here</requirements> <faq>Currently there are no FAQ items provided.</faq> <name>nut</name> - <version>2.0.4</version> + <version>2.6.4 pkg 2.0</version> <title>Services: NUT</title> <savetext>Change</savetext> <aftersaveredirect>/status_nut.php</aftersaveredirect> @@ -122,7 +122,8 @@ <type>listtopic</type> </field> <field> - <fielddescr>Remote Access Address <br>(ex: 192.168.1.0/24)</fielddescr> + <fielddescr>Remote Access Address</fielddescr> + <description><strong>NOTE: Previous versions of NUT supported internal ACLs, these no longer work. The new default is to bind to localhost ONLY - you should add NAT rules for the NUT port (3493) to allow remote access. This field no longer has any effect, but was left intact for reference.</strong></description> <fieldname>allowaddr</fieldname> <type>input</type> </field> diff --git a/config/nut/status_nut.php b/config/nut/status_nut.php index ca575d12..3bee0ba0 100644 --- a/config/nut/status_nut.php +++ b/config/nut/status_nut.php @@ -34,6 +34,13 @@ $nut_config = $config['installedpackages']['nut']['config'][0]; /* functions */ +function secs2hms($secs) { + if ($secs<0) return false; + $m = (int)($secs / 60); $s = $secs % 60; + $h = (int)($m / 60); $m = $m % 60; + return "{$h}h {$m}m {$s}s"; +} + function tblopen () { print('<table width="100%" class="tabcont" cellspacing="0" cellpadding="6">'."\n"); } @@ -224,7 +231,7 @@ include("head.inc"); tblclose(); tblopen(); - tblrow('Runtime Remaining:', $ups['battery.runtime'], ' seconds'); + tblrow('Runtime Remaining:', secs2hms($ups['battery.runtime']), ''); tblrow('Battery Voltage:', $ups['battery.voltage'], 'V'); tblrow('Input Voltage:', $ups['input.voltage'], 'V'); tblrow('Input Frequency:', $ups['input.frequency'], 'Hz'); diff --git a/config/olsrd.inc b/config/olsrd.inc new file mode 100644 index 00000000..9db79f1f --- /dev/null +++ b/config/olsrd.inc @@ -0,0 +1,296 @@ +<?php +/* COPYRIGHT */ + +require_once("config.inc"); + +function setup_wireless_olsr() { + global $config, $g; + + if ($g['platform'] == 'jail' || !$config['installedpackages']['olsrd'] || !$config['installedpackages']) + return; + if(isset($config['system']['developerspew'])) { + $mt = microtime(); + echo "setup_wireless_olsr($interface) being called $mt\n"; + } + conf_mount_rw(); + + foreach($config['installedpackages']['olsrd']['config'] as $olsrd) { + $olsr_enable = $olsrd['enable']; + if ($olsr_enable <> "on") { + if (is_process_running("olsrd")) + mwexec("/usr/bin/killall olsrd", true); + return; + } + $fd = fopen("{$g['varetc_path']}/olsr.conf", "w"); + + if($olsrd['announcedynamicroute'] or $olsrd['enableannounce'] == "on") { + $enableannounce .= "\nHna4\n"; + $enableannounce .= "{\n"; + if($olsrd['announcedynamicroute']) + $enableannounce .= "\t{$olsrd['announcedynamicroute']}\n"; + if($olsrd['enableannounce'] == "on") + $enableannounce .= "0.0.0.0 0.0.0.0"; + $enableannounce .= "\n}\n"; + } else { + $enableannounce = ""; + } + + $olsr .= <<<EODA +# +# olsr.org OLSR daemon config file +# +# Lines starting with a # are discarded +# +# This file was generated by setup_wireless_olsr() in services.inc +# + +# This file is an example of a typical +# configuration for a mostly static +# network(regarding mobility) using +# the LQ extention + +# Debug level(0-9) +# If set to 0 the daemon runs in the background + +DebugLevel 2 + +# IP version to use (4 or 6) + +IpVersion 4 + +# Clear the screen each time the internal state changes + +ClearScreen yes + +{$enableannounce} + +# Should olsrd keep on running even if there are +# no interfaces available? This is a good idea +# for a PCMCIA/USB hotswap environment. +# "yes" OR "no" + +AllowNoInt yes + +# TOS(type of service) value for +# the IP header of control traffic. +# If not set it will default to 16 + +#TosValue 16 + +# The fixed willingness to use(0-7) +# If not set willingness will be calculated +# dynamically based on battery/power status +# if such information is available + +#Willingness 4 + +# Allow processes like the GUI front-end +# to connect to the daemon. + +IpcConnect +{ + # Determines how many simultaneously + # IPC connections that will be allowed + # Setting this to 0 disables IPC + + MaxConnections 0 + + # By default only 127.0.0.1 is allowed + # to connect. Here allowed hosts can + # be added + + Host 127.0.0.1 + #Host 10.0.0.5 + + # You can also specify entire net-ranges + # that are allowed to connect. Multiple + # entries are allowed + + #Net 192.168.1.0 255.255.255.0 +} + +# Wether to use hysteresis or not +# Hysteresis adds more robustness to the +# link sensing but delays neighbor registration. +# Used by default. 'yes' or 'no' + +UseHysteresis no + +# Hysteresis parameters +# Do not alter these unless you know +# what you are doing! +# Set to auto by default. Allowed +# values are floating point values +# in the interval 0,1 +# THR_LOW must always be lower than +# THR_HIGH. + +#HystScaling 0.50 +#HystThrHigh 0.80 +#HystThrLow 0.30 + + +# Link quality level +# 0 = do not use link quality +# 1 = use link quality for MPR selection +# 2 = use link quality for MPR selection and routing +# Defaults to 0 + +LinkQualityLevel {$olsrd['enablelqe']} + +# Link quality window size +# Defaults to 10 + +LinkQualityWinSize 10 + +# Polling rate in seconds(float). +# Default value 0.05 sec + +Pollrate 0.05 + + +# TC redundancy +# Specifies how much neighbor info should +# be sent in TC messages +# Possible values are: +# 0 - only send MPR selectors +# 1 - send MPR selectors and MPRs +# 2 - send all neighbors +# +# defaults to 0 + +TcRedundancy 2 + +# +# MPR coverage +# Specifies how many MPRs a node should +# try select to reach every 2 hop neighbor +# +# Can be set to any integer >0 +# +# defaults to 1 + +MprCoverage 3 + +# Example plugin entry with parameters: + +EODA; + +if($olsrd['enablehttpinfo'] == "on") { + $olsr .= <<<EODB + +LoadPlugin "/usr/local/lib/olsrd_httpinfo.so.0.1" +{ + PlParam "port" "{$olsrd['port']}" + PlParam "Net" "{$olsrd['allowedhttpinfohost']} {$olsrd['allowedhttpinfosubnet']}" +} + +EODB; + +} + +if($olsrd['enabledsecure'] == "on") { + @file_put_contents("{$g['tmp_path']}/olsrkey.txt", $olsrd['securekey']); + $olsr .= <<<EODC + +LoadPlugin "/usr/local/lib/olsrd_secure.so.0.5" +{ + PlParam "Keyfile" "{$g['tmp_path']}/olsrkey.txt" +} + +EODC; + +} + +if($olsrd['enabledyngw'] == "on") { + + /* unset default route, olsr auto negotiates */ + mwexec("/sbin/route delete default"); + + $olsr .= <<<EODE + +LoadPlugin "/usr/local/lib/olsrd_dyn_gw.so.0.4" +{ + # how often to look for a inet gw, in seconds + # defaults to 5 secs, if commented out + PlParam "Interval" "{$olsrd['polling']}" + + # if one or more IPv4 addresses are given, do a ping on these in + # descending order to validate that there is not only an entry in + # routing table, but also a real internet connection. If any of + # these addresses could be pinged successfully, the test was + # succesful, i.e. if the ping on the 1st address was successful,the + # 2nd won't be pinged + PlParam "Ping" "{$olsrd['ping']}" + #PlParam "HNA" "192.168.81.0 255.255.255.0" +} + +EODE; + +} + +foreach($config['installedpackages']['olsrd']['config'] as $conf) { + $interfaces = explode(',', $conf['iface_array']); + foreach($interfaces as $interface) { + $realinterface = convert_friendly_interface_to_real_interface_name($interface); +$olsr .= <<<EODAD +Interface "{$realinterface}" +{ + + # Hello interval in seconds(float) + HelloInterval 2.0 + + # HELLO validity time + HelloValidityTime 20.0 + + # TC interval in seconds(float) + TcInterval 5.0 + + # TC validity time + TcValidityTime 30.0 + + # MID interval in seconds(float) + MidInterval 5.0 + + # MID validity time + MidValidityTime 30.0 + + # HNA interval in seconds(float) + HnaInterval 5.0 + + # HNA validity time + HnaValidityTime 30.0 + + # When multiple links exist between hosts + # the weight of interface is used to determine + # the link to use. Normally the weight is + # automatically calculated by olsrd based + # on the characteristics of the interface, + # but here you can specify a fixed value. + # Olsrd will choose links with the lowest value. + + # Weight 0 + + +} + +EODAD; + + } + break; +} + fwrite($fd, $olsr); + fclose($fd); + } + + if (is_process_running("olsrd")) + mwexec("/usr/bin/killall olsrd", true); + + sleep(2); + + mwexec_bg("/usr/local/sbin/olsrd -f {$g['varetc_path']}/olsr.conf"); + + conf_mount_ro(); +} + +?> diff --git a/config/olsrd.xml b/config/olsrd.xml new file mode 100644 index 00000000..9709392d --- /dev/null +++ b/config/olsrd.xml @@ -0,0 +1,141 @@ +<?xml version="1.0" encoding="utf-8" ?> +<packagegui> + <name>olsrd</name> + <version>1.0</version> + <title>OLSRD</title> + <include_file>/usr/local/pkg/olsrd.inc</include_file> + <!-- Menu is where this packages menu will appear --> + <menu> + <name>OLSRD</name> + <section>Services</section> + <configfile>olsrd.xml</configfile> + </menu> + <service> + <name>OLSRD</name> + <rcfile>/usr/local/sbin/olsrd -f /var/etc/olsr.conf</rcfile> + </service> + <tabs> + <tab> + <text>OLSRD Settings</text> + <url>/pkg_edit.php?xml=olsrd.xml&id=0</url> + <active/> + </tab> + </tabs> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.com/packages/config/olsrd.inc</item> + </additional_files_needed> + <!-- configpath gets expanded out automatically and config items will be + stored in that location --> + <configpath>['installedpackages']['OLSRD']['config']</configpath> + <!-- fields gets invoked when the user adds or edits a item. the following items + will be parsed and rendered for the user as a gui with input, and selectboxes. --> + <fields> + <field> + <fielddescr>Enable OLSR</fielddescr> + <fieldname>enable</fieldname> + <description>Enables the dynamic mesh linking daemon</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Link Quality Level</fielddescr> + <fieldname>enablelqe</fieldname> + <type>select</type> + <size>1</size> + <options> + <option><value>2</value><name>2</name></option> + <option><value>0</value><name>0</name></option> + <option><value>1</value><name>1</name></option> + </options> + </field> + <field> + <fielddescr>Interfaces</fielddescr> + <fieldname>iface_array</fieldname> + <value>lan</value> + <multiple>true</multiple> + <size>3</size> + <type>interfaces_selection</type> + <description>Select the interfaces that OLSR will bind to. You can use the CTRL or COMMAND key to select multiple interfaces.</description> + </field> + <field> + <fielddescr>Enable HTTPInfo Plugin</fielddescr> + <fieldname>enablehttpinfo</fieldname> + <description>Enables the OLSR stats web server</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>HTTPInfo Port</fielddescr> + <fieldname>port</fieldname> + <description>Port that HTTPInfo will listen on</description> + <type>input</type> + </field> + <field> + <fielddescr>Allowed host(s)</fielddescr> + <fieldname>allowedhttpinfohost</fieldname> + <description>Hosts that are allowed to access the HTTPInfo web service.</description> + <type>input</type> + </field> + <field> + <fielddescr>Allowed host(s) subnet</fielddescr> + <fieldname>allowedhttpinfosubnet</fieldname> + <description>Enter the subnet mask in form 255.255.255.0</description> + <type>input</type> + </field> + <field> + <fielddescr>Enable Dynamic Gateway</fielddescr> + <fieldname>enabledyngw</fieldname> + <description>Enables the OLSR Dynamic Gateways feature</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Announce self as Dynamic Gateway</fielddescr> + <fieldname>enableannounce</fieldname> + <description>Enables the OLSR Dynamic Gateways Announcing feature</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Announce Dynamic local route</fielddescr> + <fieldname>announcedynamicroute</fieldname> + <description>Enter the IP/Netmask</description> + <type>textarea</type> + <rows>3</rows> + <cols>50</cols> + </field> + <field> + <fielddescr>Ping</fielddescr> + <fieldname>ping</fieldname> + <description>Pings this host to ensure connectivity</description> + <type>input</type> + </field> + <field> + <fielddescr>Poll</fielddescr> + <fieldname>polling</fieldname> + <description>How often to look for a inet gw, in seconds.</description> + <type>input</type> + </field> + <field> + <fielddescr>Enable Secure Mode</fielddescr> + <fieldname>enabledsecure</fieldname> + <description>Enables the secure mode</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Key</fielddescr> + <fieldname>securekey</fieldname> + <description>Paste the secure key information here.</description> + <type>textarea</type> + <rows>5</rows> + <cols>50</cols> + </field> + </fields> + <custom_delete_php_command> + </custom_delete_php_command> + <custom_php_resync_config_command> + setup_wireless_olsr($if); + </custom_php_resync_config_command> + <custom_php_install_command> + </custom_php_install_command> + <custom_php_deinstall_command> + </custom_php_deinstall_command> +</packagegui> diff --git a/config/openbgpd/openbgpd.inc b/config/openbgpd/openbgpd.inc index 3f9d5ab0..573745be 100644 --- a/config/openbgpd/openbgpd.inc +++ b/config/openbgpd/openbgpd.inc @@ -28,57 +28,79 @@ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +require_once("config.inc"); +require_once("functions.inc"); +require_once("service-utils.inc"); + +define('PKG_BGPD_CONFIG_BASE', '/var/etc/openbgpd'); + +define('PKG_BGPD_LOGIN', "_bgpd"); +define('PKG_BGPD_UID', "130"); +define('PKG_BGPD_GROUP', "_bgpd"); +define('PKG_BGPD_GID', "130"); +define('PKG_BGPD_GECOS', "BGP Daemon"); +define('PKG_BGPD_HOMEDIR', "/var/empty"); +define('PKG_BGPD_SHELL', "/usr/sbin/nologin"); function openbgpd_install_conf() { global $config, $g; - + $pkg_login = PKG_BGPD_LOGIN; + $pkg_uid = PKG_BGPD_UID; + $pkg_group = PKG_BGPD_GROUP; + $pkg_gid = PKG_BGPD_GID; + $pkg_gecos = PKG_BGPD_GECOS; + $pkg_homedir = PKG_BGPD_HOMEDIR; + $pkg_shell = PKG_BGPD_SHELL; + conf_mount_rw(); - + + // Since we need to embed this in a string, copy to a var. Can't embed constnats. + $bgpd_config_base = PKG_BGPD_CONFIG_BASE; if ($config['installedpackages']['openbgpd']['rawconfig'] && $config['installedpackages']['openbgpd']['rawconfig']['item']) { // if there is a raw config specified in the config.xml use that instead of the assisted config $conffile = implode("\n",$config['installedpackages']['openbgpd']['rawconfig']['item']); //$conffile = $config['installedpackages']['openbgpd']['rawconfig']; } else { // generate bgpd.conf based on the assistant - if($config['installedpackages']['openbgpd']['config']) + if($config['installedpackages']['openbgpd']['config']) $openbgpd_conf = &$config['installedpackages']['openbgpd']['config'][0]; if($config['installedpackages']['openbgpd']['config'][0]['row']) - $openbgpd_rows = &$config['installedpackages']['openbgpd']['config'][0]['row']; + $openbgpd_rows = &$config['installedpackages']['openbgpd']['config'][0]['row']; if($config['installedpackages']['openbgpdgroups']['config']) $openbgpd_groups = &$config['installedpackages']['openbgpdgroups']['config']; if($config['installedpackages']['openbgpdneighbors']['config']) $openbgpd_neighbors = &$config['installedpackages']['openbgpdneighbors']['config']; - - $conffile = "# This file was created by the pfSense package manager. Do not edit!\n\n"; + + $conffile = "# This file was created by the package manager. Do not edit!\n\n"; $setkeycf = ""; - + // Setup AS # - if($openbgpd_conf['asnum']) + if($openbgpd_conf['asnum']) $conffile .= "AS {$openbgpd_conf['asnum']}\n"; - + if($openbgpd_conf['fibupdate']) $conffile .= "fib-update {$openbgpd_conf['fibupdate']}\n"; - + // Setup holdtime if defined. Default is 90. - if($openbgpd_conf['holdtime']) + if($openbgpd_conf['holdtime']) $conffile .= "holdtime {$openbgpd_conf['holdtime']}\n"; // Specify listen ip - if($openbgpd_conf['listenip']) + if($openbgpd_conf['listenip']) $conffile .= "listen on {$openbgpd_conf['listenip']}\n"; // Specify router id - if($openbgpd_conf['routerid']) + if($openbgpd_conf['routerid']) $conffile .= "router-id {$openbgpd_conf['routerid']}\n"; // Handle advertised networks if($config['installedpackages']['openbgpd']['config'][0]['row']) if(is_array($openbgpd_rows)) - foreach($openbgpd_rows as $row) + foreach($openbgpd_rows as $row) $conffile .= "network {$row['networks']}\n"; - + // Attach neighbors to their respective group owner - if(is_array($openbgpd_groups)) { + if(is_array($openbgpd_groups)) { foreach($openbgpd_groups as $group) { $conffile .= "group \"{$group['name']}\" {\n"; $conffile .= " remote-as {$group['remoteas']}\n"; @@ -98,16 +120,16 @@ function openbgpd_install_conf() { } foreach($neighbor['row'] as $row) { $conffile .= " {$row['parameters']} {$row['parmvalue']} \n"; - } + } $conffile .= "}\n"; } } } $conffile .= "}\n"; } - } + } - // Handle neighbors that do not have a group assigned to them + // Handle neighbors that do not have a group assigned to them if(is_array($openbgpd_neighbors)) { foreach($openbgpd_neighbors as $neighbor) { $used_this_item = false; @@ -131,41 +153,56 @@ function openbgpd_install_conf() { if($used_this_item) $conffile .= "}\n"; } - } - + } + // OpenBGPD filters $conffile .= "deny from any\n"; $conffile .= "deny to any\n"; if(is_array($openbgpd_neighbors)) { foreach($openbgpd_neighbors as $neighbor) { $conffile .= "allow from {$neighbor['neighbor']}\n"; - $conffile .= "allow to {$neighbor['neighbor']}\n"; + $conffile .= "allow to {$neighbor['neighbor']}\n"; } } } + safe_mkdir($bgpd_config_base); + $fd = fopen("{$bgpd_config_base}/bgpd.conf", "w"); - $fd = fopen("/usr/local/etc/bgpd.conf", "w"); - // Write out the configuration file fwrite($fd, $conffile); - + // Close file handle fclose($fd); - + // Create rc.d file - $fd = fopen("/usr/local/etc/rc.d/bgpd.sh","w"); - fwrite($fd, "#!/bin/sh\n\n"); - fwrite($fd, "# This file was created by the pfSense package manager. Do not edit!\n\n"); - fwrite($fd, "NUMBGPD=`ps auxw | grep bgpd | grep parent | grep -v grep | wc -l | awk '{print \$1}'`\n"); - fwrite($fd, "# echo \$NUMBGPD\n"); - fwrite($fd, "if [ \$NUMBGPD -lt 1 ] ; then\n"); - fwrite($fd, " /usr/local/sbin/bgpd -f /usr/local/etc/bgpd.conf\n"); - fwrite($fd, "fi\n"); - fclose($fd); - exec("chmod a+rx /usr/local/etc/rc.d/bgpd.sh"); - exec("chmod a-rw /usr/local/etc/bgpd.conf"); - exec("chmod u+rw /usr/local/etc/bgpd.conf"); - + $rc_file_stop = <<<EOF +killall -9 bgpd +EOF; + $rc_file_start = <<<EOF + +if [ `pw groupshow {$pkg_group} 2>&1 | grep -c "pw: unknown group"` -gt 0 ]; then + /usr/sbin/pw groupadd {$pkg_group} -g {$pkg_gid} +fi +if [ `pw usershow {$pkg_login} 2>&1 | grep -c "pw: no such user"` -gt 0 ]; then + /usr/sbin/pw useradd {$pkg_login} -u {$pkg_uid} -g {$pkg_gid} -c "{$pkg_gecos}" -d {$pkg_homedir} -s {$pkg_shell} +fi + +/bin/mkdir -p {$bgpd_config_base} +chmod u+rw,go-rw {$bgpd_config_base}/bgpd.conf +/usr/sbin/chown -R root:wheel {$bgpd_config_base} + +NUMBGPD=`ps auxw | grep -c '[b]gpd.*parent'` +if [ \${NUMBGPD} -lt 1 ] ; then + /usr/local/sbin/bgpd -f {$bgpd_config_base}/bgpd.conf +fi +EOF; + write_rcfile(array( + "file" => "bgpd.sh", + "start" => $rc_file_start, + "stop" => $rc_file_stop + ) + ); + // TCP-MD5 support on freebsd. See tcp(5) for more $fd = fopen("{$g['tmp_path']}/bgpdsetkey.conf", "w"); fwrite($fd, $setkeycf ); @@ -178,13 +215,17 @@ function openbgpd_install_conf() { } else { exec("bgpd"); } - + conf_mount_ro(); } // get the raw openbgpd confi file for manual inspection/editing function openbgpd_get_raw_config() { - return file_get_contents("/usr/local/etc/bgpd.conf"); + $conf = PKG_BGPD_CONFIG_BASE . "/bgpd.conf"; + if (file_exists($conf)) + return file_get_contents($conf); + else + return ""; } // serialize the raw openbgpd config file to config.xml @@ -225,19 +266,19 @@ function deinstall_openbgpd() { function check_group_usage($groupname) { global $config, $g; - if($config['installedpackages']['openbgpd']['config']) + if($config['installedpackages']['openbgpd']['config']) $openbgpd_conf = &$config['installedpackages']['openbgpd']['config'][0]; if($config['installedpackages']['openbgpd']['config'][0]['row']) - $openbgpd_rows = &$config['installedpackages']['openbgpd']['config'][0]['row']; + $openbgpd_rows = &$config['installedpackages']['openbgpd']['config'][0]['row']; if($config['installedpackages']['openbgpdgroups']['config']) $openbgpd_groups = &$config['installedpackages']['openbgpdgroups']['config']; if($config['installedpackages']['openbgpdneighbors']['config']) $openbgpd_neighbors = &$config['installedpackages']['openbgpdneighbors']['config']; - if(is_array($openbgpd_groups)) { + if(is_array($openbgpd_groups)) { foreach($openbgpd_groups as $group) { foreach($openbgpd_neighbors as $neighbor) { - if($neighbor['groupname'] == $group['name']) + if($neighbor['groupname'] == $group['name']) return $neighbor['groupname']; } } @@ -251,16 +292,16 @@ function bgpd_validate_input() { if (!empty($_POST['asnum']) && !is_numeric($_POST['asnum'])) $input_errors[] = "AS must be entered as a number only."; - + if (!empty($_POST['routerid']) && !is_ipaddr($_POST['routerid'])) $input_errors[] = "Router ID must be an IP address."; - + if (!empty($_POST['holdtime']) && !is_numeric($_POST['holdtime'])) $input_errors[] = "Holdtime must be entered as a number."; - + if (!empty($_POST['listenip']) && !is_ipaddr($_POST['listenip'])) $input_errors[] = "Listen IP must be an IP address or blank to bind to all IPs."; - + } function bgpd_validate_group() { @@ -268,12 +309,12 @@ function bgpd_validate_group() { if (!is_numeric($_POST['remoteas'])) $input_errors[] = "Remote AS must be entered as a number only."; - + if ($_POST['name'] == "") $input_errors[] = "You must enter a name."; - + $_POST['name'] = remove_bad_chars($_POST['name']); - + } function remove_bad_chars($string) { @@ -293,7 +334,7 @@ function grey_out_value_boxes() { var last_two = fieldvalue.substring(length); var without_last_two = fieldvalue.substring(0,length); if( \$('parmvalue' + x) ) { - if(last_two != ' X') { + if(last_two != ' X') { \$('parmvalue' + x).value = ''; \$('parmvalue' + x).disabled = true; } else { @@ -303,21 +344,21 @@ function grey_out_value_boxes() { } } var timerID = setTimeout("grey_out_value_boxes()", 1200); - - } + + } grey_out_value_boxes(); - </script> + </script> + - EOF; - + } function is_openbgpd_running() { - $status = `ps awux | grep bgpd | grep "parent" | grep -v grep | wc -l | awk '{ print \$1 }'`; - if(intval($status) > 0) + $status = `ps auxw | grep -c '[b]gpd.*parent'`; + if(intval($status) > 0) return true; - else + else return false; } diff --git a/config/openospfd/openospfd.inc b/config/openospfd/openospfd.inc index bea9bf20..86e043d5 100644 --- a/config/openospfd/openospfd.inc +++ b/config/openospfd/openospfd.inc @@ -26,6 +26,9 @@ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +require_once("config.inc"); +require_once("functions.inc"); +require_once("service-utils.inc"); function ospfd_display_friendlyiface () { global $evaledvar, $config, $g; @@ -74,6 +77,8 @@ function ospfd_install_conf() { if (is_array($ospfd_conf['row'])) { foreach ($ospfd_conf['row'] as $redistr) { + if (empty($redistr['routevalue'])) + continue; if (isset($redistr['redistribute'])) $conffile .= "no "; $conffile .= "redistribute {$redistr['routevalue']}\n"; diff --git a/config/openvpn-client-export/openvpn-client-export.inc b/config/openvpn-client-export/openvpn-client-export.inc index f023bf21..026efabb 100755 --- a/config/openvpn-client-export/openvpn-client-export.inc +++ b/config/openvpn-client-export/openvpn-client-export.inc @@ -3,7 +3,7 @@ openvpn-client-export.inc Copyright (C) 2009 Scott Ullrich <sullrich@gmail.com> Copyright (C) 2008 Shrew Soft Inc - Copyright (C) 2010 Ermal Lu�i + Copyright (C) 2010 Ermal Luci All rights reserved. Parts of this code was originally based on vpn_ipsec_sad.php @@ -95,10 +95,8 @@ function openvpn_client_pem_to_pk12($outpath, $outpass, $crtpath, $keypath, $cap unlink($capath); } -function openvpn_client_export_config($srvid, $usrid, $crtid, $useaddr, $usetoken, $nokeys = false, $proxy, $zipconf = false, $outpass = "", $skiptls=false, $doslines=false, $advancedoptions = "") { - global $config, $input_errors, $g; - - $nl = ($doslines) ? "\r\n" : "\n"; +function openvpn_client_export_validate_config($srvid, $usrid, $crtid) { + global $config, $g, $input_errors; // lookup server settings $settings = $config['openvpn']['openvpn-server'][$srvid]; @@ -150,6 +148,21 @@ function openvpn_client_export_config($srvid, $usrid, $crtid, $useaddr, $usetoke } else $nokeys = true; + return array($settings, $server_cert, $server_ca, $servercn, $user, $cert, $nokeys); +} + +function openvpn_client_export_config($srvid, $usrid, $crtid, $useaddr, $quoteservercn, $usetoken, $nokeys = false, $proxy, $expformat = "baseconf", $outpass = "", $skiptls=false, $doslines=false, $advancedoptions = "") { + global $config, $input_errors, $g; + + $nl = ($doslines) ? "\r\n" : "\n"; + + $validconfig = openvpn_client_export_validate_config($srvid, $usrid, $crtid); + if ($validconfig) { + list($settings, $server_cert, $server_ca, $servercn, $user, $cert, $nokeys) = $validconfig; + } else { + return false; + } + // determine basic variables if ($useaddr == "serveraddr") { $interface = $settings['interface']; @@ -162,7 +175,7 @@ function openvpn_client_export_config($srvid, $usrid, $crtid, $useaddr, $usetoke } } else if ($useaddr == "serverhostname" || empty($useaddr)) { $server_host = empty($config['system']['hostname']) ? "" : "{$config['system']['hostname']}."; - $server_host .= "{{$config['system']['domain']}"; + $server_host .= "{$config['system']['domain']}"; } else $server_host = $useaddr; @@ -185,8 +198,10 @@ function openvpn_client_export_config($srvid, $usrid, $crtid, $useaddr, $usetoke $conf .= "client{$nl}"; $conf .= "resolv-retry infinite{$nl}"; $conf .= "remote {$server_host} {$server_port}{$nl}"; - if (!empty($servercn)) - $conf .= "tls-remote {$servercn}{$nl}"; + if (!empty($servercn)) { + $qw = ($quoteservercn) ? "\"" : ""; + $conf .= "tls-remote {$qw}{$servercn}{$qw}{$nl}"; + } if (!empty($proxy)) { if ($proto == "udp") { @@ -214,17 +229,52 @@ function openvpn_client_export_config($srvid, $usrid, $crtid, $useaddr, $usetoke $prefix = openvpn_client_export_prefix($srvid); $cafile = "{$prefix}-ca.crt"; if($nokeys == false) { - if ($usetoken) { + if ($expformat == "inline") { + $conf .= "ca [inline]{$nl}"; + $conf .= "cert [inline]{$nl}"; + $conf .= "key [inline]{$nl}"; + } elseif ($expformat == "yealink_t28") { + $conf .= "ca /yealink/config/openvpn/keys/ca.crt{$nl}"; + $conf .= "cert /yealink/config/openvpn/keys/client1.crt{$nl}"; + $conf .= "key /yealink/config/openvpn/keys/client1.key{$nl}"; + } elseif ($expformat == "yealink_t38g") { + $conf .= "ca /phone/config/openvpn/keys/ca.crt{$nl}"; + $conf .= "cert /phone/config/openvpn/keys/client1.crt{$nl}"; + $conf .= "key /phone/config/openvpn/keys/client1.key{$nl}"; + } elseif ($expformat == "yealink_t38g2") { + $conf .= "ca /config/openvpn/keys/ca.crt{$nl}"; + $conf .= "cert /config/openvpn/keys/client1.crt{$nl}"; + $conf .= "key /config/openvpn/keys/client1.key{$nl}"; + } elseif ($expformat == "snom") { + $conf .= "ca /openvpn/ca.crt{$nl}"; + $conf .= "cert /openvpn/phone1.crt{$nl}"; + $conf .= "key /openvpn/phone1.key{$nl}"; + } elseif ($usetoken) { $conf .= "ca {$cafile}{$nl}"; $conf .= "cryptoapicert \"SUBJ:{$user['name']}\"{$nl}"; } else { $conf .= "pkcs12 {$prefix}.p12{$nl}"; } - } else if ($settings['mode'] == "server_user") - $conf .= "ca {$cafile}{$nl}"; + } else if ($settings['mode'] == "server_user") { + if ($expformat == "inline") + $conf .= "ca [inline]{$nl}"; + else + $conf .= "ca {$cafile}{$nl}"; + } if ($settings['tls'] && !$skiptls) { - $conf .= "tls-auth {$prefix}-tls.key 1{$nl}"; + if ($expformat == "inline") + $conf .= "tls-auth [inline] 1{$nl}"; + elseif ($expformat == "yealink_t28") + $conf .= "tls-auth /yealink/config/openvpn/keys/ta.key 1{$nl}"; + elseif ($expformat == "yealink_t38g") + $conf .= "tls-auth /phone/config/openvpn/keys/ta.key 1{$nl}"; + elseif ($expformat == "yealink_t38g2") + $conf .= "tls-auth /config/openvpn/keys/ta.key 1{$nl}"; + elseif ($expformat == "snom") + $conf .= "tls-auth /openvpn/ta.key 1{$nl}"; + else + $conf .= "tls-auth {$prefix}-tls.key 1{$nl}"; } // Prevent MITM attacks by verifying the server certificate. @@ -251,102 +301,143 @@ function openvpn_client_export_config($srvid, $usrid, $crtid, $useaddr, $usetoke $conf .= $advancedoptions; $conf .= $nl; - if ($zipconf == true) { - // create template directory - $tempdir = "{$g['tmp_path']}/{$prefix}"; - mkdir($tempdir, 0700, true); - - file_put_contents("{$tempdir}/{$prefix}.ovpn", $conf); - - $cafile = "{$tempdir}/{$cafile}"; - file_put_contents("{$cafile}", base64_decode($server_ca['crt'])); - if ($settings['tls']) { - $tlsfile = "{$tempdir}/{$prefix}-tls.key"; - file_put_contents($tlsfile, base64_decode($settings['tls'])); - } - - // write key files - if ($settings['mode'] != "server_user") { - $crtfile = "{$tempdir}/{$prefix}-cert.crt"; - file_put_contents($crtfile, base64_decode($cert['crt'])); - $keyfile = "{$tempdir}/{$prefix}.key"; - file_put_contents($keyfile, base64_decode($cert['prv'])); - - // convert to pkcs12 format - $p12file = "{$tempdir}/{$prefix}.p12"; - if ($usetoken) - openvpn_client_pem_to_pk12($p12file, $outpass, $crtfile, $keyfile); - else - openvpn_client_pem_to_pk12($p12file, $outpass, $crtfile, $keyfile, $cafile); - - } - exec("cd {$tempdir}/.. && /usr/local/bin/zip -r {$g['tmp_path']}/{$prefix}-config.zip {$prefix}"); - - // Remove temporary directory - exec("rm -rf {$tempdir}"); - return "{$prefix}-config.zip"; - } else - return $conf; + switch ($expformat) { + case "zip": + // create template directory + $tempdir = "{$g['tmp_path']}/{$prefix}"; + mkdir($tempdir, 0700, true); + + file_put_contents("{$tempdir}/{$prefix}.ovpn", $conf); + + $cafile = "{$tempdir}/{$cafile}"; + file_put_contents("{$cafile}", base64_decode($server_ca['crt'])); + if ($settings['tls']) { + $tlsfile = "{$tempdir}/{$prefix}-tls.key"; + file_put_contents($tlsfile, base64_decode($settings['tls'])); + } + + // write key files + if ($settings['mode'] != "server_user") { + $crtfile = "{$tempdir}/{$prefix}-cert.crt"; + file_put_contents($crtfile, base64_decode($cert['crt'])); + $keyfile = "{$tempdir}/{$prefix}.key"; + file_put_contents($keyfile, base64_decode($cert['prv'])); + + // convert to pkcs12 format + $p12file = "{$tempdir}/{$prefix}.p12"; + if ($usetoken) + openvpn_client_pem_to_pk12($p12file, $outpass, $crtfile, $keyfile); + else + openvpn_client_pem_to_pk12($p12file, $outpass, $crtfile, $keyfile, $cafile); + } + exec("cd {$tempdir}/.. && /usr/local/bin/zip -r {$g['tmp_path']}/{$prefix}-config.zip {$prefix}"); + // Remove temporary directory + exec("rm -rf {$tempdir}"); + return $g['tmp_path'] . "/{$prefix}-config.zip"; + break; + case "inline": + // Inline CA + $conf .= "<ca>{$nl}" . base64_decode($server_ca['crt']) . "</ca>{$nl}"; + if ($settings['mode'] != "server_user") { + // Inline Cert + $conf .= "<cert>{$nl}" . base64_decode($cert['crt']) . "</cert>{$nl}"; + // Inline Key + $conf .= "<key>{$nl}" . base64_decode($cert['prv']) . "</key>{$nl}"; + } + // Inline TLS + if ($settings['tls']) { + $conf .= "<tls-auth>{$nl}" . base64_decode($settings['tls']) . "</tls-auth>{$nl} key-direction 1{$nl}"; + } + return $conf; + break; + case "yealink_t28": + case "yealink_t38g": + case "yealink_t38g2": + // create template directory + $tempdir = "{$g['tmp_path']}/{$prefix}"; + $keydir = "{$tempdir}/keys"; + mkdir($tempdir, 0700, true); + mkdir($keydir, 0700, true); + + file_put_contents("{$tempdir}/vpn.cnf", $conf); + + $cafile = "{$keydir}/ca.crt"; + file_put_contents("{$cafile}", base64_decode($server_ca['crt'])); + if ($settings['tls']) { + $tlsfile = "{$keydir}/ta.key"; + file_put_contents($tlsfile, base64_decode($settings['tls'])); + } + + // write key files + if ($settings['mode'] != "server_user") { + $crtfile = "{$keydir}/client1.crt"; + file_put_contents($crtfile, base64_decode($cert['crt'])); + $keyfile = "{$keydir}/client1.key"; + file_put_contents($keyfile, base64_decode($cert['prv'])); + } + exec("tar -C {$tempdir} -cf {$g['tmp_path']}/client.tar ./keys ./vpn.cnf"); + // Remove temporary directory + exec("rm -rf {$tempdir}"); + return $g['tmp_path'] . "/client.tar"; + break; + case "snom": + // create template directory + $tempdir = "{$g['tmp_path']}/{$prefix}"; + mkdir($tempdir, 0700, true); + + file_put_contents("{$tempdir}/vpn.cnf", $conf); + + $cafile = "{$tempdir}/ca.crt"; + file_put_contents("{$cafile}", base64_decode($server_ca['crt'])); + if ($settings['tls']) { + $tlsfile = "{$tempdir}/ta.key"; + file_put_contents($tlsfile, base64_decode($settings['tls'])); + } + + // write key files + if ($settings['mode'] != "server_user") { + $crtfile = "{$tempdir}/phone1.crt"; + file_put_contents($crtfile, base64_decode($cert['crt'])); + $keyfile = "{$tempdir}/phone1.key"; + file_put_contents($keyfile, base64_decode($cert['prv'])); + } + exec("cd {$tempdir}/ && tar -cf {$g['tmp_path']}/vpnclient.tar *"); + // Remove temporary directory + exec("rm -rf {$tempdir}"); + return $g['tmp_path'] . "/vpnclient.tar"; + break; + default: + return $conf; + } } -function openvpn_client_export_installer($srvid, $usrid, $crtid, $useaddr, $usetoken, $outpass, $proxy, $advancedoptions) { +function openvpn_client_export_installer($srvid, $usrid, $crtid, $useaddr, $quoteservercn, $usetoken, $outpass, $proxy, $advancedoptions, $openvpn_version = "2.1") { global $config, $g, $input_errors; $uname_p = trim(exec("uname -p")); + switch ($openvpn_version) { + case "2.3-x86": + $client_install_exe = "openvpn-install-2.3-i686.exe"; + break; + case "2.3-x64": + $client_install_exe = "openvpn-install-2.3-x86_64.exe"; + break; + default: + $client_install_exe = "openvpn-install-2.2.exe"; + } + $ovpndir = "/usr/local/share/openvpn"; $workdir = "{$ovpndir}/client-export"; - if (!file_exists($workdir . "/template/openvpn-install.exe")) + if (!file_exists($workdir . "/template/{$client_install_exe}")) openvpn_client_export_install(); - // lookup server settings - $settings = $config['openvpn']['openvpn-server'][$srvid]; - if (empty($settings)) { - $input_errors[] = "Could not find a valid server config for id: {$srvid}"; - return false; - } - if ($settings['disable']) { - $input_errors[] = "This server is disabled."; - return false; - } - - $nokeys = false; - - // lookup server certificate info - $server_cert = lookup_cert($settings['certref']); - $server_ca = lookup_ca($server_cert['caref']); - if (!$server_cert || !$server_ca) { - $input_errors[] = "Could not find a valid certificate."; + $validconfig = openvpn_client_export_validate_config($srvid, $usrid, $crtid); + if ($validconfig) { + list($settings, $server_cert, $server_ca, $servercn, $user, $cert, $nokeys) = $validconfig; + } else { return false; } - // lookup user info - if ($usrid) { - $user = $config['system']['user'][$usrid]; - if (!$user) { - $input_errors[] = "Could not find the details about userid: {$usrid}"; - return false; - } - } - - // lookup user certificate info - if ($settings['mode'] == "server_tls_user") { - if ($settings['authmode'] == "Local Database") { - $cert = $user['cert'][$crtid]; - } else { - $cert = $config['cert'][$crtid]; - } - if (!$cert) - return false; - // If $cert is not an array, it's a certref not a cert. - if (!is_array($cert)) - $cert = lookup_cert($cert); - } elseif (($settings['mode'] == "server_tls") || (($settings['mode'] == "server_tls_user") && ($settings['authmode'] != "Local Database"))) { - $cert = $config['cert'][$crtid]; - if (!$cert) - return false; - } else - $nokeys = true; - // create template directory $tempdir = $g['tmp_path'] . "/openvpn-export-".uniqid(); mkdir($tempdir, 0700, true); @@ -358,8 +449,10 @@ function openvpn_client_export_installer($srvid, $usrid, $crtid, $useaddr, $uset // copy the template directory exec("cp -r {$workdir}/template/* {$tempdir}"); + // and put the required installer exe in place + exec("/bin/cp {$tempdir}/{$client_install_exe} {$tempdir}/openvpn-install.exe"); - // write cofiguration file + // write configuration file $prefix = openvpn_client_export_prefix($srvid); $cfgfile = "{$confdir}/{$prefix}-config.ovpn"; if (!empty($proxy) && $proxy['proxy_authtype'] != "none") { @@ -368,7 +461,7 @@ function openvpn_client_export_installer($srvid, $usrid, $crtid, $useaddr, $uset $pwdfle .= "{$proxy['password']}\r\n"; file_put_contents("{$confdir}/{$proxy['passwdfile']}", $pwdfle); } - $conf = openvpn_client_export_config($srvid, $usrid, $crtid, $useaddr, $usetoken, $nokeys, $proxy, false, "", false, true, $advancedoptions); + $conf = openvpn_client_export_config($srvid, $usrid, $crtid, $useaddr, $quoteservercn, $usetoken, $nokeys, $proxy, "", "baseconf", false, true, $advancedoptions); if (!$conf) { $input_errors[] = "Could not create a config to export."; return false; @@ -427,7 +520,7 @@ function openvpn_client_export_installer($srvid, $usrid, $crtid, $useaddr, $uset return $outfile; } -function viscosity_openvpn_client_config_exporter($srvid, $usrid, $crtid, $useaddr, $usetoken, $outpass, $proxy, $advancedoptions) { +function viscosity_openvpn_client_config_exporter($srvid, $usrid, $crtid, $useaddr, $quoteservercn, $usetoken, $outpass, $proxy, $advancedoptions) { global $config, $g; $uname_p = trim(exec("uname -p")); @@ -439,45 +532,13 @@ function viscosity_openvpn_client_config_exporter($srvid, $usrid, $crtid, $usead $tempdir = $g['tmp_path'] . "/openvpn-export-" . $uniq; $zipfile = $g['tmp_path'] . "/{$uniq}-Viscosity.visc.zip"; - // lookup server settings - $settings = $config['openvpn']['openvpn-server'][$srvid]; - if (empty($settings)) + $validconfig = openvpn_client_export_validate_config($srvid, $usrid, $crtid); + if ($validconfig) { + list($settings, $server_cert, $server_ca, $servercn, $user, $cert, $nokeys) = $validconfig; + } else { return false; - if ($settings['disable']) - return false; - - // lookup server certificate info - $server_cert = lookup_cert($settings['certref']); - $server_ca = lookup_ca($server_cert['caref']); - if (!$server_cert || !$server_ca) - return false; - - // lookup user info - if ($usrid) { - $user = $config['system']['user'][$usrid]; - if (!$user) - return false; } - // lookup user certificate info - if ($settings['mode'] == "server_tls_user") { - if ($settings['authmode'] == "Local Database") { - $cert = $user['cert'][$crtid]; - } else { - $cert = $config['cert'][$crtid]; - } - if (!$cert) - return false; - // If $cert is not an array, it's a certref not a cert. - if (!is_array($cert)) - $cert = lookup_cert($cert); - } elseif (($settings['mode'] == "server_tls") || (($settings['mode'] == "server_tls_user") && ($settings['authmode'] != "Local Database"))) { - $cert = $config['cert'][$crtid]; - if (!$cert) - return false; - } else - $nokeys = true; - // create template directory mkdir($tempdir, 0700, true); mkdir($tempdir . "/Viscosity.visc", 0700, true); @@ -494,7 +555,7 @@ function viscosity_openvpn_client_config_exporter($srvid, $usrid, $crtid, $usead file_put_contents("{$tempdir}/{$proxy['passwdfile']}", $pwdfle); } - $conf = openvpn_client_export_config($srvid, $usrid, $crtid, $useaddr, $usetoken, true, $proxy, false, "", true, $advancedoptions); + $conf = openvpn_client_export_config($srvid, $usrid, $crtid, $useaddr, $quoteservercn, $usetoken, true, $proxy, "baseconf", "", true, $advancedoptions); if (!$conf) return false; @@ -602,7 +663,7 @@ function openvpn_client_export_sharedkey_config($srvid, $useaddr, $proxy, $zipco } } else if ($useaddr == "serverhostname" || empty($useaddr)) { $server_host = empty($config['system']['hostname']) ? "" : "{$config['system']['hostname']}."; - $server_host .= "{{$config['system']['domain']}"; + $server_host .= "{$config['system']['domain']}"; } else $server_host = $useaddr; diff --git a/config/openvpn-client-export/openvpn-client-export.xml b/config/openvpn-client-export/openvpn-client-export.xml index 825aa60c..02949cbd 100755 --- a/config/openvpn-client-export/openvpn-client-export.xml +++ b/config/openvpn-client-export/openvpn-client-export.xml @@ -1,7 +1,7 @@ <?xml version="1.0" encoding="utf-8" ?> <packagegui> <name>OpenVPN Client Export</name> - <version>0.9.1</version> + <version>0.24</version> <title>OpenVPN Client Export</title> <include_file>/usr/local/pkg/openvpn-client-export.inc</include_file> <backup_file></backup_file> diff --git a/config/openvpn-client-export/vpn_openvpn_export.php b/config/openvpn-client-export/vpn_openvpn_export.php index 43ed56fd..414ad7d0 100755 --- a/config/openvpn-client-export/vpn_openvpn_export.php +++ b/config/openvpn-client-export/vpn_openvpn_export.php @@ -1,21 +1,21 @@ -<?php +<?php /* vpn_openvpn_export.php Copyright (C) 2008 Shrew Soft Inc. Copyright (C) 2010 Ermal Lu�i - All rights reserved. + 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 @@ -67,7 +67,7 @@ foreach($a_server as $sindex => $server) { // If $cert is not an array, it's a certref not a cert. if (!is_array($cert)) $cert = lookup_cert($cert); - + if ($cert['caref'] != $server['caref']) continue; $ras_userent = array(); @@ -112,8 +112,8 @@ $act = $_GET['act']; if (isset($_POST['act'])) $act = $_POST['act']; -$error = false; -if($act == "conf" || $act == "confall") { +if (!empty($act)) { + $srvid = $_GET['srvid']; $usrid = $_GET['usrid']; $crtid = $_GET['crtid']; @@ -132,14 +132,17 @@ if($act == "conf" || $act == "confall") { $nokeys = false; if (empty($_GET['useaddr'])) { - $error = true; $input_errors[] = "You need to specify an IP or hostname."; } else $useaddr = $_GET['useaddr']; - $advancedoptions = $_GET['advancedoptions']; + $quoteservercn = $_GET['quoteservercn']; $usetoken = $_GET['usetoken']; + if ($usetoken && ($act == "confinline")) + $input_errors[] = "You cannot use Microsoft Certificate Storage with an Inline configuration."; + if ($usetoken && (($act == "conf_yealink_t28") || ($act == "conf_yealink_t38g") || ($act == "conf_yealink_t38g2") || ($act == "conf_snom"))) + $input_errors[] = "You cannot use Microsoft Certificate Storage with a Yealink or SNOM configuration."; $password = ""; if ($_GET['password']) $password = $_GET['password']; @@ -148,24 +151,20 @@ if($act == "conf" || $act == "confall") { if (!empty($_GET['proxy_addr']) || !empty($_GET['proxy_port'])) { $proxy = array(); if (empty($_GET['proxy_addr'])) { - $error = true; $input_errors[] = "You need to specify an address for the proxy port."; } else $proxy['ip'] = $_GET['proxy_addr']; if (empty($_GET['proxy_port'])) { - $error = true; $input_errors[] = "You need to specify a port for the proxy ip."; } else $proxy['port'] = $_GET['proxy_port']; $proxy['proxy_authtype'] = $_GET['proxy_authtype']; if ($_GET['proxy_authtype'] != "none") { if (empty($_GET['proxy_user'])) { - $error = true; $input_errors[] = "You need to specify a username with the proxy config."; } else $proxy['user'] = $_GET['proxy_user']; if (!empty($_GET['proxy_user']) && empty($_GET['proxy_password'])) { - $error = true; $input_errors[] = "You need to specify a password with the proxy user."; } else $proxy['password'] = $_GET['proxy_password']; @@ -173,181 +172,71 @@ if($act == "conf" || $act == "confall") { } $exp_name = openvpn_client_export_prefix($srvid); - if ($act == "confall") - $zipconf = true; - $exp_data = openvpn_client_export_config($srvid, $usrid, $crtid, $useaddr, $usetoken, $nokeys, $proxy, $zipconf, $password, false, false, $advancedoptions); - if (!$exp_data) { - $input_errors[] = "Failed to export config files!"; - $error = true; - } - if (!$error) { - if ($act == "confall") { - $exp_name = urlencode($exp_data); - $exp_size = filesize("{$g['tmp_path']}/{$exp_data}"); - } else { - $exp_name = urlencode($exp_name."-config.ovpn"); - $exp_size = strlen($exp_data); - } - - header('Pragma: '); - header('Cache-Control: '); - header("Content-Type: application/octet-stream"); - header("Content-Disposition: attachment; filename={$exp_name}"); - header("Content-Length: $exp_size"); - if ($act == "confall") - readfile("{$g['tmp_path']}/{$exp_data}"); - else - echo $exp_data; - - @unlink($exp_data); - exit; - } -} - -if($act == "visc") { - $srvid = $_GET['srvid']; - $usrid = $_GET['usrid']; - $crtid = $_GET['crtid']; - if ($srvid === false) { - pfSenseHeader("vpn_openvpn_export.php"); - exit; - } else if (($config['openvpn']['openvpn-server'][$srvid]['mode'] != "server_user") && - (($usrid === false) || ($crtid === false))) { - pfSenseHeader("vpn_openvpn_export.php"); - exit; - } - if (empty($_GET['useaddr'])) { - $error = true; - $input_errors[] = "You need to specify an IP or hostname."; - } else - $useaddr = $_GET['useaddr']; - $advancedoptions = $_GET['advancedoptions']; - - $usetoken = $_GET['usetoken']; - $password = ""; - if ($_GET['password']) - $password = $_GET['password']; - - $proxy = ""; - if (!empty($_GET['proxy_addr']) || !empty($_GET['proxy_port'])) { - $proxy = array(); - if (empty($_GET['proxy_addr'])) { - $error = true; - $input_errors[] = "You need to specify an address for the proxy port."; - } else - $proxy['ip'] = $_GET['proxy_addr']; - if (empty($_GET['proxy_port'])) { - $error = true; - $input_errors[] = "You need to specify a port for the proxy ip."; - } else - $proxy['port'] = $_GET['proxy_port']; - $proxy['proxy_authtype'] = $_GET['proxy_authtype']; - if ($_GET['proxy_authtype'] != "none") { - if (empty($_GET['proxy_user'])) { - $error = true; - $input_errors[] = "You need to specify a username with the proxy config."; - } else - $proxy['user'] = $_GET['proxy_user']; - if (!empty($_GET['proxy_user']) && empty($_GET['proxy_password'])) { - $error = true; - $input_errors[] = "You need to specify a password with the proxy user."; - } else - $proxy['password'] = $_GET['proxy_password']; + if(substr($act, 0, 4) == "conf") { + switch ($act) { + case "confzip": + $exp_name = urlencode($exp_name."-config.zip"); + $expformat = "zip"; + break; + case "conf_yealink_t28": + $exp_name = urlencode("client.tar"); + $expformat = "yealink_t28"; + break; + case "conf_yealink_t38g": + $exp_name = urlencode("client.tar"); + $expformat = "yealink_t38g"; + break; + case "conf_yealink_t38g2": + $exp_name = urlencode("client.tar"); + $expformat = "yealink_t38g2"; + break; + case "conf_snom": + $exp_name = urlencode("vpnclient.tar"); + $expformat = "snom"; + break; + case "confinline": + $exp_name = urlencode($exp_name."-config.ovpn"); + $expformat = "inline"; + break; + default: + $exp_name = urlencode($exp_name."-config.ovpn"); + $expformat = "baseconf"; } + $exp_path = openvpn_client_export_config($srvid, $usrid, $crtid, $useaddr, $quoteservercn, $usetoken, $nokeys, $proxy, $expformat, $password, false, false, $advancedoptions); } - $exp_name = openvpn_client_export_prefix($srvid); - $exp_name = urlencode($exp_name."-Viscosity.visc.zip"); - $exp_path = viscosity_openvpn_client_config_exporter($srvid, $usrid, $crtid, $useaddr, $usetoken, $password, $proxy, $advancedoptions); - if (!$exp_path) { - $input_errors[] = "Failed to export config files!"; - $error = true; - } - if (!$error) { - $exp_size = filesize($exp_path); - - header('Pragma: '); - header('Cache-Control: '); - header("Content-Type: application/octet-stream"); - header("Content-Disposition: attachment; filename={$exp_name}"); - header("Content-Length: $exp_size"); - readfile($exp_path); - //unlink($exp_path); - exit; - } -} - -if($act == "inst") { - $srvid = $_GET['srvid']; - $usrid = $_GET['usrid']; - $crtid = $_GET['crtid']; - if ($srvid === false) { - pfSenseHeader("vpn_openvpn_export.php"); - exit; - } else if (($config['openvpn']['openvpn-server'][$srvid]['mode'] != "server_user") && - (($usrid === false) || ($crtid === false))) { - pfSenseHeader("vpn_openvpn_export.php"); - exit; + if($act == "visc") { + $exp_name = urlencode($exp_name."-Viscosity.visc.zip"); + $exp_path = viscosity_openvpn_client_config_exporter($srvid, $usrid, $crtid, $useaddr, $quoteservercn, $usetoken, $password, $proxy, $advancedoptions); } - if (empty($_GET['useaddr'])) { - $error = true; - $input_errors[] = "You need to specify an IP or hostname."; - } else - $useaddr = $_GET['useaddr']; - $advancedoptions = $_GET['advancedoptions']; - - $usetoken = $_GET['usetoken']; - $password = ""; - if ($_GET['password']) - $password = $_GET['password']; - - $proxy = ""; - if (!empty($_GET['proxy_addr']) || !empty($_GET['proxy_port'])) { - $proxy = array(); - if (empty($_GET['proxy_addr'])) { - $error = true; - $input_errors[] = "You need to specify an address for the proxy port."; - } else - $proxy['ip'] = $_GET['proxy_addr']; - if (empty($_GET['proxy_port'])) { - $error = true; - $input_errors[] = "You need to specify a port for the proxy ip."; - } else - $proxy['port'] = $_GET['proxy_port']; - $proxy['proxy_authtype'] = $_GET['proxy_authtype']; - if ($_GET['proxy_authtype'] != "none") { - if (empty($_GET['proxy_user'])) { - $error = true; - $input_errors[] = "You need to specify a username with the proxy config."; - } else - $proxy['user'] = $_GET['proxy_user']; - if (!empty($_GET['proxy_user']) && empty($_GET['proxy_password'])) { - $error = true; - $input_errors[] = "You need to specify a password with the proxy user."; - } else - $proxy['password'] = $_GET['proxy_password']; - } + if(substr($act, 0, 4) == "inst") { + $exp_name = urlencode($exp_name."-install.exe"); + $exp_path = openvpn_client_export_installer($srvid, $usrid, $crtid, $useaddr, $quoteservercn, $usetoken, $password, $proxy, $advancedoptions, substr($act, 5)); } - $exp_name = openvpn_client_export_prefix($srvid); - $exp_name = urlencode($exp_name."-install.exe"); - $exp_path = openvpn_client_export_installer($srvid, $usrid, $crtid, $useaddr, $usetoken, $password, $proxy, $advancedoptions); if (!$exp_path) { $input_errors[] = "Failed to export config files!"; - $error = true; } - if (!$error) { - $exp_size = filesize($exp_path); + if (empty($input_errors)) { + if (($act == "conf") || ($act == "confinline")) { + $exp_size = strlen($exp_path); + } else { + $exp_size = filesize($exp_path); + } header('Pragma: '); header('Cache-Control: '); header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment; filename={$exp_name}"); header("Content-Length: $exp_size"); - readfile($exp_path); - unlink($exp_path); + if (($act == "conf") || ($act == "confinline")) { + echo $exp_path; + } else { + readfile($exp_path); + @unlink($exp_path); + } exit; } } @@ -391,7 +280,7 @@ function download_begin(act, i, j) { var users = servers[index][1]; var certs = servers[index][3]; var useaddr; - + var advancedoptions; if (document.getElementById("useaddr").value == "other") { @@ -402,9 +291,12 @@ function download_begin(act, i, j) { useaddr = document.getElementById("useaddr_hostname").value; } else useaddr = document.getElementById("useaddr").value; - + advancedoptions = document.getElementById("advancedoptions").value; + var quoteservercn = 0; + if (document.getElementById("quoteservercn").checked) + quoteservercn = 1; var usetoken = 0; if (document.getElementById("usetoken").checked) usetoken = 1; @@ -414,7 +306,7 @@ function download_begin(act, i, j) { var pass = document.getElementById("pass").value; var conf = document.getElementById("conf").value; - if (usepass && (act == "inst")) { + if (usepass && (act.substring(0,4) == "inst")) { if (!pass || !conf) { alert("The password or confirm field is empty"); return; @@ -473,6 +365,7 @@ function download_begin(act, i, j) { dlurl += "&crtid=" + escape(certs[j][0]); } dlurl += "&useaddr=" + escape(useaddr); + dlurl += ""eservercn=" + escape(quoteservercn); dlurl += "&usetoken=" + escape(usetoken); if (usepass) dlurl += "&password=" + escape(pass); @@ -485,7 +378,7 @@ function download_begin(act, i, j) { dlurl += "&proxy_password=" + escape(proxypass); } } - + dlurl += "&advancedoptions=" + escape(advancedoptions); window.open(dlurl,"_self"); @@ -512,9 +405,16 @@ function server_changed() { cell2.className = "listr"; cell2.innerHTML = "<a href='javascript:download_begin(\"conf\"," + i + ", -1)'>Configuration</a>"; cell2.innerHTML += "<br/>"; - cell2.innerHTML += "<a href='javascript:download_begin(\"confall\"," + i + ", -1)'>Configuration archive</a>"; + cell2.innerHTML += "<a href='javascript:download_begin(\"confinline\"," + i + ", -1)'>Inline Configuration</a>"; cell2.innerHTML += "<br/>"; - cell2.innerHTML += "<a href='javascript:download_begin(\"inst\"," + i + ", -1)'>Windows Installer</a>"; + cell2.innerHTML += "<a href='javascript:download_begin(\"confzip\"," + i + ", -1)'>Configuration archive</a>"; + cell2.innerHTML += "<br/>Windows Installers:<br/>"; + cell2.innerHTML += " "; + cell2.innerHTML += "<a href='javascript:download_begin(\"inst\"," + i + ", -1)'>2.2</a>"; + cell2.innerHTML += " "; + cell2.innerHTML += "<a href='javascript:download_begin(\"inst-2.3-x86\"," + i + ", -1)'>2.3-x86 (Beta)</a>"; +// cell2.innerHTML += " "; +// cell2.innerHTML += "<a href='javascript:download_begin(\"inst-2.3-x64\"," + i + ", -1)'>2.3-x64 (Beta)</a>"; cell2.innerHTML += "<br/>"; cell2.innerHTML += "<a href='javascript:download_begin(\"visc\"," + i + ", -1)'>Viscosity Bundle</a>"; } @@ -534,11 +434,29 @@ function server_changed() { cell2.className = "listr"; cell2.innerHTML = "<a href='javascript:download_begin(\"conf\", -1," + j + ")'>Configuration</a>"; cell2.innerHTML += "<br/>"; - cell2.innerHTML += "<a href='javascript:download_begin(\"confall\", -1," + j + ")'>Configuration archive</a>"; + cell2.innerHTML += "<a href='javascript:download_begin(\"confinline\", -1," + j + ")'>Inline Configuration</a>"; cell2.innerHTML += "<br/>"; - cell2.innerHTML += "<a href='javascript:download_begin(\"inst\", -1," + j + ")'>Windows Installer</a>"; + cell2.innerHTML += "<a href='javascript:download_begin(\"confzip\", -1," + j + ")'>Configuration archive</a>"; + cell2.innerHTML += "<br/>Windows Installers:<br/>"; + cell2.innerHTML += " "; + cell2.innerHTML += "<a href='javascript:download_begin(\"inst\", -1," + j + ")'>2.2</a>"; + cell2.innerHTML += " "; + cell2.innerHTML += "<a href='javascript:download_begin(\"inst-2.3-x86\", -1," + j + ")'>2.3-x86 (Beta)</a>"; +// cell2.innerHTML += " "; +// cell2.innerHTML += "<a href='javascript:download_begin(\"inst-2.3-x64\", -1," + j + ")'>2.3-x64 (Beta)</a>"; cell2.innerHTML += "<br/>"; cell2.innerHTML += "<a href='javascript:download_begin(\"visc\", -1," + j + ")'>Viscosity Bundle</a>"; + if (servers[index][2] == "server_tls") { + cell2.innerHTML += "<br/>Yealink SIP Handsets: <br/>"; + cell2.innerHTML += " "; + cell2.innerHTML += "<a href='javascript:download_begin(\"conf_yealink_t28\", -1," + j + ")'>T28</a>"; + cell2.innerHTML += " "; + cell2.innerHTML += "<a href='javascript:download_begin(\"conf_yealink_t38g\", -1," + j + ")'>T38G (1)</a>"; + cell2.innerHTML += " "; + cell2.innerHTML += "<a href='javascript:download_begin(\"conf_yealink_t38g2\", -1," + j + ")'>T38G (2)</a>"; + cell2.innerHTML += "<br/>"; + cell2.innerHTML += "<a href='javascript:download_begin(\"conf_snom\", -1," + j + ")'>SNOM SIP Handset</a>"; + } } if (servers[index][2] == 'server_user') { var row = table.insertRow(table.rows.length); @@ -552,9 +470,16 @@ function server_changed() { cell2.className = "listr"; cell2.innerHTML = "<a href='javascript:download_begin(\"conf\"," + i + ")'>Configuration</a>"; cell2.innerHTML += "<br/>"; - cell2.innerHTML += "<a href='javascript:download_begin(\"confall\"," + i + ")'>Configuration archive</a>"; + cell2.innerHTML += "<a href='javascript:download_begin(\"confinline\"," + i + ")'>Inline Configuration</a>"; cell2.innerHTML += "<br/>"; - cell2.innerHTML += "<a href='javascript:download_begin(\"inst\"," + i + ")'>Windows Installer</a>"; + cell2.innerHTML += "<a href='javascript:download_begin(\"confzip\"," + i + ")'>Configuration archive</a>"; + cell2.innerHTML += "<br/>Windows Installers:<br/>"; + cell2.innerHTML += " "; + cell2.innerHTML += "<a href='javascript:download_begin(\"inst\"," + i + ")'>2.2</a>"; + cell2.innerHTML += " "; + cell2.innerHTML += "<a href='javascript:download_begin(\"inst-2.3-x86\"," + i + ")'>2.3-x86 (Beta)</a>"; +// cell2.innerHTML += " "; +// cell2.innerHTML += "<a href='javascript:download_begin(\"inst-2.3-x64\"," + i + ")'>2.3-x64 (Beta)</a>"; cell2.innerHTML += "<br/>"; cell2.innerHTML += "<a href='javascript:download_begin(\"visc\"," + i + ")'>Viscosity Bundle</a>"; } @@ -566,7 +491,7 @@ function useaddr_changed(obj) { $('HostName').show(); else $('HostName').hide(); - + } function usepass_changed() { @@ -597,7 +522,7 @@ function useproxy_changed(obj) { <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td> - <?php + <?php $tab_array = array(); $tab_array[] = array(gettext("Server"), false, "vpn_openvpn_server.php"); $tab_array[] = array(gettext("Client"), false, "vpn_openvpn_client.php"); @@ -652,6 +577,23 @@ function useproxy_changed(obj) { </td> </tr> <tr> + <td width="22%" valign="top" class="vncell">Quote Server CN</td> + <td width="78%" class="vtable"> + <table border="0" cellpadding="2" cellspacing="0"> + <tr> + <td> + <input name="quoteservercn" id="quoteservercn" type="checkbox" value="yes"> + </td> + <td> + <span class="vexpl"> + Enclose the server CN in quotes. Can help if your server CN contains spaces and certain clients cannot parse the server CN. Some clients have problems parsing the CN with quotes. Use only as needed. + </span> + </td> + </tr> + </table> + </td> + </tr> + <tr> <td width="22%" valign="top" class="vncell">Certificate Export Options</td> <td width="78%" class="vtable"> <table border="0" cellpadding="2" cellspacing="0"> diff --git a/config/pf-blocker/pfblocker.inc b/config/pf-blocker/pfblocker.inc index bb8268a1..1c107dc4 100755 --- a/config/pf-blocker/pfblocker.inc +++ b/config/pf-blocker/pfblocker.inc @@ -3,7 +3,7 @@ pfblocker.inc part of the Postfix package for pfSense Copyright (C) 2010 Erik Fonnesbeck - Copyright (C) 2011 Marcello Coutinho + Copyright (C) 2011-2012 Marcello Coutinho All rights reserved. @@ -75,50 +75,58 @@ function pfblocker_Range2CIDR($ip_min, $ip_max) { return $network . "/". (32 -strlen(decbin($ip_max_long - $ip_min_long))); } -function sync_package_pfblocker() { +function sync_package_pfblocker($cron="") { global $g,$config; - if ($g['booting'] == true){ - print "no action during boot process...\n"; - } - else{ - conf_mount_rw(); - #apply fetch timeout to pfsense-utils.inc - $pfsense_utils=file_get_contents('/etc/inc/pfsense-utils.inc'); - $new_pfsense_utils=preg_replace("/\/usr\/bin\/fetch -q/","/usr/bin/fetch -T 5 -q",$pfsense_utils); - if ($new_pfsense_utils != $pfsense_utils){ - file_put_contents('/etc/inc/pfsense-utils.inc',$new_pfsense_utils, LOCK_EX); - } - $pfblocker_enable=$config['installedpackages']['pfblocker']['config'][0]['enable_cb']; - $pfblocker_config=$config['installedpackages']['pfblocker']['config'][0]; - $table_limit =($config['system']['maximumtableentries']!= ""?$config['system']['maximumtableentries']:"100000"); - #get local web gui configuration - $web_local=($config['system']['webgui']['protocol'] != ""?$config['system']['webgui']['protocol']:"http"); - $port = $config['system']['webgui']['port']; - if($port == "") { - if($config['system']['webgui']['protocol'] == "http"){ - $port = "80"; - } - else{ - $port = "443"; + + # detect boot process or update via cron + if (is_array($_POST) && $cron==""){ + if (!preg_match("/\w+/",$_POST['__csrf_magic'])){ + log_error("No pfBlocker action during boot process."); + return; } } - $web_local .= "://127.0.0.1:".$port.'/pfblocker.php'; + + log_error("Starting pfBlocker sync process."); + conf_mount_rw(); - #check folders - $pfbdir='/usr/local/pkg/pfblocker'; - $pfb_alias_dir='/usr/local/pkg/pfblocker_aliases'; - $pfsense_alias_dir='/var/db/aliastables/'; - if (!is_dir($pfbdir)){ - mkdir ($pfbdir,0755); - } - if (!is_dir($pfb_alias_dir)){ - mkdir ($pfb_alias_dir,0755); + #apply fetch timeout to pfsense-utils.inc + $pfsense_utils=file_get_contents('/etc/inc/pfsense-utils.inc'); + $new_pfsense_utils=preg_replace("/\/usr\/bin\/fetch -q/","/usr/bin/fetch -T 5 -q",$pfsense_utils); + if ($new_pfsense_utils != $pfsense_utils){ + file_put_contents('/etc/inc/pfsense-utils.inc',$new_pfsense_utils, LOCK_EX); + } + $pfblocker_enable=$config['installedpackages']['pfblocker']['config'][0]['enable_cb']; + $pfblocker_config=$config['installedpackages']['pfblocker']['config'][0]; + $table_limit =($config['system']['maximumtableentries']!= ""?$config['system']['maximumtableentries']:"100000"); + + #get local web gui configuration + $web_local=($config['system']['webgui']['protocol'] != ""?$config['system']['webgui']['protocol']:"http"); + $port = $config['system']['webgui']['port']; + if($port == "") { + if($config['system']['webgui']['protocol'] == "http"){ + $port = "80"; } - if (! is_dir($pfsense_alias_dir)){ - mkdir ($pfsense_alias_dir,0755); + else{ + $port = "443"; + } } + $web_local .= "://127.0.0.1:".$port.'/pfblocker.php'; + + #check folders + $pfbdir='/usr/local/pkg/pfblocker'; + $pfb_alias_dir='/usr/local/pkg/pfblocker_aliases'; + $pfsense_alias_dir='/var/db/aliastables/'; + if (!is_dir($pfbdir)){ + mkdir ($pfbdir,0755); + } + if (!is_dir($pfb_alias_dir)){ + mkdir ($pfb_alias_dir,0755); + } + if (! is_dir($pfsense_alias_dir)){ + mkdir ($pfsense_alias_dir,0755); + } - $continents= array( "Africa" => "pfBlockerAfrica", + $continents= array( "Africa" => "pfBlockerAfrica", "Antartica" => "pfBlockerAntartica", "Asia" => "pfBlockerAsia", "Europe" => "pfBlockerEurope", @@ -127,110 +135,114 @@ function sync_package_pfblocker() { "South America" => "pfBlockerSouthAmerica", "Top Spammers" => "pfBlockerTopSpammers"); - #create rules vars and arrays - $new_aliases=array(); - $new_aliases_list=array(); - $permit_inbound=array(); - $permit_outbound=array(); - $deny_inbound=array(); - $deny_outbound=array(); - $aliases_list=array(); - #check if pfblocker is enabled or not. - $deny_action_inbound=($pfblocker_config['inbound_deny_action']!= ""?$pfblocker_config['inbound_deny_action']:"block"); - $deny_action_outbound=($pfblocker_config['outbound_deny_action']!= ""?$pfblocker_config['outbound_deny_action']:"reject"); - $base_rule= array( "id" => "", - "tag"=> "", - "tagged"=> "", - "max"=> "", - "max-src-nodes"=>"", - "max-src-conn"=> "", - "max-src-states"=>"", - "statetimeout"=>"", - "statetype"=>"keep state", - "os"=> ""); - ############################################# - # Assign Countries # - ############################################# - foreach ($continents as $continent => $pfb_alias){ - ${$continent}=""; - if (is_array($config['installedpackages']['pfblocker'.strtolower(preg_replace('/ /','',$continent))]['config'])){ - $continent_config=$config['installedpackages']['pfblocker'.strtolower(preg_replace('/ /','',$continent))]['config'][0]; - if ($continent_config['action'] != 'Disabled' && $continent_config['action'] != '' && $pfblocker_enable == "on"){ - foreach (explode(",", $continent_config['countries']) as $iso){ - #var_dump ($iso); - if ($iso <> "" && file_exists($pfbdir.'/'.$iso.'.txt')){ - ${$continent} .= file_get_contents($pfbdir.'/'.$iso.'.txt'); - } + #create rules vars and arrays + $new_aliases=array(); + $new_aliases_list=array(); + $permit_inbound=array(); + $permit_outbound=array(); + $deny_inbound=array(); + $deny_outbound=array(); + $aliases_list=array(); + + #check if pfblocker is enabled or not. + $deny_action_inbound=($pfblocker_config['inbound_deny_action']!= ""?$pfblocker_config['inbound_deny_action']:"block"); + $deny_action_outbound=($pfblocker_config['outbound_deny_action']!= ""?$pfblocker_config['outbound_deny_action']:"reject"); + $base_rule= array( "id" => "", + "tag"=> "", + "tagged"=> "", + "max"=> "", + "max-src-nodes"=>"", + "max-src-conn"=> "", + "max-src-states"=>"", + "statetimeout"=>"", + "statetype"=>"keep state", + "os"=> ""); + + ############################################# + # Assign Countries # + ############################################# + foreach ($continents as $continent => $pfb_alias){ + ${$continent}=""; + if (is_array($config['installedpackages']['pfblocker'.strtolower(preg_replace('/ /','',$continent))]['config'])){ + $continent_config=$config['installedpackages']['pfblocker'.strtolower(preg_replace('/ /','',$continent))]['config'][0]; + if ($continent_config['action'] != 'Disabled' && $continent_config['action'] != '' && $pfblocker_enable == "on"){ + foreach (explode(",", $continent_config['countries']) as $iso){ + #var_dump ($iso); + if ($iso <> "" && file_exists($pfbdir.'/'.$iso.'.txt')){ + ${$continent} .= file_get_contents($pfbdir.'/'.$iso.'.txt'); } - if($continent_config['countries'] != "" && $pfblocker_enable == "on"){ - #write alias files - file_put_contents($pfb_alias_dir.'/'.$pfb_alias.'.txt',${$continent},LOCK_EX); - file_put_contents($pfsense_alias_dir.'/'.$pfb_alias.'.txt',${$continent}, LOCK_EX); - #Create alias config - $new_aliases_list[]=$pfb_alias; - $new_aliases[]=array( "name"=> $pfb_alias, - "url"=> $web_local.'?pfb='.$pfb_alias, - "updatefreq"=> "32", - "address"=>"", - "descr"=> "pfBlocker country list", - "type"=> "urltable", - "detail"=> "DO NOT EDIT THIS ALIAS"); - #Create rule if action permits - switch($continent_config['action']){ - case "Deny_Both": - $rule = $base_rule; - $rule["type"] = $deny_action_inbound; - $rule["descr"]= "$pfb_alias auto rule"; - $rule["source"]= array("address"=> $pfb_alias); - $rule["destination"]=array("any"=>""); - if ($pfblocker_config['enable_log']){ - $rule["log"]=""; - } - $deny_inbound[]=$rule; - case "Deny_Outbound": - $rule = $base_rule; - $rule["type"] = $deny_action_outbound; - $rule["descr"]= "$pfb_alias auto rule"; - $rule["source"]=array("any"=>""); - $rule["destination"]= array("address"=> $pfb_alias); - if ($pfblocker_config['enable_log']){ - $rule["log"]=""; - } - $deny_outbound[]=$rule; - break; - case "Deny_Inbound": - $rule = $base_rule; - $rule["type"] = $deny_action_inbound; - $rule["descr"]= "$pfb_alias auto rule"; - $rule["source"]= array("address"=> $pfb_alias); - $rule["destination"]=array("any"=>""); - if ($pfblocker_config['enable_log']){ - $rule["log"]=""; - } - $deny_inbound[]=$rule; - break; - case "Permit_Outbound": - $rule = $base_rule; - $rule["type"] = "pass"; - $rule["descr"]= "$pfb_alias auto rule"; - $rule["source"]=array("any"=>""); - $rule["destination"]= array("address"=> $pfb_alias); - if ($pfblocker_config['enable_log']){ - $rule["log"]=""; - } - $permit_outbound[]=$rule; - break; - case "Permit_Inbound": - $rule = $base_rule; - $rule["type"] = "pass"; - $rule["descr"]= "$pfb_alias auto rule"; - $rule["source"]= array("address"=> $pfb_alias); - $rule["destination"]=array("any"=>""); - if ($pfblocker_config['enable_log']){ - $rule["log"]=""; - } - $permit_inbound[]=$rule; - break; + } + if($continent_config['countries'] != "" && $pfblocker_enable == "on"){ + #write alias files + file_put_contents($pfb_alias_dir.'/'.$pfb_alias.'.txt',${$continent},LOCK_EX); + file_put_contents($pfsense_alias_dir.'/'.$pfb_alias.'.txt',${$continent}, LOCK_EX); + + #Create alias config + $new_aliases_list[]=$pfb_alias; + $new_aliases[]=array( "name"=> $pfb_alias, + "url"=> $web_local.'?pfb='.$pfb_alias, + "updatefreq"=> "32", + "address"=>"", + "descr"=> "pfBlocker country list", + "type"=> "urltable", + "detail"=> "DO NOT EDIT THIS ALIAS"); + + #Create rule if action permits + switch($continent_config['action']){ + case "Deny_Both": + $rule = $base_rule; + $rule["type"] = $deny_action_inbound; + $rule["descr"]= "$pfb_alias auto rule"; + $rule["source"]= array("address"=> $pfb_alias); + $rule["destination"]=array("any"=>""); + if ($pfblocker_config['enable_log']){ + $rule["log"]=""; + } + $deny_inbound[]=$rule; + case "Deny_Outbound": + $rule = $base_rule; + $rule["type"] = $deny_action_outbound; + $rule["descr"]= "$pfb_alias auto rule"; + $rule["source"]=array("any"=>""); + $rule["destination"]= array("address"=> $pfb_alias); + if ($pfblocker_config['enable_log']){ + $rule["log"]=""; + } + $deny_outbound[]=$rule; + break; + case "Deny_Inbound": + $rule = $base_rule; + $rule["type"] = $deny_action_inbound; + $rule["descr"]= "$pfb_alias auto rule"; + $rule["source"]= array("address"=> $pfb_alias); + $rule["destination"]=array("any"=>""); + if ($pfblocker_config['enable_log']){ + $rule["log"]=""; + } + $deny_inbound[]=$rule; + break; + case "Permit_Outbound": + $rule = $base_rule; + $rule["type"] = "pass"; + $rule["descr"]= "$pfb_alias auto rule"; + $rule["source"]=array("any"=>""); + $rule["destination"]= array("address"=> $pfb_alias); + if ($pfblocker_config['enable_log']){ + $rule["log"]=""; + } + $permit_outbound[]=$rule; + break; + case "Permit_Inbound": + $rule = $base_rule; + $rule["type"] = "pass"; + $rule["descr"]= "$pfb_alias auto rule"; + $rule["source"]= array("address"=> $pfb_alias); + $rule["destination"]=array("any"=>""); + if ($pfblocker_config['enable_log']){ + $rule["log"]=""; + } + $permit_inbound[]=$rule; + break; } } @@ -317,12 +329,12 @@ function sync_package_pfblocker() { #create alias $new_aliases_list[]=$alias; $new_aliases[]=array( "name"=> $alias, - "url"=> $web_local.'?pfb='.$alias, - "updatefreq"=> "32", - "address"=>"", - "descr"=> "pfBlocker user list", - "type"=> "urltable", - "detail"=> "DO NOT EDIT THIS ALIAS"); + "url"=> $web_local.'?pfb='.$alias, + "updatefreq"=> "32", + "address"=>"", + "descr"=> "pfBlocker user list", + "type"=> "urltable", + "detail"=> "DO NOT EDIT THIS ALIAS"); #Create rule if action permits switch($list['action']){ case "Deny_Both": @@ -456,23 +468,32 @@ function sync_package_pfblocker() { } if ($message == ""){ - $last_iface=""; $rules=$config['filter']['rule']; $new_rules=array(); - # The assumption is that the rules in the config come in groups by interface then priority. - # e.g. all rules for WAN (highest priority first), then for LAN then for OPT1 etc. - # Note that floating rules (interface is "") can appear mixed in the list. + $interfaces_processed=array(); + # The rules in the config come in priority order, + # but the interface to which each rule applies can be all mixed up in the list. + # e.g. some WAN rules, then some LAN rules, then some floating rules, then more + # LAN rules, some OPT1 rules, some more LAN rules and so on. + # So we have to allow for this, and only add pfBlocker rules the first time an + # interface is found in the rules list. foreach ($rules as $rule){ - # If this next rule is for a non-blank interface, different to the previous interface, + # If this next rule is for a non-blank interface, different from any interface already processed, # then add any needed pfblocker rules to the interface. This puts pfblocker rules at the # top of the list for each interface, after any built-in rules (e.g. anti-lockout) - if (($rule['interface'] != "") && ($rule['interface'] <> $last_iface)){ - $last_iface = $rule['interface']; + $found_new_interface = TRUE; + foreach ($interfaces_processed as $processed_interface){ + if ($processed_interface == $rule['interface']){ + $found_new_interface = FALSE; + } + } + if (($rule['interface'] != "") && ($found_new_interface)){ + $interfaces_processed[] = $rule['interface']; #apply pfblocker rules if enabled #Inbound foreach ($inbound_interfaces as $inbound_interface){ - if ($inbound_interface==$last_iface){ + if ($inbound_interface==$rule['interface']){ #permit rules if (is_array($permit_inbound)){ foreach ($permit_inbound as $cb_rules){ @@ -491,7 +512,7 @@ function sync_package_pfblocker() { } #Outbound foreach ($outbound_interfaces as $outbound_interface){ - if ($outbound_interface==$last_iface){ + if ($outbound_interface==$rule['interface']){ #permit rules if (is_array($permit_outbound)){ foreach ($permit_outbound as $cb_rules){ @@ -582,7 +603,6 @@ function sync_package_pfblocker() { } conf_mount_ro(); } -} function pfblocker_validate_input($post, &$input_errors) { global $config; diff --git a/config/pf-blocker/pfblocker.php b/config/pf-blocker/pfblocker.php index af489b81..17fb10e7 100644 --- a/config/pf-blocker/pfblocker.php +++ b/config/pf-blocker/pfblocker.php @@ -10,11 +10,11 @@ function get_networks($pfb){ print $return; } -# to be uncomented when this packages gets stable state -#if($_SERVER['REMOTE_ADDR']== '127.0.0.1'){ -if (preg_match("/(\w+)/",$_REQUEST['pfb'],$matches)) - get_networks($matches[1]); -#} +if($_SERVER['REMOTE_ADDR']== '127.0.0.1'){ + if (preg_match("/(\w+)/",$_REQUEST['pfb'],$matches)){ + get_networks($matches[1]); + } + } if ($argv[1]=='uc') pfblocker_get_countries(); if ($argv[1]=='cron'){ @@ -50,7 +50,7 @@ if ($argv[1]=='cron'){ if ($updates > 0){ include "/usr/local/pkg/pfblocker.inc"; - sync_package_pfblocker(); + sync_package_pfblocker("cron"); } } diff --git a/config/pf-blocker/pfblocker.xml b/config/pf-blocker/pfblocker.xml index 650f2909..b4da539c 100755 --- a/config/pf-blocker/pfblocker.xml +++ b/config/pf-blocker/pfblocker.xml @@ -230,8 +230,8 @@ <fielddescr>Donation</fielddescr> <fieldname>donation</fieldname> <type>checkbox</type> - <description><![CDATA[If you like this package, please <a target=_new href='http://www.pfsense.org/index.php?option=com_content&task=view&id=47&Itemid=77'>donate to pfSense project</a>.<br> - If you want that your donation goes to these package developers, make a note on donation forwarding it to us.<br>]]></description> + <description><![CDATA[If you like this package, please <a target=_new href='http://www.pfsense.org/index.php?option=com_content&task=view&id=47&Itemid=77'>donate to the pfSense project</a>.<br> + If you want your donation to go to these package developers, make a note on the donation forwarding it to us.<br>]]></description> </field> </fields> <custom_php_install_command> diff --git a/config/postfix/postfix.inc b/config/postfix/postfix.inc index f76b523a..e64f8cca 100644 --- a/config/postfix/postfix.inc +++ b/config/postfix/postfix.inc @@ -34,6 +34,10 @@ require_once("functions.inc"); require_once("pkg-utils.inc"); require_once("globals.inc"); +$uname=posix_uname(); +if ($uname['machine']=='amd64') + ini_set('memory_limit', '250M'); + function px_text_area_decode($text){ return preg_replace('/\r\n/', "\n",base64_decode($text)); } @@ -148,7 +152,7 @@ function check_cron(){ "command"=> $cron_cmd); switch ($matches[2]){ case m: - $cron_postfix["month"]="*/".$matches[1]; + $cron_postfix["minute"]="*/".$matches[1]; break; case h: $cron_postfix["minute"]="0"; @@ -204,11 +208,13 @@ function check_cron(){ #check valid_recipients cron if ($cron["command"] == $cron_cmd){ #postfix cron cmd found - if($postfix_enabled=="on") + if($postfix_enabled=="on"){ $cron_found=$cron; - if($postfix_recipients_config['enable_ldap'] && $postfix_enabled=="on") - #update cron schedule - $new_cron['item'][]=$cron_postfix; + if($postfix_recipients_config['enable_ldap'] || $postfix_recipients_config['enable_url']){ + #update cron schedule + $new_cron['item'][]=$cron_postfix; + } + } } #check sqlite update queue else if(!preg_match("/.usr.local.www.postfix.php/",$cron["command"])){ @@ -219,7 +225,7 @@ function check_cron(){ } $write_cron=1; # Check if crontab must be changed to valid recipients cmd - if ($postfix_recipients_config['enable_ldap']){ + if ($postfix_recipients_config['enable_ldap'] || $postfix_recipients_config['enable_url']){ if ($cron_found!=$cron_postfix){ #update postfix cron schedule if (! is_array($cron_found) && $postfix_enabled=="on") @@ -268,6 +274,17 @@ function check_cron(){ function sync_package_postfix() { global $config; + # detect boot process + if (is_array($_POST)){ + if (preg_match("/\w+/",$_POST['__csrf_magic'])) + unset($boot_process); + else + $boot_process="on"; + } + + if(is_process_running("master") && isset($boot_process)) + return; + #check patch in /etc/inc/config. $relay_domains = ""; $transport = ""; @@ -448,7 +465,9 @@ smtpd_sender_restrictions = reject_non_fqdn_sender, permit # Allow connections from specified local clients and strong check everybody else. -smtpd_client_restrictions = check_client_access pcre:/usr/local/etc/postfix/cal_pcre, +smtpd_client_restrictions = permit_mynetworks, + reject_unauth_destination, + check_client_access pcre:/usr/local/etc/postfix/cal_pcre, check_client_access cidr:/usr/local/etc/postfix/cal_cidr, reject_unknown_client_hostname, reject_unauth_pipelining, @@ -456,23 +475,22 @@ smtpd_client_restrictions = check_client_access pcre:/usr/local/etc/postfix/cal_ permit smtpd_recipient_restrictions = permit_mynetworks, + reject_unauth_destination, + reject_unauth_pipelining, check_client_access pcre:/usr/local/etc/postfix/cal_pcre, check_client_access cidr:/usr/local/etc/postfix/cal_cidr, + check_sender_access hash:/usr/local/etc/postfix/sender_access, reject_invalid_helo_hostname, - reject_unknown_recipient_domain, reject_non_fqdn_helo_hostname, + reject_unknown_recipient_domain, reject_non_fqdn_recipient, - reject_unauth_destination, - reject_unauth_pipelining, reject_multi_recipient_bounce, - check_sender_access hash:/usr/local/etc/postfix/sender_access, SPFSPFSPFRBLRBLRBL EOF; } else { - #erro nas listas de bloqueio $postfix_main .= <<<EOF #Just reject after helo,sender,client,recipient tests smtpd_delay_reject = yes @@ -485,14 +503,20 @@ smtpd_sender_restrictions = reject_unknown_sender_domain, RBLRBLRBL # Allow connections from specified local clients and rbl check everybody else if rbl check are set. -smtpd_client_restrictions = check_client_access pcre:/usr/local/etc/postfix/cal_pcre, - check_client_access cidr:/usr/local/etc/postfix/cal_cidr, +smtpd_client_restrictions = permit_mynetworks, + reject_unauth_destination, + check_sender_access hash:/usr/local/etc/postfix/sender_access, + check_client_access pcre:/usr/local/etc/postfix/cal_pcre, + check_client_access cidr:/usr/local/etc/postfix/cal_cidr RBLRBLRBL # Whitelisting: local clients may specify any destination domain. #, smtpd_recipient_restrictions = permit_mynetworks, reject_unauth_destination, + check_sender_access hash:/usr/local/etc/postfix/sender_access, + check_client_access pcre:/usr/local/etc/postfix/cal_pcre, + check_client_access cidr:/usr/local/etc/postfix/cal_cidr, SPFSPFSPFRBLRBLRBL EOF; @@ -678,7 +702,11 @@ MASTEREOF2; touch("/etc/mail/aliases"); exec("/usr/local/bin/newaliases"); postfix_start(); - postfix_sync_on_changes(); + + #Do not sync during boot + if(!isset($boot_process)) + postfix_sync_on_changes(); + } function postfix_start(){ global $config; diff --git a/config/postfix/postfix.php b/config/postfix/postfix.php index 9f15973c..ff42918c 100644 --- a/config/postfix/postfix.php +++ b/config/postfix/postfix.php @@ -1,744 +1,748 @@ -<?php
-/*
- postfix.php
- part of pfSense (http://www.pfsense.com/)
- Copyright (C) 2011 Marcello Coutinho <marcellocoutinho@gmail.com>
- based on varnish_view_config.
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
-*/
-require_once("/etc/inc/util.inc");
-require_once("/etc/inc/functions.inc");
-require_once("/etc/inc/pkg-utils.inc");
-require_once("/etc/inc/globals.inc");
-require_once("/usr/local/pkg/postfix.inc");
-
-function get_remote_log(){
- global $config,$g,$postfix_dir;
- $curr_time = time();
- $log_time=date('YmdHis',$curr_time);
- #get protocol
- if($config['system']['webgui']['protocol'] != "")
- $synchronizetoip = $config['system']['webgui']['protocol']. "://";
- #get port
- $port = $config['system']['webgui']['port'];
- #if port is empty lets rely on the protocol selection
- if($port == "")
- $port =($config['system']['webgui']['protocol'] == "http"?"80":"443");
- $synchronizetoip .= $sync_to_ip;
- if (is_array($config['installedpackages']['postfixsync']))
- foreach($config['installedpackages']['postfixsync']['config'][0]['row'] as $sh){
- $sync_to_ip = $sh['ipaddress'];
- $sync_type = $sh['sync_type'];
- $password = $sh['password'];
- $file= '/var/db/postfix/'.$server.'.sql';
- #get remote data
- if ($sync_type=='fetch'){
- $url= $synchronizetoip . $sync_to_ip;
- print "$sync_to_ip $url, $port\n";
- $method = 'pfsense.exec_php';
- $execcmd = "require_once('/usr/local/www/postfix.php');\n";
- $execcmd .= '$toreturn=get_sql('.$log_time.');';
- /* assemble xmlrpc payload */
- $params = array(XML_RPC_encode($password),
- XML_RPC_encode($execcmd));
- log_error("postfix get sql data from {$sync_to_ip}.");
- $msg = new XML_RPC_Message($method, $params);
- $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port);
- $cli->setCredentials('admin', $password);
- #$cli->setDebug(1);
- $resp = $cli->send($msg, "250");
- $a=$resp->value();
- $errors=0;
- #var_dump($sql);
- foreach($a as $b)
- foreach ($b as $c)
- foreach ($c as $d)
- foreach ($d as $e){
- $update=unserialize($e['string']);
- print $update['day']."\n";
- if ($update['day'] != ""){
- create_db($update['day'].".db");
- if ($debug=true)
- print $update['day'] ." writing from remote system to db...";
- $dbhandle = sqlite_open($postfix_dir.'/'.$update['day'].".db", 0666, $error);
- #file_put_contents("/tmp/".$key.'-'.$update['day'].".sql",gzuncompress(base64_decode($update['sql'])), LOCK_EX);
- $ok = sqlite_exec($dbhandle, gzuncompress(base64_decode($update['sql'])), $error);
- if (!$ok){
- $errors++;
- die ("Cannot execute query. $error\n".$update['sql']."\n");
- }
- else{
- if ($debug=true)
- print "ok\n";
- }
- sqlite_close($dbhandle);
- }
- }
- if ($errors ==0){
- $method = 'pfsense.exec_php';
- $execcmd = "require_once('/usr/local/www/postfix.php');\n";
- $execcmd .= 'flush_sql('.$log_time.');';
- /* assemble xmlrpc payload */
- $params = array(XML_RPC_encode($password),
- XML_RPC_encode($execcmd));
- log_error("postfix flush sql buffer file from {$sync_to_ip}.");
- $msg = new XML_RPC_Message($method, $params);
- $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port);
- $cli->setCredentials('admin', $password);
- #$cli->setDebug(1);
- $resp = $cli->send($msg, "250");
- }
- }
- }
-}
-function get_sql($log_time){
- global $config,$xmlrpc_g;
- $server=$_SERVER['REMOTE_ADDR'];
-
- if (is_array($config['installedpackages']['postfixsync']))
- foreach($config['installedpackages']['postfixsync']['config'][0]['row'] as $sh){
- $sync_to_ip = $sh['ipaddress'];
- $sync_type = $sh['sync_type'];
- $password = $sh['password'];
- $file= '/var/db/postfix/'.$server.'.sql';
- if ($sync_to_ip==$server && $sync_type=='share' && file_exists($file)){
- rename($file,$file.".$log_time");
- return (file($file.".$log_time"));
- }
- }
- return "";
-}
-
-function flush_sql($log_time){
- if (preg_match("/\d+\.\d+\.\d+\.\d+/",$_SERVER['REMOTE_ADDR']))
- unlink_if_exists('/var/db/postfix/'.$_SERVER['REMOTE_ADDR'].".sql.$log_time");
-}
-
-function grep_log(){
- global $postfix_dir,$postfix_arg,$config,$g;
-
- $total_lines=0;
- $days=array();
- $grep="\(MailScanner\|postfix.cleanup\|postfix.smtp\|postfix.error\|postfix.qmgr\)";
- $curr_time = time();
- $log_time=strtotime($postfix_arg['time'],$curr_time);
- $m=date('M',strtotime($postfix_arg['time'],$curr_time));
- $j=substr(" ".date('j',strtotime($postfix_arg['time'],$curr_time)),-3);
- # file grep loop
- foreach ($postfix_arg['grep'] as $hour){
- print "/usr/bin/grep '^".$m.$j." ".$hour.".*".$grep."' /var/log/maillog\n";
- $lists=array();
- exec("/usr/bin/grep " . escapeshellarg('^'.$m.$j." ".$hour.".*".$grep)." /var/log/maillog", $lists);
- foreach ($lists as $line){
- #check where is first mail record
- if (preg_match("/ delay=(\d+)/",$line,$delay)){
- $day=date("Y-m-d",strtotime("-".$delay[1]." second",$log_time));
- if (! in_array($day,$days)){
- $days[]=$day;
- create_db($day.".db");
- print "Found logs to $day.db\n";
- $stm_queue[$day]="BEGIN;\n";
- $stm_noqueue[$day]="BEGIN;\n";
- }
- }
- else{
- $day=date("Y-m-d",strtotime($postfix_arg['time'],$curr_time));
- if (! in_array($day,$days)){
- $days[]=$day;
- create_db($day.".db");
- print "Found logs to $day.db\n";
- $stm_queue[$day]="BEGIN;\n";
- $stm_noqueue[$day]="BEGIN;\n";
- }
- }
- $status=array();
- $total_lines++;
- #Nov 8 09:31:50 srvch011 postfix/smtpd[43585]: 19C281F59C8: client=pm03-974.auinmem.br[177.70.0.3]
- if(preg_match("/(\w+\s+\d+\s+[0-9,:]+) (\w+) postfix.smtpd\W\d+\W+(\w+): client=(.*)/",$line,$email)){
- $values="'".$email[3]."','".$email[1]."','".$email[2]."','".$email[4]."'";
- if(${$email[3]}!=$email[3])
- $stm_queue[$day].='insert or ignore into mail_from(sid,date,server,client) values ('.$values.');'."\n";
- ${$email[3]}=$email[3];
- }
- #Dec 2 22:21:18 pfsense MailScanner[60670]: Requeue: 8DC3BBDEAF.A29D3 to 5AD9ABDEB5
- else if (preg_match("/(\w+\s+\d+\s+[0-9,:]+) (\w+) MailScanner.*Requeue: (\w+)\W\w+ to (\w+)/",$line,$email)){
- $stm_queue[$day].= "update or ignore mail_from set sid='".$email[4]."' where sid='".$email[3]."';\n";
- }
- #Dec 5 14:06:10 srvchunk01 MailScanner[19589]: Message 775201F44B1.AED2C from 209.185.111.50 (marcellocoutinho@mailtest.com) to sede.mail.test.com is spam, SpamAssassin (not cached, escore=99.202, requerido 6, autolearn=spam, DKIM_SIGNED 0.10, DKIM_VALID -0.10, DKIM_VALID_AU -0.10, FREEMAIL_FROM 0.00, HTML_MESSAGE 0.00, RCVD_IN_DNSWL_LOW -0.70, WORM_TEST2 100.00)
- else if (preg_match("/(\w+\s+\d+\s+[0-9,:]+) (\w+) MailScanner\W\d+\W+\w+\s+(\w+).* is spam, (.*)/",$line,$email)){
- $stm_queue[$day].= "insert or ignore into mail_status (info) values ('spam');\n";
- print "\n#######################################\nSPAM:".$email[4].$email[3].$email[2]."\n#######################################\n";
- $stm_queue[$day].= "update or ignore mail_to set status=(select id from mail_status where info='spam'), status_info='".preg_replace("/(\<|\>|\s+|\'|\")/"," ",$email[4])."' where from_id in (select id from mail_from where sid='".$email[3]."' and server='".$email[2]."');\n";
- }
- #Nov 14 09:29:32 srvch011 postfix/error[58443]: 2B8EB1F5A5A: to=<hildae.sva@pi.email.com>, relay=none, delay=0.66, delays=0.63/0/0/0.02, dsn=4.4.3, status=deferred (delivery temporarily suspended: Host or domain name not found. Name service error for name=mail.pi.test.com type=A: Host not found, try again)
- #Nov 3 21:45:32 srvch011 postfix/smtp[18041]: 4CE321F4887: to=<viinil@vitive.com.br>, relay=smtpe1.eom[81.00.20.9]:25, delay=1.9, delays=0.06/0.01/0.68/1.2, dsn=2.0.0, status=sent (250 2.0.0 Ok: queued as 2C33E2382C8)
- #Nov 16 00:00:14 srvch011 postfix/smtp[7363]: 7AEB91F797D: to=<alessandra.bueno@mg.test.com>, relay=mail.mg.test.com[172.25.3.5]:25, delay=39, delays=35/1.1/0.04/2.7, dsn=5.7.1, status=bounced (host mail.mg.test.com[172.25.3.5] said: 550 5.7.1 Unable to relay for alessandra.bueno@mg.test.com (in reply to RCPT TO command))
- else if(preg_match("/(\w+\s+\d+\s+[0-9,:]+) (\w+) postfix.\w+\W\d+\W+(\w+): to=\<(.*)\>, relay=(.*), delay=([0-9,.]+), .* dsn=([0-9,.]+), status=(\w+) (.*)/",$line,$email)){
- $stm_queue[$day].= "insert or ignore into mail_status (info) values ('".$email[8]."');\n";
- $stm_queue[$day].= "insert or ignore into mail_to (from_id,too,status,status_info,relay,delay,dsn) values ((select id from mail_from where sid='".$email[3]."' and server='".$email[2]."'),'".strtolower($email[4])."',(select id from mail_status where info='".$email[8]."'),'".preg_replace("/(\<|\>|\s+|\'|\")/"," ",$email[9])."','".$email[5]."','".$email[6]."','".$email[7]."');\n";
- $stm_queue[$day].= "update or ignore mail_to set status=(select id from mail_status where info='".$email[8]."'), status_info='".preg_replace("/(\<|\>|\s+|\'|\")/"," ",$email[9])."', dsn='".$email[7]."', delay='".$email[6]."', relay='".$email[5]."', too='".strtolower($email[4])."' where from_id in (select id from mail_from where sid='".$email[3]."' and server='".$email[2]."');\n";
- }
- #Nov 13 01:48:44 srvch011 postfix/cleanup[16914]: D995B1F570B: message-id=<61.40.11745.10E3FBE4@ofertas6>
- else if(preg_match("/(\w+\s+\d+\s+[0-9,:]+) (\w+) postfix.cleanup\W\d+\W+(\w+): message-id=\<(.*)\>/",$line,$email)){
- $stm_queue[$day].="update mail_from set msgid='".$email[4]."' where sid='".$email[3]."';\n";
- }
- #Nov 14 02:40:05 srvch011 postfix/qmgr[46834]: BC5931F4F13: from=<ceag@mx.crmcom.br>, size=32727, nrcpt=1 (queue active)
- else if(preg_match("/(\w+\s+\d+\s+[0-9,:]+) (\w+) postfix.qmgr\W\d+\W+(\w+): from=\<(.*)\>\W+size=(\d+)/",$line,$email)){
- $stm_queue[$day].= "update mail_from set fromm='".strtolower($email[4])."', size='".$email[5]."' where sid='".$email[3]."';\n";
- }
- #Nov 13 00:09:07 srvch011 postfix/bounce[56376]: 9145C1F67F7: sender non-delivery notification: D5BD31F6865
- #else if(preg_match("/(\w+\s+\d+\s+[0-9,:]+) (\w+) postfix.bounce\W\d+\W+(\w+): sender non-delivery notification: (\w+)/",$line,$email)){
- # $stm_queue[$day].= "update mail_queue set bounce='".$email[4]."' where sid='".$email[3]."';\n";
- #}
- #Nov 14 01:41:44 srvch011 postfix/smtpd[15259]: warning: 1EF3F1F573A: queue file size limit exceeded
- else if(preg_match("/(\w+\s+\d+\s+[0-9,:]+) (\w+) postfix.smtpd\W\d+\W+warning: (\w+): queue file size limit exceeded/",$line,$email)){
- $stm_queue[$day].= "insert or ignore into mail_status (info) values ('".$email[8]."');\n";
- $stm_queue[$day].= "update mail_to set status=(select id from mail_status where info='reject'), status_info='queue file size limit exceeded' where from_id in (select id from mail_from where sid='".$email[3]."' and server='".$email[2]."');\n";
- }
-
- #Nov 9 02:14:57 srvch011 postfix/cleanup[6856]: 617A51F5AC5: warning: header Subject: Mapeamento de Processos from lxalpha.12b.com.br[66.109.29.225]; from=<apache@lxalpha.12b.com.br> to=<ritiele.faria@mail.test.com> proto=ESMTP helo=<lxalpha.12b.com.br>
- #Nov 8 09:31:50 srvch011 postfix/cleanup[11471]: 19C281F59C8: reject: header From: "Giuliana Flores - Parceiro do Grupo Virtual" <publicidade@parceiro-grupovirtual.com.br> from pm03-974.auinmeio.com.br[177.70.232.225]; from=<publicidade@parceiro-grupovirtual.com.br> to=<jorge.lustosa@mail.test.com> proto=ESMTP helo=<pm03-974.auinmeio.com.br>: 5.7.1 [SN007]
- #Nov 13 00:03:24 srvch011 postfix/cleanup[4192]: 8A5B31F52D2: reject: body http://platform.roastcrack.info/mj0ie6p-48qtiyq from move2.igloojack.info[173.239.63.16]; from=<ljmd6u8lrxke4@move2.igloojack.info> to=<edileva@aasdf..br> proto=SMTP helo=<move2.igloojack.info>: 5.7.1 [BD040]
- #Nov 14 01:41:35 srvch011 postfix/cleanup[58446]: 1EF3F1F573A: warning: header Subject: =?windows-1252?Q?IMOVEL_Voc=EA_=E9_um_Cliente_especial_da_=93CENTURY21=22?=??=?windows-1252?Q?Veja_o_que_tenho_para_voc=EA?= from mail-yw0-f51.google.com[209.85.213.51]; from=<sergioalexandre6308@gmail.com> to=<sinza@tr.br> proto=ESMTP helo=<mail-yw0-f51.google.com>
- else if(preg_match("/(\w+\s+\d+\s+[0-9,:]+) (\w+) postfix.cleanup\W\d+\W+(\w+): (\w+): (.*) from ([a-z,A-Z,0-9,.,-]+)\W([0-9,.]+)\W+from=\<(.*)\> to=\<(.*)\>.*helo=\W([a-z,A-Z,0-9,.,-]+)(.*)/",$line,$email)){
- $status['date']=$email[1];
- $status['server']=$email[2];
- $status['sid']=$email[3];
- $status['remote_hostname']=$email[6];
- $status['remote_ip']=$email[7];
- $status['from']=$email[8];
- $status['to']=$email[9];
- $status['helo']=$email[10];
- $status['status']=$email[4];
- $stm_queue[$day].= "insert or ignore into mail_status (info) values ('".$email[4]."');\n";
- if ($email[4] =="warning"){
- if (${$status['sid']}=='hold'){
- $status['status']='hold';
- }
- else{
- $status['status']='incoming';
- $stm_queue[$day].= "insert or ignore into mail_status (info) values ('".$status['status']."');\n";
- }
- #print "$line\n";
- $status['status_info']=preg_replace("/(\<|\>|\s+|\'|\")/"," ",$email[11]);
- $status['subject']=preg_replace("/header Subject: /","",$email[5]);
- $status['subject']=preg_replace("/(\<|\>|\s+|\'|\")/"," ",$status['subject']);
- $stm_queue[$day].="update mail_from set subject='".$status['subject']."', fromm='".strtolower($status['from'])."',helo='".$status['helo']."' where sid='".$status['sid']."';\n";
- $stm_queue[$day].="insert or ignore into mail_to (from_id,too,status,status_info) VALUES ((select id from mail_from where sid='".$email[3]."' and server='".$email[2]."'),'".strtolower($status['to'])."',(select id from mail_status where info='".$status['status']."'),'".$status['status_info']."');\n";
- $stm_queue[$day].="update or ignore mail_to set status=(select id from mail_status where info='".$status['status']."'), status_info='".$status['status_info']."', too='".strtolower($status['to'])."' where from_id in (select id from mail_from where sid='".$status['sid']."' and server='".$email[2]."');\n";
- }
- else{
- ${$status['sid']}=$status['status'];
- $stm_queue[$day].="update mail_from set fromm='".strtolower($status['from'])."',helo='".$status['helo']."' where sid='".$status['sid']."';\n";
- $status['status_info']=preg_replace("/(\<|\>|\s+|\'|\")/"," ",$email[5].$email[11]);
- $stm_queue[$day].="insert or ignore into mail_to (from_id,too,status,status_info) VALUES ((select id from mail_from where sid='".$email[3]."' and server='".$email[2]."'),'".strtolower($status['to'])."',(select id from mail_status where info='".$email[4]."'),'".$status['status_info']."');\n";
- $stm_queue[$day].="update or ignore mail_to set status=(select id from mail_status where info='".$email[4]."'), status_info='".$status['status_info']."', too='".strtolower($status['to'])."' where from_id in (select id from mail_from where sid='".$status['sid']."' and server='".$email[2]."');\n";
- }
- }
- #Nov 9 02:14:34 srvch011 postfix/smtpd[38129]: NOQUEUE: reject: RCPT from unknown[201.36.0.7]: 450 4.7.1 Client host rejected: cannot find your hostname, [201.36.98.7]; from=<maladireta@esadcos.com.br> to=<sexec.09vara@go.domain.test.com> proto=ESMTP helo=<capri0.wb.com.br>
- else if(preg_match("/(\w+\s+\d+\s+[0-9,:]+) (\w+) postfix.smtpd\W\d+\W+NOQUEUE:\s+(\w+): (.*); from=\<(.*)\> to=\<(.*)\>.*helo=\<(.*)\>/",$line,$email)){
- $status['date']=$email[1];
- $status['server']=$email[2];
- $status['status']=$email[3];
- $status['status_info']=$email[4];
- $status['from']=$email[5];
- $status['to']=$email[6];
- $status['helo']=$email[7];
- $values="'".$status['date']."','".$status['status']."','".$status['status_info']."','".strtolower($status['from'])."','".strtolower($status['to'])."','".$status['helo']."','".$status['server']."'";
- $stm_noqueue[$day].='insert or ignore into mail_noqueue(date,status,status_info,fromm,too,helo,server) values ('.$values.');'."\n";
- }
- if ($total_lines%1500 == 0){
- #save log in database
- write_db($stm_noqueue,"noqueue",$days);
- write_db($stm_queue,"from",$days);
- foreach ($days as $d){
- $stm_noqueue[$d]="BEGIN;\n";
- $stm_queue[$d]="BEGIN;\n";
- }
- }
- if ($total_lines%1500 == 0)
- print "$line\n";
- }
- #save log in database
- write_db($stm_noqueue,"noqueue",$days);
- write_db($stm_queue,"from",$days);
- foreach ($days as $d){
- $stm_noqueue[$d]="BEGIN;\n";
- $stm_queue[$d]="BEGIN;\n";
- }
- }
-
- $config=parse_xml_config("{$g['conf_path']}/config.xml", $g['xml_rootobj']);
- print count($config['installedpackages']);
- #start db replication if configured
- if ($config['installedpackages']['postfixsync']['config'][0]['rsync'])
- foreach ($config['installedpackages']['postfixsync']['config'] as $rs )
- foreach($rs['row'] as $sh){
- $sync_to_ip = $sh['ipaddress'];
- $sync_type = $sh['sync_type'];
- $password = $sh['password'];
- print "checking replication to $sync_to_ip...";
- if ($password && $sync_to_ip && preg_match("/(both|database)/",$sync_type))
- postfix_do_xmlrpc_sync($sync_to_ip, $password,$sync_type);
- print "ok\n";
- }
-
-}
-
-function write_db($stm,$table,$days){
- global $postfix_dir,$config,$g;
- conf_mount_rw();
- $do_sync=array();
- print "writing to database...";
- foreach ($days as $day)
- if (strlen($stm[$day]) > 10){
- if ($config['installedpackages']['postfixsync']['config'][0])
- foreach ($config['installedpackages']['postfixsync']['config'] as $rs )
- foreach($rs['row'] as $sh){
- $sync_to_ip = $sh['ipaddress'];
- $sync_type = $sh['sync_type'];
- $password = $sh['password'];
- $sql_file='/var/db/postfix/'.$sync_to_ip.'.sql';
- ${$sync_to_ip}="";
- if (file_exists($sql_file))
- ${$sync_to_ip}=file_get_contents($sql_file);
- if ($sync_to_ip && $sync_type=="share"){
- ${$sync_to_ip}.=serialize(array('day'=> $day,'sql'=> base64_encode(gzcompress($stm[$day]."COMMIT;",9))))."\n";
- if (! in_array($sync_to_ip,$do_sync))
- $do_sync[]=$sync_to_ip;
- }
- }
- #write local db file
- create_db($day.".db");
- if ($debug=true)
- print " writing to local db $day...";
- $dbhandle = sqlite_open($postfix_dir.$day.".db", 0666, $error);
- if (!$dbhandle) die ($error);
- #file_put_contents("/tmp/".$key.'-'.$update['day'].".sql",gzuncompress(base64_decode($update['sql'])), LOCK_EX);
- $ok = sqlite_exec($dbhandle, $stm[$day]."COMMIT;", $error);
- if (!$ok){
- if ($debug=true)
- print ("Cannot execute query. $error\n".$stm[$day]."COMMIT;\n");
- }
- else{
- if ($debug=true)
- print "ok\n";
- }
- sqlite_close($dbhandle);
- }
- #write update sql files
- if (count ($do_sync) > 0 ){
-
- foreach($do_sync as $ip)
- file_put_contents('/var/db/postfix/'.$ip.'.sql',${$ip},LOCK_EX);
- conf_mount_ro();
- }
- #write local file
-
-}
-
-function create_db($postfix_db){
- global $postfix_dir,$postfix_arg;
- if (! is_dir($postfix_dir))
- mkdir($postfix_dir,0775);
- $new_db=(file_exists($postfix_dir.$postfix_db)?1:0);
-$stm = <<<EOF
- CREATE TABLE "mail_from"(
- "id" INTEGER PRIMARY KEY,
- "sid" VARCHAR(11) NOT NULL,
- "client" TEXT NOT NULL,
- "msgid" TEXT,
- "fromm" TEXT,
- "size" INTEGER,
- "subject" TEXT,
- "date" TEXT NOT NULL,
- "server" TEXT,
- "helo" TEXT
-);
- CREATE TABLE "mail_to"(
- "id" INTEGER PRIMARY KEY,
- "from_id" INTEGER NOT NULL,
- "too" TEXT,
- "status" INTEGER,
- "status_info" TEXT,
- "smtp" TEXT,
- "delay" TEXT,
- "relay" TEXT,
- "dsn" TEXT,
- "server" TEXT,
- "bounce" TEXT,
- FOREIGN KEY (status) REFERENCES mail_status(id),
- FOREIGN KEY (from_id) REFERENCES mail_from(id)
-);
-
-
-CREATE TABLE "mail_status"(
- "id" INTEGER PRIMARY KEY,
- "info" varchar(35) NOT NULL
-);
-
-CREATE TABLE "mail_noqueue"(
- "id" INTEGER PRIMARY KEY,
- "date" TEXT NOT NULL,
- "server" TEXT NOT NULL,
- "status" TEXT NOT NULL,
- "status_info" INTEGER NOT NULL,
- "fromm" TEXT NOT NULL,
- "too" TEXT NOT NULL,
- "helo" TEXT NOT NULL
-);
-
-CREATE TABLE "db_version"(
- "value" varchar(10),
- "info" TEXT
-);
-
-insert or ignore into db_version ('value') VALUES ('2.3.1');
-
-CREATE INDEX "noqueue_unique" on mail_noqueue (date ASC, fromm ASC, too ASC);
-CREATE INDEX "noqueue_helo" on mail_noqueue (helo ASC);
-CREATE INDEX "noqueue_too" on mail_noqueue (too ASC);
-CREATE INDEX "noqueue_fromm" on mail_noqueue (fromm ASC);
-CREATE INDEX "noqueue_info" on mail_noqueue (status_info ASC);
-CREATE INDEX "noqueue_status" on mail_noqueue (status ASC);
-CREATE INDEX "noqueue_server" on mail_noqueue (server ASC);
-CREATE INDEX "noqueue_date" on mail_noqueue (date ASC);
-
-CREATE UNIQUE INDEX "status_info" on mail_status (info ASC);
-
-CREATE UNIQUE INDEX "from_sid_server" on mail_from (sid ASC,server ASC);
-CREATE INDEX "from_client" on mail_from (client ASC);
-CREATE INDEX "from_helo" on mail_from (helo ASC);
-CREATE INDEX "from_server" on mail_from (server ASC);
-CREATE INDEX "from_subject" on mail_from (subject ASC);
-CREATE INDEX "from_msgid" on mail_from (msgid ASC);
-CREATE INDEX "from_fromm" on mail_from (fromm ASC);
-CREATE INDEX "from_date" on mail_from (date ASC);
-
-CREATE UNIQUE INDEX "mail_to_unique" on mail_to (from_id ASC, too ASC);
-CREATE INDEX "to_bounce" on mail_to (bounce ASC);
-CREATE INDEX "to_relay" on mail_to (relay ASC);
-CREATE INDEX "to_smtp" on mail_to (smtp ASC);
-CREATE INDEX "to_info" on mail_to (status_info ASC);
-CREATE INDEX "to_status" on mail_to (status ASC);
-CREATE INDEX "to_too" on mail_to (too ASC);
-
-EOF;
-#test file version
-print "checking". $postfix_dir.$postfix_db."\n";
-$dbhandle = sqlite_open($postfix_dir.$postfix_db, 0666, $error);
-if (!$dbhandle) die ($error);
-$ok = sqlite_exec($dbhandle,"select value from db_version", $error);
-sqlite_close($dbhandle);
-if (!$ok){
- print "delete previous table version\n";
- if (file_exists($postfix_dir.$postfix_db))
- unlink($postfix_dir.$postfix_db);
- $new_db=0;
-}
-if ($new_db==0){
- $dbhandle = sqlite_open($postfix_dir.$postfix_db, 0666, $error);
- $ok = sqlite_exec($dbhandle, $stm, $error);
- if (!$ok)
- print ("Cannot execute query. $error\n");
- $ok = sqlite_exec($dbhandle, $stm2, $error);
- if (!$ok)
- print ("Cannot execute query. $error\n");
- sqlite_close($dbhandle);
- }
-}
-
-$postfix_dir="/var/db/postfix/";
-$curr_time = time();
-#console script call
-if ($argv[1]!=""){
-switch ($argv[1]){
- case "01min":
- $postfix_arg=array( 'grep' => array(date("H:i",strtotime('-1 min',$curr_time))),
- 'time' => '-1 min');
- break;
- case "10min":
- $postfix_arg=array( 'grep' => array(substr(date("H:i",strtotime('-10 min',$curr_time)),0,-1)),
- 'time' => '-10 min');
- break;
- case "01hour":
- $postfix_arg=array( 'grep' => array(date("H:",strtotime('-01 hour',$curr_time))),
- 'time' => '-01 hour');
- break;
- case "04hour":
- $postfix_arg=array( 'grep' => array(date("H:",strtotime('-04 hour',$curr_time)),date("H:",strtotime('-03 hour',$curr_time)),
- date("H:",strtotime('-02 hour',$curr_time)),date("H:",strtotime('-01 hour',$curr_time))),
- 'time' => '-04 hour');
- break;
- case "24hours":
- $postfix_arg=array( 'grep' => array('00:','01:','02:','03:','04:','05:','06:','07:','08:','09:','10:','11:',
- '12:','13:','14:','15:','16:','17:','18:','19:','20:','21:','22:','23:'),
- 'time' => '-01 day');
- break;
- case "02days":
- $postfix_arg=array( 'grep' => array('00:','01:','02:','03:','04:','05:','06:','07:','08:','09:','10:','11:',
- '12:','13:','14:','15:','16:','17:','18:','19:','20:','21:','22:','23:'),
- 'time' => '-02 day');
- break;
- case "03days":
- $postfix_arg=array( 'grep' => array('00:','01:','02:','03:','04:','05:','06:','07:','08:','09:','10:','11:',
- '12:','13:','14:','15:','16:','17:','18:','19:','20:','21:','22:','23:'),
- 'time' => '-03 day');
- break;
-
- default:
- die ("invalid parameters\n");
-}
-# get remote log from remote server
-get_remote_log();
-# get local log from logfile
-grep_log();
-}
-
-#http client call
-if ($_REQUEST['files']!= ""){
- #do search
- if($_REQUEST['queue']=="QUEUE"){
- $stm="select * from mail_from, mail_to ,mail_status where mail_from.id=mail_to.from_id and mail_to.status=mail_status.id ";
- $last_next=" and ";
- }
- else{
- $stm="select * from mail_noqueue";
- $last_next=" where ";
- }
- $limit_prefix=(preg_match("/\d+/",$_REQUEST['limit'])?"limit ":"");
- $limit=(preg_match("/\d+/",$_REQUEST['limit'])?$_REQUEST['limit']:"");
- $files= explode(",", $_REQUEST['files']);
- $stm_fetch=array();
- $total_result=0;
- foreach ($files as $postfix_db)
- if (file_exists($postfix_dir.'/'.$postfix_db)){
- $dbhandle = sqlite_open($postfix_dir.'/'.$postfix_db, 0666, $error);
- if ($_REQUEST['from']!= ""){
- $next=($last_next==" and "?" and ":" where ");
- $last_next=" and ";
- if (preg_match('/\*/',$_REQUEST['from']))
- $stm .=$next."fromm like '".preg_replace('/\*/','%',$_REQUEST['from'])."'";
- else
- $stm .=$next."fromm in('".$_REQUEST['from']."')";
- }
- if ($_REQUEST['to']!= ""){
- $next=($last_next==" and "?" and ":" where ");
- $last_next=" and ";
- if (preg_match('/\*/',$_REQUEST['to']))
- $stm .=$next."too like '".preg_replace('/\*/','%',$_REQUEST['to'])."'";
- else
- $stm .=$next."too in('".$_REQUEST['to']."')";
- }
- if ($_REQUEST['sid']!= "" && $_REQUEST['queue']=="QUEUE"){
- $next=($last_next==" and "?" and ":" where ");
- $last_next=" and ";
- $stm .=$next."sid in('".$_REQUEST['sid']."')";
- }
- if ($_REQUEST['relay']!= "" && $_REQUEST['queue']=="QUEUE"){
- $next=($last_next==" and "?" and ":" where ");
- $last_next=" and ";
- if (preg_match('/\*/',$_REQUEST['subject']))
- $stm .=$next."relay like '".preg_replace('/\*/','%',$_REQUEST['relay'])."'";
- else
- $stm .=$next."relay = '".$_REQUEST['relay']."'";
- }
- if ($_REQUEST['subject']!= "" && $_REQUEST['queue']=="QUEUE"){
- $next=($last_next==" and "?" and ":" where ");
- $last_next=" and ";
- if (preg_match('/\*/',$_REQUEST['subject']))
- $stm .=$next."subject like '".preg_replace('/\*/','%',$_REQUEST['subject'])."'";
- else
- $stm .=$next."subject = '".$_REQUEST['subject']."'";
- }
- if ($_REQUEST['msgid']!= "" && $_REQUEST['queue']=="QUEUE"){
- $next=($last_next==" and "?" and ":" where ");
- $last_next=" and ";
- if (preg_match('/\*/',$_REQUEST['msgid']))
- $stm .=$next."msgid like '".preg_replace('/\*/','%',$_REQUEST['msgid'])."'";
- else
- $stm .=$next."msgid = '".$_REQUEST['msgid']."'";
- }
- if ($_REQUEST['server']!= "" ){
- $next=($last_next==" and "?" and ":" where ");
- $last_next=" and ";
- if( $_REQUEST['queue']=="QUEUE")
- $stm .=$next."mail_from.server = '".$_REQUEST['server']."'";
- else
- $stm .=$next."server = '".$_REQUEST['server']."'";
- }
-
- if ($_REQUEST['status']!= ""){
- $next=($last_next==" and "?" and ":" where ");
- $last_next=" and ";
- $stm .=$next."mail_status.info = '".$_REQUEST['status']."'";
- }
- #print "<pre>".$stm;
- #$stm = "select * from mail_to,mail_status where mail_to.status=mail_status.id";
- $result = sqlite_query($dbhandle, $stm." order by date desc $limit_prefix $limit ");
- #$result = sqlite_query($dbhandle, $stm." $limit_prefix $limit ");
- if (preg_match("/\d+/",$_REQUEST['limit'])){
- for ($i = 1; $i <= $limit; $i++) {
- $row = sqlite_fetch_array($result, SQLITE_ASSOC);
- if (is_array($row))
- $stm_fetch[]=$row;
- }
- }
- else{
- $stm_fetch = sqlite_fetch_all($result, SQLITE_ASSOC);
- }
- sqlite_close($dbhandle);
- }
- $fields= explode(",", $_REQUEST['fields']);
- if ($_REQUEST['sbutton']=='export'){
- print '<table class="tabcont" width="100%" border="0" cellpadding="8" cellspacing="0">';
- print '<tr><td colspan="'.count($fields).'" valign="top" class="listtopic">'.gettext("Search Results").'</td></tr>';
- print '<tr>';
- $header="";
- foreach ($stm_fetch as $mail){
- foreach ($mail as $key => $data){
- if (!preg_match("/$key/",$header))
- $header .= $key.",";
- $export.=preg_replace('/,/',"",$mail[$key]).",";
- }
- $export.= "\n";
- }
- print '<td class="tabcont"><textarea id="varnishlogs" rows="50" cols="100%">';
- print "This export is in csv format, paste it without this line on any software that handles csv files.\n\n".$header."\n".$export;
- print "</textarea></td></tr></table>";
- }
- else{
- if ($_REQUEST['queue']=="NOQUEUE"){
- print '<table class="tabcont" width="100%" border="0" cellpadding="8" cellspacing="0">';
- print '<tr><td colspan="'.count($fields).'" valign="top" class="listtopic">'.gettext("Search Results").'</td></tr>';
- print '<tr>';
- if(in_array("date",$fields))
- print '<td class="listlr"><strong>date</strong></td>';
- if(in_array("server",$fields))
- print '<td class="listlr"><strong>server</strong></td>';
- if(in_array("from",$fields))
- print '<td class="listlr"><strong>From</strong></td>';
- if(in_array("to",$fields))
- print '<td class="listlr"><strong>to</strong></td>';
- if(in_array("helo",$fields))
- print '<td class="listlr"><strong>Helo</strong></td>';
- if(in_array("status",$fields))
- print '<td class="listlr"><strong>Status</strong></td>';
- if(in_array("status_info",$fields))
- print '<td class="listlr"><strong>Status Info</strong></td>';
- print '</tr>';
- foreach ($stm_fetch as $mail){
- print '<tr>';
- if(in_array("date",$fields))
- print '<td class="listlr">'.$mail['date'].'</td>';
- if(in_array("server",$fields))
- print '<td class="listlr">'.$mail['server'].'</td>';
- if(in_array("from",$fields))
- print '<td class="listlr">'.$mail['fromm'].'</td>';
- if(in_array("to",$fields))
- print '<td class="listlr">'.$mail['too'].'</td>';
- if(in_array("helo",$fields))
- print '<td class="listlr">'.$mail['helo'].'</td>';
- if(in_array("status",$fields))
- print '<td class="listlr">'.$mail['status'].'</td>';
- if(in_array("status_info",$fields))
- print '<td class="listlr">'.$mail['status_info'].'</td>';
- print '</tr>';
- $total_result++;
- }
- }
- else{
- print '<table class="tabcont" width="100%" border="0" cellpadding="8" cellspacing="0">';
- print '<tr><td colspan="'.count($fields).'" valign="top" class="listtopic">'.gettext("Search Results").'</td></tr>';
- print '<tr>';
- if(in_array("date",$fields))
- print '<td class="listlr" ><strong>Date</strong></td>';
- if(in_array("server",$fields))
- print '<td class="listlr" ><strong>Server</strong></td>';
- if(in_array("from",$fields))
- print '<td class="listlr" ><strong>From</strong></td>';
- if(in_array("to",$fields))
- print '<td class="listlr" ><strong>to</strong></td>';
- if(in_array("subject",$fields))
- print '<td class="listlr" ><strong>Subject</strong></td>';
- if(in_array("delay",$fields))
- print '<td class="listlr" ><strong>Delay</strong></td>';
- if(in_array("status",$fields))
- print '<td class="listlr" ><strong>Status</strong></td>';
- if(in_array("status_info",$fields))
- print '<td class="listlr" ><strong>Status Info</strong></td>';
- if(in_array("size",$fields))
- print '<td class="listlr" ><strong>Size</strong></td>';
- if(in_array("helo",$fields))
- print '<td class="listlr" ><strong>Helo</strong></td>';
- if(in_array("sid",$fields))
- print '<td class="listlr" ><strong>SID</strong></td>';
- if(in_array("msgid",$fields))
- print '<td class="listlr" ><strong>MSGID</strong></td>';
- if(in_array("bounce",$fields))
- print '<td class="listlr" ><strong>Bounce</strong></td>';
- if(in_array("relay",$fields))
- print '<td class="listlr" ><strong>Relay</strong></td>';
- print '</tr>';
- foreach ($stm_fetch as $mail){
- if(in_array("date",$fields))
- print '<td class="listlr">'.$mail['mail_from.date'].'</td>';
- if(in_array("server",$fields))
- print '<td class="listlr">'.$mail['mail_from.server'].'</td>';
- if(in_array("from",$fields))
- print '<td class="listlr">'.$mail['mail_from.fromm'].'</td>';
- if(in_array("to",$fields))
- print '<td class="listlr">'.$mail['mail_to.too'].'</td>';
- if(in_array("subject",$fields))
- print '<td class="listlr">'.$mail['mail_from.subject'].'</td>';
- if(in_array("delay",$fields))
- print '<td class="listlr">'.$mail['mail_to.delay'].'</td>';
- if(in_array("status",$fields))
- print '<td class="listlr">'.$mail['mail_status.info'].'</td>';
- if(in_array("status_info",$fields))
- print '<td class="listlr">'.$mail['mail_to.status_info'].'</td>';
- if(in_array("size",$fields))
- print '<td class="listlr">'.$mail['mail_from.size'].'</td>';
- if(in_array("helo",$fields))
- print '<td class="listlr">'.$mail['mail_from.helo'].'</td>';
- if(in_array("sid",$fields))
- print '<td class="listlr">'.$mail['mail_from.sid'].'</td>';
- if(in_array("msgid",$fields))
- print '<td class="listlr">'.$mail['mail_from.msgid'].'</td>';
- if(in_array("bounce",$fields))
- print '<td class="listlr">'.$mail['mail_to.bounce'].'</td>';
- if(in_array("relay",$fields))
- print '<td class="listlr">'.$mail['mail_to.relay'].'</td>';
- print '</tr>';
- $total_result++;
- }
- }
- print '<tr>';
- print '<td ><strong>Total:</strong></td>';
- print '<td ><strong>'.$total_result.'</strong></td>';
- print '</tr>';
- print '</table>';
- }
-}
+<?php +/* + postfix.php + part of pfSense (http://www.pfsense.com/) + Copyright (C) 2011 Marcello Coutinho <marcellocoutinho@gmail.com> + based on varnish_view_config. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. +*/ +require_once("/etc/inc/util.inc"); +require_once("/etc/inc/functions.inc"); +require_once("/etc/inc/pkg-utils.inc"); +require_once("/etc/inc/globals.inc"); +require_once("/usr/local/pkg/postfix.inc"); + +$uname=posix_uname(); +if ($uname['machine']=='amd64') + ini_set('memory_limit', '250M'); + +function get_remote_log(){ + global $config,$g,$postfix_dir; + $curr_time = time(); + $log_time=date('YmdHis',$curr_time); + #get protocol + if($config['system']['webgui']['protocol'] != "") + $synchronizetoip = $config['system']['webgui']['protocol']. "://"; + #get port + $port = $config['system']['webgui']['port']; + #if port is empty lets rely on the protocol selection + if($port == "") + $port =($config['system']['webgui']['protocol'] == "http"?"80":"443"); + $synchronizetoip .= $sync_to_ip; + if (is_array($config['installedpackages']['postfixsync'])) + foreach($config['installedpackages']['postfixsync']['config'][0]['row'] as $sh){ + $sync_to_ip = $sh['ipaddress']; + $sync_type = $sh['sync_type']; + $password = $sh['password']; + $file= '/var/db/postfix/'.$server.'.sql'; + #get remote data + if ($sync_type=='fetch'){ + $url= $synchronizetoip . $sync_to_ip; + print "$sync_to_ip $url, $port\n"; + $method = 'pfsense.exec_php'; + $execcmd = "require_once('/usr/local/www/postfix.php');\n"; + $execcmd .= '$toreturn=get_sql('.$log_time.');'; + /* assemble xmlrpc payload */ + $params = array(XML_RPC_encode($password), + XML_RPC_encode($execcmd)); + log_error("postfix get sql data from {$sync_to_ip}."); + $msg = new XML_RPC_Message($method, $params); + $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); + $cli->setCredentials('admin', $password); + #$cli->setDebug(1); + $resp = $cli->send($msg, "250"); + $a=$resp->value(); + $errors=0; + #var_dump($sql); + foreach($a as $b) + foreach ($b as $c) + foreach ($c as $d) + foreach ($d as $e){ + $update=unserialize($e['string']); + print $update['day']."\n"; + if ($update['day'] != ""){ + create_db($update['day'].".db"); + if ($debug=true) + print $update['day'] ." writing from remote system to db..."; + $dbhandle = sqlite_open($postfix_dir.'/'.$update['day'].".db", 0666, $error); + #file_put_contents("/tmp/".$key.'-'.$update['day'].".sql",gzuncompress(base64_decode($update['sql'])), LOCK_EX); + $ok = sqlite_exec($dbhandle, gzuncompress(base64_decode($update['sql'])), $error); + if (!$ok){ + $errors++; + die ("Cannot execute query. $error\n".$update['sql']."\n"); + } + else{ + if ($debug=true) + print "ok\n"; + } + sqlite_close($dbhandle); + } + } + if ($errors ==0){ + $method = 'pfsense.exec_php'; + $execcmd = "require_once('/usr/local/www/postfix.php');\n"; + $execcmd .= 'flush_sql('.$log_time.');'; + /* assemble xmlrpc payload */ + $params = array(XML_RPC_encode($password), + XML_RPC_encode($execcmd)); + log_error("postfix flush sql buffer file from {$sync_to_ip}."); + $msg = new XML_RPC_Message($method, $params); + $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); + $cli->setCredentials('admin', $password); + #$cli->setDebug(1); + $resp = $cli->send($msg, "250"); + } + } + } +} +function get_sql($log_time){ + global $config,$xmlrpc_g; + $server=$_SERVER['REMOTE_ADDR']; + + if (is_array($config['installedpackages']['postfixsync'])) + foreach($config['installedpackages']['postfixsync']['config'][0]['row'] as $sh){ + $sync_to_ip = $sh['ipaddress']; + $sync_type = $sh['sync_type']; + $password = $sh['password']; + $file= '/var/db/postfix/'.$server.'.sql'; + if ($sync_to_ip==$server && $sync_type=='share' && file_exists($file)){ + rename($file,$file.".$log_time"); + return (file($file.".$log_time")); + } + } + return ""; +} + +function flush_sql($log_time){ + if (preg_match("/\d+\.\d+\.\d+\.\d+/",$_SERVER['REMOTE_ADDR'])) + unlink_if_exists('/var/db/postfix/'.$_SERVER['REMOTE_ADDR'].".sql.$log_time"); +} + +function grep_log(){ + global $postfix_dir,$postfix_arg,$config,$g; + + $total_lines=0; + $days=array(); + $grep="\(MailScanner\|postfix.cleanup\|postfix.smtp\|postfix.error\|postfix.qmgr\)"; + $curr_time = time(); + $log_time=strtotime($postfix_arg['time'],$curr_time); + $m=date('M',strtotime($postfix_arg['time'],$curr_time)); + $j=substr(" ".date('j',strtotime($postfix_arg['time'],$curr_time)),-3); + # file grep loop + foreach ($postfix_arg['grep'] as $hour){ + print "/usr/bin/grep '^".$m.$j." ".$hour.".*".$grep."' /var/log/maillog\n"; + $lists=array(); + exec("/usr/bin/grep " . escapeshellarg('^'.$m.$j." ".$hour.".*".$grep)." /var/log/maillog", $lists); + foreach ($lists as $line){ + #check where is first mail record + if (preg_match("/ delay=(\d+)/",$line,$delay)){ + $day=date("Y-m-d",strtotime("-".$delay[1]." second",$log_time)); + if (! in_array($day,$days)){ + $days[]=$day; + create_db($day.".db"); + print "Found logs to $day.db\n"; + $stm_queue[$day]="BEGIN;\n"; + $stm_noqueue[$day]="BEGIN;\n"; + } + } + else{ + $day=date("Y-m-d",strtotime($postfix_arg['time'],$curr_time)); + if (! in_array($day,$days)){ + $days[]=$day; + create_db($day.".db"); + print "Found logs to $day.db\n"; + $stm_queue[$day]="BEGIN;\n"; + $stm_noqueue[$day]="BEGIN;\n"; + } + } + $status=array(); + $total_lines++; + #Nov 8 09:31:50 srvch011 postfix/smtpd[43585]: 19C281F59C8: client=pm03-974.auinmem.br[177.70.0.3] + if(preg_match("/(\w+\s+\d+\s+[0-9,:]+) (\w+) postfix.smtpd\W\d+\W+(\w+): client=(.*)/",$line,$email)){ + $values="'".$email[3]."','".$email[1]."','".$email[2]."','".$email[4]."'"; + if(${$email[3]}!=$email[3]) + $stm_queue[$day].='insert or ignore into mail_from(sid,date,server,client) values ('.$values.');'."\n"; + ${$email[3]}=$email[3]; + } + #Dec 2 22:21:18 pfsense MailScanner[60670]: Requeue: 8DC3BBDEAF.A29D3 to 5AD9ABDEB5 + else if (preg_match("/(\w+\s+\d+\s+[0-9,:]+) (\w+) MailScanner.*Requeue: (\w+)\W\w+ to (\w+)/",$line,$email)){ + $stm_queue[$day].= "update or ignore mail_from set sid='".$email[4]."' where sid='".$email[3]."';\n"; + } + #Dec 5 14:06:10 srvchunk01 MailScanner[19589]: Message 775201F44B1.AED2C from 209.185.111.50 (marcellocoutinho@mailtest.com) to sede.mail.test.com is spam, SpamAssassin (not cached, escore=99.202, requerido 6, autolearn=spam, DKIM_SIGNED 0.10, DKIM_VALID -0.10, DKIM_VALID_AU -0.10, FREEMAIL_FROM 0.00, HTML_MESSAGE 0.00, RCVD_IN_DNSWL_LOW -0.70, WORM_TEST2 100.00) + else if (preg_match("/(\w+\s+\d+\s+[0-9,:]+) (\w+) MailScanner\W\d+\W+\w+\s+(\w+).* is spam, (.*)/",$line,$email)){ + $stm_queue[$day].= "insert or ignore into mail_status (info) values ('spam');\n"; + print "\n#######################################\nSPAM:".$email[4].$email[3].$email[2]."\n#######################################\n"; + $stm_queue[$day].= "update or ignore mail_to set status=(select id from mail_status where info='spam'), status_info='".preg_replace("/(\<|\>|\s+|\'|\")/"," ",$email[4])."' where from_id in (select id from mail_from where sid='".$email[3]."' and server='".$email[2]."');\n"; + } + #Nov 14 09:29:32 srvch011 postfix/error[58443]: 2B8EB1F5A5A: to=<hildae.sva@pi.email.com>, relay=none, delay=0.66, delays=0.63/0/0/0.02, dsn=4.4.3, status=deferred (delivery temporarily suspended: Host or domain name not found. Name service error for name=mail.pi.test.com type=A: Host not found, try again) + #Nov 3 21:45:32 srvch011 postfix/smtp[18041]: 4CE321F4887: to=<viinil@vitive.com.br>, relay=smtpe1.eom[81.00.20.9]:25, delay=1.9, delays=0.06/0.01/0.68/1.2, dsn=2.0.0, status=sent (250 2.0.0 Ok: queued as 2C33E2382C8) + #Nov 16 00:00:14 srvch011 postfix/smtp[7363]: 7AEB91F797D: to=<alessandra.bueno@mg.test.com>, relay=mail.mg.test.com[172.25.3.5]:25, delay=39, delays=35/1.1/0.04/2.7, dsn=5.7.1, status=bounced (host mail.mg.test.com[172.25.3.5] said: 550 5.7.1 Unable to relay for alessandra.bueno@mg.test.com (in reply to RCPT TO command)) + else if(preg_match("/(\w+\s+\d+\s+[0-9,:]+) (\w+) postfix.\w+\W\d+\W+(\w+): to=\<(.*)\>, relay=(.*), delay=([0-9,.]+), .* dsn=([0-9,.]+), status=(\w+) (.*)/",$line,$email)){ + $stm_queue[$day].= "insert or ignore into mail_status (info) values ('".$email[8]."');\n"; + $stm_queue[$day].= "insert or ignore into mail_to (from_id,too,status,status_info,relay,delay,dsn) values ((select id from mail_from where sid='".$email[3]."' and server='".$email[2]."'),'".strtolower($email[4])."',(select id from mail_status where info='".$email[8]."'),'".preg_replace("/(\<|\>|\s+|\'|\")/"," ",$email[9])."','".$email[5]."','".$email[6]."','".$email[7]."');\n"; + $stm_queue[$day].= "update or ignore mail_to set status=(select id from mail_status where info='".$email[8]."'), status_info='".preg_replace("/(\<|\>|\s+|\'|\")/"," ",$email[9])."', dsn='".$email[7]."', delay='".$email[6]."', relay='".$email[5]."', too='".strtolower($email[4])."' where from_id in (select id from mail_from where sid='".$email[3]."' and server='".$email[2]."');\n"; + } + #Nov 13 01:48:44 srvch011 postfix/cleanup[16914]: D995B1F570B: message-id=<61.40.11745.10E3FBE4@ofertas6> + else if(preg_match("/(\w+\s+\d+\s+[0-9,:]+) (\w+) postfix.cleanup\W\d+\W+(\w+): message-id=\<(.*)\>/",$line,$email)){ + $stm_queue[$day].="update mail_from set msgid='".$email[4]."' where sid='".$email[3]."';\n"; + } + #Nov 14 02:40:05 srvch011 postfix/qmgr[46834]: BC5931F4F13: from=<ceag@mx.crmcom.br>, size=32727, nrcpt=1 (queue active) + else if(preg_match("/(\w+\s+\d+\s+[0-9,:]+) (\w+) postfix.qmgr\W\d+\W+(\w+): from=\<(.*)\>\W+size=(\d+)/",$line,$email)){ + $stm_queue[$day].= "update mail_from set fromm='".strtolower($email[4])."', size='".$email[5]."' where sid='".$email[3]."';\n"; + } + #Nov 13 00:09:07 srvch011 postfix/bounce[56376]: 9145C1F67F7: sender non-delivery notification: D5BD31F6865 + #else if(preg_match("/(\w+\s+\d+\s+[0-9,:]+) (\w+) postfix.bounce\W\d+\W+(\w+): sender non-delivery notification: (\w+)/",$line,$email)){ + # $stm_queue[$day].= "update mail_queue set bounce='".$email[4]."' where sid='".$email[3]."';\n"; + #} + #Nov 14 01:41:44 srvch011 postfix/smtpd[15259]: warning: 1EF3F1F573A: queue file size limit exceeded + else if(preg_match("/(\w+\s+\d+\s+[0-9,:]+) (\w+) postfix.smtpd\W\d+\W+warning: (\w+): queue file size limit exceeded/",$line,$email)){ + $stm_queue[$day].= "insert or ignore into mail_status (info) values ('".$email[8]."');\n"; + $stm_queue[$day].= "update mail_to set status=(select id from mail_status where info='reject'), status_info='queue file size limit exceeded' where from_id in (select id from mail_from where sid='".$email[3]."' and server='".$email[2]."');\n"; + } + + #Nov 9 02:14:57 srvch011 postfix/cleanup[6856]: 617A51F5AC5: warning: header Subject: Mapeamento de Processos from lxalpha.12b.com.br[66.109.29.225]; from=<apache@lxalpha.12b.com.br> to=<ritiele.faria@mail.test.com> proto=ESMTP helo=<lxalpha.12b.com.br> + #Nov 8 09:31:50 srvch011 postfix/cleanup[11471]: 19C281F59C8: reject: header From: "Giuliana Flores - Parceiro do Grupo Virtual" <publicidade@parceiro-grupovirtual.com.br> from pm03-974.auinmeio.com.br[177.70.232.225]; from=<publicidade@parceiro-grupovirtual.com.br> to=<jorge.lustosa@mail.test.com> proto=ESMTP helo=<pm03-974.auinmeio.com.br>: 5.7.1 [SN007] + #Nov 13 00:03:24 srvch011 postfix/cleanup[4192]: 8A5B31F52D2: reject: body http://platform.roastcrack.info/mj0ie6p-48qtiyq from move2.igloojack.info[173.239.63.16]; from=<ljmd6u8lrxke4@move2.igloojack.info> to=<edileva@aasdf..br> proto=SMTP helo=<move2.igloojack.info>: 5.7.1 [BD040] + #Nov 14 01:41:35 srvch011 postfix/cleanup[58446]: 1EF3F1F573A: warning: header Subject: =?windows-1252?Q?IMOVEL_Voc=EA_=E9_um_Cliente_especial_da_=93CENTURY21=22?=??=?windows-1252?Q?Veja_o_que_tenho_para_voc=EA?= from mail-yw0-f51.google.com[209.85.213.51]; from=<sergioalexandre6308@gmail.com> to=<sinza@tr.br> proto=ESMTP helo=<mail-yw0-f51.google.com> + else if(preg_match("/(\w+\s+\d+\s+[0-9,:]+) (\w+) postfix.cleanup\W\d+\W+(\w+): (\w+): (.*) from ([a-z,A-Z,0-9,.,-]+)\W([0-9,.]+)\W+from=\<(.*)\> to=\<(.*)\>.*helo=\W([a-z,A-Z,0-9,.,-]+)(.*)/",$line,$email)){ + $status['date']=$email[1]; + $status['server']=$email[2]; + $status['sid']=$email[3]; + $status['remote_hostname']=$email[6]; + $status['remote_ip']=$email[7]; + $status['from']=$email[8]; + $status['to']=$email[9]; + $status['helo']=$email[10]; + $status['status']=$email[4]; + $stm_queue[$day].= "insert or ignore into mail_status (info) values ('".$email[4]."');\n"; + if ($email[4] =="warning"){ + if (${$status['sid']}=='hold'){ + $status['status']='hold'; + } + else{ + $status['status']='incoming'; + $stm_queue[$day].= "insert or ignore into mail_status (info) values ('".$status['status']."');\n"; + } + #print "$line\n"; + $status['status_info']=preg_replace("/(\<|\>|\s+|\'|\")/"," ",$email[11]); + $status['subject']=preg_replace("/header Subject: /","",$email[5]); + $status['subject']=preg_replace("/(\<|\>|\s+|\'|\")/"," ",$status['subject']); + $stm_queue[$day].="update mail_from set subject='".$status['subject']."', fromm='".strtolower($status['from'])."',helo='".$status['helo']."' where sid='".$status['sid']."';\n"; + $stm_queue[$day].="insert or ignore into mail_to (from_id,too,status,status_info) VALUES ((select id from mail_from where sid='".$email[3]."' and server='".$email[2]."'),'".strtolower($status['to'])."',(select id from mail_status where info='".$status['status']."'),'".$status['status_info']."');\n"; + $stm_queue[$day].="update or ignore mail_to set status=(select id from mail_status where info='".$status['status']."'), status_info='".$status['status_info']."', too='".strtolower($status['to'])."' where from_id in (select id from mail_from where sid='".$status['sid']."' and server='".$email[2]."');\n"; + } + else{ + ${$status['sid']}=$status['status']; + $stm_queue[$day].="update mail_from set fromm='".strtolower($status['from'])."',helo='".$status['helo']."' where sid='".$status['sid']."';\n"; + $status['status_info']=preg_replace("/(\<|\>|\s+|\'|\")/"," ",$email[5].$email[11]); + $stm_queue[$day].="insert or ignore into mail_to (from_id,too,status,status_info) VALUES ((select id from mail_from where sid='".$email[3]."' and server='".$email[2]."'),'".strtolower($status['to'])."',(select id from mail_status where info='".$email[4]."'),'".$status['status_info']."');\n"; + $stm_queue[$day].="update or ignore mail_to set status=(select id from mail_status where info='".$email[4]."'), status_info='".$status['status_info']."', too='".strtolower($status['to'])."' where from_id in (select id from mail_from where sid='".$status['sid']."' and server='".$email[2]."');\n"; + } + } + #Nov 9 02:14:34 srvch011 postfix/smtpd[38129]: NOQUEUE: reject: RCPT from unknown[201.36.0.7]: 450 4.7.1 Client host rejected: cannot find your hostname, [201.36.98.7]; from=<maladireta@esadcos.com.br> to=<sexec.09vara@go.domain.test.com> proto=ESMTP helo=<capri0.wb.com.br> + else if(preg_match("/(\w+\s+\d+\s+[0-9,:]+) (\w+) postfix.smtpd\W\d+\W+NOQUEUE:\s+(\w+): (.*); from=\<(.*)\> to=\<(.*)\>.*helo=\<(.*)\>/",$line,$email)){ + $status['date']=$email[1]; + $status['server']=$email[2]; + $status['status']=$email[3]; + $status['status_info']=$email[4]; + $status['from']=$email[5]; + $status['to']=$email[6]; + $status['helo']=$email[7]; + $values="'".$status['date']."','".$status['status']."','".$status['status_info']."','".strtolower($status['from'])."','".strtolower($status['to'])."','".$status['helo']."','".$status['server']."'"; + $stm_noqueue[$day].='insert or ignore into mail_noqueue(date,status,status_info,fromm,too,helo,server) values ('.$values.');'."\n"; + } + if ($total_lines%1500 == 0){ + #save log in database + write_db($stm_noqueue,"noqueue",$days); + write_db($stm_queue,"from",$days); + foreach ($days as $d){ + $stm_noqueue[$d]="BEGIN;\n"; + $stm_queue[$d]="BEGIN;\n"; + } + } + if ($total_lines%1500 == 0) + print "$line\n"; + } + #save log in database + write_db($stm_noqueue,"noqueue",$days); + write_db($stm_queue,"from",$days); + foreach ($days as $d){ + $stm_noqueue[$d]="BEGIN;\n"; + $stm_queue[$d]="BEGIN;\n"; + } + } + + $config=parse_xml_config("{$g['conf_path']}/config.xml", $g['xml_rootobj']); + print count($config['installedpackages']); + #start db replication if configured + if ($config['installedpackages']['postfixsync']['config'][0]['rsync']) + foreach ($config['installedpackages']['postfixsync']['config'] as $rs ) + foreach($rs['row'] as $sh){ + $sync_to_ip = $sh['ipaddress']; + $sync_type = $sh['sync_type']; + $password = $sh['password']; + print "checking replication to $sync_to_ip..."; + if ($password && $sync_to_ip && preg_match("/(both|database)/",$sync_type)) + postfix_do_xmlrpc_sync($sync_to_ip, $password,$sync_type); + print "ok\n"; + } + +} + +function write_db($stm,$table,$days){ + global $postfix_dir,$config,$g; + conf_mount_rw(); + $do_sync=array(); + print "writing to database..."; + foreach ($days as $day) + if (strlen($stm[$day]) > 10){ + if ($config['installedpackages']['postfixsync']['config'][0]) + foreach ($config['installedpackages']['postfixsync']['config'] as $rs ) + foreach($rs['row'] as $sh){ + $sync_to_ip = $sh['ipaddress']; + $sync_type = $sh['sync_type']; + $password = $sh['password']; + $sql_file='/var/db/postfix/'.$sync_to_ip.'.sql'; + ${$sync_to_ip}=""; + if (file_exists($sql_file)) + ${$sync_to_ip}=file_get_contents($sql_file); + if ($sync_to_ip && $sync_type=="share"){ + ${$sync_to_ip}.=serialize(array('day'=> $day,'sql'=> base64_encode(gzcompress($stm[$day]."COMMIT;",9))))."\n"; + if (! in_array($sync_to_ip,$do_sync)) + $do_sync[]=$sync_to_ip; + } + } + #write local db file + create_db($day.".db"); + if ($debug=true) + print " writing to local db $day..."; + $dbhandle = sqlite_open($postfix_dir.$day.".db", 0666, $error); + if (!$dbhandle) die ($error); + #file_put_contents("/tmp/".$key.'-'.$update['day'].".sql",gzuncompress(base64_decode($update['sql'])), LOCK_EX); + $ok = sqlite_exec($dbhandle, $stm[$day]."COMMIT;", $error); + if (!$ok){ + if ($debug=true) + print ("Cannot execute query. $error\n".$stm[$day]."COMMIT;\n"); + } + else{ + if ($debug=true) + print "ok\n"; + } + sqlite_close($dbhandle); + } + #write update sql files + if (count ($do_sync) > 0 ){ + + foreach($do_sync as $ip) + file_put_contents('/var/db/postfix/'.$ip.'.sql',${$ip},LOCK_EX); + conf_mount_ro(); + } + #write local file + +} + +function create_db($postfix_db){ + global $postfix_dir,$postfix_arg; + if (! is_dir($postfix_dir)) + mkdir($postfix_dir,0775); + $new_db=(file_exists($postfix_dir.$postfix_db)?1:0); +$stm = <<<EOF + CREATE TABLE "mail_from"( + "id" INTEGER PRIMARY KEY, + "sid" VARCHAR(11) NOT NULL, + "client" TEXT NOT NULL, + "msgid" TEXT, + "fromm" TEXT, + "size" INTEGER, + "subject" TEXT, + "date" TEXT NOT NULL, + "server" TEXT, + "helo" TEXT +); + CREATE TABLE "mail_to"( + "id" INTEGER PRIMARY KEY, + "from_id" INTEGER NOT NULL, + "too" TEXT, + "status" INTEGER, + "status_info" TEXT, + "smtp" TEXT, + "delay" TEXT, + "relay" TEXT, + "dsn" TEXT, + "server" TEXT, + "bounce" TEXT, + FOREIGN KEY (status) REFERENCES mail_status(id), + FOREIGN KEY (from_id) REFERENCES mail_from(id) +); + + +CREATE TABLE "mail_status"( + "id" INTEGER PRIMARY KEY, + "info" varchar(35) NOT NULL +); + +CREATE TABLE "mail_noqueue"( + "id" INTEGER PRIMARY KEY, + "date" TEXT NOT NULL, + "server" TEXT NOT NULL, + "status" TEXT NOT NULL, + "status_info" INTEGER NOT NULL, + "fromm" TEXT NOT NULL, + "too" TEXT NOT NULL, + "helo" TEXT NOT NULL +); + +CREATE TABLE "db_version"( + "value" varchar(10), + "info" TEXT +); + +insert or ignore into db_version ('value') VALUES ('2.3.1'); + +CREATE INDEX "noqueue_unique" on mail_noqueue (date ASC, fromm ASC, too ASC); +CREATE INDEX "noqueue_helo" on mail_noqueue (helo ASC); +CREATE INDEX "noqueue_too" on mail_noqueue (too ASC); +CREATE INDEX "noqueue_fromm" on mail_noqueue (fromm ASC); +CREATE INDEX "noqueue_info" on mail_noqueue (status_info ASC); +CREATE INDEX "noqueue_status" on mail_noqueue (status ASC); +CREATE INDEX "noqueue_server" on mail_noqueue (server ASC); +CREATE INDEX "noqueue_date" on mail_noqueue (date ASC); + +CREATE UNIQUE INDEX "status_info" on mail_status (info ASC); + +CREATE UNIQUE INDEX "from_sid_server" on mail_from (sid ASC,server ASC); +CREATE INDEX "from_client" on mail_from (client ASC); +CREATE INDEX "from_helo" on mail_from (helo ASC); +CREATE INDEX "from_server" on mail_from (server ASC); +CREATE INDEX "from_subject" on mail_from (subject ASC); +CREATE INDEX "from_msgid" on mail_from (msgid ASC); +CREATE INDEX "from_fromm" on mail_from (fromm ASC); +CREATE INDEX "from_date" on mail_from (date ASC); + +CREATE UNIQUE INDEX "mail_to_unique" on mail_to (from_id ASC, too ASC); +CREATE INDEX "to_bounce" on mail_to (bounce ASC); +CREATE INDEX "to_relay" on mail_to (relay ASC); +CREATE INDEX "to_smtp" on mail_to (smtp ASC); +CREATE INDEX "to_info" on mail_to (status_info ASC); +CREATE INDEX "to_status" on mail_to (status ASC); +CREATE INDEX "to_too" on mail_to (too ASC); + +EOF; +#test file version +print "checking". $postfix_dir.$postfix_db."\n"; +$dbhandle = sqlite_open($postfix_dir.$postfix_db, 0666, $error); +if (!$dbhandle) die ($error); +$ok = sqlite_exec($dbhandle,"select value from db_version", $error); +sqlite_close($dbhandle); +if (!$ok){ + print "delete previous table version\n"; + if (file_exists($postfix_dir.$postfix_db)) + unlink($postfix_dir.$postfix_db); + $new_db=0; +} +if ($new_db==0){ + $dbhandle = sqlite_open($postfix_dir.$postfix_db, 0666, $error); + $ok = sqlite_exec($dbhandle, $stm, $error); + if (!$ok) + print ("Cannot execute query. $error\n"); + $ok = sqlite_exec($dbhandle, $stm2, $error); + if (!$ok) + print ("Cannot execute query. $error\n"); + sqlite_close($dbhandle); + } +} + +$postfix_dir="/var/db/postfix/"; +$curr_time = time(); +#console script call +if ($argv[1]!=""){ +switch ($argv[1]){ + case "01min": + $postfix_arg=array( 'grep' => array(date("H:i",strtotime('-1 min',$curr_time))), + 'time' => '-1 min'); + break; + case "10min": + $postfix_arg=array( 'grep' => array(substr(date("H:i",strtotime('-10 min',$curr_time)),0,-1)), + 'time' => '-10 min'); + break; + case "01hour": + $postfix_arg=array( 'grep' => array(date("H:",strtotime('-01 hour',$curr_time))), + 'time' => '-01 hour'); + break; + case "04hour": + $postfix_arg=array( 'grep' => array(date("H:",strtotime('-04 hour',$curr_time)),date("H:",strtotime('-03 hour',$curr_time)), + date("H:",strtotime('-02 hour',$curr_time)),date("H:",strtotime('-01 hour',$curr_time))), + 'time' => '-04 hour'); + break; + case "24hours": + $postfix_arg=array( 'grep' => array('00:','01:','02:','03:','04:','05:','06:','07:','08:','09:','10:','11:', + '12:','13:','14:','15:','16:','17:','18:','19:','20:','21:','22:','23:'), + 'time' => '-01 day'); + break; + case "02days": + $postfix_arg=array( 'grep' => array('00:','01:','02:','03:','04:','05:','06:','07:','08:','09:','10:','11:', + '12:','13:','14:','15:','16:','17:','18:','19:','20:','21:','22:','23:'), + 'time' => '-02 day'); + break; + case "03days": + $postfix_arg=array( 'grep' => array('00:','01:','02:','03:','04:','05:','06:','07:','08:','09:','10:','11:', + '12:','13:','14:','15:','16:','17:','18:','19:','20:','21:','22:','23:'), + 'time' => '-03 day'); + break; + + default: + die ("invalid parameters\n"); +} +# get remote log from remote server +get_remote_log(); +# get local log from logfile +grep_log(); +} + +#http client call +if ($_REQUEST['files']!= ""){ + #do search + if($_REQUEST['queue']=="QUEUE"){ + $stm="select * from mail_from, mail_to ,mail_status where mail_from.id=mail_to.from_id and mail_to.status=mail_status.id "; + $last_next=" and "; + } + else{ + $stm="select * from mail_noqueue"; + $last_next=" where "; + } + $limit_prefix=(preg_match("/\d+/",$_REQUEST['limit'])?"limit ":""); + $limit=(preg_match("/\d+/",$_REQUEST['limit'])?$_REQUEST['limit']:""); + $files= explode(",", $_REQUEST['files']); + $stm_fetch=array(); + $total_result=0; + foreach ($files as $postfix_db) + if (file_exists($postfix_dir.'/'.$postfix_db)){ + $dbhandle = sqlite_open($postfix_dir.'/'.$postfix_db, 0666, $error); + if ($_REQUEST['from']!= ""){ + $next=($last_next==" and "?" and ":" where "); + $last_next=" and "; + if (preg_match('/\*/',$_REQUEST['from'])) + $stm .=$next."fromm like '".preg_replace('/\*/','%',$_REQUEST['from'])."'"; + else + $stm .=$next."fromm in('".$_REQUEST['from']."')"; + } + if ($_REQUEST['to']!= ""){ + $next=($last_next==" and "?" and ":" where "); + $last_next=" and "; + if (preg_match('/\*/',$_REQUEST['to'])) + $stm .=$next."too like '".preg_replace('/\*/','%',$_REQUEST['to'])."'"; + else + $stm .=$next."too in('".$_REQUEST['to']."')"; + } + if ($_REQUEST['sid']!= "" && $_REQUEST['queue']=="QUEUE"){ + $next=($last_next==" and "?" and ":" where "); + $last_next=" and "; + $stm .=$next."sid in('".$_REQUEST['sid']."')"; + } + if ($_REQUEST['relay']!= "" && $_REQUEST['queue']=="QUEUE"){ + $next=($last_next==" and "?" and ":" where "); + $last_next=" and "; + if (preg_match('/\*/',$_REQUEST['subject'])) + $stm .=$next."relay like '".preg_replace('/\*/','%',$_REQUEST['relay'])."'"; + else + $stm .=$next."relay = '".$_REQUEST['relay']."'"; + } + if ($_REQUEST['subject']!= "" && $_REQUEST['queue']=="QUEUE"){ + $next=($last_next==" and "?" and ":" where "); + $last_next=" and "; + if (preg_match('/\*/',$_REQUEST['subject'])) + $stm .=$next."subject like '".preg_replace('/\*/','%',$_REQUEST['subject'])."'"; + else + $stm .=$next."subject = '".$_REQUEST['subject']."'"; + } + if ($_REQUEST['msgid']!= "" && $_REQUEST['queue']=="QUEUE"){ + $next=($last_next==" and "?" and ":" where "); + $last_next=" and "; + if (preg_match('/\*/',$_REQUEST['msgid'])) + $stm .=$next."msgid like '".preg_replace('/\*/','%',$_REQUEST['msgid'])."'"; + else + $stm .=$next."msgid = '".$_REQUEST['msgid']."'"; + } + if ($_REQUEST['server']!= "" ){ + $next=($last_next==" and "?" and ":" where "); + $last_next=" and "; + if( $_REQUEST['queue']=="QUEUE") + $stm .=$next."mail_from.server = '".$_REQUEST['server']."'"; + else + $stm .=$next."server = '".$_REQUEST['server']."'"; + } + + if ($_REQUEST['status']!= ""){ + $next=($last_next==" and "?" and ":" where "); + $last_next=" and "; + $stm .=$next."mail_status.info = '".$_REQUEST['status']."'"; + } + #print "<pre>".$stm; + #$stm = "select * from mail_to,mail_status where mail_to.status=mail_status.id"; + $result = sqlite_query($dbhandle, $stm." order by date desc $limit_prefix $limit "); + #$result = sqlite_query($dbhandle, $stm." $limit_prefix $limit "); + if (preg_match("/\d+/",$_REQUEST['limit'])){ + for ($i = 1; $i <= $limit; $i++) { + $row = sqlite_fetch_array($result, SQLITE_ASSOC); + if (is_array($row)) + $stm_fetch[]=$row; + } + } + else{ + $stm_fetch = sqlite_fetch_all($result, SQLITE_ASSOC); + } + sqlite_close($dbhandle); + } + $fields= explode(",", $_REQUEST['fields']); + if ($_REQUEST['sbutton']=='export'){ + print '<table class="tabcont" width="100%" border="0" cellpadding="8" cellspacing="0">'; + print '<tr><td colspan="'.count($fields).'" valign="top" class="listtopic">'.gettext("Search Results").'</td></tr>'; + print '<tr>'; + $header=""; + foreach ($stm_fetch as $mail){ + foreach ($mail as $key => $data){ + if (!preg_match("/$key/",$header)) + $header .= $key.","; + $export.=preg_replace('/,/',"",$mail[$key]).","; + } + $export.= "\n"; + } + print '<td class="tabcont"><textarea id="varnishlogs" rows="50" cols="100%">'; + print "This export is in csv format, paste it without this line on any software that handles csv files.\n\n".$header."\n".$export; + print "</textarea></td></tr></table>"; + } + else{ + if ($_REQUEST['queue']=="NOQUEUE"){ + print '<table class="tabcont" width="100%" border="0" cellpadding="8" cellspacing="0">'; + print '<tr><td colspan="'.count($fields).'" valign="top" class="listtopic">'.gettext("Search Results").'</td></tr>'; + print '<tr>'; + if(in_array("date",$fields)) + print '<td class="listlr"><strong>date</strong></td>'; + if(in_array("server",$fields)) + print '<td class="listlr"><strong>server</strong></td>'; + if(in_array("from",$fields)) + print '<td class="listlr"><strong>From</strong></td>'; + if(in_array("to",$fields)) + print '<td class="listlr"><strong>to</strong></td>'; + if(in_array("helo",$fields)) + print '<td class="listlr"><strong>Helo</strong></td>'; + if(in_array("status",$fields)) + print '<td class="listlr"><strong>Status</strong></td>'; + if(in_array("status_info",$fields)) + print '<td class="listlr"><strong>Status Info</strong></td>'; + print '</tr>'; + foreach ($stm_fetch as $mail){ + print '<tr>'; + if(in_array("date",$fields)) + print '<td class="listlr">'.$mail['date'].'</td>'; + if(in_array("server",$fields)) + print '<td class="listlr">'.$mail['server'].'</td>'; + if(in_array("from",$fields)) + print '<td class="listlr">'.$mail['fromm'].'</td>'; + if(in_array("to",$fields)) + print '<td class="listlr">'.$mail['too'].'</td>'; + if(in_array("helo",$fields)) + print '<td class="listlr">'.$mail['helo'].'</td>'; + if(in_array("status",$fields)) + print '<td class="listlr">'.$mail['status'].'</td>'; + if(in_array("status_info",$fields)) + print '<td class="listlr">'.$mail['status_info'].'</td>'; + print '</tr>'; + $total_result++; + } + } + else{ + print '<table class="tabcont" width="100%" border="0" cellpadding="8" cellspacing="0">'; + print '<tr><td colspan="'.count($fields).'" valign="top" class="listtopic">'.gettext("Search Results").'</td></tr>'; + print '<tr>'; + if(in_array("date",$fields)) + print '<td class="listlr" ><strong>Date</strong></td>'; + if(in_array("server",$fields)) + print '<td class="listlr" ><strong>Server</strong></td>'; + if(in_array("from",$fields)) + print '<td class="listlr" ><strong>From</strong></td>'; + if(in_array("to",$fields)) + print '<td class="listlr" ><strong>to</strong></td>'; + if(in_array("subject",$fields)) + print '<td class="listlr" ><strong>Subject</strong></td>'; + if(in_array("delay",$fields)) + print '<td class="listlr" ><strong>Delay</strong></td>'; + if(in_array("status",$fields)) + print '<td class="listlr" ><strong>Status</strong></td>'; + if(in_array("status_info",$fields)) + print '<td class="listlr" ><strong>Status Info</strong></td>'; + if(in_array("size",$fields)) + print '<td class="listlr" ><strong>Size</strong></td>'; + if(in_array("helo",$fields)) + print '<td class="listlr" ><strong>Helo</strong></td>'; + if(in_array("sid",$fields)) + print '<td class="listlr" ><strong>SID</strong></td>'; + if(in_array("msgid",$fields)) + print '<td class="listlr" ><strong>MSGID</strong></td>'; + if(in_array("bounce",$fields)) + print '<td class="listlr" ><strong>Bounce</strong></td>'; + if(in_array("relay",$fields)) + print '<td class="listlr" ><strong>Relay</strong></td>'; + print '</tr>'; + foreach ($stm_fetch as $mail){ + if(in_array("date",$fields)) + print '<td class="listlr">'.$mail['mail_from.date'].'</td>'; + if(in_array("server",$fields)) + print '<td class="listlr">'.$mail['mail_from.server'].'</td>'; + if(in_array("from",$fields)) + print '<td class="listlr">'.$mail['mail_from.fromm'].'</td>'; + if(in_array("to",$fields)) + print '<td class="listlr">'.$mail['mail_to.too'].'</td>'; + if(in_array("subject",$fields)) + print '<td class="listlr">'.$mail['mail_from.subject'].'</td>'; + if(in_array("delay",$fields)) + print '<td class="listlr">'.$mail['mail_to.delay'].'</td>'; + if(in_array("status",$fields)) + print '<td class="listlr">'.$mail['mail_status.info'].'</td>'; + if(in_array("status_info",$fields)) + print '<td class="listlr">'.$mail['mail_to.status_info'].'</td>'; + if(in_array("size",$fields)) + print '<td class="listlr">'.$mail['mail_from.size'].'</td>'; + if(in_array("helo",$fields)) + print '<td class="listlr">'.$mail['mail_from.helo'].'</td>'; + if(in_array("sid",$fields)) + print '<td class="listlr">'.$mail['mail_from.sid'].'</td>'; + if(in_array("msgid",$fields)) + print '<td class="listlr">'.$mail['mail_from.msgid'].'</td>'; + if(in_array("bounce",$fields)) + print '<td class="listlr">'.$mail['mail_to.bounce'].'</td>'; + if(in_array("relay",$fields)) + print '<td class="listlr">'.$mail['mail_to.relay'].'</td>'; + print '</tr>'; + $total_result++; + } + } + print '<tr>'; + print '<td ><strong>Total:</strong></td>'; + print '<td ><strong>'.$total_result.'</strong></td>'; + print '</tr>'; + print '</table>'; + } +} ?>
\ No newline at end of file diff --git a/config/postfix/postfix.widget.php b/config/postfix/postfix.widget.php index c439b5ce..70051c1d 100755 --- a/config/postfix/postfix.widget.php +++ b/config/postfix/postfix.widget.php @@ -27,6 +27,11 @@ @require_once("guiconfig.inc"); @require_once("pfsense-utils.inc"); @require_once("functions.inc"); + +$uname=posix_uname(); +if ($uname['machine']=='amd64') + ini_set('memory_limit', '250M'); + function open_table(){ echo "<table style=\"padding-top:0px; padding-bottom:0px; padding-left:0px; padding-right:0px\" width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">"; echo" <tr>"; diff --git a/config/postfix/postfix_acl.xml b/config/postfix/postfix_acl.xml index 2a2b4633..efc72721 100644 --- a/config/postfix/postfix_acl.xml +++ b/config/postfix/postfix_acl.xml @@ -118,13 +118,14 @@ <fielddescr>Sender</fielddescr> <fieldname>sender_access</fieldname> <description><![CDATA[<strong>HASH filters</strong> that implements whitelisting and blacklisting of full or partial email addresses and domains as specified in the MAIL FROM field :<br> - myfriend@example.com OK<br> + myfriend@example.com DUNNO<br> junk@spam.com REJECT<br> marketing@ REJECT<br> - theboss@ OK<br> + theboss@ DUNNO<br> deals.marketing.com REJECT<br> - somedomain.com OK<br> - See http://www.postfix.org/postconf.5.html#smtpd_sender_restrictions for more help]]> + somedomain.com DUNNO<br><br> + See http://www.postfix.org/postconf.5.html#smtpd_sender_restrictions for more help<br> + <strong>Note: a result of "OK" in this field is not allowed/wanted for safety reasons(it may accept forged senders as it will not do other spam checks). Instead, use DUNNO in order to exclude specific hosts from blacklists.</strong>]]> </description> <type>textarea</type> <cols>83</cols> diff --git a/config/postfix/postfix_queue.php b/config/postfix/postfix_queue.php index ce4d6cc6..914ad88e 100755 --- a/config/postfix/postfix_queue.php +++ b/config/postfix/postfix_queue.php @@ -29,6 +29,11 @@ */ require("guiconfig.inc"); + +$uname=posix_uname(); +if ($uname['machine']=='amd64') + ini_set('memory_limit', '250M'); + function get_cmd(){ if ($_REQUEST['cmd'] =='mailq'){ #exec("/usr/local/bin/mailq" . escapeshellarg('^'.$m.$j." ".$hour.".*".$grep)." /var/log/maillog", $lists); diff --git a/config/postfix/postfix_search.php b/config/postfix/postfix_search.php index 6152140d..2b831f72 100755 --- a/config/postfix/postfix_search.php +++ b/config/postfix/postfix_search.php @@ -30,6 +30,10 @@ require("guiconfig.inc"); +$uname=posix_uname(); +if ($uname['machine']=='amd64') + ini_set('memory_limit', '250M'); + $pfSversion = str_replace("\n", "", file_get_contents("/etc/version")); if(strstr($pfSversion, "1.2")) $one_two = true; diff --git a/config/quagga_ospfd/quagga_ospfd.inc b/config/quagga_ospfd/quagga_ospfd.inc index 755f6c98..598d3c00 100644 --- a/config/quagga_ospfd/quagga_ospfd.inc +++ b/config/quagga_ospfd/quagga_ospfd.inc @@ -1,7 +1,7 @@ <?php /* quagga_ospfd.inc - Copyright (C) 2010 Ermal Luçi + Copyright (C) 2010 Ermal Lu�i Copyright (C) 2012 Jim Pingle part of pfSense All rights reserved. @@ -27,6 +27,19 @@ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +require_once("config.inc"); +require_once("functions.inc"); +require_once("service-utils.inc"); + +define('PKG_QUAGGA_CONFIG_BASE', '/var/etc/quagga'); + +$pkg_login = "quagga"; +$pkg_uid = "101"; +$pkg_group = "quagga"; +$pkg_gid = "101"; +$pkg_gecos = "Quagga route daemon pseudo user"; +$pkg_homedir = "/var/etc/quagga"; +$pkg_shell = "/usr/sbin/nologin"; function quagga_ospfd_get_interfaces() { global $config; @@ -54,9 +67,11 @@ function quagga_ospfd_get_interfaces() { } function quagga_ospfd_install_conf() { - global $config, $g, $input_errors; + global $config, $g, $input_errors, $pkg_login, $pkg_uid, $pkg_group, $pkg_gid, $pkg_gecos, $pkg_homedir, $pkg_shell; conf_mount_rw(); + // Since we need to embed this in a string, copy to a var. Can't embed constnats. + $quagga_config_base = PKG_QUAGGA_CONFIG_BASE; if ($config['installedpackages']['quaggaospfd']['rawconfig'] && $config['installedpackages']['quaggaospfd']['rawconfig']['item']) { // if there is a raw config specifyed in tthe config.xml use that instead of the assisted config @@ -82,6 +97,7 @@ function quagga_ospfd_install_conf() { /* Interface Settings */ $passive_interfaces = array(); $interface_networks = array(); + if ($config['installedpackages']['quaggaospfdinterfaces']['config']) { foreach ($config['installedpackages']['quaggaospfdinterfaces']['config'] as $conf) { $realif = get_real_interface($conf['interface']); @@ -94,9 +110,9 @@ function quagga_ospfd_install_conf() { } if ($conf['md5password'] && !empty($conf['password'])) { $conffile .= " ip ospf authentication message-digest\n"; - $conffile .= " ip ospf message-digest-key 1 md5 \"" . substr($conf['password'], 0, 15) . "\"\n"; + $conffile .= " ip ospf message-digest-key 1 md5 " . substr($conf['password'], 0, 15) . "\n"; } else if (!empty($conf['password'])) { - $conffile .= " ip ospf authentication-key \"" . substr($conf['password'], 0, 8) . "\"\n"; + $conffile .= " ip ospf authentication-key " . substr($conf['password'], 0, 8) . "\n"; } if (!empty($conf['routerpriorityelections'])) { $conffile .= " ip ospf priority {$conf['routerpriorityelections']}\n"; @@ -116,7 +132,31 @@ function quagga_ospfd_install_conf() { if ($interface_subnet == 32) $interface_subnet = 30; $subnet = gen_subnet($interface_ip, $interface_subnet); - $interface_networks[] = "{$subnet}/{$interface_subnet}"; + if (!empty($conf['interfacearea'])) { + $interface_networks[] = array( "subnet" => "{$subnet}/{$interface_subnet}", "area" => $conf['interfacearea']); + } + else { + $interface_networks[] = array( "subnet" => "{$subnet}/{$interface_subnet}", "area" => $ospfd_conf['area']); + } + + + + } + } + + + $redist = ""; + $noredist = ""; + if (is_array($ospfd_conf['row'])) { + foreach ($ospfd_conf['row'] as $redistr) { + if (empty($redistr['routevalue'])) + continue; + if (isset($redistr['redistribute'])) { + $noredist .= " access-list dnr-list deny {$redistr['routevalue']}\n"; + } else { + $area = ($redistr['routearea'] == "") ? $ospfd_conf['area'] : $redistr['routearea']; + $redist .= " network {$redistr['routevalue']} area {$area}\n"; + } } } @@ -139,6 +179,10 @@ function quagga_ospfd_install_conf() { if ($ospfd_conf['redistributestatic']) $conffile .= " redistribute static\n"; + + if ($ospfd_conf['redistributekernel']) + $conffile .= " redistribute kernel\n"; + if ($ospfd_conf['redistributedefaultroute']) $conffile .= " default-information originate\n"; @@ -153,25 +197,35 @@ function quagga_ospfd_install_conf() { if ($ospfd_conf['rfc1583']) $conffile .= " ospf rfc1583compatibility\n"; - if (is_array($passive_interfaces)) + if (is_array($passive_interfaces)) { foreach ($passive_interfaces as $pint) $conffile .= " passive-interface {$pint}\n"; + } - if (is_array($interface_networks)) - foreach ($interface_networks as $ifn) - if (is_subnet($ifn)) - $conffile .= " network {$ifn} area {$ospfd_conf['area']}\n"; - if (is_array($ospfd_conf['row'])) { - foreach ($ospfd_conf['row'] as $redistr) { - if (isset($redistr['redistribute'])) - $conffile .= " no "; - $conffile .= " network {$redistr['routevalue']} area {$ospfd_conf['area']}\n"; + if (is_array($interface_networks)) { + foreach ($interface_networks as $ifn) { + if (is_subnet($ifn['subnet'])) { + $conffile .= " network {$ifn['subnet']} area {$ifn['area']}\n"; + } } } - } - $fd = fopen("/usr/local/etc/quagga/ospfd.conf", "w"); + if (!empty($redist)) + $conffile .= $redist; + + if (!empty($noredist)) { + $conffile .= " distribute-list dnr-list out connected\n"; + $conffile .= " distribute-list dnr-list out kernel\n"; + $conffile .= " distribute-list dnr-list out static\n"; + //$conffile .= " distribute-list dnr-list out ospf\n"; + $conffile .= $noredist; + $conffile .= " access-list dnr-list permit any\n"; + } + + } + safe_mkdir($quagga_config_base); + $fd = fopen("{$quagga_config_base}/ospfd.conf", "w"); // Write out the configuration file fwrite($fd, $conffile); @@ -185,23 +239,43 @@ function quagga_ospfd_install_conf() { $zebraconffile .= "password {$ospfd_conf['password']}\n"; if ($ospfd_conf['logging']) $zebraconffile .= "log syslog\n"; - $fd = fopen("/usr/local/etc/quagga/zebra.conf", "w"); + $fd = fopen("{$quagga_config_base}/zebra.conf", "w"); fwrite($fd, $zebraconffile); fclose($fd); // Create rc.d file $rc_file_stop = <<<EOF -kill -9 `cat /var/run/quagga/zebra.pid` -kill -9 `cat /var/run/quagga/ospfd.pid` +if [ -e /var/run/quagga/zebra.pid ]; then + kill -9 `cat /var/run/quagga/zebra.pid` + rm -f /var/run/quagga/zebra.pid +fi +if [ -e /var/run/quagga/ospfd.pid ]; then + kill -9 `cat /var/run/quagga/ospfd.pid` + rm -f /var/run/quagga/ospfd.pid +fi EOF; $rc_file_start = <<<EOF /bin/mkdir -p /var/run/quagga /bin/mkdir -p /var/log/quagga -/usr/sbin/chown -R quagga:quagga /usr/local/etc/quagga/ +rm -f /var/run/quagga/zebra.pid +rm -f /var/run/quagga/ospfd.pid + +if [ `pw groupshow {$pkg_group} 2>&1 | grep -c "pw: unknown group"` -gt 0 ]; then + /usr/sbin/pw groupadd {$pkg_group} -g {$pkg_gid} +fi +if [ `pw usershow {$pkg_login} 2>&1 | grep -c "pw: no such user"` -gt 0 ]; then + /usr/sbin/pw useradd {$pkg_login} -u {$pkg_uid} -g {$pkg_gid} -c "{$pkg_gecos}" -d {$pkg_homedir} -s {$pkg_shell} +fi + +/usr/sbin/chown -R quagga:quagga {$quagga_config_base} /usr/sbin/chown -R quagga:quagga /var/run/quagga /usr/sbin/chown -R quagga:quagga /var/log/quagga -/usr/local/sbin/zebra -d -/usr/local/sbin/ospfd -d +# Ensure no other copies of the daemons are running or it breaks. +killall -9 zebra 2>/dev/null +killall -9 ospfd 2>/dev/null +sleep 1 +/usr/local/sbin/zebra -d -f {$quagga_config_base}/zebra.conf +/usr/local/sbin/ospfd -d -f {$quagga_config_base}/ospfd.conf EOF; write_rcfile(array( "file" => "quagga.sh", @@ -212,8 +286,8 @@ EOF; // Ensure files have correct permissions exec("chmod a+rx /usr/local/etc/rc.d/quagga.sh"); - exec("chmod u+rw,go-rw /usr/local/etc/quagga/ospfd.conf"); - exec("chmod u+rw,go-rw /usr/local/etc/quagga/zebra.conf"); + exec("chmod u+rw,go-rw {$quagga_config_base}/ospfd.conf"); + exec("chmod u+rw,go-rw {$quagga_config_base}/zebra.conf"); // Kick off newly created rc.d script exec("/usr/local/etc/rc.d/quagga.sh restart"); @@ -240,6 +314,8 @@ function quagga_ospfd_validate_interface() { function quagga_ospfd_validate_input() { global $config, $g, $input_errors; + if ($_POST['password'] <> "" && (strpos($_POST['password'], "'") !== false)) + $input_errors[] = "Password cannot contain a single quote (')"; if (!empty($_POST['routerid']) && !is_ipaddr($_POST['routerid'])) $input_errors[] = "Router ID must be an address."; if (!is_ipaddr($_POST['area'])) @@ -254,7 +330,7 @@ function quagga_ospfd_validate_input() { // get the raw ospfd confi file for manual inspection/editing function quagga_ospfd_get_raw_config() { - return file_get_contents("/usr/local/etc/quagga/ospfd.conf"); + return file_get_contents(PKG_QUAGGA_CONFIG_BASE . "/ospfd.conf"); } // serialize the raw ospfd confi file to config.xml diff --git a/config/quagga_ospfd/quagga_ospfd.xml b/config/quagga_ospfd/quagga_ospfd.xml index 3e76c4e4..d1e96efa 100644 --- a/config/quagga_ospfd/quagga_ospfd.xml +++ b/config/quagga_ospfd/quagga_ospfd.xml @@ -1,6 +1,6 @@ <packagegui> <name>quagga_ospfd</name> - <version>0.1</version> + <version>0.5</version> <title>Services: Quagga OSPFd</title> <include_file>/usr/local/pkg/quagga_ospfd.inc</include_file> <aftersaveredirect>pkg_edit.php?xml=quagga_ospfd.xml&id=0</aftersaveredirect> @@ -122,10 +122,17 @@ <field> <fielddescr>Redistribute static</fielddescr> <fieldname>redistributestatic</fieldname> - <description>Enables the redistribution of static routes</description> + <description>Enables the redistribution of static routes (only works if you are using quagga static routes)</description> <type>checkbox</type> </field> <field> + <fielddescr>Redistribute Kernel</fielddescr> + <fieldname>redistributekernel</fieldname> + <description>Enables the redistribution of kernel routing table (this is required if using pfsense static routes)</description> + <type>checkbox</type> + </field> + + <field> <fielddescr>SPF Hold Time</fielddescr> <fieldname>spfholdtime</fieldname> <description>Set the SPF holdtime in MILLIseconds. The minimum time between two consecutive shortest path first calculations. The default value is 5 seconds; the valid range is 1-5 seconds.</description> @@ -161,6 +168,12 @@ <type>input</type> <size>25</size> </rowhelperfield> + <rowhelperfield> + <fielddescr>Area ID</fielddescr> + <fieldname>routearea</fieldname> + <type>input</type> + <size>10</size> + </rowhelperfield> </rowhelper> </field> </fields> diff --git a/config/quagga_ospfd/quagga_ospfd_interfaces.xml b/config/quagga_ospfd/quagga_ospfd_interfaces.xml index e0f55a58..21bc877f 100644 --- a/config/quagga_ospfd/quagga_ospfd_interfaces.xml +++ b/config/quagga_ospfd/quagga_ospfd_interfaces.xml @@ -69,6 +69,12 @@ <type>input</type> </field> <field> + <fielddescr>Area</fielddescr> + <fieldname>interfacearea</fieldname> + <description>The area for this interface (leave blank for default).</description> + <type>input</type> + </field> + <field> <fielddescr>Description</fielddescr> <fieldname>descr</fieldname> <size>30</size> diff --git a/config/quagga_ospfd/quaggactl b/config/quagga_ospfd/quaggactl index 198a8411..6db7232e 100644 --- a/config/quagga_ospfd/quaggactl +++ b/config/quagga_ospfd/quaggactl @@ -1,11 +1,12 @@ #!/bin/sh RC_SCRIPT=/usr/local/etc/rc.d/quagga.sh +QUAGGA_CONFIG_BASE=/var/etc/quagga -ZEBRA_CONFIG=/usr/local/etc/quagga/zebra.conf +ZEBRA_CONFIG=${QUAGGA_CONFIG_BASE}/zebra.conf ZEBRA_PORT=2601 ZEBRA_PASSWORD=`/usr/bin/grep '^password ' ${ZEBRA_CONFIG} | /usr/bin/awk '{print $2};'` -OSPF_CONFIG=/usr/local/etc/quagga/ospfd.conf +OSPF_CONFIG=${QUAGGA_CONFIG_BASE}/ospfd.conf OSPF_PORT=2604 OSPF_PASSWORD=`/usr/bin/grep '^password ' ${OSPF_CONFIG} | /usr/bin/awk '{print $2};'` @@ -27,6 +28,10 @@ restart) $RC_SCRIPT restart ;; zebra) + if [ "`pgrep zebra`" = "" ]; then + echo "zebra does not appear to be running" + exit 1 + fi case $2 in cpu*) daemon_command ${ZEBRA_PORT} ${ZEBRA_PASSWORD} "show thread cpu" @@ -42,7 +47,11 @@ zebra) daemon_command ${ZEBRA_PORT} ${ZEBRA_PASSWORD} "show ip route" ;; esac ;; -ospf) +ospf*) + if [ "`pgrep ospfd`" = "" ]; then + echo "ospfd does not appear to be running" + exit 1 + fi case $2 in cpu*) daemon_command ${OSPF_PORT} ${OSPF_PASSWORD} "show thread cpu" diff --git a/config/sarg/sarg.inc b/config/sarg/sarg.inc index e762d9b8..a6dbb081 100644 --- a/config/sarg/sarg.inc +++ b/config/sarg/sarg.inc @@ -31,13 +31,28 @@ POSSIBILITY OF SUCH DAMAGE. */ /* ========================================================================== */ +$pf_version=substr(trim(file_get_contents("/etc/version")),0,3); +if ($pf_version > 2.0){ + define('SARG_DIR', '/usr/pbi/sarg-' . php_uname("m")); + define('SQUID_DIR', '/usr/pbi/squid-' . php_uname("m")); + define('DANSG_DIR', '/usr/pbi/dansguardian-' . php_uname("m")); + } +else{ + define('SARG_DIR', '/usr/local'); + define('SQUID_DIR', '/usr/local'); + define('DANSG_DIR', '/usr/local'); +} + +$uname=posix_uname(); +if ($uname['machine']=='amd64') + ini_set('memory_limit', '250M'); // STATIC VARS -$sarg_proxy=array( 'squid_rc'=>'/usr/local/etc/rc.d/squid.sh', - 'squid_config'=>'/var/squid/logs/access.log', - 'squidguard_config'=>'/usr/local/etc/squidGuard/squidGuard.conf', +$sarg_proxy=array( 'squid_rc'=> SQUID_DIR . '/etc/rc.d/squid.sh', + 'squid_config'=> '/var/squid/logs/access.log', + 'squidguard_config'=> SARG_DIR . '/etc/squidGuard/squidGuard.conf', 'squidguard_block_log'=>'/var/squidGuard/log/block.log', - 'dansguardian_config'=>'/usr/local/etc/dansguardian/dansguardian.conf', + 'dansguardian_config'=> DANSG_DIR . '/etc/dansguardian/dansguardian.conf', 'dansguardian_log'=>'/var/log/dansguardian/access.log'); // END STATIC VARS @@ -80,17 +95,51 @@ function run_sarg($id=-1) { global $config, $g,$sarg_proxy; #mount filesystem writeable conf_mount_rw(); - $cmd = "/usr/local/bin/sarg"; + $cmd = SARG_DIR . "/bin/sarg"; if ($id >= 0 && is_array($config['installedpackages']['sargschedule']['config'])){ $args=$config['installedpackages']['sargschedule']['config'][$id]['args']; $action=$config['installedpackages']['sargschedule']['config'][$id]['action']; + $gzip=$config['installedpackages']['sargschedule']['config'][$id]['gzip']; + $find=$config['installedpackages']['sargschedule']['config'][$id]['find']; + $gziplevel=$config['installedpackages']['sargschedule']['config'][$id]['gziplevel']; + $daylimit=$config['installedpackages']['sargschedule']['config'][$id]['daylimit']; } else{ $args=$_POST['args']; $action=$_POST['action']; + $gzip=$_POST['gzip']; + $find=$_POST['find']; + $gziplevel=$_POST['gziplevel']; + $daylimit=""; } - log_error("Sarg: force refresh now with '".$args."' args and ".$action." action after sarg finish."); + $find=(preg_match("/(\d+)/",$find,$find_matches) ? $find_matches[1] : "60"); + log_error("Sarg: force refresh now with {$args} args, compress({$gzip}) and {$action} action after sarg finish."); + $gzip_script="#!/bin/sh\n"; + if ($gzip=="on"){ + #remove old file if exists + unlink_if_exists("/root/sarg_run_{$id}.sh"); + $gzip_script.=<<<EOF +for a in `/usr/bin/find /usr/local/sarg-reports -cmin -{$find} -type d -mindepth 1 -maxdepth 1` +do +echo \$a +/usr/bin/find \$a -name "*html" | xargs gzip {$gziplevel} +done + +EOF; + } + if (preg_match("/(\d+)/",$daylimit,$day_matches)){ + $gzip_script.=<<<EOF +for a in `/usr/bin/find /usr/local/sarg-reports -ctime +{$find} -type d -mindepth 1 -maxdepth 1` +do +echo \$a +rm -rf \$a +done + +EOF; + } + #create a new file to speedup find search + file_put_contents("/root/sarg_run_{$id}.sh",$gzip_script,LOCK_EX); mwexec($cmd. " ".$args); #check if there is a script to run after file save if (is_array($config['installedpackages']['sarg'])) @@ -99,12 +148,16 @@ function run_sarg($id=-1) { if ($action =="both" || $action=="rotate"){ log_error('executing squidguard log rotate after sarg.'); log_rotate($sarg_proxy['squidguard_block_log']); + file_put_contents($sarg_proxy['squidguard_block_log'],"",LOCK_EX); + chown($sarg_proxy['squidguard_block_log'],'proxy'); + chgrp($sarg_proxy['squidguard_block_log'],'proxy'); + mwexec(SQUID_DIR . '/sbin/squid -k reconfigure'); } - #Leve this case without break to include squid log file on squidguard option + #leave this case without break to run squid rotate too. case "squid": if ($action =="both" || $action=="rotate"){ log_error('executing squid log rotate after sarg.'); - mwexec('squid -k rotate'); + mwexec(SQUID_DIR . '/sbin/squid -k rotate'); } if ($action =="both" || $action=="restart"){ if (file_exists($sarg_proxy['squid_rc'])) @@ -119,12 +172,25 @@ function run_sarg($id=-1) { } break; } + #check compress option + if ($gzip=="on") + mwexec_bg("/bin/sh /root/sarg_run_{$id}.sh"); + #mount filesystem readonly conf_mount_ro(); } function sync_package_sarg() { global $config, $g,$sarg_proxy; + + # detect boot process + if (is_array($_POST)){ + if (!preg_match("/\w+/",$_POST['__csrf_magic'])) + return; + } + #check pkg.php sent a sync request + + $update_conf=0; #mount filesystem writeable conf_mount_rw(); @@ -150,6 +216,7 @@ function sync_package_sarg() { 'ldap_port'=> '389', 'ntlm_user_format'=>'domainname+username'); $sarguser=$config['installedpackages']['sarguser']['config'][0]; + $access_log=$sarg['proxy_server']; switch ($sarg['proxy_server']){ case 'dansguardian': $access_log= $sarg_proxy['dansguardian_log']; @@ -168,7 +235,7 @@ function sync_package_sarg() { $access_log = $config['installedpackages']['squid']['config'][0]['log_dir']. '/access.log'; break; } - if (!file_exists($access_log)){ + if (!file_exists($access_log) && $access_log !=""){ $error="Sarg config error: ".$sarg['proxy_server']." log file ($access_log) does not exists"; log_error($error); file_notice("Sarg", $error, "Sarg Settings", ""); @@ -194,7 +261,7 @@ function sync_package_sarg() { $date_format=(empty($sarg['report_date_format'])?"u":$sarg['report_date_format']); $report_type=preg_replace('/,/',' ',$sarg['report_type']); $report_charset=(empty($sarg['report_charset'])?"UTF-8":$sarg['report_charset']); - $exclude_string=(empty($sarg['exclude_string'])?"":'exclude_string"'.$sarg['exclude_string']."'"); + $exclude_string=(empty($sarg['exclude_string'])?"":'exclude_string "'.$sarg['exclude_string'].'"'); #limits $max_elapsed=(empty($sarg['max_elapsed'])?"0":$sarg['max_elapsed']); @@ -218,8 +285,8 @@ function sync_package_sarg() { $usertab="none"; } else{ - $usertab="/usr/local/etc/sarg/usertab.conf"; - file_put_contents('/usr/local/etc/sarg/usertab.conf', sarg_text_area_decode($sarguser['usertab']),LOCK_EX); + $usertab= SARG_DIR . "/etc/sarg/usertab.conf"; + file_put_contents( SARG_DIR . '/etc/sarg/usertab.conf', sarg_text_area_decode($sarguser['usertab']),LOCK_EX); } if($sarguser['ldap_enable']){ $LDAPHost=(empty($sarguser['ldap_host'])?"":"LDAPHost ".$sarguser['ldap_host']); @@ -231,20 +298,35 @@ function sync_package_sarg() { $LDAPFilterSearch=(empty($sarguser['ldap_filter_search'])?"":"LDAPFilterSearch ".$sarguser['ldap_filter_search']); } - #dirs - $dirs=array("/usr/local/www/sarg-reports"); + + #move old reports + if (is_dir("/usr/local/www/sarg-reports") && !is_dir("/usr/local/sarg-reports")) + rename("/usr/local/www/sarg-reports","/usr/local/sarg-reports"); + + #check dirs + $dirs=array("/usr/local/sarg-reports","/usr/local/www/sarg-images","/usr/local/www/sarg-images/temp"); foreach ($dirs as $dir) if (!is_dir($dir)) mkdir ($dir,0755,true); - + + #images + $simages=array("datetime.png","graph.png","sarg-squidguard-block.png","sarg.png"); + $simgdir1="/usr/local/www/sarg-images"; + $simgdir2= SARG_DIR . "/etc/sarg/images"; + foreach ($simages as $simage){ + if (!file_exists("{$simgdir1}/{$simage}")) + copy("{$simgdir2}/{$simage}","{$simgdir1}/{$simage}"); + } + + //log_error($_POST['__csrf_magic']." sarg log:". $access_log); #create sarg config files + $sarg_dir= SARG_DIR; include("/usr/local/pkg/sarg.template"); - file_put_contents("/usr/local/etc/sarg/sarg.conf", $sg, LOCK_EX); - file_put_contents('/usr/local/etc/sarg/exclude_hosts.conf', sarg_text_area_decode($sarg['exclude_hostlist']),LOCK_EX); - file_put_contents('/usr/local/etc/sarg/exclude_codes.conf', sarg_text_area_decode($sarg['exclude_codelist']),LOCK_EX); - file_put_contents('/usr/local/etc/sarg/hostalias',sarg_text_area_decode($sarg['hostalias']),LOCK_EX); - file_put_contents('/usr/local/etc/sarg/exclude_users.conf', sarg_text_area_decode($sarguser['exclude_userlist']),LOCK_EX); - + file_put_contents( SARG_DIR . "/etc/sarg/sarg.conf", $sg, LOCK_EX); + file_put_contents( SARG_DIR . '/etc/sarg/exclude_hosts.conf', sarg_text_area_decode($sarg['exclude_hostlist']),LOCK_EX); + file_put_contents( SARG_DIR . '/etc/sarg/exclude_codes', sarg_text_area_decode($sarg['exclude_codelist']),LOCK_EX); + file_put_contents( SARG_DIR . '/etc/sarg/hostalias',sarg_text_area_decode($sarg['hostalias']),LOCK_EX); + file_put_contents( SARG_DIR . '/etc/sarg/exclude_users.conf', sarg_text_area_decode($sarguser['exclude_userlist']),LOCK_EX); #check cron_tab $new_cron=array(); $cron_found=0; diff --git a/config/sarg/sarg.php b/config/sarg/sarg.php index c2ec00c2..98e6c426 100644 --- a/config/sarg/sarg.php +++ b/config/sarg/sarg.php @@ -39,6 +39,10 @@ require_once("/etc/inc/pkg-utils.inc"); require_once("/etc/inc/globals.inc"); require_once("/usr/local/pkg/sarg.inc"); +$uname=posix_uname(); +if ($uname['machine']=='amd64') + ini_set('memory_limit', '250M'); + if (preg_match ("/(\d+)/",$argv[1],$matches)) run_sarg($matches[1]); diff --git a/config/sarg/sarg.priv.inc b/config/sarg/sarg.priv.inc new file mode 100644 index 00000000..2de21519 --- /dev/null +++ b/config/sarg/sarg.priv.inc @@ -0,0 +1,12 @@ +<?php + +global $priv_list; + +$priv_list['page-status-sarg-reports'] = array(); +$priv_list['page-status-sarg-reports']['name'] = "WebCfg - Status: Sarg reports"; +$priv_list['page-status-sarg-reports']['descr'] = "Allow access to sarg reports page."; +$priv_list['page-status-sarg-reports']['match'] = array(); +$priv_list['page-status-sarg-reports']['match'][] = "sarg_reports.php*"; +$priv_list['page-status-sarg-reports']['match'][] = "sarg_realtime.php*"; + +?>
\ No newline at end of file diff --git a/config/sarg/sarg.template b/config/sarg/sarg.template index 913dc892..abda925b 100644 --- a/config/sarg/sarg.template +++ b/config/sarg/sarg.template @@ -33,7 +33,7 @@ # sarg.conf # # TAG: access_log file -# Where is the access.lo +# Where is the access.log # sarg -l file # access_log {$access_log} @@ -42,7 +42,7 @@ access_log {$access_log} # Use graphics where is possible. # graph_days_bytes_bar_color blue|green|yellow|orange|brown|red # -graphs ${graphs} +graphs {$graphs} #graph_days_bytes_bar_color orange # TAG: graph_font @@ -149,7 +149,7 @@ graphs ${graphs} # The reports will be saved in that directory # sarg -o dir # -output_dir /usr/local/www/sarg-reports +output_dir /usr/local/sarg-reports # TAG: anonymous_output_files yes/no # Use anonymous file and directory names in the report. If it is set to @@ -194,7 +194,7 @@ user_sort_field {$sarguser['user_sort_field']} {$sort_order} # users within the file will be excluded from reports. # you can use indexonly to have only index.html file. # -exclude_users /usr/local/etc/sarg/exclude_users.conf +exclude_users {$sarg_dir}/etc/sarg/exclude_users.conf # TAG: exclude_hosts file # Hosts, domains or subnets will be excluded from reports. @@ -204,7 +204,7 @@ exclude_users /usr/local/etc/sarg/exclude_users.conf # s1.acme.foo - exclude hostname only # *.acme.foo - exclude full domain name # -exclude_hosts /usr/local/etc/sarg/exclude_hosts.conf +exclude_hosts {$sarg_dir}/etc/sarg/exclude_hosts.conf # TAG: useragent_log file # useragent.log file patch to generate useragent report. @@ -224,7 +224,7 @@ date_format {$date_format} #per_user_limit none # TAG: lastlog n -# How many reports files must be keept in reports directory. +# How many reports files must be kept in reports directory. # The oldest report file will be automatically removed. # 0 - no limit. # @@ -312,7 +312,7 @@ use_comma {$use_comma} # Only codes matching exactly one of the line is rejected. The # comparison is not case sensitive. # -exclude_codes /usr/local/etc/sarg/exclude_codes +exclude_codes {$sarg_dir}/etc/sarg/exclude_codes # TAG: replace_index string # Replace "index.html" in the main index file with this string @@ -806,6 +806,6 @@ sorttable /sarg_sorttable.js # *.freeav.net antivirus:freeav # *.mail.live.com # 65.52.00.00/14 *.mail.live.com -hostalias /usr/local/etc/sarg/hostalias +hostalias {$sarg_dir}/etc/sarg/hostalias EOF; ?> diff --git a/config/sarg/sarg.xml b/config/sarg/sarg.xml index f1ce5d93..bb345379 100644 --- a/config/sarg/sarg.xml +++ b/config/sarg/sarg.xml @@ -18,7 +18,7 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, + 1. Redistributions of source code MUST retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright @@ -88,11 +88,6 @@ <chmod>0755</chmod> </additional_files_needed> <additional_files_needed> - <item>http://www.pfsense.org/packages/config/sarg/sarg_queue.php</item> - <prefix>/usr/local/www/</prefix> - <chmod>0755</chmod> - </additional_files_needed> - <additional_files_needed> <item>http://www.pfsense.org/packages/config/sarg/sarg_reports.php</item> <prefix>/usr/local/www/</prefix> <chmod>0755</chmod> @@ -112,6 +107,11 @@ <prefix>/usr/local/pkg/</prefix> <chmod>0755</chmod> </additional_files_needed> + <additional_files_needed> + <item>http://www.pfsense.org/packages/config/sarg/sarg.priv.inc</item> + <prefix>/etc/inc/priv/</prefix> + <chmod>0755</chmod> + </additional_files_needed> <tabs> <tab> <text>General</text> @@ -275,14 +275,23 @@ <size>10</size> </field> <field> - <fielddescr>Reports limits</fielddescr> + <fielddescr>Reports list limits</fielddescr> <fieldname>lastlog</fieldname> - <description><![CDATA[How many reports files must be keept in reports directory.<br> + <description><![CDATA[How many reports files must be kept in reports directory.<br> The oldest report file will be automatically removed.0 means no limit.]]></description> <type>input</type> <size>10</size> </field> <field> + <fielddescr>Reports days limits</fielddescr> + <fieldname>daylimit</fieldname> + <description><![CDATA[How many days reports files must be kept in reports directory.<br> + Older report file will be automatically removed.<br> + Leave empty to do not remove old reports.]]></description> + <type>input</type> + <size>10</size> + </field> + <field> <fielddescr>Top Users Limit</fielddescr> <fieldname>topuser_num</fieldname> <description><![CDATA[How many users in topsites report. 0 = no limit]]></description> diff --git a/config/sarg/sarg_frame.php b/config/sarg/sarg_frame.php index 73e3a469..4d3421ab 100755 --- a/config/sarg/sarg_frame.php +++ b/config/sarg/sarg_frame.php @@ -27,7 +27,12 @@ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +require_once("authgui.inc"); +$uname=posix_uname(); +if ($uname['machine']=='amd64') + ini_set('memory_limit', '250M'); + if(preg_match("/(\S+)\W(\w+.html)/",$_REQUEST['file'],$matches)){ #https://192.168.1.1/sarg_reports.php?file=2012Mar30-2012Mar30/index.html $url=$matches[2]; @@ -38,21 +43,39 @@ else{ $prefix=""; } $url=($_REQUEST['file'] == ""?"index.html":$_REQUEST['file']); -if (file_exists("/usr/local/www/sarg-reports/".$url)) +$dir="/usr/local/sarg-reports"; +$rand=rand(100000000000,999999999999); +$report=""; +if (file_exists("{$dir}/{$url}")) + $report=file_get_contents("{$dir}/{$url}"); +else if (file_exists("{$dir}/{$url}.gz")) { + $data = gzfile("{$dir}/{$url}.gz"); + $report = implode($data); + unset ($data); + } +if ($report != "" ) { - $report=file_get_contents("/usr/local/www/sarg-reports/".$url); $pattern[0]="/href=\W(\S+html)\W/"; - $replace[0]="href=/sarg_frame.php?prevent=".rand(100000000000,999999999999)."&file=$prefix/$1"; - $pattern[1]='/img src="(\w+\.\w+)/'; - $replace[1]='img src="/sarg-reports'.$prefix.'/$1'; + $replace[0]="href=/sarg_frame.php?prevent=".$rand."&file=$prefix/$1"; + $pattern[1]='/img src="\S+\W([a-zA-Z0-9.-]+.png)/'; + $replace[1]='img src="/sarg-images/$1'; $pattern[2]='@img src="([.a-z/]+)/(\w+\.\w+)@'; - $replace[2]='img src="/sarg-reports'.$prefix.'/$1/$2'; - $pattern[3]='/<head>/'; - $replace[3]='<head><META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE"><META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">'; + $replace[2]='img src="/sarg-images'.$prefix.'/$1/$2'; + $pattern[3]='/img src="([a-zA-Z0-9.-_]+).png/'; + $replace[3]='img src="/sarg-images/temp/$1.'.$rand.'.png'; + $pattern[4]='/<head>/'; + $replace[4]='<head><META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE"><META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">'; + + #look for graph files inside reports. + if (preg_match_all('/img src="([a-zA-Z0-9._-]+).png/',$report,$images)){ + for ($x=0;$x<count($images[1]);$x++){ + copy("{$dir}/{$prefix}/{$images[1][$x]}.png","/usr/local/www/sarg-images/temp/{$images[1][$x]}.{$rand}.png"); + } + } print preg_replace($pattern,$replace,$report); } else{ - print "<pre>Error: Could not find report index file.<br>Check sarg settings and try to force sarg schedule."; + print "<pre>Error: Could not find report index file.<br>Check and save sarg settings and try to force sarg schedule."; } ?>
\ No newline at end of file diff --git a/config/sarg/sarg_queue.php b/config/sarg/sarg_queue.php deleted file mode 100755 index 8b8329a5..00000000 --- a/config/sarg/sarg_queue.php +++ /dev/null @@ -1,241 +0,0 @@ -<?php -/* - sarg_queue.php - part of pfSense (http://www.pfsense.com/) - Copyright (C) 2012 Marcello Coutinho <marcellocoutinho@gmail.com> - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. -*/ - -require("guiconfig.inc"); -function get_cmd(){ - global $config,$g; - if ($_REQUEST['cmd'] =='sarg'){ - - #Check report xml info - if (!is_array($config['installedpackages']['sargrealtime'])){ - $config['installedpackages']['sargrealtime']['config'][0]['realtime_types']= ""; - $config['installedpackages']['sargrealtime']['config'][0]['realtime_users']= ""; - } - #Check report http actions to show - if ($config['installedpackages']['sargrealtime']['config'][0]['realtime_types'] != $_REQUEST['qshape']){ - $config['installedpackages']['sargrealtime']['config'][0]['realtime_types']= $_REQUEST['qshape']; - $update_config++; - } - - #Check report users show - if ($config['installedpackages']['sargrealtime']['config'][0]['realtime_users'] != $_REQUEST['qtype']){ - $config['installedpackages']['sargrealtime']['config'][0]['realtime_users']= $_REQUEST['qtype']; - $update_config++; - } - - if($update_config > 0){ - write_config; - #write changes to sarg_file - $sarg_config=file_get_contents('/usr/local/etc/sarg/sarg.conf'); - $pattern[0]='/realtime_types\s+[A-Z,,]+/'; - $pattern[1]='/realtime_unauthenticated_records\s+\w+/'; - $replace[0]="realtime_types ".$_REQUEST['qshape']; - $replace[1]="realtime_unauthenticated_records ".$_REQUEST['qtype']; - file_put_contents('/usr/local/etc/sarg/sarg.conf', preg_replace($pattern,$replace,$sarg_config),LOCK_EX); - } - exec("/usr/local/bin/sarg -r", $sarg); - $patern[0]="/<?(html|head|style)>/"; - $replace[0]=""; - $patern[1]="/header_\w/"; - $replace[1]="listtopic"; - $patern[2]="/class=.data./"; - $replace[2]='class="listlr"'; - $patern[3]="/cellpadding=.\d./"; - $replace[3]='cellpadding="0"'; - $patern[4]="/cellspacing=.\d./"; - $replace[4]='cellspacing="0"'; - $patern[5]="/sarg/"; - $replace[5]='cellspacing="0"'; - - foreach ($sarg as $line){ - if (preg_match("/<.head>/",$line)) - $print ="ok"; - if ($print =="ok" && !preg_match("/(sarg realtime|Auto Refresh)/i",$line)) - print preg_replace($patern,$replace,$line); - } - } -} - -if ($_REQUEST['cmd']!=""){ - get_cmd(); - } -else{ - $pfSversion = str_replace("\n", "", file_get_contents("/etc/version")); - if(strstr($pfSversion, "1.2")) - $one_two = true; - - $pgtitle = "Status: Postfix Mail Queue"; - include("head.inc"); - - ?> - <body link="#0000CC" vlink="#0000CC" alink="#0000CC"> - <?php include("fbegin.inc"); ?> - - <?php if($one_two): ?> - <p class="pgtitle"><?=$pgtitle?></font></p> - <?php endif; ?> - - <?php if ($savemsg) print_info_box($savemsg); ?> - - <form action="sarg_realtimex.php" method="post"> - - <div id="mainlevel"> - <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr><td> - <?php - $tab_array = array(); - $tab_array[] = array(gettext("Settings"), false, "/pkg_edit.php?xml=sarg.xml&id=0"); - $tab_array[] = array(gettext("View Report"), false, "/sarg-reports/"); - $tab_array[] = array(gettext("Realtime"), true, "/sarg_real_time.php"); - $tab_array[] = array(gettext("XMLRPC Sync"), false, "/pkg_edit.php?xml=sarg_sync.xml&id=0"); - $tab_array[] = array(gettext("Help"), false, "/pkg_edit.php?xml=sarg_about.php"); - display_top_tabs($tab_array); - ?> - </td></tr> - <tr> - <td> - <div id="mainarea"> - <table class="tabcont" width="100%" border="0" cellpadding="8" cellspacing="0"> - <tr><td></td></tr> - <tr> - <td colspan="2" valign="top" class="listtopic"><?=gettext("Sarg Realtime"); ?></td></tr> - <tr> - <td width="22%" valign="top" class="vncell"><?=gettext("Log command: ");?></td> - <td width="78%" class="vtable"> - <select name="drop3" id="cmd"> - <option value="sarg" selected="selected">Sarg Realtime</option> - </select><br><?=gettext("Select queue command to run.");?></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell"><?=gettext("update frequency: ");?></td> - <td width="78%" class="vtable"> - <select name="drop3" id="updatef"> - <option value="1">01 second</option> - <option value="3" selected="selected">03 seconds</option> - <option value="5">05 seconds</option> - <option value="15">15 Seconds</option> - <option value="30">30 Seconds</option> - <option value="60">One minute</option> - <option value="1">Never</option> - </select><br><?=gettext("Select how often queue cmd will run.");?></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell"><?=gettext("Report Types: ");?></td> - <td width="78%" class="vtable"> - <select name="drop3" id="qshape" multiple="multiple" size="5"> - <option value="GET" selected="selected">GET</option> - <option value="PUT" selected="selected">PUT</option> - <option value="CONNECT" selected="selected">CONNECT</option> - <option value="ICP_QUERY">ICP_QUERY</option> - <option value="POST">POST</option> - </select><br><?=gettext("Which records must be in realtime report.");?></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell"><?=gettext("unauthenticated_records: ");?></td> - <td width="78%" class="vtable"> - <select name="drop3" id="qtype"> - <option value="show" selected>show</option> - <option value="hide">hide</option> - </select><br><?=gettext("What to do with unauthenticated records in realtime report.");?></td> - </tr> - - <tr> - <td width="22%" valign="top"></td> - <td width="78%"><input name="Submit" type="button" class="formbtn" id="run" value="<?=gettext("show log");?>" onclick="get_queue('mailq')"><div id="search_help"></div></td> - </table> - </div> - </td> - </tr> - </table> - <br> - <div> - <table class="tabcont" width="100%" border="0" cellpadding="8" cellspacing="0"> - <tr> - <td class="tabcont" > - <div id="file_div"></div> - - </td> - </tr> - </table> - </div> - </div> - </form> - <script type="text/javascript"> - function loopSelected(id) - { - var selectedArray = new Array(); - var selObj = document.getElementById(id); - var i; - var count = 0; - for (i=0; i<selObj.options.length; i++) { - if (selObj.options[i].selected) { - selectedArray[count] = selObj.options[i].value; - count++; - } - } - return(selectedArray); - } - - function get_queue(loop) { - //prevent multiple instances - if ($('run').value=="show log" || loop== 'running'){ - $('run').value="running..."; - $('search_help').innerHTML ="<br><strong>You can change options while running.<br>To Stop seach, change update frequency to Never.</strong>"; - var q_args=loopSelected('qshape'); - var pars = 'cmd='+$('cmd').options[$('cmd').selectedIndex].value; - var pars = pars + '&qshape='+q_args; - var pars = pars + '&type='+$('qtype').options[$('qtype').selectedIndex].value; - var url = "/sarg_queue.php"; - var myAjax = new Ajax.Request( - url, - { - method: 'post', - parameters: pars, - onComplete: activitycallback_queue_file - }); - } - } - function activitycallback_queue_file(transport) { - $('file_div').innerHTML = transport.responseText; - var update=$('updatef').options[$('updatef').selectedIndex].value * 1000; - if (update > 1000){ - setTimeout('get_queue("running")', update); - } - else{ - $('run').value="show log"; - $('search_help').innerHTML =""; - } - } - </script> - <?php - include("fend.inc"); - } - ?> - </body> - </html> diff --git a/config/sarg/sarg_realtime.php b/config/sarg/sarg_realtime.php index 0b8b2cc5..76e89769 100755 --- a/config/sarg/sarg_realtime.php +++ b/config/sarg/sarg_realtime.php @@ -27,7 +27,17 @@ POSSIBILITY OF SUCH DAMAGE. */ -require("guiconfig.inc"); +$pf_version=substr(trim(file_get_contents("/etc/version")),0,3); +if ($pf_version > 2.0) + define('SARG_DIR', '/usr/pbi/sarg-' . php_uname("m")); +else + define('SARG_DIR', '/usr/local'); + +$uname=posix_uname(); +if ($uname['machine']=='amd64') + ini_set('memory_limit', '250M'); + + function get_cmd(){ global $config,$g; #print $_REQUEST['type']; @@ -53,14 +63,14 @@ function get_cmd(){ if($update_config > 0){ write_config(); #write changes to sarg_file - $sarg_config=file_get_contents('/usr/local/etc/sarg/sarg.conf'); + $sarg_config=file_get_contents(SARG_DIR . '/etc/sarg/sarg.conf'); $pattern[0]='/realtime_types\s+[A-Z,,]+/'; $replace[0]="realtime_types ".$_REQUEST['qshape']; $pattern[1]='/realtime_unauthenticated_records\s+\w+/'; $replace[1]="realtime_unauthenticated_records ".$_REQUEST['type']; - file_put_contents('/usr/local/etc/sarg/sarg.conf', preg_replace($pattern,$replace,$sarg_config),LOCK_EX); + file_put_contents(SARG_DIR . '/etc/sarg/sarg.conf', preg_replace($pattern,$replace,$sarg_config),LOCK_EX); } - exec("/usr/local/bin/sarg -r", $sarg); + exec(SARG_DIR ."/bin/sarg -r",$sarg); $pattern[0]="/<?(html|head|style)>/"; $replace[0]=""; $pattern[1]="/header_\w/"; @@ -73,7 +83,6 @@ function get_cmd(){ $replace[4]='cellspacing="0"'; $pattern[5]="/sarg/"; $replace[5]='cellspacing="0"'; - foreach ($sarg as $line){ if (preg_match("/<.head>/",$line)) $print ="ok"; @@ -84,9 +93,12 @@ function get_cmd(){ } if ($_REQUEST['cmd']!=""){ + require_once("authgui.inc"); + require_once("functions.inc"); get_cmd(); } else{ + require("guiconfig.inc"); $pfSversion = str_replace("\n", "", file_get_contents("/etc/version")); if(strstr($pfSversion, "1.2")) $one_two = true; @@ -104,7 +116,7 @@ else{ <?php if ($savemsg) print_info_box($savemsg); ?> - <form action="postfix_view_config.php" method="post"> + <form action="sarg_realtime.php" method="post"> <div id="mainlevel"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> @@ -204,17 +216,19 @@ else{ } return(selectedArray); } - function get_queue(loop) { //prevent multiple instances if ($('run').value=="show log" || loop== 'running'){ $('run').value="running..."; $('search_help').innerHTML ="<br><strong>You can change options while running.<br>To Stop seach, change update frequency to Never.</strong>"; + var axel = Math.random() + ""; + var num = axel * 1000000000000000000; var q_args=loopSelected('qshape'); var pars = 'cmd='+$('cmd').options[$('cmd').selectedIndex].value; var pars = pars + '&qshape='+q_args; + var pars = pars + '&prevent='+num; var pars = pars + '&type='+$('qtype').options[$('qtype').selectedIndex].value; - var url = "/sarg_queue.php"; + var url = "/sarg_realtime.php"; var myAjax = new Ajax.Request( url, { diff --git a/config/sarg/sarg_reports.php b/config/sarg/sarg_reports.php index b64e9966..b1792312 100755 --- a/config/sarg/sarg_reports.php +++ b/config/sarg/sarg_reports.php @@ -61,6 +61,7 @@ require("guiconfig.inc"); $tab_array[] = array(gettext("XMLRPC Sync"), false, "/pkg_edit.php?xml=sarg_sync.xml&id=0"); $tab_array[] = array(gettext("Help"), false, "/pkg_edit.php?xml=sarg_about.php"); display_top_tabs($tab_array); + exec('rm -f /usr/local/www/sarg-images/temp/*'); ?> </td></tr> <tr> diff --git a/config/sarg/sarg_schedule.xml b/config/sarg/sarg_schedule.xml index 3d065a7a..4a7309af 100644 --- a/config/sarg/sarg_schedule.xml +++ b/config/sarg/sarg_schedule.xml @@ -105,13 +105,18 @@ <fieldname>args</fieldname> </columnitem> <columnitem> + <fielddescr>Gzip</fielddescr> + <fieldname>gzip</fieldname> + </columnitem> + <columnitem> <fielddescr>Post Action</fielddescr> <fieldname>action</fieldname> </columnitem> <columnitem> <fielddescr>Description</fielddescr> <fieldname>description</fieldname> - </columnitem> + </columnitem> + <movable>arrow</movable> </adddeleteeditpagefields> <fields> <field> @@ -163,6 +168,44 @@ </options> <description>Choose an action after sarg finishes</description> </field> + <field> + <type>listtopic</type> + <fieldname>temp</fieldname> + <name>Compress Options</name> + </field> + <field> + <fielddescr>Enable Compression</fielddescr> + <fieldname>gzip</fieldname> + <description><![CDATA[Enable this option to compress sarg report html files using gzip and reduce 4 times sarg reports data.]]></description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Compression level</fielddescr> + <fieldname>gziplevel</fieldname> + <type>select</type> + <options> + <option><name>Default gzip compression (Recommended)</name><value></value></option> + <option><name>1 (fast)</name><value>--fast</value></option> + <option><name>2</name><value>-2</value></option> + <option><name>3</name><value>-3</value></option> + <option><name>4</name><value>-4</value></option> + <option><name>5</name><value>-5</value></option> + <option><name>6</name><value>-6</value></option> + <option><name>7</name><value>-7</value></option> + <option><name>8</name><value>-8</value></option> + <option><name>9 (best)</name><value>--best</value></option> + </options> + <description>Choose gzip compression level.</description> + </field> + <field> + <fielddescr>Find Limit</fielddescr> + <fieldname>find</fieldname> + <type>input</type> + <default_value>60</default_value> + <size>5</size> + <description><![CDATA[To speed up find process, restrict find search to report files created/changed n minutes ago.<br> + Default is to 60 minutes. If your reports take longer to be created, increase this value.]]></description> + </field> </fields> <custom_php_install_command> sarg_php_install_command(); diff --git a/config/siproxd.inc b/config/siproxd.inc index f0ec9f94..13254a42 100644 --- a/config/siproxd.inc +++ b/config/siproxd.inc @@ -30,10 +30,22 @@ if(!function_exists("filter_configure")) require_once("filter.inc"); +// Check to find out on which system the package is running +if (substr(trim(file_get_contents("/etc/version")),0,3) == "2.0") { + define('SIPROXD', '/usr/local'); +} else { + define('SIPROXD', '/usr/pbi/siproxd-' . php_uname("m")); +} +// End of system check + function sync_package_sipproxd_users() { conf_mount_rw(); + + // put the constant to a variable + $varSIPROXD = SIPROXD; + global $config; - $fout = fopen("/usr/local/etc/siproxd_passwd.cfg","w"); + $fout = fopen("$varSIPROXD/etc/siproxd_passwd.cfg","w"); fwrite($fout, "# This file was automatically generated by the pfSense\n# package management system.\n\n"); if($config['installedpackages']['siproxdusers']['config'] != "") { foreach($config['installedpackages']['siproxdusers']['config'] as $rowhelper) { @@ -48,6 +60,9 @@ function sync_package_sipproxd_users() { function siproxd_generate_rules($type) { global $config; + // put the constant to a variable + $varSIPROXD = SIPROXD; + $siproxd_conf = &$config['installedpackages']['siproxdsettings']['config'][0]; if (!is_service_running('siproxd')) { log_error("Sipproxd is installed but not started. Not installing redirect rules."); @@ -92,6 +107,9 @@ function siproxd_generate_rules($type) { function sync_package_siproxd() { global $config; + // put the constant to a variable + $varSIPROXD = SIPROXD; + conf_mount_rw(); $siproxd_chroot = "/var/siproxd/"; @@ -99,9 +117,9 @@ function sync_package_siproxd() { @chown($siproxd_chroot, "nobody"); @chgrp($siproxd_chroot, "nobody"); - unlink_if_exists("/usr/local/etc/rc.d/siproxd"); + unlink_if_exists("$varSIPROXD/etc/rc.d/siproxd"); $siproxd_conf = &$config['installedpackages']['siproxdsettings']['config'][0]; - $fout = fopen("/usr/local/etc/siproxd.conf","w"); + $fout = fopen("$varSIPROXD/etc/siproxd.conf","w"); fwrite($fout, "# This file was automatically generated by the pfSense\n"); fwrite($fout, "# package management system.\n\n"); @@ -167,7 +185,7 @@ function sync_package_siproxd() { if($siproxd_conf['authentication']) { fwrite($fout, "proxy_auth_realm = Authentication_Realm\n"); - fwrite($fout, "proxy_auth_pwfile = /usr/local/etc/siproxd_passwd.cfg\n"); + fwrite($fout, "proxy_auth_pwfile = $varSIPROXD/etc/siproxd_passwd.cfg\n"); } if($siproxd_conf['debug_level'] != "") { @@ -203,7 +221,7 @@ function sync_package_siproxd() { if ($siproxd_conf['tcp_keepalive'] != "") fwrite($fout, "tcp_keepalive = " . $siproxd_conf['tcp_keepalive'] . "\n"); - fwrite($fout, "plugindir=/usr/local/lib/siproxd/\n"); + fwrite($fout, "plugindir=$varSIPROXD/lib/siproxd/\n"); fwrite($fout, "load_plugin=plugin_logcall.la\n"); if ($siproxd_conf['plugin_defaulttarget'] != "") @@ -231,7 +249,7 @@ function sync_package_siproxd() { write_rcfile(array( "file" => "siproxd.sh", - "start" => "/usr/local/sbin/siproxd -c /usr/local/etc/siproxd.conf &", + "start" => "$varSIPROXD/sbin/siproxd -c $varSIPROXD/etc/siproxd.conf &", "stop" => "/usr/bin/killall -9 siproxd" ) ); diff --git a/config/snort/bin/oinkmaster_contrib/README.contrib b/config/snort-dev/bin/oinkmaster_contrib/README.contrib index 6923fa26..6923fa26 100644 --- a/config/snort/bin/oinkmaster_contrib/README.contrib +++ b/config/snort-dev/bin/oinkmaster_contrib/README.contrib diff --git a/config/snort/bin/oinkmaster_contrib/addmsg.pl b/config/snort-dev/bin/oinkmaster_contrib/addmsg.pl index e5866d6f..e5866d6f 100644 --- a/config/snort/bin/oinkmaster_contrib/addmsg.pl +++ b/config/snort-dev/bin/oinkmaster_contrib/addmsg.pl diff --git a/config/snort/bin/oinkmaster_contrib/addsid.pl b/config/snort-dev/bin/oinkmaster_contrib/addsid.pl index 64255d22..64255d22 100644 --- a/config/snort/bin/oinkmaster_contrib/addsid.pl +++ b/config/snort-dev/bin/oinkmaster_contrib/addsid.pl diff --git a/config/snort/bin/oinkmaster_contrib/create-sidmap.pl b/config/snort-dev/bin/oinkmaster_contrib/create-sidmap.pl index 26a9040c..26a9040c 100644 --- a/config/snort/bin/oinkmaster_contrib/create-sidmap.pl +++ b/config/snort-dev/bin/oinkmaster_contrib/create-sidmap.pl diff --git a/config/snort/bin/oinkmaster_contrib/make_snortsam_map.pl b/config/snort-dev/bin/oinkmaster_contrib/make_snortsam_map.pl index 42ce2b3b..42ce2b3b 100644 --- a/config/snort/bin/oinkmaster_contrib/make_snortsam_map.pl +++ b/config/snort-dev/bin/oinkmaster_contrib/make_snortsam_map.pl diff --git a/config/snort/bin/oinkmaster_contrib/makesidex.pl b/config/snort-dev/bin/oinkmaster_contrib/makesidex.pl index 80354735..80354735 100644 --- a/config/snort/bin/oinkmaster_contrib/makesidex.pl +++ b/config/snort-dev/bin/oinkmaster_contrib/makesidex.pl diff --git a/config/snort/bin/oinkmaster_contrib/oinkgui.pl b/config/snort-dev/bin/oinkmaster_contrib/oinkgui.pl index 4e96f7db..4e96f7db 100644 --- a/config/snort/bin/oinkmaster_contrib/oinkgui.pl +++ b/config/snort-dev/bin/oinkmaster_contrib/oinkgui.pl diff --git a/config/snort/bin/oinkmaster_contrib/oinkmaster.pl b/config/snort-dev/bin/oinkmaster_contrib/oinkmaster.pl index f9c4d215..f9c4d215 100644 --- a/config/snort/bin/oinkmaster_contrib/oinkmaster.pl +++ b/config/snort-dev/bin/oinkmaster_contrib/oinkmaster.pl diff --git a/config/snort/bin/oinkmaster_contrib/snort_rename.pl b/config/snort-dev/bin/oinkmaster_contrib/snort_rename.pl index e5f0d39e..e5f0d39e 100644 --- a/config/snort/bin/oinkmaster_contrib/snort_rename.pl +++ b/config/snort-dev/bin/oinkmaster_contrib/snort_rename.pl diff --git a/config/snort/css/sexybuttons.css b/config/snort-dev/css/sexybuttons.css index c3834b44..c3834b44 100644 --- a/config/snort/css/sexybuttons.css +++ b/config/snort-dev/css/sexybuttons.css diff --git a/config/snort/css/style.css b/config/snort-dev/css/style.css index b484966c..b484966c 100644 --- a/config/snort/css/style.css +++ b/config/snort-dev/css/style.css diff --git a/config/snort/help_and_info.php b/config/snort-dev/help_and_info.php index af8eb4ae..af8eb4ae 100644 --- a/config/snort/help_and_info.php +++ b/config/snort-dev/help_and_info.php diff --git a/config/snort-dev/snort.inc b/config/snort-dev/snort.inc new file mode 100644 index 00000000..3a1df760 --- /dev/null +++ b/config/snort-dev/snort.inc @@ -0,0 +1,2706 @@ +<?php +/* + snort.inc + Copyright (C) 2006 Scott Ullrich + Copyright (C) 2009-2010 Robert Zelaya + Copyright (C) 2011 Ermal Luci + 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. + */ + +require_once("pfsense-utils.inc"); +require_once("config.inc"); +require_once("functions.inc"); + +// Needed on 2.0 because of filter_get_vpns_list() +require_once("filter.inc"); + +/* package version */ +$snort_package_version = 'Snort-dev 2.9.2.3 pkg v. 3.0'; +$snort_rules_file = "snortrules-snapshot-2922.tar.gz"; + +/* Allow additional execution time 0 = no limit. */ +ini_set('max_execution_time', '9999'); +ini_set('max_input_time', '9999'); + +/* define oinkid */ +if ($config['installedpackages']['snortglobal']) + $oinkid = $config['installedpackages']['snortglobal']['oinkmastercode']; +else + $config['installedpackages']['snortglobal'] = array(); + +/* find out if were in 1.2.3-RELEASE */ +if (intval($config['version']) > 6) + $snort_pfsense_basever = 'no'; +else + $snort_pfsense_basever = 'yes'; + +/* find out what arch where in x86 , x64 */ +global $snort_arch; +$snort_arch = 'x86'; +$snort_arch_ck = php_uname("m"); +if ($snort_arch_ck == 'i386') + $snort_arch = 'x86'; +else if ($snort_arch_ck == "amd64") + $snort_arch = 'x64'; +else + $snort_arch = "Unknown"; + +/* tell me my theme */ +$pfsense_theme_is = $config['theme']; + +/* func builds custom white lists */ +function find_whitelist_key($find_wlist_number) { + global $config, $g; + + if (!is_array($config['installedpackages']['snortglobal']['whitelist'])) + $config['installedpackages']['snortglobal']['whitelist'] = array(); + if (!is_array($config['installedpackages']['snortglobal']['whitelist']['item'])) + return 0; /* XXX */ + + foreach ($config['installedpackages']['snortglobal']['whitelist']['item'] as $w_key => $value) { + if ($value['name'] == $find_wlist_number) + return $w_key; + } +} + +/* func builds custom suppress lists */ +function find_suppress_key($find_slist_number) { + global $config, $g; + + if (!is_array($config['installedpackages']['snortglobal']['suppress'])) + $config['installedpackages']['snortglobal']['suppress'] = array(); + if (!is_array($config['installedpackages']['snortglobal']['suppress']['item'])) + return 0; /* XXX */ + + foreach ($config['installedpackages']['snortglobal']['suppress']['item'] as $s_key => $value) { + if ($value['name'] == $find_slist_number) + return $s_key; + } +} + +function snort_find_interface_ipv6($interface, $flush = false) +{ + global $interface_ipv6_arr_cache; + global $interface_snv6_arr_cache; + global $config; + + $interface = trim($interface); + $interface = get_real_interface($interface); + + if (!does_interface_exist($interface)) + return; + + /* Setup IP cache */ + if (!isset($interface_ipv6_arr_cache[$interface]) or $flush) { + $ifinfo = pfSense_get_interface_addresses($interface); + // FIXME: Add IPv6 support to the pfSense module + exec("/sbin/ifconfig {$interface} inet6", $output); + foreach($output as $line) { + if(preg_match("/inet6/", $line)) { + $parts = explode(" ", $line); + if(preg_match("/fe80::/", $parts[1])) { + $ifinfo['ipaddrv6'] = $parts[1]; + if($parts[2] == "-->") { + $parts[5] = "126"; + $ifinfo['subnetbitsv6'] = $parts[5]; + } else { + $ifinfo['subnetbitsv6'] = $parts[3]; + } + } + } + } + $interface_ipv6_arr_cache[$interface] = $ifinfo['ipaddrv6']; + $interface_snv6_arr_cache[$interface] = $ifinfo['subnetbitsv6']; + } + + return $interface_ipv6_arr_cache[$interface]; +} + +function snort_get_interface_ipv6($interface = "wan") +{ + global $config; + $realif = get_failover_interface($interface); + switch($config['interfaces'][$interface]['ipaddrv6']) { + case "6rd": + case "6to4": + $realif = "stf0"; + break; + } + if (!$realif) { + if (preg_match("/^carp/i", $interface)) + $realif = $interface; + else if (preg_match("/^[a-z0-9]+_vip/i", $interface)) + $realif = $interface; + else + return null; + } + + $curip = snort_find_interface_ipv6($realif); + + if (strstr($curip, '%', TRUE)) { + $curip = strstr($curip, '%', TRUE); + }else if (is_ipaddrv6($curip)){ + $curip = $curip; + } + + if ($curip && is_ipaddrv6($curip) && ($curip != "::")) + return $curip; + else + return null; +} + +/* func builds custom whitelests */ +function build_base_whitelist($build_netlist, $wanip, $wangw, $wandns, $vips, $vpns, $userwips) { + global $config, $g, $snort_pfsense_basever; + + // build an interface array list + $int_array = get_configured_interface_list(); + + /* calculate ipv4 interface subnet information */ + $home_net = ''; + $snort_calc_iface_subnet_list = function($int) use(&$home_net) { + + $subnet = get_interface_ip($int); + $sn = get_interface_subnet($int); + $subnet_v6 = snort_get_interface_ipv6($int); + $sn_v6 = get_interface_subnetv6($int); + + if (is_ipaddr($subnet) && !empty($subnet)) { + $home_net .= "{$subnet}/{$sn},"; + } + + if (is_ipaddr($subnet_v6) && !empty($subnet_v6)) { + $home_net .= "{$subnet_v6}/{$sn_v6},"; + } + + }; + + /* Add Gateway on WAN interface to whitelist (For RRD graphs) */ + $snort_calc_gateway_list = function($int) use (&$home_net) { + + $gw = get_interface_gateway($int); + $sn = get_interface_subnet($int); + $gw_v6 = get_interface_gateway_v6($int); + $sn_v6 = get_interface_subnetv6($int); + + + if(!empty($gw) && is_ipaddr($gw)) { + $home_net .= "{$gw}/{$sn},"; + } + + if(!empty($gw_v6) && is_ipaddr($gw_v6)) { + $home_net .= "{$gw_v6}/{$sn_v6},"; + } + + }; + + // iterate through interface list and write out whitelist items and also compile a home_net list for snort. + foreach ($int_array as $int) { + + if (!empty($int)) { + $snort_calc_iface_subnet_list($int); + + if ($wangw == 'yes') + $snort_calc_gateway_list($int); + + } + + } + + /* + * Add DNS server for WAN interface to whitelist + * + * NOTE: does this get ipv6 ips + */ + $snort_dns_list = function() use(&$home_net) { + + $dns_servers = get_dns_servers(); + foreach ($dns_servers as $dns) { + if(!empty($dns) && is_ipaddr($dns)) { + $home_net .= "{$dns},"; + } + } + + }; + + if($wandns == 'yes') { + $snort_dns_list(); + } + + /* + * iterate all vips and add to whitelist + * NOTE: does this get ipv6 ips + * + */ + $snort_vips_list = function() use(&$home_net, &$config) { + + if (is_array($config['virtualip']) && is_array($config['virtualip']['vip'])) { + foreach($config['virtualip']['vip'] as $vip) + if(!empty($vip['subnet'])) + $home_net .= "{$vip['subnet']},"; + } + + }; + + if($vips == 'yes') { + $snort_vips_list(); + } + + /* + * grab a list of vpns and whitelist if user desires added by nestorfish 954 + * + * NOTE: does this get ipv6 ips + */ + $snort_vpns_list = function() use(&$home_net, &$config) { + $vpns_list = filter_get_vpns_list(); + + if (!empty($vpns_list)) { + // convert spaces to , returns + $vpns_list = str_replace(' ', ",", $vpns_list); + $vpns_list = str_replace(' ', ",", $vpns_list); + + $home_net .= "{$vpns_list},"; + } + + }; + + if ($vpns == 'yes') { + $snort_vpns_list(); + } + + $snort_userwips_list = function() use(&$home_net, &$userwips, &$config) { + + if (!is_array($config['installedpackages']['snortglobal']['whitelist']['item'])) + $config['installedpackages']['snortglobal']['whitelist']['item'] = array(); + + $home_net .= $config['installedpackages']['snortglobal']['whitelist']['item'][$userwips]['address'] . ','; + + }; + + if ($userwips > -1) { + $snort_userwips_list(); + } + + // add loopback iface + $home_net .= '127.0.0.1,'; + $home_net .= '::1,'; + + /* + * makes sure there is no duplicates + * splits $home_net to (ipv6 ip), (ipv6 cidr), (ipv4 ip), (ipv4 cidr) + */ + $snort_clean_home_net = function() use(&$home_net) { + + $home_net = trim($home_net); + $home_net = explode(',', $home_net); + $net_ipv4_cidr = array(); + $net_ipv4 = array(); + $net_ipv6_cidr = array(); + $net_ipv6 = array(); + + // split into 4 arrays + foreach ($home_net as $net_ip) { + + if (preg_match("/\./", $net_ip)) { + if (preg_match("/\//", $net_ip)) { + if (!in_array($net_ip, $net_ipv4_cidr)) + array_push($net_ipv4_cidr, $net_ip); + }else{ + if (!in_array($net_ip, $net_ipv4)) + array_push($net_ipv4, $net_ip); + } + } + + if (preg_match("/:/", $net_ip)) { + if (preg_match("/\//", $net_ip)) { + if (!in_array($net_ip, $net_ipv6_cidr)) + array_push($net_ipv6_cidr, $net_ip); + }else{ + if (!in_array($net_ip, $net_ipv6)) + array_push($net_ipv6, $net_ip); + } + } + } // end foreach + + // TODO: make sure that ips are not in cidr + + $home_net = ''; + foreach ($net_ipv4_cidr as $net_ipv4_cidr_ip) { + if (!empty($net_ipv4_cidr_ip)) + $home_net .= $net_ipv4_cidr_ip . ','; + } + foreach ($net_ipv4 as $net_ipv4_ip) { + if (!empty($net_ipv4_ip)) + $home_net .= $net_ipv4_ip . ','; + } + foreach ($net_ipv6_cidr as $net_ipv6_cidr_ip) { + if (!empty($net_ipv6_cidr_ip)) + $home_net .= $net_ipv6_cidr_ip . ','; + } + foreach ($net_ipv6 as $net_ipv6_ip) { + if (!empty($net_ipv6_ip)) + $home_net .= $net_ipv6_ip . ','; + } + + // remove , if its the last char + if($home_net[strlen($home_net)-1] === ',') { + $home_net = substr_replace($home_net, '', -1); + } + + }; + + $snort_clean_home_net(); + + return $home_net; + +} // end func builds custom whitelests + + +/* checks to see if snort is running yes/no and stop/start */ +function snortRunningChk($type, $snort_uuid, $if_real) { + global $config; + + if ($type === 'snort') { + $snort_pgrep_chk = exec("/bin/pgrep -f 'snort.*R {$snort_uuid}'"); + } + + if ($type === 'barnyard2') { + $snort_pgrep_chk = exec("/bin/pgrep -f 'barnyard2.*{$snort_uuid}_{$if_real}'"); + } + + if (!empty($snort_pgrep_chk)) { + return $snort_pgrep_chk; + } + + return NULL; + +} + +function Running_Stop($snort_uuid, $if_real, $id) { + global $config, $g; + + // if snort.sh crashed this will remove the pid + @unlink("{$g['tmp_path']}/snort.sh.pid"); + + // wait until snort stops + $snort_WaitForStop = function ($type) use (&$snort_uuid, &$if_real) { + + $snort_pgrep_chk = snortRunningChk($type, $snort_uuid, $if_real); + + if (!empty($snort_pgrep_chk)){ + exec("/usr/bin/touch /tmp/snort_{$if_real}{$snort_uuid}.stoplck"); + } + + $i = 0; + while(file_exists("/tmp/snort_{$if_real}{$snort_uuid}.stoplck") || file_exists("/var/log/snort/run/{$type}_{$if_real}{$snort_uuid}.pid")) { + $i++; + exec("/usr/bin/logger -p daemon.info -i -t SnortStop '{$type} Stop count...{$i}'"); + + $snort_pgrep_chk = snortRunningChk($type, $snort_uuid, $if_real); + + if (empty($snort_pgrep_chk)){ + @exec("/bin/rm /tmp/snort_{$if_real}{$snort_uuid}.stoplck"); + } + + sleep(2); + + } + }; + + if (isvalidpid("/var/log/snort/run/snort_{$if_real}{$snort_uuid}.pid")) { + + // send kill cmd + killbypid("/var/log/snort/run/snort_{$if_real}{$snort_uuid}.pid"); + exec("/bin/rm /var/log/snort/run/snort_{$if_real}{$snort_uuid}.pid.lck"); + + // wait until snort stops + $snort_WaitForStop('snort'); + + } + + if (isvalidpid("/var/log/snort/run/barnyard2_{$if_real}{$snort_uuid}.pid")) { + + // send kill cmd + killbypid("/var/log/snort/run/barnyard2_{$if_real}{$snort_uuid}.pid"); + exec("/bin/rm /var/log/snort/run/barnyard2_{$snort_uuid}_{$if_real}.pid.lck"); + + // wait until barnyard2 stops + $snort_WaitForStop('barnyard2'); + + } + + // TODO: Add a GUI option that lets the user keep full logs + /* + @exec("/bin/rm /var/log/snort/run/snort_{$if_real}{$snort_uuid}*"); + @exec("/bin/rm /var/log/snort/{$snort_uuid}_{$if_real}/snort.u1*"); + @exec("/bin/rm /var/log/snort/{$snort_uuid}_{$if_real}/snort.u2*"); + + @exec("/bin/rm /var/log/snort/run/barnyard2_{$snort_uuid}_{$if_real}*"); + @exec("/bin/rm /var/log/snort/barnyard2/{$snort_uuid}_{$if_real}/snort.u1*"); + @exec("/bin/rm /var/log/snort/barnyard2/{$snort_uuid}_{$if_real}/snort.u2*"); + */ + + // Log Iface stop + exec("/usr/bin/logger -p daemon.info -i -t SnortStartup 'Interface Rule STOP for {$snort_uuid}_{$if_real}...'"); +} + +function Running_Start($snort_uuid, $if_real, $id) { + global $config; + + /* if snort.sh crashed this will remove the pid */ + @unlink("{$g['tmp_path']}/snort.sh.pid"); + + // wait until snort starts + $snort_WaitForStart = function ($type) use (&$snort_uuid, &$if_real) { + + // calls to see if snort or barnyard is running + $snort_pgrep_chk = snortRunningChk($type, $snort_uuid, $if_real); + + if (empty($snort_pgrep_chk)){ + exec("/usr/bin/touch /tmp/snort_{$if_real}{$snort_uuid}.startlck"); + } + + $i = 0; + while(file_exists("/tmp/snort_{$if_real}{$snort_uuid}.startlck") || !file_exists("/var/log/snort/run/{$type}_{$if_real}{$snort_uuid}.pid")) { + + $i++; + exec("/usr/bin/logger -p daemon.info -i -t SnortStart 'Snort Start count...{$i}'"); + + $snort_pgrep_chk = snortRunningChk($type, $snort_uuid, $if_real); + + // stop if snort error is in syslogd + $snort_error_chk = exec("/usr/bin/grep -e 'snort.*{$snort_pgrep_chk}.*FATAL.*ERROR.*' /var/log/system.log"); + if(!empty($snort_error_chk)) { + break; + } + + if (!empty($snort_pgrep_chk)){ + @exec("/bin/rm /tmp/snort_{$if_real}{$snort_uuid}.startlck"); + } + sleep(2); + } + }; + + // only start if iface is on or iface is not running + $snort_info_chk = $config['installedpackages']['snortglobal']['rule'][$id]['enable']; + $snortRunningChkPreStart = snortRunningChk($id, $snort_uuid, $if_real); + if ($snort_info_chk === 'on' && empty($snortRunningChkPreStart)) { + + // start snort cmd + exec("/usr/local/bin/snort -R \"{$snort_uuid}\" -D -q -l /var/log/snort/{$snort_uuid}_{$if_real} --pid-path /var/log/snort/run -G {$snort_uuid} -c /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/snort.conf -i {$if_real}"); + + // wait until snort starts + $snort_WaitForStart('snort'); + + }else{ + return; + } + + // define snortbarnyardlog_chk + $snortbarnyardlog_info_chk = $config['installedpackages']['snortglobal']['rule'][$id]['barnyard_enable']; + if ($snortbarnyardlog_info_chk == 'on') { + + // start barnyard2 cmd + exec("/usr/local/bin/barnyard2 -f \"snort.u2\" --pid-path /var/log/snort/run -c /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/barnyard2.conf -d /var/log/snort/{$snort_uuid}_{$if_real} -D -q"); + + // wait until snort starts + $snort_WaitForStart('barnyard2'); + + } + + /* Log Iface stop */ + exec("/usr/bin/logger -p daemon.info -i -t SnortStartup 'Interface Rule START for {$id}_{$snort_uuid}_{$if_real}...'"); +} + +function snort_get_friendly_interface($interface) { + + if (function_exists('convert_friendly_interface_to_friendly_descr')) + $iface = convert_friendly_interface_to_friendly_descr($interface); + else { + if (!$interface || ($interface == "wan")) + $iface = "WAN"; + else if(strtolower($interface) == "lan") + $iface = "LAN"; + else if(strtolower($interface) == "pppoe") + $iface = "PPPoE"; + else if(strtolower($interface) == "pptp") + $iface = "PPTP"; + else + $iface = strtoupper($interface); + } + + return $iface; +} + +/* get the real iface name of wan */ +function snort_get_real_interface($interface) { + global $config; + + $lc_interface = strtolower($interface); + if (function_exists('get_real_interface')) + return get_real_interface($lc_interface); + else { + if ($lc_interface == "lan") { + if ($config['inerfaces']['lan']) + return $config['interfaces']['lan']['if']; + return $interface; + } + if ($lc_interface == "wan") + return $config['interfaces']['wan']['if']; + $ifdescrs = array(); + for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) { + $ifname = "opt{$j}"; + if(strtolower($ifname) == $lc_interface) + return $config['interfaces'][$ifname]['if']; + if(isset($config['interfaces'][$ifname]['descr']) && (strtolower($config['interfaces'][$ifname]['descr']) == $lc_interface)) + return $config['interfaces'][$ifname]['if']; + } + } + + return $interface; +} + +/* + this code block is for deleteing logs while keeping the newest file, + snort is linked to these files while running, do not take the easy way out + by touch and rm, snort will lose sync and not log. + + this code needs to be watched. + */ + +/* list dir files */ +function snort_file_list($snort_log_dir, $snort_log_file) +{ + $dir = opendir ("$snort_log_dir"); + while (false !== ($file = readdir($dir))) { + if (strpos($file, "$snort_log_file",1) ) + $file_list[] = basename($file); + } + return $file_list; +} + +/* snort dir files */ +function snort_file_sort($snort_file1, $snort_file2) +{ + if ($snort_file1 == $snort_file2) + return 0; + + return ($snort_file1 < $snort_file2); // ? -1 : 1; // this flips the array +} + +/* build files newest first array */ +function snort_build_order($snort_list) +{ + foreach ($snort_list as $value_list) + $list_order[] = $value_list; + + return $list_order; +} + +/* keep the newest remove the rest */ +function snort_remove_files($snort_list_rm, $snort_file_safe) +{ + foreach ($snort_list_rm as $value_list) { + if ($value_list != $snort_file_safe) + @unlink("/var/log/snort/$value_list"); + else + file_put_contents("/var/log/snort/$snort_file_safe", ""); + } +} + +/* + * TODO: + * This is called by snort_alerts.php. + * + * This func needs to be made to only clear one interface rule log + * at a time. + * + */ +function post_delete_logs() +{ + global $config, $g; + + /* do not start config build if rules is empty */ + if (!is_array($config['installedpackages']['snortglobal']['rule'])) + return; + + $snort_log_dir = '/var/log/snort'; + + foreach ($config['installedpackages']['snortglobal']['rule'] as $value) { + $result_lan = $value['interface']; + $if_real = snort_get_real_interface($result_lan); + $snort_uuid = $value['uuid']; + + if ($if_real != '' && $snort_uuid != '') { + if ($value['snortunifiedlog'] == 'on') { + $snort_log_file_u2 = "snort.u2."; + $snort_list_u2 = snort_file_list($snort_log_dir, $snort_log_file_u2); + if (is_array($snort_list_u2)) { + usort($snort_list_u2, "snort_file_sort"); + $snort_u2_rm_list = snort_build_order($snort_list_u2); + snort_remove_files($snort_u2_rm_list, $snort_u2_rm_list[0]); + } + } else + exec("/bin/rm $snort_log_dir/{$snort_uuid}_{$if_real}/snort.u2*"); + + if ($value['tcpdumplog'] == 'on') { + $snort_log_file_tcpd = "snort.tcpdump."; + $snort_list_tcpd = snort_file_list($snort_log_dir, $snort_log_file_tcpd); + if (is_array($snort_list_tcpd)) { + usort($snort_list_tcpd, "snort_file_sort"); + $snort_tcpd_rm_list = snort_build_order($snort_list_tcpd); + snort_remove_files($snort_tcpd_rm_list, $snort_tcpd_rm_list[0]); + } + } else { + exec("/bin/rm $snort_log_dir/{$snort_uuid}_{$if_real}/snort.tcpdump*"); + + if ($value['perform_stat'] == 'on') + @file_put_contents("$snort_log_dirt/{$snort_uuid}_{$if_real}/snort.stats", ""); + } + } + } // end foreach +} + +function snort_postinstall() +{ + global $config, $g, $snort_pfsense_basever, $snort_arch; + + /* snort -> advanced features */ + if (is_array($config['installedpackages']['snortglobal'])) { + $bpfbufsize = $config['installedpackages']['snortglobal']['bpfbufsize']; + $bpfmaxbufsize = $config['installedpackages']['snortglobal']['bpfmaxbufsize']; + $bpfmaxinsns = $config['installedpackages']['snortglobal']['bpfmaxinsns']; + } + + /* cleanup default files */ + @rename('/usr/local/etc/snort/snort.conf-sample', '/usr/local/etc/snort/snort.conf'); + @rename('/usr/local/etc/snort/threshold.conf-sample', '/usr/local/etc/snort/threshold.conf'); + @rename('/usr/local/etc/snort/sid-msg.map-sample', '/usr/local/etc/snort/sid-msg.map'); + @rename('/usr/local/etc/snort/unicode.map-sample', '/usr/local/etc/snort/unicode.map'); + @rename('/usr/local/etc/snort/classification.config-sample', '/usr/local/etc/snort/classification.config'); + @rename('/usr/local/etc/snort/generators-sample', '/usr/local/etc/snort/generators'); + @rename('/usr/local/etc/snort/reference.config-sample', '/usr/local/etc/snort/reference.config'); + @rename('/usr/local/etc/snort/gen-msg.map-sample', '/usr/local/etc/snort/gen-msg.map'); + @unlink('/usr/local/etc/snort/sid'); + @unlink('/usr/local/etc/rc.d/snort'); + @unlink('/usr/local/etc/rc.d/bardyard2'); + + /* remove example files */ + if (file_exists('/usr/local/lib/snort/dynamicrules/lib_sfdynamic_example_rule.so.0')) + exec('/bin/rm /usr/local/lib/snort/dynamicrules/lib_sfdynamic_example*'); + + if (file_exists('/usr/local/lib/snort/dynamicpreprocessor/lib_sfdynamic_preprocessor_example.so')) + exec('/bin/rm /usr/local/lib/snort/dynamicpreprocessor/lib_sfdynamic_preprocessor_example*'); + + /* create a few directories and ensure the sample files are in place */ + if (!is_dir('/usr/local/etc/snort')) + exec('/bin/mkdir -p /usr/local/etc/snort/custom_rules'); + if (!is_dir('/usr/local/etc/snort/whitelist')) + exec('/bin/mkdir -p /usr/local/etc/snort/whitelist/'); + /* NOTE: the diff between the if check and the exec() extra run is by design */ + if (!is_dir('/var/log/snort')) + exec('/bin/mkdir -p /var/log/snort/run'); + else + exec('/bin/rm -r /var/log/snort/*; /bin/mkdir -p /var/log/snort/run'); + + if (!is_dir('/var/log/snort/barnyard2')) + exec('/bin/mkdir -p /var/log/snort/barnyard2'); + if (!is_dir('/usr/local/lib/snort/dynamicrules/')) + exec('/bin/mkdir -p /usr/local/lib/snort/dynamicrules/'); + if (!file_exists('/var/db/whitelist')) + touch('/var/db/whitelist'); + + /* XXX: These are needed if you run snort as snort user + mwexec('/usr/sbin/chown -R snort:snort /var/log/snort', true); + mwexec('/usr/sbin/chown -R snort:snort /usr/local/etc/snort', true); + mwexec('/usr/sbin/chown -R snort:snort /usr/local/lib/snort', true); + mwexec('/usr/sbin/chown snort:snort /tmp/snort*', true); + mwexec('/usr/sbin/chown snort:snort /var/db/whitelist', true); + */ + /* important */ + mwexec('/bin/chmod 660 /var/db/whitelist', true); + mwexec('/bin/chmod -R 660 /usr/local/etc/snort/*', true); + mwexec('/bin/chmod -R 660 /tmp/snort*', true); + mwexec('/bin/chmod -R 660 /var/run/snort*', true); + mwexec('/bin/chmod -R 660 /var/snort/run/*', true); + mwexec('/bin/chmod 770 /usr/local/lib/snort', true); + mwexec('/bin/chmod 770 /usr/local/etc/snort', true); + mwexec('/bin/chmod 770 /usr/local/etc/whitelist', true); + mwexec('/bin/chmod 770 /var/log/snort', true); + mwexec('/bin/chmod 770 /var/log/snort/run', true); + mwexec('/bin/chmod 770 /var/log/snort/barnyard2', true); + + /* move files around, make it look clean */ + mwexec('/bin/mkdir -p /usr/local/www/snort/css'); + mwexec('/bin/mkdir -p /usr/local/www/snort/images'); + + chdir ("/usr/local/www/snort/css/"); + exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort-dev/css/style.css'); + exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort-dev/css/sexybuttons.css'); + chdir("/usr/local/www/snort/images/"); + exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort-dev/images/alert.jpg'); + exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort-dev/images/down.gif'); + exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort-dev/images/down2.gif'); + exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort-dev/images/icon-table-sort.png'); + exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort-dev/images/icon-table-sort-asc.png'); + exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort-dev/images/icon-table-sort-desc.png'); + exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort-dev/images/up.gif'); + exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort-dev/images/up2.gif'); + exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort-dev/images/logo.jpg'); + exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort-dev/images/icon_excli.png'); + exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort-dev/images/arrow_down.png'); + exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort-dev/images/awesome-overlay-sprite.png'); + exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort-dev/images/logo22.png'); + exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort-dev/images/page_white_text.png'); + + /* remake saved settings */ + if ($config['installedpackages']['snortglobal']['forcekeepsettings'] == 'on') { + update_status(gettext("Saved settings detected...")); + update_output_window(gettext("Please wait... rebuilding files...")); + sync_snort_package_config(); + update_output_window(gettext("Finnished Rebuilding files...")); + } +} + +function snort_Getdirsize($node) { + if(!is_readable($node)) + return false; + + $blah = exec( "/usr/bin/du -kd $node" ); + return substr( $blah, 0, strpos($blah, 9) ); +} + +/* func for log dir size limit cron */ +function snort_snortloglimit_install_cron($should_install) { + global $config, $g; + + if (!is_array($config['cron']['item'])) + $config['cron']['item'] = array(); + + $x=0; + $is_installed = false; + foreach($config['cron']['item'] as $item) { + if (strstr($item['command'], '/usr/local/pkg/snort/snort_check_cron_misc.inc')) { + $is_installed = true; + break; + } + $x++; + } + + switch($should_install) { + case true: + if(!$is_installed) { + + $cron_item = array(); + $cron_item['minute'] = "*/5"; + $cron_item['hour'] = "*"; + $cron_item['mday'] = "*"; + $cron_item['month'] = "*"; + $cron_item['wday'] = "*"; + $cron_item['who'] = "root"; + $cron_item['command'] = "/usr/bin/nice -n20 /usr/local/bin/php -f /usr/local/pkg/snort/snort_check_cron_misc.inc"; + $config['cron']['item'][] = $cron_item; + } + break; + case false: + if($is_installed == true) + unset($config['cron']['item'][$x]); + break; + } +} + +/* func for updating cron */ +function snort_rm_blocked_install_cron($should_install) { + global $config, $g; + + if (!is_array($config['cron']['item'])) + $config['cron']['item'] = array(); + + $x=0; + $is_installed = false; + foreach($config['cron']['item'] as $item) { + if (strstr($item['command'], "snort2c")) { + $is_installed = true; + break; + } + $x++; + } + + $snort_rm_blocked_info_ck = $config['installedpackages']['snortglobal']['rm_blocked']; + if ($snort_rm_blocked_info_ck == "1h_b") { + $snort_rm_blocked_min = "*/5"; + $snort_rm_blocked_hr = "*"; + $snort_rm_blocked_mday = "*"; + $snort_rm_blocked_month = "*"; + $snort_rm_blocked_wday = "*"; + $snort_rm_blocked_expire = "3600"; + } + if ($snort_rm_blocked_info_ck == "3h_b") { + $snort_rm_blocked_min = "*/15"; + $snort_rm_blocked_hr = "*"; + $snort_rm_blocked_mday = "*"; + $snort_rm_blocked_month = "*"; + $snort_rm_blocked_wday = "*"; + $snort_rm_blocked_expire = "10800"; + } + if ($snort_rm_blocked_info_ck == "6h_b") { + $snort_rm_blocked_min = "*/30"; + $snort_rm_blocked_hr = "*"; + $snort_rm_blocked_mday = "*"; + $snort_rm_blocked_month = "*"; + $snort_rm_blocked_wday = "*"; + $snort_rm_blocked_expire = "21600"; + } + if ($snort_rm_blocked_info_ck == "12h_b") { + $snort_rm_blocked_min = "2"; + $snort_rm_blocked_hr = "*/1"; + $snort_rm_blocked_mday = "*"; + $snort_rm_blocked_month = "*"; + $snort_rm_blocked_wday = "*"; + $snort_rm_blocked_expire = "43200"; + } + if ($snort_rm_blocked_info_ck == "1d_b") { + $snort_rm_blocked_min = "2"; + $snort_rm_blocked_hr = "*/2"; + $snort_rm_blocked_mday = "*"; + $snort_rm_blocked_month = "*"; + $snort_rm_blocked_wday = "*"; + $snort_rm_blocked_expire = "86400"; + } + if ($snort_rm_blocked_info_ck == "4d_b") { + $snort_rm_blocked_min = "2"; + $snort_rm_blocked_hr = "*/8"; + $snort_rm_blocked_mday = "*"; + $snort_rm_blocked_month = "*"; + $snort_rm_blocked_wday = "*"; + $snort_rm_blocked_expire = "345600"; + } + if ($snort_rm_blocked_info_ck == "7d_b") { + $snort_rm_blocked_min = "2"; + $snort_rm_blocked_hr = "*/14"; + $snort_rm_blocked_mday = "*"; + $snort_rm_blocked_month = "*"; + $snort_rm_blocked_wday = "*"; + $snort_rm_blocked_expire = "604800"; + } + if ($snort_rm_blocked_info_ck == "28d_b") { + $snort_rm_blocked_min = "2"; + $snort_rm_blocked_hr = "0"; + $snort_rm_blocked_mday = "*/2"; + $snort_rm_blocked_month = "*"; + $snort_rm_blocked_wday = "*"; + $snort_rm_blocked_expire = "2419200"; + } + switch($should_install) { + case true: + if(!$is_installed) { + $cron_item = array(); + $cron_item['minute'] = "$snort_rm_blocked_min"; + $cron_item['hour'] = "$snort_rm_blocked_hr"; + $cron_item['mday'] = "$snort_rm_blocked_mday"; + $cron_item['month'] = "$snort_rm_blocked_month"; + $cron_item['wday'] = "$snort_rm_blocked_wday"; + $cron_item['who'] = "root"; + $cron_item['command'] = "/usr/bin/nice -n20 /usr/local/sbin/expiretable -t $snort_rm_blocked_expire snort2c"; + $config['cron']['item'][] = $cron_item; + } + break; + case false: + if ($is_installed == true) + unset($config['cron']['item'][$x]); + break; + } +} + +/* func to install snort update */ +function snort_rules_up_install_cron($should_install) { + global $config, $g; + + if(!$config['cron']['item']) + $config['cron']['item'] = array(); + + $x=0; + $is_installed = false; + foreach($config['cron']['item'] as $item) { + if (strstr($item['command'], "snort_check_for_rule_updates.php")) { + $is_installed = true; + break; + } + $x++; + } + $snort_rules_up_info_ck = $config['installedpackages']['snortglobal']['autorulesupdate7']; + if ($snort_rules_up_info_ck == "6h_up") { + $snort_rules_up_min = "3"; + $snort_rules_up_hr = "*/6"; + $snort_rules_up_mday = "*"; + $snort_rules_up_month = "*"; + $snort_rules_up_wday = "*"; + } + if ($snort_rules_up_info_ck == "12h_up") { + $snort_rules_up_min = "3"; + $snort_rules_up_hr = "*/12"; + $snort_rules_up_mday = "*"; + $snort_rules_up_month = "*"; + $snort_rules_up_wday = "*"; + } + if ($snort_rules_up_info_ck == "1d_up") { + $snort_rules_up_min = "3"; + $snort_rules_up_hr = "0"; + $snort_rules_up_mday = "*/1"; + $snort_rules_up_month = "*"; + $snort_rules_up_wday = "*"; + } + if ($snort_rules_up_info_ck == "4d_up") { + $snort_rules_up_min = "3"; + $snort_rules_up_hr = "0"; + $snort_rules_up_mday = "*/4"; + $snort_rules_up_month = "*"; + $snort_rules_up_wday = "*"; + } + if ($snort_rules_up_info_ck == "7d_up") { + $snort_rules_up_min = "3"; + $snort_rules_up_hr = "0"; + $snort_rules_up_mday = "*/7"; + $snort_rules_up_month = "*"; + $snort_rules_up_wday = "*"; + } + if ($snort_rules_up_info_ck == "28d_up") { + $snort_rules_up_min = "3"; + $snort_rules_up_hr = "0"; + $snort_rules_up_mday = "*/28"; + $snort_rules_up_month = "*"; + $snort_rules_up_wday = "*"; + } + switch($should_install) { + case true: + if(!$is_installed) { + $cron_item = array(); + $cron_item['minute'] = "$snort_rules_up_min"; + $cron_item['hour'] = "$snort_rules_up_hr"; + $cron_item['mday'] = "$snort_rules_up_mday"; + $cron_item['month'] = "$snort_rules_up_month"; + $cron_item['wday'] = "$snort_rules_up_wday"; + $cron_item['who'] = "root"; + $cron_item['command'] = "/usr/bin/nice -n20 /usr/local/bin/php -f /usr/local/pkg/snort/snort_check_for_rule_updates.php >> /tmp/snort_update.log"; + $config['cron']['item'][] = $cron_item; + } + break; + case false: + if($is_installed == true) + unset($config['cron']['item'][$x]); + break; + } +} + +/* Only run when all ifaces needed to sync. Expects filesystem rw */ +function sync_snort_package_config() +{ + global $config, $g; + + /* RedDevil suggested code */ + /* TODO: more testing needs to be done */ + /* may cause voip to fail */ + //exec("/sbin/sysctl net.bpf.bufsize=8388608"); + //exec("/sbin/sysctl net.bpf.maxbufsize=4194304"); + //exec("/sbin/sysctl net.bpf.maxinsns=512"); + //exec("/sbin/sysctl net.inet.tcp.rfc1323=1"); + + conf_mount_rw(); + + /* do not start config build if rules is empty */ + if (!is_array($config['installedpackages']['snortglobal']['rule'])) { + exec('/bin/rm /usr/local/etc/rc.d/snort.sh'); + conf_mount_ro(); + return; + } + + foreach ($config['installedpackages']['snortglobal']['rule'] as $id => $value) { + $if_real = snort_get_real_interface($value['interface']); + $snort_uuid = $value['uuid']; + + if ($if_real != '' && $snort_uuid != '') { + + // only build whitelist when needed + if ($value['blockoffenders7'] === 'on') { + create_snort_whitelist($id, $if_real); + } + + // only build threshold when needed + if ($value['suppresslistname'] !== 'default'){ + create_snort_suppress($id, $if_real); + } + + // create snort configuration file + create_snort_conf($id, $if_real, $snort_uuid); + + // if rules exist cp rules to each iface + create_rules_iface($id, $if_real, $snort_uuid); + + // create barnyard2 configuration file + if ($value['barnyard_enable'] == 'on') { + create_barnyard2_conf($id, $if_real, $snort_uuid); + } + } + } + + /* create snort bootup file snort.sh only create once */ + create_snort_sh(); + + /* all new files are for the user snort nologin */ + if (!is_dir("/var/log/snort/{$snort_uuid}_{$if_real}")) + exec("/bin/mkdir -p /var/log/snort/{$snort_uuid}_{$if_real}"); + + if (!is_dir('/var/log/snort/run')) + exec('/bin/mkdir -p /var/log/snort/run'); + + if (!is_dir("/var/log/snort/barnyard2/{$snort_uuid}_{$if_real}")) + exec("/bin/mkdir -p /var/log/snort/barnyard2/{$snort_uuid}_{$if_real}"); + + /* XXX: These are needed if snort is run as snort user + mwexec('/usr/sbin/chown -R snort:snort /var/log/snort', true); + mwexec('/usr/sbin/chown -R snort:snort /usr/local/etc/snort', true); + mwexec('/usr/sbin/chown -R snort:snort /usr/local/lib/snort', true); + mwexec('/usr/sbin/chown snort:snort /tmp/snort*', true); + mwexec('/usr/sbin/chown snort:snort /var/db/whitelist', true); + */ + + /* important */ + mwexec('/bin/chmod 770 /var/db/whitelist', true); + mwexec('/bin/chmod 770 /var/run/snort*', true); + mwexec('/bin/chmod 770 /tmp/snort*', true); + mwexec('/bin/chmod -R 770 /var/log/snort', true); + mwexec('/bin/chmod -R 770 /usr/local/lib/snort', true); + mwexec('/bin/chmod -R 770 /usr/local/etc/snort/', true); + + conf_mount_ro(); +} + +/* Start of main config files */ + +/* create threshold file */ +function create_snort_suppress($id, $if_real) { + global $config, $g; + + /* make sure dir is there */ + if (!is_dir('/usr/local/etc/snort/suppress')) + exec('/bin/mkdir -p /usr/local/etc/snort/suppress'); + + if (!is_array($config['installedpackages']['snortglobal']['rule'])) + return; + + if ($config['installedpackages']['snortglobal']['rule'][$id]['suppresslistname'] != 'default') { + $whitelist_key_s = find_suppress_key($config['installedpackages']['snortglobal']['rule'][$id]['suppresslistname']); + + /* file name */ + $suppress_file_name = $config['installedpackages']['snortglobal']['suppress']['item'][$whitelist_key_s]['name']; + + /* Message */ + $s_data = '# This file is auto generated by the snort package. Please do not edit this file by hand.' . "\n\n"; + + /* user added arguments */ + $s_data .= str_replace("\r", "", base64_decode($config['installedpackages']['snortglobal']['suppress']['item'][$whitelist_key_s]['suppresspassthru'])); + + /* open snort's whitelist for writing */ + @file_put_contents("/usr/local/etc/snort/suppress/$suppress_file_name", $s_data); + } +} + +function create_snort_whitelist($id, $if_real) { + global $config, $g; + + /* make sure dir is there */ + if (!is_dir('/usr/local/etc/snort/whitelist')) + exec('/bin/mkdir -p /usr/local/etc/snort/whitelist'); + + if ($config['installedpackages']['snortglobal']['rule'][$id]['whitelistname'] == 'default') { + + $w_data = build_base_whitelist('whitelist', 'yes', 'yes', 'yes', 'yes', 'yes', 'no'); + + /* open snort's whitelist for writing */ + @file_put_contents("/usr/local/etc/snort/whitelist/defaultwlist", $w_data); + + } else if (!empty($config['installedpackages']['snortglobal']['rule'][$id]['whitelistname'])) { + $whitelist_key_w = find_whitelist_key($config['installedpackages']['snortglobal']['rule'][$id]['whitelistname']); + + if (!is_array($config['installedpackages']['snortglobal']['whitelist']['item'])) { + return; + } + + $whitelist = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_w]; + $w_data = build_base_whitelist($whitelist['snortlisttype'], $whitelist['wanips'], $whitelist['wangateips'], $whitelist['wandnsips'], $whitelist['vips'], $whitelist['vpnips'], $whitelist_key_w); + + // convert spaces to carriage returns + $w_data = str_replace(',', "\n", $w_data); + $w_data = str_replace(',,', "\n", $w_data); + + /* open snort's whitelist for writing */ + @file_put_contents("/usr/local/etc/snort/whitelist/" . $config['installedpackages']['snortglobal']['rule'][$id]['whitelistname'], $w_data); + } +} + +function create_snort_homenet($id, $if_real) { + global $config, $g; + + if ($config['installedpackages']['snortglobal']['rule'][$id]['homelistname'] == 'default' || $config['installedpackages']['snortglobal']['rule'][$id]['homelistname'] == '') + return build_base_whitelist('netlist', 'yes', 'yes', 'yes', 'yes', 'yes', 'no'); + else if (!empty($config['installedpackages']['snortglobal']['rule'][$id]['homelistname'])) { + $whitelist_key_h = find_whitelist_key($config['installedpackages']['snortglobal']['rule'][$id]['homelistname']); + + if (!is_array($config['installedpackages']['snortglobal']['whitelist']['item'])) + return; + + $build_netlist_h = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_h]['snortlisttype']; + $wanip_h = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_h]['wanips']; + $wangw_h = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_h]['wangateips']; + $wandns_h = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_h]['wandnsips']; + $vips_h = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_h]['vips']; + $vpns_h = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_h]['vpnips']; + + return build_base_whitelist($build_netlist_h, $wanip_h, $wangw_h, $wandns_h, $vips_h, $vpns_h, $whitelist_key_h); + } +} + +function create_snort_externalnet($id, $if_real) { + global $config, $g; + + if (!empty($config['installedpackages']['snortglobal']['rule'][$id]['externallistname'])) { + $whitelist_key_ex = find_whitelist_key($config['installedpackages']['snortglobal']['rule'][$id]['externallistname']); + + if (!is_array($config['installedpackages']['snortglobal']['whitelist']['item'])) + return; + + $build_netlist_ex = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_ex]['snortlisttype']; + $wanip_ex = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_ex]['wanips']; + $wangw_ex = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_ex]['wangateips']; + $wandns_ex = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_ex]['wandnsips']; + $vips_ex = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_ex]['vips']; + $vpns_ex = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_ex]['vpnips']; + + return build_base_whitelist($build_netlist_ex, $wanip_ex, $wangw_ex, $wandns_ex, $vips_ex, $vpns_ex, $whitelist_key_ex); + } +} + +// open snort.sh for writing +function create_snort_sh() +{ + global $config, $g; + + $snortconf =& $config['installedpackages']['snortglobal']['rule']; + + // do not start config build if rules is empty + if (!is_array($snortconf) || empty($snortconf)) { + return; + } + + $i = 0; + foreach ($snortconf as $value) { + $snort_uuid = $value['uuid']; + $result_lan = $value['interface']; + $if_real = snort_get_real_interface($result_lan); + + $snortstart_list .= "{$snort_uuid}_{$if_real}_{$i}" . ','; + + $i++; + + } // end foreach + + // remove , if its the last char + if($snortstart_list[strlen($snortstart_list)-1] === ',') { + $snortstart_list = substr_replace($snortstart_list, '', -1); + } + + +$snort_sh_text = <<<EOD + +#!/bin/sh +######## +# This file was automatically generated +# by the pfSense service handler. +# Code added to protect from double starts on pfSense bootup +######## Begining of Main snort.sh + +rc_start() { + +if [ -f /tmp/snort.sh.pid ]; then + exit; +fi + +/bin/echo "snort.sh run" > /tmp/snort.sh.pid + + +/usr/local/bin/php -f /usr/local/pkg/snort/snort_startstop.php snortstart={$snortstart_list} & + + +/bin/rm /tmp/snort.sh.pid + +} + +rc_stop() { + +if [ -f /tmp/snort.sh.pid ]; then + exit; +fi + +/bin/echo "snort.sh run" > /tmp/snort.sh.pid + + +/usr/local/bin/php -f /usr/local/pkg/snort/snort_startstop.php snortstop={$snortstart_list} & + + +/bin/rm /tmp/snort.sh.pid + +} + +case $1 in + start) + rc_start + ;; + stop) + rc_stop + ;; + restart) + rc_start + ;; +esac + +EOD; + + // write out snort.sh + $bconf = fopen("/usr/local/etc/rc.d/snort.sh", "w"); + if(!$bconf) { + log_error("Could not open /usr/local/etc/rc.d/snort.sh for writing."); + return; + } + fwrite($bconf, $snort_sh_text); + fclose($bconf); + @chmod("/usr/local/etc/rc.d/snort.sh", 0755); +} + +/* if rules exist copy to new interfaces */ +function create_rules_iface($id, $if_real, $snort_uuid) +{ + global $config, $g; + + $if_rule_dir = "/usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}"; + $folder_chk = (count(glob("{$if_rule_dir}/rules/*")) === 0) ? 'empty' : 'full'; + + if ($folder_chk == "empty") { + if (!is_dir("/usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/rules")) + exec("/bin/mkdir -p /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/rules"); + exec("/bin/cp /usr/local/etc/snort/rules/* {$if_rule_dir}/rules"); + if (file_exists("/usr/local/etc/snort/custom_rules/local_{$snort_uuid}_{$if_real}.rules")) + exec("/bin/cp /usr/local/etc/snort/custom_rules/local_{$snort_uuid}_{$if_real}.rules {$if_rule_dir}/local_{$snort_uuid}_{$if_real}.rules"); + } +} + +/* open barnyard2.conf for writing */ +function create_barnyard2_conf($id, $if_real, $snort_uuid) { + global $config, $g; + + if (!file_exists("/usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/barnyard2.conf")) + exec("/usr/bin/touch /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/barnyard2.conf"); + + if (!file_exists("/var/log/snort/{$snort_uuid}_{$if_real}/barnyard2.waldo")) { + mwexec("/usr/bin/touch /var/log/snort/{$snort_uuid}_{$if_real}/barnyard2.waldo", true); + /* XXX: This is needed if snort is run as snort user */ + //mwexec("/usr/sbin/chown snort:snort /var/log/snort/barnyard2/{$snort_uuid}_{$if_real}.waldo", true); + mwexec("/bin/chmod 770 /var/log/snort/{$snort_uuid}_{$if_real}/barnyard2.waldo", true); + } + + $barnyard2_conf_text = generate_barnyard2_conf($id, $if_real, $snort_uuid); + + /* write out barnyard2_conf */ + $bconf = fopen("/usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/barnyard2.conf", "w"); + if(!$bconf) { + log_error("Could not open /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/barnyard2.conf for writing."); + return; + } + fwrite($bconf, $barnyard2_conf_text); + fclose($bconf); +} + +/* open barnyard2.conf for writing" */ +function generate_barnyard2_conf($id, $if_real, $snort_uuid) { + global $config, $g; + + /* define snortbarnyardlog */ + /* TODO: add support for the other 5 output plugins */ + + $snortbarnyardlog_database_info_chk = $config['installedpackages']['snortglobal']['rule'][$id]['barnyard_mysql']; + $snortbarnyardlog_hostname_info_chk = exec("/bin/hostname"); + /* user add arguments */ + $snortbarnyardlog_config_pass_thru = str_replace("\r", "", base64_decode($config['installedpackages']['snortglobal']['rule'][$id]['barnconfigpassthru'])); + + $barnyard2_conf_text = <<<EOD + +# barnyard2.conf +# barnyard2 can be found at http://www.securixlive.com/barnyard2/index.php +# +# set the appropriate paths to the file(s) your Snort process is using + +config reference_file: /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/reference.config +config classification_file: /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/classification.config +config gen_file: /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/gen-msg.map +config sid_file: /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/sid-msg.map + +config hostname: $snortbarnyardlog_hostname_info_chk +config interface: {$snort_uuid}_{$if_real} +config decode_data_link +config waldo_file: /var/log/snort/{$snort_uuid}_{$if_real}/barnyard2.waldo + +## START user pass through ## + + {$snortbarnyardlog_config_pass_thru} + +## END user pass through ## + +# Step 2: setup the input plugins +input unified2 + +config logdir: /var/log/snort/{$snort_uuid}_{$if_real} + +# database: log to a variety of databases +# output database: log, mysql, user=xxxx password=xxxxxx dbname=xxxx host=xxx.xxx.xxx.xxxx + + $snortbarnyardlog_database_info_chk + +EOD; + + return $barnyard2_conf_text; +} + +function create_snort_conf($id, $if_real, $snort_uuid) +{ + global $config, $g; + + if (!empty($if_real)&& !empty($snort_uuid)) { + if (!is_dir("/usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}")) { + exec("/bin/mkdir -p /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}"); + @touch("/usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/snort.conf"); + } + + $snort_conf_text = generate_snort_conf($id, $if_real, $snort_uuid); + if (empty($snort_conf_text)) + return; + + /* write out snort.conf */ + $conf = fopen("/usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/snort.conf", "w"); + if(!$conf) { + log_error("Could not open /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/snort.conf for writing."); + return -1; + } + fwrite($conf, $snort_conf_text); + fclose($conf); + } +} + +function snort_deinstall() { + global $config, $g; + + /* remove custom sysctl */ + remove_text_from_file("/etc/sysctl.conf", "sysctl net.bpf.bufsize=20480"); + + /* decrease bpf buffers back to 4096, from 20480 */ + exec('/sbin/sysctl net.bpf.bufsize=4096'); + mwexec('/usr/bin/killall snort', true); + sleep(2); + mwexec('/usr/bin/killall -9 snort', true); + sleep(2); + mwexec('/usr/bin/killall barnyard2', true); + sleep(2); + mwexec('/usr/bin/killall -9 barnyard2', true); + sleep(2); + mwexec('/usr/sbin/pw userdel snort; /usr/sbin/pw groupdel snort', true); + mwexec('/bin/rm -rf /usr/local/etc/snort*; /bin/rm -rf /usr/local/pkg/snort*', true); + mwexec('/bin/rm -r /usr/local/bin/barnyard2', true); + mwexec('/bin/rm -rf /usr/local/www/snort; /bin/rm -rf /var/log/snort; /bin/rm -rf /usr/local/lib/snort', true); + + /* Remove snort cron entries Ugly code needs smoothness*/ + if (!function_exists('snort_deinstall_cron')) { + function snort_deinstall_cron($crontask) { + global $config, $g; + + if(!is_array($config['cron']['item'])) + return; + + $x=0; + $is_installed = false; + foreach($config['cron']['item'] as $item) { + if (strstr($item['command'], $crontask)) { + $is_installed = true; + break; + } + $x++; + } + if ($is_installed == true) + unset($config['cron']['item'][$x]); + } + } + + snort_deinstall_cron("snort2c"); + snort_deinstall_cron("snort_check_for_rule_updates.php"); + snort_deinstall_cron("/usr/local/pkg/snort/snort_check_cron_misc.inc"); + configure_cron(); + + /* Unset snort registers in conf.xml IMPORTANT snort will not start with out this */ + /* Keep this as a last step */ + if ($config['installedpackages']['snortglobal']['forcekeepsettings'] != 'on') + unset($config['installedpackages']['snortglobal']); +} + +function generate_snort_conf($id, $if_real, $snort_uuid) +{ + global $config, $g, $snort_pfsense_basever; + + if (!is_array($config['installedpackages']['snortglobal']['rule'])) + return; + + $snortcfg =& $config['installedpackages']['snortglobal']['rule'][$id]; + + /* custom home nets */ + $home_net = create_snort_homenet($id, $if_real); + + if ($snortcfg['externallistname'] == 'default') + $external_net = '!$HOME_NET'; + else + $external_net = create_snort_externalnet($id, $if_real); + + /* obtain external interface */ + /* XXX: make multi wan friendly */ + $snort_ext_int = $snortcfg['interface']; + + /* user added arguments */ + $snort_config_pass_thru = str_replace("\r", "", base64_decode($snortcfg['configpassthru'])); + + /* create basic files */ + if (!is_dir("/usr/local/etc/snort/snort/snort_{$snort_uuid}_{$if_real}")) + exec("/bin/mkdir -p /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}"); + + exec("/bin/cp /usr/local/etc/snort/gen-msg.map /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/gen-msg.map"); + exec("/bin/cp /usr/local/etc/snort/classification.config /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/classification.config"); + exec("/bin/cp /usr/local/etc/snort/reference.config /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/reference.config"); + exec("/bin/cp /usr/local/etc/snort/sid-msg.map /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/sid-msg.map"); + exec("/bin/cp /usr/local/etc/snort/unicode.map /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/unicode.map"); + exec("/bin/cp /usr/local/etc/snort/threshold.conf /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/threshold.conf"); + exec("/usr/bin/touch /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/barnyard2.conf"); + + if (!is_dir("/usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/rules")) + exec("/bin/mkdir -p /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/rules"); + + /* define basic log filename */ + $snortunifiedlogbasic_type = ""; + if ($snortcfg['snortunifiedlogbasic'] == "on") + $snortunifiedlogbasic_type = "output unified: filename snort.u1, limit 128"; + + /* + * + * define cvs log filename + * this should be the default instead of alert_full it is much easier to parse + * + */ + $snortalertcvs_type = ""; + if ($snortcfg['snortalertcvs'] == "on") + $snortalertcvs_type = "output alert_csv: /var/log/snort/{$snort_uuid}_{$if_real}/alert.csv default 128"; + + /* define snortalertlogtype */ + if ($config['installedpackages']['snortglobal']['snortalertlogtype'] == "fast") + $snortalertlogtype_type = "output alert_fast: alert"; + else + $snortalertlogtype_type = "output alert_full: alert"; + + /* define alertsystemlog */ + $alertsystemlog_type = ""; + if ($snortcfg['alertsystemlog'] == "on") + $alertsystemlog_type = "output alert_syslog: log_alert"; + + /* define tcpdumplog */ + $tcpdumplog_type = ""; + if ($snortcfg['tcpdumplog'] == "on") + $tcpdumplog_type = "output log_tcpdump: snort.tcpdump"; + + /* define snortunifiedlog */ + $snortunifiedlog_type = ""; + if ($snortcfg['snortunifiedlog'] == "on") + $snortunifiedlog_type = "output unified2: filename snort.u2, limit 128"; + + /* define spoink */ + $spoink_type = ""; + if ($snortcfg['blockoffenders7'] == "on") { + if ($snortcfg['whitelistname'] == "default") + $spoink_whitelist_name = 'defaultwlist'; + else if (file_exists("/usr/local/etc/snort/whitelist/{$snortcfg['whitelistname']}")) + $spoink_whitelist_name = $snortcfg['whitelistname']; + + $pfkill = ""; + if ($snortcfg['blockoffenderskill'] == "on") + $pfkill = "kill"; + + $spoink_type = "output alert_pf: /usr/local/etc/snort/whitelist/{$spoink_whitelist_name},snort2c,{$snortcfg['blockoffendersip']},{$pfkill}"; + } + + /* define threshold file */ + $threshold_file_name = ""; + if ($snortcfg['suppresslistname'] != 'default') { + if (file_exists("/usr/local/etc/snort/suppress/{$snortcfg['suppresslistname']}")) + $threshold_file_name = "include /usr/local/etc/snort/suppress/{$snortcfg['suppresslistname']}"; + } + + /* define servers and ports snortdefservers */ + /* def DNS_SERVSERS */ + $def_dns_servers_info_chk = $snortcfg['def_dns_servers']; + if ($def_dns_servers_info_chk == "") + $def_dns_servers_type = "\$HOME_NET"; + else + $def_dns_servers_type = "$def_dns_servers_info_chk"; + + /* def DNS_PORTS */ + $def_dns_ports_info_chk = $snortcfg['def_dns_ports']; + if ($def_dns_ports_info_chk == "") + $def_dns_ports_type = "53"; + else + $def_dns_ports_type = "$def_dns_ports_info_chk"; + + /* def SMTP_SERVSERS */ + $def_smtp_servers_info_chk = $snortcfg['def_smtp_servers']; + if ($def_smtp_servers_info_chk == "") + $def_smtp_servers_type = "\$HOME_NET"; + else + $def_smtp_servers_type = "$def_smtp_servers_info_chk"; + + /* def SMTP_PORTS */ + $def_smtp_ports_info_chk = $snortcfg['def_smtp_ports']; + if ($def_smtp_ports_info_chk == "") + $def_smtp_ports_type = "25"; + else + $def_smtp_ports_type = "$def_smtp_ports_info_chk"; + + /* def MAIL_PORTS */ + $def_mail_ports_info_chk = $snortcfg['def_mail_ports']; + if ($def_mail_ports_info_chk == "") + $def_mail_ports_type = "25,143,465,691"; + else + $def_mail_ports_type = "$def_mail_ports_info_chk"; + + /* def HTTP_SERVSERS */ + $def_http_servers_info_chk = $snortcfg['def_http_servers']; + if ($def_http_servers_info_chk == "") + $def_http_servers_type = "\$HOME_NET"; + else + $def_http_servers_type = "$def_http_servers_info_chk"; + + /* def WWW_SERVSERS */ + $def_www_servers_info_chk = $snortcfg['def_www_servers']; + if ($def_www_servers_info_chk == "") + $def_www_servers_type = "\$HOME_NET"; + else + $def_www_servers_type = "$def_www_servers_info_chk"; + + /* def HTTP_PORTS */ + $def_http_ports_info_chk = $snortcfg['def_http_ports']; + if ($def_http_ports_info_chk == "") + $def_http_ports_type = "80"; + else + $def_http_ports_type = "$def_http_ports_info_chk"; + + /* def SQL_SERVSERS */ + $def_sql_servers_info_chk = $snortcfg['def_sql_servers']; + if ($def_sql_servers_info_chk == "") + $def_sql_servers_type = "\$HOME_NET"; + else + $def_sql_servers_type = "$def_sql_servers_info_chk"; + + /* def ORACLE_PORTS */ + $def_oracle_ports_info_chk = $snortcfg['def_oracle_ports']; + if ($def_oracle_ports_info_chk == "") + $def_oracle_ports_type = "1521"; + else + $def_oracle_ports_type = "$def_oracle_ports_info_chk"; + + /* def MSSQL_PORTS */ + $def_mssql_ports_info_chk = $snortcfg['def_mssql_ports']; + if ($def_mssql_ports_info_chk == "") + $def_mssql_ports_type = "1433"; + else + $def_mssql_ports_type = "$def_mssql_ports_info_chk"; + + /* def TELNET_SERVSERS */ + $def_telnet_servers_info_chk = $snortcfg['def_telnet_servers']; + if ($def_telnet_servers_info_chk == "") + $def_telnet_servers_type = "\$HOME_NET"; + else + $def_telnet_servers_type = "$def_telnet_servers_info_chk"; + + /* def TELNET_PORTS */ + $def_telnet_ports_info_chk = $snortcfg['def_telnet_ports']; + if ($def_telnet_ports_info_chk == "") + $def_telnet_ports_type = "23"; + else + $def_telnet_ports_type = "$def_telnet_ports_info_chk"; + + /* def SNMP_SERVSERS */ + $def_snmp_servers_info_chk = $snortcfg['def_snmp_servers']; + if ($def_snmp_servers_info_chk == "") + $def_snmp_servers_type = "\$HOME_NET"; + else + $def_snmp_servers_type = "$def_snmp_servers_info_chk"; + + /* def SNMP_PORTS */ + $def_snmp_ports_info_chk = $snortcfg['def_snmp_ports']; + if ($def_snmp_ports_info_chk == "") + $def_snmp_ports_type = "161"; + else + $def_snmp_ports_type = "$def_snmp_ports_info_chk"; + + /* def FTP_SERVSERS */ + $def_ftp_servers_info_chk = $snortcfg['def_ftp_servers']; + if ($def_ftp_servers_info_chk == "") + $def_ftp_servers_type = "\$HOME_NET"; + else + $def_ftp_servers_type = "$def_ftp_servers_info_chk"; + + /* def FTP_PORTS */ + $def_ftp_ports_info_chk = $snortcfg['def_ftp_ports']; + if ($def_ftp_ports_info_chk == "") + $def_ftp_ports_type = "21"; + else + $def_ftp_ports_type = "$def_ftp_ports_info_chk"; + + /* def SSH_SERVSERS */ + $def_ssh_servers_info_chk = $snortcfg['def_ssh_servers']; + if ($def_ssh_servers_info_chk == "") + $def_ssh_servers_type = "\$HOME_NET"; + else + $def_ssh_servers_type = "$def_ssh_servers_info_chk"; + + /* if user has defined a custom ssh port, use it */ + if(isset($config['system']['ssh']['port'])) + $ssh_port = $config['system']['ssh']['port']; + else + $ssh_port = "22"; + + /* def SSH_PORTS */ + $def_ssh_ports_info_chk = $snortcfg['def_ssh_ports']; + if ($def_ssh_ports_info_chk == "") + $def_ssh_ports_type = "{$ssh_port}"; + else + $def_ssh_ports_type = "$def_ssh_ports_info_chk"; + + /* def POP_SERVSERS */ + $def_pop_servers_info_chk = $snortcfg['def_pop_servers']; + if ($def_pop_servers_info_chk == "") + $def_pop_servers_type = "\$HOME_NET"; + else + $def_pop_servers_type = "$def_pop_servers_info_chk"; + + /* def POP2_PORTS */ + $def_pop2_ports_info_chk = $snortcfg['def_pop2_ports']; + if ($def_pop2_ports_info_chk == "") + $def_pop2_ports_type = "109"; + else + $def_pop2_ports_type = "$def_pop2_ports_info_chk"; + + /* def POP3_PORTS */ + $def_pop3_ports_info_chk = $snortcfg['def_pop3_ports']; + if ($def_pop3_ports_info_chk == "") + $def_pop3_ports_type = "110"; + else + $def_pop3_ports_type = "$def_pop3_ports_info_chk"; + + /* def IMAP_SERVSERS */ + $def_imap_servers_info_chk = $snortcfg['def_imap_servers']; + if ($def_imap_servers_info_chk == "") + $def_imap_servers_type = "\$HOME_NET"; + else + $def_imap_servers_type = "$def_imap_servers_info_chk"; + + /* def IMAP_PORTS */ + $def_imap_ports_info_chk = $snortcfg['def_imap_ports']; + if ($def_imap_ports_info_chk == "") + $def_imap_ports_type = "143"; + else + $def_imap_ports_type = "$def_imap_ports_info_chk"; + + /* def SIP_PROXY_IP */ + $def_sip_proxy_ip_info_chk = $snortcfg['def_sip_proxy_ip']; + if ($def_sip_proxy_ip_info_chk == "") + $def_sip_proxy_ip_type = "\$HOME_NET"; + else + $def_sip_proxy_ip_type = "$def_sip_proxy_ip_info_chk"; + + /* def SIP_PROXY_PORTS */ + $def_sip_proxy_ports_info_chk = $snortcfg['def_sip_proxy_ports']; + if ($def_sip_proxy_ports_info_chk == "") + $def_sip_proxy_ports_type = "5060:5090,16384:32768"; + else + $def_sip_proxy_ports_type = "$def_sip_proxy_ports_info_chk"; + + /* def SIP_SERVERS */ + $def_sip_servers_info_chk = $snortcfg['def_sip_servers']; + if ($def_sip_servers_info_chk == "") + $def_sip_servers_type = "\$HOME_NET"; + else + $def_sip_servers_type = "$def_sip_servers_info_chk"; + + /* def SIP_PORTS */ + $def_sip_ports_info_chk = $snortcfg['def_sip_ports']; + if ($def_sip_ports_info_chk == "") + $def_sip_ports_type = "5060:5090,16384:32768"; + else + $def_sip_ports_type = "$def_sip_ports_info_chk"; + + /* def AUTH_PORTS */ + $def_auth_ports_info_chk = $snortcfg['def_auth_ports']; + if ($def_auth_ports_info_chk == "") + $def_auth_ports_type = "113"; + else + $def_auth_ports_type = "$def_auth_ports_info_chk"; + + /* def FINGER_PORTS */ + $def_finger_ports_info_chk = $snortcfg['def_finger_ports']; + if ($def_finger_ports_info_chk == "") + $def_finger_ports_type = "79"; + else + $def_finger_ports_type = "$def_finger_ports_info_chk"; + + /* def IRC_PORTS */ + $def_irc_ports_info_chk = $snortcfg['def_irc_ports']; + if ($def_irc_ports_info_chk == "") + $def_irc_ports_type = "6665,6666,6667,6668,6669,7000"; + else + $def_irc_ports_type = "$def_irc_ports_info_chk"; + + /* def NNTP_PORTS */ + $def_nntp_ports_info_chk = $snortcfg['def_nntp_ports']; + if ($def_nntp_ports_info_chk == "") + $def_nntp_ports_type = "119"; + else + $def_nntp_ports_type = "$def_nntp_ports_info_chk"; + + /* def RLOGIN_PORTS */ + $def_rlogin_ports_info_chk = $snortcfg['def_rlogin_ports']; + if ($def_rlogin_ports_info_chk == "") + $def_rlogin_ports_type = "513"; + else + $def_rlogin_ports_type = "$def_rlogin_ports_info_chk"; + + /* def RSH_PORTS */ + $def_rsh_ports_info_chk = $snortcfg['def_rsh_ports']; + if ($def_rsh_ports_info_chk == "") + $def_rsh_ports_type = "514"; + else + $def_rsh_ports_type = "$def_rsh_ports_info_chk"; + + /* def SSL_PORTS */ + $def_ssl_ports_info_chk = $snortcfg['def_ssl_ports']; + if ($def_ssl_ports_info_chk == "") + $def_ssl_ports_type = "443,465,563,636,989,990,992,993,994,995"; + else + $def_ssl_ports_type = "$def_ssl_ports_info_chk"; + + /* if user is on pppoe, we really want to use ng0 interface */ + if ($snort_pfsense_basever == 'yes' && $snort_ext_int == "wan") + $snort_ext_int = get_real_wan_interface(); + + /* set the snort performance model */ + if($snortcfg['performance']) + $snort_performance = $snortcfg['performance']; + else + $snort_performance = "ac-bnfa"; + + + /* generate rule sections to load */ + $selected_rules_sections = ""; + if (!empty($snortcfg['rulesets'])) { + $enabled_rulesets_array = explode('||', $snortcfg['rulesets']); + foreach($enabled_rulesets_array as $enabled_item) + $selected_rules_sections .= "include \$RULE_PATH/{$enabled_item}\n"; + } + + /* preprocessor code */ + + /* def perform_stat */ + $snort_perform_stat = <<<EOD + +########################## + # +# NEW # +# Performance Statistics # + # +########################## + +preprocessor perfmonitor: time 300 file /var/log/snort/{$snort_uuid}_{$if_real}/snort.stats pktcnt 10000 + +EOD; + + $def_perform_stat_info_chk = $snortcfg['perform_stat']; + if ($def_perform_stat_info_chk == "on") + $def_perform_stat_type = "$snort_perform_stat"; + else + $def_perform_stat_type = ""; + + $def_flow_depth_info_chk = $snortcfg['flow_depth']; + if (empty($def_flow_depth_info_chk)) + $def_flow_depth_type = '0'; + else + $def_flow_depth_type = $snortcfg['flow_depth']; + + /* def http_inspect */ + $snort_http_inspect = <<<EOD + +################# + # +# HTTP Inspect # + # +################# + +preprocessor http_inspect: global iis_unicode_map unicode.map 1252 compress_depth 65535 decompress_depth 65535 + +# TODO: pfsense GUI needed for ports +preprocessor http_inspect_server: server default \ + http_methods { GET POST PUT SEARCH MKCOL COPY MOVE LOCK UNLOCK NOTIFY POLL BCOPY BDELETE BMOVE LINK UNLINK OPTIONS HEAD DELETE TRACE TRACK CONNECT SOURCE SUBSCRIBE UNSUBSCRIBE PROPFIND PROPPATCH BPROPFIND BPROPPATCH RPC_CONNECT PROXY_SUCCESS BITS_POST CCM_POST SMS_POST RPC_IN_DATA RPC_OUT_DATA RPC_ECHO_DATA } \ + ports { 80 8080 } \ + non_strict \ + non_rfc_char { 0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 } \ + flow_depth {$def_flow_depth_type} \ + apache_whitespace no \ + directory no \ + iis_backslash no \ + u_encode yes \ + extended_response_inspection \ + inspect_gzip \ + normalize_utf \ + unlimited_decompress \ + ascii no \ + chunk_length 500000 \ + bare_byte yes \ + double_decode yes \ + iis_unicode no \ + iis_delimiter no \ + multi_slash no \ + server_flow_depth 0 \ + client_flow_depth 0 \ + post_depth 65495 \ + oversize_dir_length 500 \ + max_header_length 750 \ + max_headers 100 \ + max_spaces 0 \ + small_chunk_length { 10 5 } \ + enable_cookie \ + normalize_javascript \ + utf_8 no \ + webroot no + +EOD; + + $def_http_inspect_info_chk = $snortcfg['http_inspect']; + if ($def_http_inspect_info_chk == "on") + $def_http_inspect_type = "$snort_http_inspect"; + else + $def_http_inspect_type = ""; + + /* def other_preprocs */ + $snort_other_preprocs = <<<EOD + +################## + # +# Other preprocs # + # +################## + +preprocessor rpc_decode: 111 32770 32771 32772 32773 32774 32775 32776 32777 32778 32779 +preprocessor bo + +EOD; + + $def_other_preprocs_info_chk = $snortcfg['other_preprocs']; + if ($def_other_preprocs_info_chk == "on") + $def_other_preprocs_type = "$snort_other_preprocs"; + else + $def_other_preprocs_type = ""; + + /* def ftp_preprocessor */ + $snort_ftp_preprocessor = <<<EOD + +##################### + # +# ftp preprocessor # + # +##################### + +preprocessor ftp_telnet: global \ + inspection_type stateful \ + encrypted_traffic no + +preprocessor ftp_telnet_protocol: telnet \ + normalize \ + ayt_attack_thresh 200 \ + detect_anomalies + +preprocessor ftp_telnet_protocol: \ + ftp server default \ + def_max_param_len 100 \ + # TODO add pfsense GUI + ports { 21 } \ + telnet_cmds yes \ + 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 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 { 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 ] } > + +preprocessor ftp_telnet_protocol: ftp client default \ + max_resp_len 256 \ + bounce yes \ + telnet_cmds yes + +EOD; + + $def_ftp_preprocessor_info_chk = $snortcfg['ftp_preprocessor']; + if ($def_ftp_preprocessor_info_chk == "on") + $def_ftp_preprocessor_type = "$snort_ftp_preprocessor"; + else + $def_ftp_preprocessor_type = ""; + + /* def smtp_preprocessor */ + $snort_smtp_preprocessor = <<<EOD + +##################### + # +# SMTP preprocessor # + # +##################### + +# TODO add pfsense GUI +preprocessor SMTP: ports { 25 465 691 } \ + inspection_type stateful \ + b64_decode_depth 0 \ + qp_decode_depth 0 \ + bitenc_decode_depth 0 \ + uu_decode_depth 0 \ + log_mailfrom \ + log_rcptto \ + log_filename \ + log_email_hdrs \ + normalize cmds \ + normalize_cmds { ATRN AUTH BDAT CHUNKING DATA DEBUG EHLO EMAL ESAM ESND ESOM ETRN EVFY } \ + normalize_cmds { EXPN HELO HELP IDENT MAIL NOOP ONEX QUEU QUIT RCPT RSET SAML SEND SOML } \ + normalize_cmds { STARTTLS TICK TIME TURN TURNME VERB VRFY X-ADAT X-DRCP X-ERCP X-EXCH50 } \ + normalize_cmds { X-EXPS X-LINK2STATE XADR XAUTH XCIR XEXCH50 XGEN XLICENSE XQUE XSTA XTRN XUSR } \ + max_command_line_len 512 \ + 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 DATA RSET QUIT ONEX QUEU STARTTLS TICK TIME TURNME VERB X-EXPS X-LINK2STATE XADR XAUTH XCIR XEXCH50 XGEN XLICENSE XQUE XSTA XTRN XUSR } \ + valid_cmds { ATRN AUTH BDAT CHUNKING DATA DEBUG EHLO EMAL ESAM ESND ESOM ETRN EVFY } \ + valid_cmds { EXPN HELO HELP IDENT MAIL NOOP ONEX QUEU QUIT RCPT RSET SAML SEND SOML } \ + valid_cmds { STARTTLS TICK TIME TURN TURNME VERB VRFY X-ADAT X-DRCP X-ERCP X-EXCH50 } \ + valid_cmds { X-EXPS X-LINK2STATE XADR XAUTH XCIR XEXCH50 XGEN XLICENSE XQUE XSTA XTRN XUSR } \ + xlink2state { enabled } + +EOD; + + $def_smtp_preprocessor_info_chk = $snortcfg['smtp_preprocessor']; + if ($def_smtp_preprocessor_info_chk == "on") + $def_smtp_preprocessor_type = "$snort_smtp_preprocessor"; + else + $def_smtp_preprocessor_type = ""; + + /* def sf_portscan */ + $snort_sf_portscan = <<<EOD + +################ + # +# sf Portscan # + # +################ + +preprocessor sfportscan: scan_type { all } \ + proto { all } \ + memcap { 10000000 } \ + sense_level { medium } \ + ignore_scanners { \$HOME_NET } + +EOD; + + $def_sf_portscan_info_chk = $snortcfg['sf_portscan']; + if ($def_sf_portscan_info_chk == "on") + $def_sf_portscan_type = "$snort_sf_portscan"; + else + $def_sf_portscan_type = ""; + + /* def dce_rpc_2 */ + $snort_dce_rpc_2 = <<<EOD + +############### + # +# NEW # +# DCE/RPC 2 # + # +############### + +preprocessor dcerpc2: memcap 102400, events [smb, co, cl] +preprocessor dcerpc2_server: default, policy WinXP, \ + detect [smb [139,445], 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_dce_rpc_2_info_chk = $snortcfg['dce_rpc_2']; + if ($def_dce_rpc_2_info_chk == "on") + $def_dce_rpc_2_type = "$snort_dce_rpc_2"; + else + $def_dce_rpc_2_type = ""; + + /* def dns_preprocessor */ + $snort_dns_preprocessor = <<<EOD + +#################### + # +# DNS preprocessor # + # +#################### + +# TODO add pfsense GUI +preprocessor dns: \ + ports { 53 } \ + enable_rdata_overflow + +EOD; + + $def_dns_preprocessor_info_chk = $snortcfg['dns_preprocessor']; + if ($def_dns_preprocessor_info_chk == "on") + $def_dns_preprocessor_type = "$snort_dns_preprocessor"; + else + $def_dns_preprocessor_type = ""; + + /* def SSL_PORTS IGNORE */ + $def_ssl_ports_ignore_info_chk = $snortcfg['def_ssl_ports_ignore']; + if ($def_ssl_ports_ignore_info_chk == "") + $def_ssl_ports_ignore_type = "443 465 563 636 989 990 992 993 994 995"; + else + $def_ssl_ports_ignore_type = "$def_ssl_ports_ignore_info_chk"; + + /* stream5 queued settings */ + + + $def_max_queued_bytes_info_chk = $snortcfg['max_queued_bytes']; + if ($def_max_queued_bytes_info_chk == '') + $def_max_queued_bytes_type = ''; + else + $def_max_queued_bytes_type = ' max_queued_bytes ' . $snortcfg['max_queued_bytes'] . ','; + + $def_max_queued_segs_info_chk = $snortcfg['max_queued_segs']; + if ($def_max_queued_segs_info_chk == '') + $def_max_queued_segs_type = ''; + else + $def_max_queued_segs_type = ' max_queued_segs ' . $snortcfg['max_queued_segs'] . ','; + + /* build snort configuration file */ + $snort_conf_text = <<<EOD + +############################################################################## +# # +# snort configuration file generated by the pfSense package manager system # +# see /usr/local/pkg/snort.inc # +# for snort ver. 2.9.2.3 # +# more information Snort can be found at http://www.snort.org/ # +# # +############################################################################## + +######################### + # +# Define Local Network # + # +######################### + +ipvar HOME_NET [{$home_net}] +ipvar EXTERNAL_NET [{$external_net}] + +################### + # +# Define Servers # + # +################### + +ipvar DNS_SERVERS [{$def_dns_servers_type}] +ipvar SMTP_SERVERS [{$def_smtp_servers_type}] +ipvar HTTP_SERVERS [{$def_http_servers_type}] +ipvar SQL_SERVERS [{$def_sql_servers_type}] +ipvar TELNET_SERVERS [{$def_telnet_servers_type}] +ipvar FTP_SERVERS [{$def_ftp_servers_type}] +ipvar SSH_SERVERS [{$def_ssh_servers_type}] +ipvar SIP_PROXY_IP [{$def_sip_proxy_ip_type}] +ipvar SIP_SERVERS [{$def_sip_servers_type}] +ipvar 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] +# def below may have been removed +ipvar POP_SERVERS [{$def_pop_servers_type}] +ipvar IMAP_SERVERS [{$def_imap_servers_type}] +ipvar RPC_SERVERS [\$HOME_NET] +ipvar WWW_SERVERS [{$def_www_servers_type}] +ipvar SNMP_SERVERS [{$def_snmp_servers_type}] + + +######################## + # +# Define Server Ports # + # +######################## + +portvar HTTP_PORTS [{$def_http_ports_type}] +portvar SHELLCODE_PORTS !80 +portvar ORACLE_PORTS [{$def_oracle_ports_type}] +portvar FTP_PORTS [{$def_ftp_ports_type}] +portvar SSH_PORTS [{$def_ssh_ports_type}] +portvar SIP_PORTS [{$def_sip_ports_type}] +### Below ports need new gui ### +portvar FILE_DATA_PORTS [\$HTTP_PORTS,110,143] +portvar GTP_PORTS [2123,2152,3386] +portvar MODBUS_PORTS [502] +portvar DNP3_PORTS [20000] +# These ports may have been removed left here so no custom rules break +portvar AUTH_PORTS [{$def_auth_ports_type}] +portvar DNS_PORTS [{$def_dns_ports_type}] +portvar FINGER_PORTS [{$def_finger_ports_type}] +portvar IMAP_PORTS [{$def_imap_ports_type}] +portvar IRC_PORTS [{$def_irc_ports_type}] +portvar MSSQL_PORTS [{$def_mssql_ports_type}] +portvar NNTP_PORTS [{$def_nntp_ports_type}] +portvar POP2_PORTS [{$def_pop2_ports_type}] +portvar POP3_PORTS [{$def_pop3_ports_type}] +portvar SUNRPC_PORTS [111,32770,32771,32772,32773,32774,32775,32776,32777,32778,32779] +portvar RLOGIN_PORTS [{$def_rlogin_ports_type}] +portvar RSH_PORTS [{$def_rsh_ports_type}] +portvar SMB_PORTS [139,445] +portvar SMTP_PORTS [{$def_smtp_ports_type}] +portvar SNMP_PORTS [{$def_snmp_ports_type}] +portvar TELNET_PORTS [{$def_telnet_ports_type}] +portvar MAIL_PORTS [{$def_mail_ports_type}] +portvar SSL_PORTS [{$def_sip_proxy_ports_type}] +portvar SIP_PROXY_PORTS [{$def_sip_ports_type}] + +# These ports may have been removed left here so no custom rules break +# DCERPC NCACN-IP-TCP +portvar DCERPC_NCACN_IP_TCP [139,445] +portvar DCERPC_NCADG_IP_UDP [138,1024:] +portvar DCERPC_NCACN_IP_LONG [135,139,445,593,1024:] +portvar DCERPC_NCACN_UDP_LONG [135,1024:] +portvar DCERPC_NCACN_UDP_SHORT [135,593,1024:] +portvar DCERPC_NCACN_TCP [2103,2105,2107] +portvar DCERPC_BRIGHTSTORE [6503,6504] + + +##################### + # +# Define Rule Paths # + # +##################### + +var RULE_PATH /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/rules +var PREPROC_RULE_PATH /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/preproc_rules +var SO_RULE_PATH /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/so_rules + +############################################################# +# # +# reputation preprocessor, ALWAYS USE FULL PATHS, BUG 89986 # +# # +############################################################# + +#var WHITE_LIST_PATH ../rules +#var BLACK_LIST_PATH ../rules + +################################ + # +# Configure the snort decoder # + # +################################ + +config checksum_mode: all +config disable_decode_alerts +config disable_tcpopt_experimental_alerts +config disable_tcpopt_obsolete_alerts +config disable_ttcp_alerts +config disable_tcpopt_alerts +config disable_tcpopt_ttcp_alerts +config disable_ipopt_alerts +config disable_decode_drops + +################ The following is for inline mode tunning ################ + +# config enable_decode_oversized_alerts +# config enable_decode_oversized_drops +# config flowbits_size: 64 + +#### make sure I enable gui for this ########## +# config ignore_ports: tcp 21 6667:6671 1356 # +# config ignore_ports: udp 1:17 53 # +############################################### + +# Configure active response for non inline +# config response: eth0 attempts 2 + +# Configure DAQ related options for inline mode +# +# config daq: <type> +# config daq_dir: <dir> +# config daq_mode: <mode> +# config daq_var: <var> +# +# <type> ::= pcap | afpacket | dump | nfq | ipq | ipfw +# <mode> ::= read-file | passive | inline +# <var> ::= arbitrary <name>=<value passed to DAQ +# <dir> ::= path as to where to look for DAQ module so's + +## gui needed for pfsense ## +# config daq: afpacket + +############################################################# + +######################################## +# Configure specific UID and GID +# to run snort as after dropping privs +# +# config set_gid: +# config set_uid: +######################################## + +######################################## +# +# Configure default snaplen. Snort +# defaults to MTU of in use interface +# +# config snaplen: +# +# TODO: gui needed for pfsense +# +######################################## + +################################################################ +# +# Configure default bpf_file to use for filtering what traffic +# reaches snort. options (-F) +# +# config bpf_file: +# +# TODO: gui needed for pfsense +# +############################################################### + +##################################################################### +# +# Configure default log directory for snort to log to. options (-l) +# +# config logdir: +# +##################################################################### + +################################### + # +# Configure the detection engine # +# Use lower memory models # + # +################################### + +# TODO: gui needed for pfsense +# Configure PCRE match limitations +config pcre_match_limit: 3500 +config pcre_match_limit_recursion: 1500 + +############################################################################# +# # +# Configure the detection engine # +# Use lower memory models for pfsense # +# # +# # +# Notes # +# # +# ac, ac-q, ac-bnfa, ac-bnfa-q, lowmem, lowmem-q # +# ac-split shorthand for search-method ac, split-any-any, intel-cpm,ac-nq, # +# ac-bnfa-nq This is the default search method if none is specified. # +# lowmem-nq, ac-std, acs, ac-banded, ac-sparsebands # +# # +############################################################################# + +config detection: search-method {$snort_performance} search-optimize max-pattern-len 20 +config event_queue: max_queue 8 log 3 order_events content_length + +################################################### +# Configure GTP if it is to be used +#################################################### + +# TODO: gui needed for pfsense +# config enable_gtp + +################################################### +# Per packet and rule latency enforcement, README.ppm +################################################### + +# Per Packet latency configuration +#config ppm: max-pkt-time 250, \ +# fastpath-expensive-packets, \ +# pkt-log + +# Per Rule latency configuration +#config ppm: max-rule-time 200, \ +# threshold 3, \ +# suspend-expensive-rules, \ +# suspend-timeout 20, \ +# rule-log alert + +################################################### +# Configure Perf Profiling for debugging, README.PerfProfiling +################################################### + +#config profile_rules: print all, sort avg_ticks +#config profile_preprocs: print all, sort avg_ticks + +################################################### +# Configure protocol aware flushing. README.stream5 +################################################### +config paf_max: 16000 + +################################################## +# Configure dynamic loaded libraries +################################################## + +dynamicpreprocessor directory /usr/local/lib/snort/dynamicpreprocessor +dynamicengine /usr/local/lib/snort/dynamicengine/libsf_engine.so +dynamicdetection directory /usr/local/lib/snort/dynamicrules + +################### + # +# Flow and stream # + # +################### + +# TODO: gui needed for pfsense +# GTP Control Channle Preprocessor, README.GTP +# preprocessor gtp: ports { 2123 3386 2152 } + +#################################################### +# Inline packet normalization, README.normalize +# Does nothing in IDS mode +# +# preprocessor normalize_ip4 +# preprocessor normalize_tcp: ips ecn stream +# preprocessor normalize_icmp4 +# preprocessor normalize_ip6 +# preprocessor normalize_icmp6 +#################################################### + +# this tuning ,may need testing +preprocessor frag3_global: max_frags 65536 +preprocessor frag3_engine: policy bsd detect_anomalies + +preprocessor stream5_global: track_tcp yes, track_udp yes, track_icmp yes, max_tcp 262144, max_udp 131072, max_active_responses 2, min_response_seconds 5 + +preprocessor stream5_tcp: policy BSD, ports both all, timeout 180, {$def_max_queued_bytes_type}{$def_max_queued_segs_type} +preprocessor stream5_udp: timeout 180 +preprocessor stream5_icmp: + + {$def_perform_stat_type} + + {$def_http_inspect_type} + + {$def_other_preprocs_type} + + {$def_ftp_preprocessor_type} + + {$def_smtp_preprocessor_type} + + {$def_sf_portscan_type} + +######################## + # +# ARP spoof detection. # + # +######################## + +# preprocessor arpspoof +# preprocessor arpspoof_detect_host: 192.168.40.1 f0:0f:00:f0:0f:00 + +########################## + # +# SSH anomaly detection # + # +########################## + +preprocessor ssh: server_ports { 22 } \ + autodetect \ + max_client_bytes 19600 \ + max_encrypted_packets 20 \ + max_server_version_len 100 \ + enable_respoverflow enable_ssh1crc32 \ + enable_srvoverflow enable_protomismatch + + + {$def_dce_rpc_2_type} + + {$def_dns_preprocessor_type} + +############################## + # +# NEW # +# Ignore SSL and Encryption # + # +############################## + +preprocessor ssl: ports { {$def_ssl_ports_ignore_type} }, trustservers, noinspect_encrypted + + +########################################################### + # +# SDF sensitive data preprocessor, README.sensitive_data # + # +########################################################### + +# TODO: add pfsense GUI +preprocessor sensitive_data: alert_threshold 20 + +############################################################# + # +# SIP Session Initiation Protocol preprocessor, README.sip # + # +############################################################# + +# TODO: add pfsense GUI +preprocessor sip: max_sessions 40000, \ + ports { 5060 5061 5600 }, \ + methods { invite \ + cancel \ + ack \ + bye \ + register \ + options \ + refer \ + subscribe \ + update \ + join \ + info \ + message \ + notify \ + benotify \ + do \ + qauth \ + sprack \ + publish \ + service \ + unsubscribe \ + prack }, \ + max_uri_len 512, \ + max_call_id_len 80, \ + max_requestName_len 20, \ + max_from_len 256, \ + max_to_len 256, \ + max_via_len 1024, \ + max_contact_len 512, \ + max_content_len 2048 + +################################## + # +# IMAP preprocessor, README.imap # + # +################################## + +# TODO: add pfsense GUI +preprocessor imap: \ + ports { 143 } \ + b64_decode_depth 0 \ + qp_decode_depth 0 \ + bitenc_decode_depth 0 \ + uu_decode_depth 0 + +################################## + # +# POP preprocessor, README.pop # + # +################################## + +# TODO: add pfsense GUI +preprocessor pop: \ + ports { 110 } \ + b64_decode_depth 0 \ + qp_decode_depth 0 \ + bitenc_decode_depth 0 \ + uu_decode_depth 0 + +####################################### + # +# Modbus preprocessor, README.modbus # +# Used for SCADA # + # +####################################### + +# TODO: add pfsense GUI +preprocessor modbus: ports { 502 } + + +############################################### + # +# DNP3 preprocessor, EADME.dnp3 # + # +############################################### + +# TODO: add pfsense GUI +preprocessor dnp3: ports { 20000 } \ + memcap 262144 \ + check_crc + +############################################### + # +# Reputation preprocessor, README.reputation # + # +############################################### + +#preprocessor reputation: \ +# memcap 500, \ +# priority whitelist, \ +# nested_ip inner, \ +# whitelist \$WHITE_LIST_PATH/white_list.rules, \ +# blacklist \$BLACK_LIST_PATH/black_list.rules + + +##################### + # +# Snort Output Logs # + # +##################### + +$snortalertlogtype_type +$alertsystemlog_type +$tcpdumplog_type +$snortunifiedlogbasic_type +$snortunifiedlog_type +$snortalertcvs_type +$spoink_type + +################# + # +# Misc Includes # + # +################# + +include /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/reference.config +include /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/classification.config +$threshold_file_name + +# Snort user pass through configuration +{$snort_config_pass_thru} + +################### + # +# Rules Selection # + # +################### + + +{$selected_rules_sections} + + +EOD; + + return $snort_conf_text; +} + +/* hide progress bar */ +function hide_progress_bar_status() { + global $snort_filename, $snort_filename_md5, $console_mode; + + ob_flush(); + if(!$console_mode) + echo "\n<script type=\"text/javascript\">document.progressbar.style.visibility='hidden';\n</script>"; +} + +/* unhide progress bar */ +function unhide_progress_bar_status() { + global $snort_filename, $snort_filename_md5, $console_mode; + + ob_flush(); + if(!$console_mode) + echo "\n<script type=\"text/javascript\">document.progressbar.style.visibility='visible';\n</script>"; +} + +/* update both top and bottom text box during an operation */ +function update_all_status($status) { + global $snort_filename, $snort_filename_md5, $console_mode; + + ob_flush(); + if(!$console_mode) { + update_status($status); + update_output_window($status); + } +} + +######## new + +// returns array that matches pattern, option to replace objects in matches +function snortScanDirFilter($arrayList, $pattmatch, $pattreplace, $pattreplacewith) +{ + foreach ( $arrayList as $val ) + { + if (preg_match($pattmatch, $val, $matches)) { + if ($pattreplace != '') { + $matches2 = preg_replace($pattreplace, $pattreplacewith, $matches[0]); + $filterDirList[] = $matches2; + }else{ + $filterDirList[] = $matches[0]; + } + } + } + return $filterDirList; +} + +?> diff --git a/config/snort-dev/snort.xml b/config/snort-dev/snort.xml index 207fae8b..4f687c9c 100644 --- a/config/snort-dev/snort.xml +++ b/config/snort-dev/snort.xml @@ -7,7 +7,10 @@ /* $Id$ */ /* ========================================================================== */ /* + authng.xml part of pfSense (http://www.pfsense.com) + Copyright (C) 2007 to whom it may belong + All rights reserved. Based on m0n0wall (http://m0n0.ch/wall) Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. @@ -15,37 +18,26 @@ */ /* ========================================================================== */ /* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - Pfsense Old snort GUI - Copyright (C) 2006 Scott Ullrich. - - Pfsense snort GUI - Copyright (C) 2008-2012 Robert Zelaya. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. + 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. + 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. - 3. Neither the name of the pfSense nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - 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 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. */ /* ========================================================================== */ ]]> @@ -53,12 +45,12 @@ <description>Describe your package here</description> <requirements>Describe your package requirements here</requirements> <faq>Currently there are no FAQ items provided.</faq> - <name>Orion</name> - <version>2.9.1</version> - <title>Services:2.9.1 pkg v. 2.0</title> - <include_file>/usr/local/pkg/snort/snort_install.inc</include_file> + <name>Snort</name> + <version>2.9.2.3</version> + <title>Services:2.9.2.3 pkg v. 2.2</title> + <include_file>/usr/local/pkg/snort/snort.inc</include_file> <menu> - <name>Orion</name> + <name>Snort</name> <tooltiptext>Setup snort specific settings</tooltiptext> <section>Services</section> <url>/snort/snort_interfaces.php</url> @@ -67,64 +59,45 @@ <name>snort</name> <rcfile>snort.sh</rcfile> <executable>snort</executable> - <description>Snort is the most widely deployed IDS/IPS technology worldwide.</description> + <description>Snort is the most widely deployed IDS/IPS technology + worldwide.</description> </service> <tabs> </tabs> <additional_files_needed> <prefix>/usr/local/pkg/snort/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort.xml</item> - </additional_files_needed> - <additional_files_needed> - <prefix>/usr/local/pkg/snort/</prefix> - <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snortDB</item> - </additional_files_needed> - <additional_files_needed> - <prefix>/usr/local/pkg/snort/</prefix> - <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snortDBrules</item> - </additional_files_needed> - <additional_files_needed> - <prefix>/usr/local/pkg/snort/</prefix> - <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snortDBtemp</item> - </additional_files_needed> - <additional_files_needed> - <prefix>/usr/local/pkg/snort/</prefix> - <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_build.inc</item> + <item>http://www.pfsense.com/packages/config/snort-dev/snort.inc</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/snort/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_download_rules.inc</item> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_gui.inc</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/snort/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_gui.inc</item> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_check_cron_misc.inc</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/pkg/snort/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_head.inc</item> - </additional_files_needed> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_startstop.php</item> + </additional_files_needed> <additional_files_needed> - <prefix>/usr/local/pkg/snort/</prefix> + <prefix>/usr/local/bin/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_headbase.inc</item> + <item>http://www.pfsense.com/packages/config/snort-dev/bin/oinkmaster_contrib/create-sidmap.pl</item> </additional_files_needed> <additional_files_needed> - <prefix>/usr/local/pkg/snort/</prefix> + <prefix>/usr/local/bin/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_install.inc</item> + <item>http://www.pfsense.com/packages/config/snort-dev/bin/oinkmaster_contrib/oinkmaster.pl</item> </additional_files_needed> <additional_files_needed> - <prefix>/usr/local/pkg/snort/</prefix> + <prefix>/usr/local/bin/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_new.inc</item> + <item>http://www.pfsense.com/packages/config/snort-dev/bin/oinkmaster_contrib/snort_rename.pl</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/www/snort/</prefix> @@ -149,67 +122,52 @@ <additional_files_needed> <prefix>/usr/local/www/snort/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_download_updates.php</item> - </additional_files_needed> - <additional_files_needed> - <prefix>/usr/local/www/snort/</prefix> - <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_help_info.php</item> - </additional_files_needed> - <additional_files_needed> - <prefix>/usr/local/www/snort/</prefix> - <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces.php</item> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_download_rules.php</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/www/snort/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_edit.php</item> - </additional_files_needed> - <additional_files_needed> - <prefix>/usr/local/www/snort/</prefix> - <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_global.php</item> + <item>http://www.pfsense.com/packages/config/snort-dev/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>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_rules.php</item> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_check_for_rule_updates.php</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/www/snort/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_rules_edit.php</item> + <item>http://www.pfsense.com/packages/config/snort-dev/help_and_info.php</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/www/snort/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_suppress.php</item> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces.php</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/www/snort/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_suppress_edit.php</item> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_edit.php</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/www/snort/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_whitelist.php</item> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_global.php</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/www/snort/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_whitelist_edit.php</item> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_rules.php</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/www/snort/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_json_get.php</item> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_rules_edit.php</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/www/snort/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_json_post.php</item> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_rulesets.php</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/www/snort/</prefix> @@ -219,49 +177,29 @@ <additional_files_needed> <prefix>/usr/local/www/snort/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_rules.php</item> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_whitelist.php</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/www/snort/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_rulesets.php</item> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_whitelist_edit.php</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/www/snort/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_rules_ips.php</item> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_suppress.php</item> </additional_files_needed> <additional_files_needed> <prefix>/usr/local/www/snort/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort-dev/snort_rulesets_ips.php</item> - </additional_files_needed> - <additional_files_needed> - <prefix>/usr/local/bin/</prefix> - <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort/bin/oinkmaster_contrib/create-sidmap.pl</item> - </additional_files_needed> - <additional_files_needed> - <prefix>/usr/local/bin/</prefix> - <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort/bin/oinkmaster_contrib/make_snortsam_map.pl</item> - </additional_files_needed> - <additional_files_needed> - <prefix>/usr/local/bin/</prefix> - <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort/bin/oinkmaster_contrib/oinkmaster.pl</item> - </additional_files_needed> - <additional_files_needed> - <prefix>/usr/local/bin/</prefix> - <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort/bin/oinkmaster_contrib/snort_rename.pl</item> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_suppress_edit.php</item> </additional_files_needed> <fields> </fields> <custom_add_php_command> </custom_add_php_command> <custom_php_resync_config_command> - sync_snort_package(); + sync_snort_package_config(); </custom_php_resync_config_command> <custom_php_install_command> snort_postinstall(); diff --git a/config/snort-dev/snort_alerts.php b/config/snort-dev/snort_alerts.php index 3cb79c5c..3eafcf21 100644 --- a/config/snort-dev/snort_alerts.php +++ b/config/snort-dev/snort_alerts.php @@ -1,18 +1,16 @@ <?php /* $Id$ */ /* - + snort_alerts.php part of pfSense - All rights reserved. + Copyright (C) 2005 Bill Marquette <bill.marquette@gmail.com>. Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + Copyright (C) 2006 Scott Ullrich All rights reserved. - Pfsense Old snort GUI - Copyright (C) 2006 Scott Ullrich. - - Pfsense snort GUI - Copyright (C) 2008-2012 Robert Zelaya. + Modified for the Pfsense snort package v. 1.8+ + Copyright (C) 2009 Robert Zelaya Sr. Developer Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -24,10 +22,6 @@ notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - 3. Neither the name of the pfSense nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - 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 @@ -38,152 +32,556 @@ 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_new.inc"); require_once("/usr/local/pkg/snort/snort_gui.inc"); +require_once("/usr/local/pkg/snort/snort.inc"); + +/* load only javascript that is needed */ +$snort_load_sortabletable = 'yes'; +$snort_load_mootools = 'yes'; + +$snortalertlogt = $config['installedpackages']['snortglobal']['snortalertlogtype']; + +if (!is_array($config['installedpackages']['snortglobal']['rule'])) + $config['installedpackages']['snortglobal']['rule'] = array(); +$a_instance = &$config['installedpackages']['snortglobal']['rule']; +$snort_uuid = $a_instance[0]['uuid']; +$if_real = snort_get_real_interface($a_instance[0]['interface']); + +if ($_POST['instance']) { + $snort_uuid = $a_instance[$_POST]['instance']['uuid']; + $if_real = snort_get_real_interface($a_instance[$_POST]['instance']['interface']); +} + + +if (is_array($config['installedpackages']['snortglobal']['alertsblocks'])) { + $pconfig['arefresh'] = $config['installedpackages']['snortglobal']['alertsblocks']['arefresh']; + $pconfig['alertnumber'] = $config['installedpackages']['snortglobal']['alertsblocks']['alertnumber']; + $anentries = $pconfig['alertnumber']; +} else { + $anentries = '250'; + $pconfig['alertnumber'] = '250'; + $pconfig['arefresh'] = 'off'; +} + +if ($_POST['save']) +{ + //unset($input_errors); + //$pconfig = $_POST; + + /* input validation */ + if ($_POST['save']) + { + + // if (($_POST['radiusacctport'] && !is_port($_POST['radiusacctport']))) { + // $input_errors[] = "A valid port number must be specified. [".$_POST['radiusacctport']."]"; + // } + + } + + /* no errors */ + if (!$input_errors) { + if (!is_array($config['installedpackages']['snortglobal']['alertsblocks'])) + $config['installedpackages']['snortglobal']['alertsblocks'] = array(); + $config['installedpackages']['snortglobal']['alertsblocks']['arefresh'] = $_POST['arefresh'] ? 'on' : 'off'; + $config['installedpackages']['snortglobal']['alertsblocks']['alertnumber'] = $_POST['alertnumber']; + + write_config(); + + header("Location: /snort/snort_alerts.php"); + exit; + } + +} + +if ($_GET['action'] == "clear" || $_POST['clear']) +{ + if (file_exists("/var/log/snort/{$snort_uuid}_{$if_real}/alert")) + { + conf_mount_rw(); + @file_put_contents("/var/log/snort/{$snort_uuid}_{$if_real}/alert", ""); + post_delete_logs(); + /* XXX: This is needed is snort is run as snort user */ + //mwexec('/usr/sbin/chown snort:snort /var/log/snort/*', true); + mwexec('/bin/chmod 660 /var/log/snort/*', true); + mwexec('/usr/bin/killall -HUP snort', true); + conf_mount_ro(); + } + header("Location: /snort/snort_alerts.php"); + exit; +} + +if ($_POST['download']) +{ + + $save_date = exec('/bin/date "+%Y-%m-%d-%H-%M-%S"'); + $file_name = "snort_logs_{$save_date}.tar.gz"; + exec("/usr/bin/tar cfz /tmp/{$file_name} /var/log/snort/{$snort_uuid}_{$if_real}"); + + if (file_exists("/tmp/{$file_name}")) { + $file = "/tmp/snort_logs_{$save_date}.tar.gz"; + header("Expires: Mon, 26 Jul 1997 05:00:00 GMT\n"); + header("Pragma: private"); // needed for IE + header("Cache-Control: private, must-revalidate"); // needed for IE + header('Content-type: application/force-download'); + header('Content-Transfer-Encoding: Binary'); + header("Content-length: ".filesize($file)); + header("Content-disposition: attachment; filename = {$file_name}"); + readfile("$file"); + exec("/bin/rm /tmp/{$file_name}"); + } + + header("Location: /snort/snort_alerts.php"); + exit; +} + + +/* WARNING: took me forever to figure reg expression, dont lose */ +// $fileline = '12/09-18:12:02.086733 [**] [122:6:0] (portscan) TCP Filtered Decoy Portscan [**] [Priority: 3] {PROTO:255} 125.135.214.166 -> 70.61.243.50'; +function get_snort_alert_date($fileline) +{ + /* date full date \d+\/\d+-\d+:\d+:\d+\.\d+\s */ + if (preg_match("/\d+\/\d+-\d+:\d+:\d\d/", $fileline, $matches1)) + $alert_date = "$matches1[0]"; + + return $alert_date; +} + +function get_snort_alert_disc($fileline) +{ + /* disc */ + if (preg_match("/\[\*\*\] (\[.*\]) (.*) (\[\*\*\])/", $fileline, $matches)) + $alert_disc = "$matches[2]"; + + return $alert_disc; +} -//Set no caching -header("Expires: Mon, 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"); +function get_snort_alert_class($fileline) +{ + /* class */ + if (preg_match('/\[Classification:\s.+[^\d]\]/', $fileline, $matches2)) + $alert_class = "$matches2[0]"; -$generalSettings = snortSql_fetchAllSettings('snortDB', 'SnortSettings', 'id', '1'); + return $alert_class; +} -$alertnumber = $generalSettings['alertnumber']; +function get_snort_alert_priority($fileline) +{ + /* Priority */ + if (preg_match('/Priority:\s\d/', $fileline, $matches3)) + $alert_priority = "$matches3[0]"; -$arefresh_on = ($generalSettings['arefresh'] == 'on' ? 'checked' : ''); + return $alert_priority; +} - $pgtitle = "Services: Snort: Alerts"; - include("/usr/local/pkg/snort/snort_head.inc"); +function get_snort_alert_proto($fileline) +{ + /* Priority */ + if (preg_match('/\{.+\}/', $fileline, $matches3)) + $alert_proto = "$matches3[0]"; + + return $alert_proto; +} + +function get_snort_alert_proto_full($fileline) +{ + /* Protocal full */ + if (preg_match('/.+\sTTL/', $fileline, $matches2)) + $alert_proto_full = "$matches2[0]"; + + return $alert_proto_full; +} + +function get_snort_alert_ip_src($fileline) +{ + /* SRC IP */ + $re1='.*?'; # Non-greedy match on filler + $re2='((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?![\\d])'; # IPv4 IP Address 1 + + if ($c=preg_match_all ("/".$re1.$re2."/is", $fileline, $matches4)) + $alert_ip_src = $matches4[1][0]; + + return $alert_ip_src; +} + +function get_snort_alert_src_p($fileline) +{ + /* source port */ + if (preg_match('/:\d+\s-/', $fileline, $matches5)) + $alert_src_p = "$matches5[0]"; + + return $alert_src_p; +} + +function get_snort_alert_flow($fileline) +{ + /* source port */ + if (preg_match('/(->|<-)/', $fileline, $matches5)) + $alert_flow = "$matches5[0]"; + + return $alert_flow; +} + +function get_snort_alert_ip_dst($fileline) +{ + /* DST IP */ + $re1dp='.*?'; # Non-greedy match on filler + $re2dp='(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?![\\d])'; # Uninteresting: ipaddress + $re3dp='.*?'; # Non-greedy match on filler + $re4dp='((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?![\\d])'; # IPv4 IP Address 1 + + if ($c=preg_match_all ("/".$re1dp.$re2dp.$re3dp.$re4dp."/is", $fileline, $matches6)) + $alert_ip_dst = $matches6[1][0]; + + return $alert_ip_dst; +} + +function get_snort_alert_dst_p($fileline) +{ + /* dst port */ + if (preg_match('/:\d+$/', $fileline, $matches7)) + $alert_dst_p = "$matches7[0]"; + + return $alert_dst_p; +} + +function get_snort_alert_dst_p_full($fileline) +{ + /* dst port full */ + if (preg_match('/:\d+\n[A-Z]+\sTTL/', $fileline, $matches7)) + $alert_dst_p = "$matches7[0]"; + + return $alert_dst_p; +} + +function get_snort_alert_sid($fileline) +{ + /* SID */ + if (preg_match('/\[\d+:\d+:\d+\]/', $fileline, $matches8)) + $alert_sid = "$matches8[0]"; + + return $alert_sid; +} + +$pgtitle = "Services: Snort: Snort Alerts"; +include_once("head.inc"); ?> - + <body link="#0000CC" vlink="#0000CC" alink="#0000CC"> -<!-- loading msg --> -<div id="loadingWaiting"> - <div class="snortModal" style="top: 200px; left: 700px;"> - <div class="snortModalTop"> - <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> - </div> - <div class="snortModalTitle"> - <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> - </div> - <div> - <p class="loadingWaitingMessage"></p> - </div> - </div> -</div> +<?php -<?php include("fbegin.inc"); ?> -<!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"> -<a href="../index.php" id="status-link2"> -<img src="./images/transparent.gif" border="0"></img> -</a> -</div> +include_once("fbegin.inc"); +echo $snort_general_css; + +/* refresh every 60 secs */ +if ($pconfig['arefresh'] == 'on') + echo "<meta http-equiv=\"refresh\" content=\"60;url=/snort/snort_alerts.php\" />\n"; +?> -<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> +<div class="body2"><?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td> - - <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> - <ul class="newtabmenu"> - <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> - <li><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> - <li><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> - <li><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> - <li class="newtabmenu_active"><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> - <li><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> - <li><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> - <li><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> - <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> - </ul> - </div> - - </td> - </tr> - <tr> - <td id="tdbggrey"> - <table width="100%" border="0" cellpadding="10px" cellspacing="0"> - <tr> - <td class="tabnavtbl"> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> - <!-- START MAIN AREA --> - - <tr id="maintable" data-options='{"pagetable":"SnortSettings"}'> <!-- db to lookup --> - <td colspan="2" valign="top" class="listtopic" width="21%">Last 255 Alert Entries</td> - <td colspan="2" valign="top" class="listtopic">Latest Alert Entries Are Listed First</td> +<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"), true, "/snort/snort_alerts.php"); + $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); + $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); + $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Help"), false, "/snort/help_and_info.php"); + display_top_tabs($tab_array); +?> +</td></tr> +<tr> + <td> + <div id="mainarea2"> + <table class="tabcont" width="100%" border="1" cellspacing="0" cellpadding="0"> + <form action="/snort/snort_alerts.php" method="post" id="formalert"> + <tr> + <td width="22%" colspan="0" class="listtopic">Last <?=$anentries;?> Alert Entries.</td> + <td width="78%" class="listtopic">Latest Alert Entries Are Listed First.</td> </tr> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> <tr> - <td class="vncell2" valign="center" width="21%"><span class="vexpl">Save or Remove Logs</span></td> - <td class="vtable" width="40%"> - <form id="iform" > - <input name="snortlogsdownload" type="submit" class="formbtn" value="Download" > - <input type="hidden" name="snortlogsdownload" value="1" /> - <span class="vexpl">Save All Log Files.</span> - </form> + <td width="22%" class="vncell">Instance to inspect</td> + <td width="78%" class="vtable"> + <br/> <select name="instance" id="instance" class="formfld unkown" onChange="document.getElementById('formalert').submit()"> + <?php + foreach ($a_instance as $id => $instance) { + echo "<option value='{$id}'> (" . snort_get_friendly_interface($instance['interface']) . "){$instance['descr']}</option>\n"; + } + ?> + </select><br/> Choose which instance alerts you want to inspect. </td> - <td class="vtable"> - <form id="iform2" > - <input name="snortlogsdelete" type="submit" class="formbtn" value="Clear" onclick="return confirm('Do you really want to remove all your logs ? All Snort Logs will be removed !')" > - <input type="hidden" name="snortlogsdelete" value="1" /> - <span class="vexpl red"><strong>Warning:</strong></span><span class="vexpl"> all logs will be deleted.</span> - </form> + <tr> + <td width="22%" class="vncell">Save or Remove Logs</td> + <td width="78%" class="vtable"> + <input name="download" type="submit" class="formbtn" value="Download"> All + log files will be saved. <a href="/snort/snort_alerts.php?action=clear"> + <input name="delete" type="button" class="formbtn" value="Clear" + onclick="return confirm('Do you really want to remove all instance logs?')"></a> + <span class="red"><strong>Warning:</strong></span> all log files will be deleted. </td> - <div class="hiddendownloadlink"></div> </tr> <tr> - <td class="vncell2" valign="center"><span class="vexpl">Auto Refresh and Log View</span></td> - <td class="vtable"> - <form id="iform3" > + <td width="22%" class="vncell">Auto Refresh and Log View</td> + <td width="78%" class="vtable"> <input name="save" type="submit" class="formbtn" value="Save"> - <input id="cancel" type="button" class="formbtn" value="Cancel"> - <input name="arefresh" id="arefresh" type="checkbox" value="on" <?=htmlspecialchars($arefresh_on);?> > - <span class="vexpl">Auto Refresh</span> - <span class="vexpl"><strong>Default ON</strong>.</span> + Refresh <input name="arefresh" type="checkbox" value="on" + <?php if ($config['installedpackages']['snortglobal']['alertsblocks']['arefresh']=="on") echo "checked"; ?>> + <strong>Default</strong> is <strong>ON</strong>. + <input name="alertnumber" type="text" class="formfld" id="alertnumber" size="5" value="<?=htmlspecialchars($anentries);?>"> + Enter the number of log entries to view. <strong>Default</strong> is <strong>250</strong>. </td> - <td class="vtable"> - <input name="alertnumber" type="text" class="formfld2" id="alertnumber" size="5" value="<?=htmlspecialchars($alertnumber);?>" > - <span class="vexpl">Limit entries to view. <strong>Default 250</strong>.</span> - - <input type="hidden" name="snortSaveSettings" value="1" /> <!-- what to do, save --> - <input type="hidden" name="dbName" value="snortDB" /> <!-- what db --> - <input type="hidden" name="dbTable" value="SnortSettings" /> <!-- what db table --> - <input type="hidden" name="ifaceTab" value="snort_alerts" /> <!-- what interface tab --> - - </form> - </td> - </tr> - </table> - - - <!-- STOP MAIN AREA --> + </tr> + </form> </table> + </div> </td> - </tr> - </table> - </td> </tr> </table> +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <td width="100%"><br> + <div class="tableFilter"> + <form id="tableFilter" + onsubmit="myTable.filter(this.id); return false;">Filter: <select + id="column"> + <option value="1">PRIORITY</option> + <option value="2">PROTO</option> + <option value="3">DESCRIPTION</option> + <option value="4">CLASS</option> + <option value="5">SRC</option> + <option value="6">SRC PORT</option> + <option value="7">FLOW</option> + <option value="8">DST</option> + <option value="9">DST PORT</option> + <option value="10">SID</option> + <option value="11">Date</option> + </select> <input type="text" id="keyword" /> <input type="submit" + value="Submit" /> <input type="reset" value="Clear" /></form> + </div> + <table class="allRow" id="myTable" width="100%" border="2" + cellpadding="1" cellspacing="1"> + <thead> + <th axis="number">#</th> + <th axis="string">PRI</th> + <th axis="string">PROTO</th> + <th axis="string">DESCRIPTION</th> + <th axis="string">CLASS</th> + <th axis="string">SRC</th> + <th axis="string">SPORT</th> + <th axis="string">FLOW</th> + <th axis="string">DST</th> + <th axis="string">DPORT</th> + <th axis="string">SID</th> + <th axis="date">Date</th> + </thead> + <tbody> + <?php + + /* make sure alert file exists */ + if (!file_exists("/var/log/snort/{$snort_uuid}_{$if_real}/alert")) + exec("/usr/bin/touch /var/log/snort/{$snort_uuid}_{$if_real}/alert"); + + $logent = $anentries; + + /* detect the alert file type */ + if ($snortalertlogt == 'full') + $alerts_array = array_reverse(array_filter(explode("\n\n", file_get_contents("/var/log/snort/{$snort_uuid}_{$if_real}/alert")))); + else + $alerts_array = array_reverse(array_filter(split("\n", file_get_contents("/var/log/snort/{$snort_uuid}_{$if_real}/alert")))); + + + + if (is_array($alerts_array)) { + + $counter = 0; + foreach($alerts_array as $fileline) + { + + if($logent <= $counter) + continue; + + $counter++; + + /* Date */ + $alert_date_str = get_snort_alert_date($fileline); + + if($alert_date_str != '') + { + $alert_date = $alert_date_str; + }else{ + $alert_date = 'empty'; + } + + /* Discription */ + $alert_disc_str = get_snort_alert_disc($fileline); + + if($alert_disc_str != '') + { + $alert_disc = $alert_disc_str; + }else{ + $alert_disc = 'empty'; + } + + /* Classification */ + $alert_class_str = get_snort_alert_class($fileline); + + if($alert_class_str != '') + { + + $alert_class_match = array('[Classification:',']'); + $alert_class = str_replace($alert_class_match, '', "$alert_class_str"); + }else{ + $alert_class = 'Prep'; + } + + /* Priority */ + $alert_priority_str = get_snort_alert_priority($fileline); + + if($alert_priority_str != '') + { + $alert_priority_match = array('Priority: ',']'); + $alert_priority = str_replace($alert_priority_match, '', "$alert_priority_str"); + }else{ + $alert_priority = 'empty'; + } + + /* Protocol */ + /* Detect alert file type */ + if ($snortalertlogt == 'full') + { + $alert_proto_str = get_snort_alert_proto_full($fileline); + }else{ + $alert_proto_str = get_snort_alert_proto($fileline); + } + + if($alert_proto_str != '') + { + $alert_proto_match = array(" TTL",'{','}'); + $alert_proto = str_replace($alert_proto_match, '', "$alert_proto_str"); + }else{ + $alert_proto = 'empty'; + } + + /* IP SRC */ + $alert_ip_src_str = get_snort_alert_ip_src($fileline); + + if($alert_ip_src_str != '') + { + $alert_ip_src = $alert_ip_src_str; + }else{ + $alert_ip_src = 'empty'; + } + + /* IP SRC Port */ + $alert_src_p_str = get_snort_alert_src_p($fileline); + + if($alert_src_p_str != '') + { + $alert_src_p_match = array(' -',':'); + $alert_src_p = str_replace($alert_src_p_match, '', "$alert_src_p_str"); + }else{ + $alert_src_p = 'empty'; + } + + /* Flow */ + $alert_flow_str = get_snort_alert_flow($fileline); + + if($alert_flow_str != '') + { + $alert_flow = $alert_flow_str; + }else{ + $alert_flow = 'empty'; + } + + /* IP Destination */ + $alert_ip_dst_str = get_snort_alert_ip_dst($fileline); + + if($alert_ip_dst_str != '') + { + $alert_ip_dst = $alert_ip_dst_str; + }else{ + $alert_ip_dst = 'empty'; + } + + /* IP DST Port */ + if ($snortalertlogt == 'full') + { + $alert_dst_p_str = get_snort_alert_dst_p_full($fileline); + }else{ + $alert_dst_p_str = get_snort_alert_dst_p($fileline); + } + + if($alert_dst_p_str != '') + { + $alert_dst_p_match = array(':',"\n"," TTL"); + $alert_dst_p_str2 = str_replace($alert_dst_p_match, '', "$alert_dst_p_str"); + $alert_dst_p_match2 = array('/[A-Z]/'); + $alert_dst_p = preg_replace($alert_dst_p_match2, '', "$alert_dst_p_str2"); + }else{ + $alert_dst_p = 'empty'; + } + + /* SID */ + $alert_sid_str = get_snort_alert_sid($fileline); + + if($alert_sid_str != '') + { + $alert_sid_match = array('[',']'); + $alert_sid = str_replace($alert_sid_match, '', "$alert_sid_str"); + }else{ + $alert_sid_str = 'empty'; + } + + /* NOTE: using one echo improves performance by 2x */ + if ($alert_disc != 'empty') + { + echo "<tr id=\"{$counter}\"> + <td class=\"centerAlign\">{$counter}</td> + <td class=\"centerAlign\">{$alert_priority}</td> + <td class=\"centerAlign\">{$alert_proto}</td> + <td>{$alert_disc}</td> + <td class=\"centerAlign\">{$alert_class}</td> + <td>{$alert_ip_src}</td> + <td class=\"centerAlign\">{$alert_src_p}</td> + <td class=\"centerAlign\">{$alert_flow}</td> + <td>{$alert_ip_dst}</td> + <td class=\"centerAlign\">{$alert_dst_p}</td> + <td class=\"centerAlign\">{$alert_sid}</td> + <td>{$alert_date}</td> + </tr>\n"; + } + + // <script type="text/javascript"> + // var myTable = {}; + // window.addEvent('domready', function(){ + // myTable = new sortableTable('myTable', {overCls: 'over', onClick: function(){alert(this.id)}}); + // }); + // </script> + + } + } + + ?> + </tbody> + </table> + </td> +</table> + </div> +<?php +include("fend.inc"); -<!-- footer do not touch below --> -<?php -include("fend.inc"); echo $snort_custom_rnd_box; -?> - +?> </body> </html> diff --git a/config/snort-dev/snort_barnyard.php b/config/snort-dev/snort_barnyard.php index 1cd2113b..b647c007 100644 --- a/config/snort-dev/snort_barnyard.php +++ b/config/snort-dev/snort_barnyard.php @@ -1,19 +1,13 @@ <?php /* $Id$ */ /* - - part of pfSense - All rights reserved. + snort_interfaces.php + part of m0n0wall (http://m0n0.ch/wall) Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + Copyright (C) 2008-2009 Robert Zelaya. All rights reserved. - Pfsense Old snort GUI - Copyright (C) 2006 Scott Ullrich. - - Pfsense snort GUI - Copyright (C) 2008-2012 Robert Zelaya. - Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -24,10 +18,6 @@ notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - 3. Neither the name of the pfSense nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - 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 @@ -38,252 +28,242 @@ 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. - */ +/* + +TODO: Nov 12 09 +Clean this code up its ugly +Important add error checking + +*/ + require_once("guiconfig.inc"); -require_once("/usr/local/pkg/snort/snort_new.inc"); require_once("/usr/local/pkg/snort/snort_gui.inc"); +require_once("/usr/local/pkg/snort/snort.inc"); -//Set no caching -header("Expires: Mon, 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"); +global $g; -// set page vars +$id = $_GET['id']; +if (isset($_POST['id'])) + $id = $_POST['id']; +if (is_null($id)) { + header("Location: /snort/snort_interfaces.php"); + exit; +} -$uuid = $_GET['uuid']; -if (isset($_POST['uuid'])) -$uuid = $_POST['uuid']; +if (!is_array($config['installedpackages']['snortglobal']['rule'])) + $config['installedpackages']['snortglobal']['rule'] = array(); +$a_nat = &$config['installedpackages']['snortglobal']['rule']; -if ($uuid == '') { - echo 'error: no uuid'; - exit(0); +if (isset($_GET['dup'])) { + $id = $_GET['dup']; + $after = $_GET['dup']; } +$pconfig = array(); +if (isset($id) && $a_nat[$id]) { + /* old options */ + $pconfig = $a_nat[$id]; + $pconfig['barnyard_enable'] = $a_nat[$id]['barnyard_enable']; + $pconfig['barnyard_mysql'] = $a_nat[$id]['barnyard_mysql']; + $pconfig['barnconfigpassthru'] = base64_decode($a_nat[$id]['barnconfigpassthru']); +} -$a_list = snortSql_fetchAllSettings('snortDB', 'SnortIfaces', 'uuid', $uuid); +if (isset($_GET['dup'])) + unset($id); - if (!is_array($a_list)) - { - $a_list = array(); - } +$if_real = snort_get_real_interface($pconfig['interface']); +$snort_uuid = $pconfig['uuid']; +/* alert file */ +$d_snortconfdirty_path = "/var/run/snort_conf_{$snort_uuid}_{$if_real}.dirty"; +if ($_POST) { - $pgtitle = "Snort: Interface: Barnyard2 Edit"; - include("/usr/local/pkg/snort/snort_head.inc"); + /* XXX: Mising error reporting?! + * check for overlaps + foreach ($a_nat as $natent) { + if (isset($id) && ($a_nat[$id]) && ($a_nat[$id] === $natent)) + continue; + if ($natent['interface'] != $_POST['interface']) + continue; + } + */ + + /* if no errors write to conf */ + if (!$input_errors) { + $natent = array(); + /* repost the options already in conf */ + $natent = $pconfig; + + $natent['barnyard_enable'] = $_POST['barnyard_enable'] ? 'on' : 'off'; + $natent['barnyard_mysql'] = $_POST['barnyard_mysql'] ? $_POST['barnyard_mysql'] : $pconfig['barnyard_mysql']; + $natent['barnconfigpassthru'] = $_POST['barnconfigpassthru'] ? base64_encode($_POST['barnconfigpassthru']) : $pconfig['barnconfigpassthru']; + if ($_POST['barnyard_enable'] == "on") + $natent['snortunifiedlog'] = 'on'; + else + $natent['snortunifiedlog'] = 'off'; + + if (isset($id) && $a_nat[$id]) + $a_nat[$id] = $natent; + else { + if (is_numeric($after)) + array_splice($a_nat, $after+1, 0, array($natent)); + else + $a_nat[] = $natent; + } -?> + write_config(); + sync_snort_package_config(); + + /* after click go to this page */ + 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_barnyard.php?id=$id"); + exit; + } +} +$pgtitle = "Snort: Interface: $id$if_real Barnyard2 Edit"; +include_once("head.inc"); -<!-- START page custom script --> -<script language="JavaScript"> +?> +<body + link="#0000CC" vlink="#0000CC" alink="#0000CC"> -// start a jQuery sand box -jQuery(document).ready(function() { - - // START disable option for snort_interfaces_edit.php - endis = !(jQuery('input[name=barnyard_enable]:checked').val()); - - disableInputs=new Array( - "barnyard_mysql", - "barnconfigpassthru", - "dce_rpc", - "dns_preprocessor", - "ftp_preprocessor", - "http_inspect", - "other_preprocs", - "perform_stat", - "sf_portscan", - "smtp_preprocessor" - ); - - - jQuery('[name=interface]').attr('disabled', 'true'); - - - if (endis) - { - for (var i = 0; i < disableInputs.length; i++) - { - jQuery('[name=' + disableInputs[i] + ']').attr('disabled', 'true'); - } - } - jQuery("input[name=barnyard_enable]").live('click', function() { - - endis = !(jQuery('input[name=barnyard_enable]:checked').val()); - - if (endis) - { - for (var i = 0; i < disableInputs.length; i++) - { - jQuery('[name=' + disableInputs[i] + ']').attr('disabled', 'true'); - } - }else{ - for (var i = 0; i < disableInputs.length; i++) - { - jQuery('[name=' + disableInputs[i] + ']').removeAttr('disabled'); - } - } +<?php include("fbegin.inc"); ?> +<?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> - - }); - // STOP disable option for snort_interfaces_edit.php - - -}); // end of on ready +<?php +echo "{$snort_general_css}\n"; +?> -</script> +<div class="body2"> +<noscript> +<div class="alert" ALIGN=CENTER><img + src="../themes/<?php echo $g['theme']; ?>/images/icons/icon_alert.gif" /><strong>Please +enable JavaScript to view this content +</CENTER></div> +</noscript> +<script language="JavaScript"> +<!-- +function enable_change(enable_change) { + endis = !(document.iform.barnyard_enable.checked || enable_change); + // make shure a default answer is called if this is envoked. + endis2 = (document.iform.barnyard_enable); + document.iform.barnyard_mysql.disabled = endis; + document.iform.barnconfigpassthru.disabled = endis; +} +//--> +</script> <body link="#0000CC" vlink="#0000CC" alink="#0000CC"> +<form action="snort_barnyard.php" method="post" + enctype="multipart/form-data" name="iform" id="iform"><?php -<!-- loading msg --> -<div id="loadingWaiting"> - <div class="snortModal" style="top: 200px; left: 700px;"> - <div class="snortModalTop"> - <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> - </div> - <div class="snortModalTitle"> - <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> - </div> - <div> - <p class="loadingWaitingMessage"></p> - </div> - </div> -</div> + /* Display Alert message */ + if ($input_errors) { + print_input_errors($input_errors); // TODO: add checks + } -<?php include("fbegin.inc"); ?> -<!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"> -<a href="../index.php" id="status-link2"> -<img src="./images/transparent.gif" border="0"></img> -</a> -</div> + if ($savemsg) { + print_info_box2($savemsg); + } -<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> + ?> <table width="100%" border="0" cellpadding="0" cellspacing="0"> +<tr><td> +<?php + $tab_array = array(); + $tabid = 0; + $tab_array[$tabid] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); + $tabid++; + $tab_array[$tabid] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Servers"), false, "/snort/snort_define_servers.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Barnyard2"), true, "/snort/snort_barnyard.php?id={$id}"); + display_top_tabs($tab_array); +?> +</td></tr> <tr> - <td> - - <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> - <ul class="newtabmenu"> - <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> - <li><a href="/snort/snort_interfaces_edit.php?uuid=<?=$uuid;?>"><span>If Settings</span></a></li> - <li><a href="/snort/snort_rulesets.php?uuid=<?=$uuid;?>"><span>Categories</span></a></li> - <li><a href="/snort/snort_rules.php?uuid=<?=$uuid;?>"><span>Rules</span></a></li> - <li><a href="/snort/snort_rulesets_ips.php?uuid=<?=$uuid;?>"><span>Ruleset Ips</span></a></li> - <li><a href="/snort/snort_define_servers.php?uuid=<?=$uuid;?>"><span>Servers</span></a></li> - <li><a href="/snort/snort_preprocessors.php?uuid=<?=$uuid;?>"><span>Preprocessors</span></a></li> - <li class="newtabmenu_active"><a href="/snort/snort_barnyard.php?uuid=<?=$uuid;?>"><span>Barnyard2</span></a></li> - </ul> - </div> - - </td> - </tr> - <tr> - <td id="tdbggrey"> - <table width="100%" border="0" cellpadding="10px" cellspacing="0"> - <tr> - <td class="tabnavtbl"> + <td class="tabcont"> <table width="100%" border="0" cellpadding="6" cellspacing="0"> - <!-- START MAIN AREA --> - - <form id="iform" > - <input type="hidden" name="snortSaveSettings" value="1" /> <!-- what to do, save --> - <input type="hidden" name="dbName" value="snortDB" /> <!-- what db--> - <input type="hidden" name="dbTable" value="SnortIfaces" /> <!-- what db table--> - <input type="hidden" name="ifaceTab" value="snort_barnyard" /> <!-- what interface tab --> - <input name="uuid" type="hidden" value="<?=$uuid; ?>"> - - <tr> - <td colspan="2" valign="top" class="listtopic">General Barnyard2 Settings</td> + <td colspan="2" valign="top" class="listtopic">General Barnyard2 + Settings</td> </tr> <tr> <td width="22%" valign="top" class="vncellreq2">Enable</td> <td width="78%" class="vtable"> - <input name="barnyard_enable" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['barnyard_enable'] == 'on' || $a_list['barnyard_enable'] == '' ? 'checked' : '';?> > - <span class="vexpl"><strong>Enable Barnyard2 on this Interface</strong><br> - This will enable barnyard2 for this interface. You will also have to set the database credentials.</span> - </td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Interface</td> - <td width="78%" class="vtable"> - <select name="interface" class="formfld" > - <option value="wan" selected><?=strtoupper($a_list['interface']); ?></option> - </select> - <br> - <span class="vexpl">Choose which interface this rule applies to.<br> - Hint: in most cases, you'll want to use WAN here.</span></span> - </td> + <input name="barnyard_enable" type="checkbox" value="on" <?php if ($pconfig['barnyard_enable'] == "on") echo "checked"; ?> onClick="enable_change(false)"> + <strong>Enable Barnyard2 </strong><br> + This will enable barnyard2 for this interface. You will also have to set the database credentials.</td> </tr> <tr> <td colspan="2" valign="top" class="listtopic">Mysql Settings</td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Log to a Mysql Database</td> - <td width="78%" class="vtable"> - <input name="barnyard_mysql" type="text" class="formfld" id="barnyard_mysql" size="100" value="<?=$a_list['barnyard_mysql']; ?>"> - <br> - <span class="vexpl">Example: output database: alert, mysql, dbname=snort user=snort host=localhost password=xyz<br> - Example: output database: log, mysql, dbname=snort user=snort host=localhost password=xyz</span> - </td> + <td width="78%" class="vtable"><input name="barnyard_mysql" + type="text" class="formfld" id="barnyard_mysql" size="100" + value="<?=htmlspecialchars($pconfig['barnyard_mysql']);?>"> <br> + <span class="vexpl">Example: output database: alert, mysql, + dbname=snort user=snort host=localhost password=xyz<br> + Example: output database: log, mysql, dbname=snort user=snort + host=localhost password=xyz</span></td> </tr> <tr> <td colspan="2" valign="top" class="listtopic">Advanced Settings</td> </tr> <tr> - <td width="22%" valign="top" class="vncell2">Advanced configuration pass through</td> - <td width="78%" class="vtable"> - <textarea name="barnconfigpassthru" cols="75" rows="12" id="barnconfigpassthru" class="formpre2"><?=$a_list['barnconfigpassthru']; ?></textarea> - <br> - <span class="vexpl">Arguments here will be automatically inserted into the running barnyard2 configuration.</span> - </td> + <td width="22%" valign="top" class="vncell2">Advanced configuration + pass through</td> + <td width="78%" class="vtable"><textarea name="barnconfigpassthru" + cols="100" rows="7" id="barnconfigpassthru" class="formpre"><?=htmlspecialchars($pconfig['barnconfigpassthru']);?></textarea> + <br> + Arguments here will be automatically inserted into the running + barnyard2 configuration.</td> </tr> <tr> <td width="22%" valign="top"> </td> <td width="78%"> <input name="Submit" type="submit" class="formbtn" value="Save"> - <input type="button" class="formbtn" value="Cancel" > - </td> + <input name="id" type="hidden" value="<?=$id;?>"> </td> </tr> <tr> <td width="22%" valign="top"> </td> - <td width="78%"> - <span class="vexpl"><span class="red"><strong>Note:</strong></span> - Please save your settings befor you click start.</span> - </td> + <td width="78%"><span class="vexpl"><span class="red"><strong>Note:</strong></span> + <br> + Please save your settings befor you click start. </td> </tr> - - - </form> - <!-- STOP MAIN AREA --> </table> - </td> - </tr> - </table> - </td> - </tr> -</table> -</div> +</table> +</form> -<!-- footer do not touch below --> -<?php -include("fend.inc"); -echo $snort_custom_rnd_box; -?> - +</div> +<script language="JavaScript"> +<!-- +enable_change(false); +//--> +</script> +<?php include("fend.inc"); ?> </body> </html> diff --git a/config/snort-dev/snort_blocked.php b/config/snort-dev/snort_blocked.php index fdc12480..932e0983 100644 --- a/config/snort-dev/snort_blocked.php +++ b/config/snort-dev/snort_blocked.php @@ -1,18 +1,12 @@ <?php /* $Id$ */ /* - - part of pfSense - All rights reserved. - - Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + snort_blocked.php + Copyright (C) 2006 Scott Ullrich All rights reserved. - Pfsense Old snort GUI - Copyright (C) 2006 Scott Ullrich. - - Pfsense snort GUI - Copyright (C) 2008-2012 Robert Zelaya. + Modified for the Pfsense snort package v. 1.8+ + Copyright (C) 2009 Robert Zelaya Sr. Developer Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -24,10 +18,6 @@ notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - 3. Neither the name of the pfSense nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - 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 @@ -38,156 +28,399 @@ 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_new.inc"); require_once("/usr/local/pkg/snort/snort_gui.inc"); +require_once("/usr/local/pkg/snort/snort.inc"); + +if (!is_array($config['installedpackages']['snortglobal']['alertsblocks'])) + $config['installedpackages']['snortglobal']['alertsblocks'] = array(); + +$pconfig['brefresh'] = $config['installedpackages']['snortglobal']['alertsblocks']['brefresh']; +$pconfig['blertnumber'] = $config['installedpackages']['snortglobal']['alertsblocks']['blertnumber']; + +if ($pconfig['blertnumber'] == '' || $pconfig['blertnumber'] == '0') +{ + $bnentries = '500'; +}else{ + $bnentries = $pconfig['blertnumber']; +} + +if($_POST['todelete'] or $_GET['todelete']) { + if($_POST['todelete']) + $ip = $_POST['todelete']; + if($_GET['todelete']) + $ip = $_GET['todelete']; + exec("/sbin/pfctl -t snort2c -T delete {$ip}"); +} + +if ($_POST['remove']) { + exec("/sbin/pfctl -t snort2c -T flush"); + sleep(1); + header("Location: /snort/snort_blocked.php"); + exit; + +} + +/* TODO: build a file with block ip and disc */ +if ($_POST['download']) +{ + + ob_start(); //important or other posts will fail + $save_date = exec('/bin/date "+%Y-%m-%d-%H-%M-%S"'); + $file_name = "snort_blocked_{$save_date}.tar.gz"; + exec('/bin/mkdir /tmp/snort_blocked'); + exec('/sbin/pfctl -t snort2c -T show > /tmp/snort_block.pf'); + + $blocked_ips_array_save = str_replace(' ', '', array_filter(explode("\n", file_get_contents('/tmp/snort_block.pf')))); + + if ($blocked_ips_array_save[0] != '') { + /* build the list */ + file_put_contents("/tmp/snort_blocked/snort_block.pf", ""); + foreach($blocked_ips_array_save as $counter => $fileline3) + file_put_contents("/tmp/snort_blocked/snort_block.pf", "{$fileline3}\n", FILE_APPEND); + } + + exec("/usr/bin/tar cfz /tmp/snort_blocked_{$save_date}.tar.gz /tmp/snort_blocked"); + + if(file_exists("/tmp/snort_blocked_{$save_date}.tar.gz")) { + $file = "/tmp/snort_blocked_{$save_date}.tar.gz"; + header("Expires: Mon, 26 Jul 1997 05:00:00 GMT\n"); + header("Pragma: private"); // needed for IE + header("Cache-Control: private, must-revalidate"); // needed for IE + header('Content-type: application/force-download'); + header('Content-Transfer-Encoding: Binary'); + header("Content-length: ".filesize($file)); + header("Content-disposition: attachment; filename = {$file_name}"); + readfile("$file"); + exec("/bin/rm /tmp/snort_blocked_{$save_date}.tar.gz"); + exec("/bin/rm /tmp/snort_block.pf"); + exec("/bin/rm /tmp/snort_blocked/snort_block.pf"); + od_end_clean(); //importanr or other post will fail + } else + echo 'Error no saved file.'; + +} + +if ($_POST['save']) +{ + + /* input validation */ + if ($_POST['save']) + { + + + } + + /* no errors */ + if (!$input_errors) + { + $config['installedpackages']['snortglobal']['alertsblocks']['brefresh'] = $_POST['brefresh'] ? 'on' : 'off'; + $config['installedpackages']['snortglobal']['alertsblocks']['blertnumber'] = $_POST['blertnumber']; + + write_config(); -//Set no caching -header("Expires: Mon, 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_blocked.php"); + } -$generalSettings = snortSql_fetchAllSettings('snortDB', 'SnortSettings', 'id', '1'); +} -$blertnumber = $generalSettings['blertnumber']; +/* build filter funcs */ +function get_snort_alert_ip_src($fileline) +{ + /* SRC IP */ + $re1='.*?'; # Non-greedy match on filler + $re2='((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?![\\d])'; # IPv4 IP Address 1 -$brefresh_on = ($generalSettings['brefresh'] == 'on' ? 'checked' : ''); + if ($c=preg_match_all ("/".$re1.$re2."/is", $fileline, $matches4)) + $alert_ip_src = $matches4[1][0]; - $pgtitle = "Services: Snort Blocked Hosts"; - include("/usr/local/pkg/snort/snort_head.inc"); + return $alert_ip_src; +} + +function get_snort_alert_disc($fileline) +{ + /* disc */ + if (preg_match("/\[\*\*\] (\[.*\]) (.*) (\[\*\*\])/", $fileline, $matches)) + $alert_disc = "$matches[2]"; + + return $alert_disc; +} + +/* build sec filters */ +function get_snort_block_ip($fileline) +{ + /* ip */ + if (preg_match("/\[\d+\.\d+\.\d+\.\d+\]/", $fileline, $matches)) + $alert_block_ip = "$matches[0]"; + + return $alert_block_ip; +} + +function get_snort_block_disc($fileline) +{ + /* disc */ + if (preg_match("/\]\s\[.+\]$/", $fileline, $matches)) + $alert_block_disc = "$matches[0]"; + + return $alert_block_disc; +} + +/* tell the user what settings they have */ +$blockedtab_msg_chk = $config['installedpackages']['snortglobal']['rm_blocked']; +if ($blockedtab_msg_chk == "1h_b") { + $blocked_msg = "hour"; +} +if ($blockedtab_msg_chk == "3h_b") { + $blocked_msg = "3 hours"; +} +if ($blockedtab_msg_chk == "6h_b") { + $blocked_msg = "6 hours"; +} +if ($blockedtab_msg_chk == "12h_b") { + $blocked_msg = "12 hours"; +} +if ($blockedtab_msg_chk == "1d_b") { + $blocked_msg = "day"; +} +if ($blockedtab_msg_chk == "4d_b") { + $blocked_msg = "4 days"; +} +if ($blockedtab_msg_chk == "7d_b") { + $blocked_msg = "7 days"; +} +if ($blockedtab_msg_chk == "28d_b") { + $blocked_msg = "28 days"; +} + +if ($blockedtab_msg_chk != "never_b") +{ + $blocked_msg_txt = "Hosts are removed every <strong>$blocked_msg</strong>."; +}else{ + $blocked_msg_txt = "Settings are set to never <strong>remove</strong> hosts."; +} + +$pgtitle = "Services: Snort Blocked Hosts"; +include_once("head.inc"); ?> - - -<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> - -<!-- loading msg --> -<div id="loadingWaiting"> - <div class="snortModal" style="top: 200px; left: 700px;"> - <div class="snortModalTop"> - <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> - </div> - <div class="snortModalTitle"> - <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> - </div> - <div> - <p class="loadingWaitingMessage"></p> - </div> - </div> -</div> - -<?php include("fbegin.inc"); ?> -<!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"> -<a href="../index.php" id="status-link2"> -<img src="./images/transparent.gif" border="0"></img> -</a> -</div> - -<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> - -<table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td> - <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> - <ul class="newtabmenu"> - <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> - <li><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> - <li><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> - <li><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> - <li><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> - <li class="newtabmenu_active"><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> - <li><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> - <li><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> - <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> - </ul> - </div> +<body link="#000000" vlink="#000000" alink="#000000"> - </td> - </tr> +<?php + +include_once("fbegin.inc"); +echo $snort_general_css; + +/* refresh every 60 secs */ +if ($pconfig['brefresh'] == 'on') + echo "<meta http-equiv=\"refresh\" content=\"60;url=/snort/snort_blocked.php\" />\n"; +?> + +<div class="body2"><?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> + +<?php if ($savemsg) print_info_box($savemsg); ?> +<table width="99%" border="0" cellpadding="0" cellspacing="0"> +<tr><td> +<?php + $tab_array = array(); + $tab_array[0] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); + $tab_array[1] = array(gettext("Global Settings"), false, "/snort/snort_interfaces_global.php"); + $tab_array[2] = array(gettext("Updates"), false, "/snort/snort_download_updates.php"); + $tab_array[3] = array(gettext("Alerts"), false, "/snort/snort_alerts.php"); + $tab_array[4] = array(gettext("Blocked"), true, "/snort/snort_blocked.php"); + $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); + $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Help"), false, "/snort/help_and_info.php"); + display_top_tabs($tab_array); +?> +</td></tr> <tr> - <td id="tdbggrey"> - <table width="100%" border="0" cellpadding="10px" cellspacing="0"> - <tr> - <td class="tabnavtbl"> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> - <!-- START MAIN AREA --> - - <tr id="maintable" data-options='{"pagetable":"SnortSettings"}'> <!-- db to lookup --> - <td width="22%" colspan="0" class="listtopic">Last 500 Blocked.</td> - <td class="listtopic">This page lists hosts that have been blocked by Snort. Hosts are removed every <strong>hour</strong>.</td> + <td> + <div id="mainarea2"> + + <table id="maintable" class="tabcont" width="100%" border="0" + cellpadding="0" cellspacing="0"> + <tr> + <td width="22%" colspan="0" class="listtopic">Last <?=$bnentries;?> + Blocked.</td> + <td width="78%" class="listtopic">This page lists hosts that have + been blocked by Snort. <?=$blocked_msg_txt;?></td> </tr> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> <tr> - <td class="vncell2" valign="center" width="22%"><span class="vexpl">Save or Remove Hosts</span></td> - <td width="40%" class="vtable"> - <form id="iform" > - <input name="snortblockedlogsdownload" type="submit" class="formbtn" value="Download" > - <input type="hidden" name="snortblockedlogsdownload" value="1" /> - <span class="vexpl">Save All Blocked Hosts</span> - </form> + <td width="22%" class="vncell">Save or Remove Hosts</td> + <td width="78%" class="vtable"> + <form action="/snort/snort_blocked.php" method="post"><input + name="download" type="submit" class="formbtn" value="Download"> All + blocked hosts will be saved. <input name="remove" type="submit" + class="formbtn" value="Clear"> <span class="red"><strong>Warning:</strong></span> + all hosts will be removed.</form> </td> - <td class="vtable"> - <form id="iform2" > - <input name="remove" type="submit" class="formbtn" value="Clear" onclick="return confirm('Do you really want to remove all blocked hosts ? All Blocked Hosts will be removed !')" > - <input type="hidden" name="snortflushpftable" value="1" /> - <span class="vexpl red"><strong>Warning:</strong></span><span class="vexpl"> all hosts will be removed.</span> - </form> - </td> - - <div class="hiddendownloadlink"> - </div> - </tr> <tr> - <td class="vncell2" valign="center"><span class="vexpl">Auto Refresh and Log View</span></td> - <td class="vtable"> - <form id="iform3" > - <input name="save" type="submit" class="formbtn" value="Save"> - <input id="cancel" type="button" class="formbtn" value="Cancel"> - <span class="vexpl">Auto Refresh</span> - <input name="brefresh" id="brefresh" type="checkbox" value="on" <?=$brefresh_on; ?> > - <span class="vexpl"><strong>Default ON</strong>.</span> - </td> - <td class="vtable"> - <input name="blertnumber" type="text" class="formfld2" id="blertnumber" size="5" value="<?=$blertnumber;?>" > - <span class="vexpl">Limit entries to view. <strong>Default 500</strong>.</span> - - <input type="hidden" name="snortSaveSettings" value="1" /> <!-- what to do, save --> - <input type="hidden" name="dbName" value="snortDB" /> <!-- what db --> - <input type="hidden" name="dbTable" value="SnortSettings" /> <!-- what db table --> - <input type="hidden" name="ifaceTab" value="snort_blocked" /> <!-- what interface tab --> - + <td width="22%" class="vncell">Auto Refresh and Log View</td> + <td width="78%" class="vtable"> + <form action="/snort/snort_blocked.php" method="post"><input + name="save" type="submit" class="formbtn" value="Save"> Refresh <input + name="brefresh" type="checkbox" value="on" + <?php if ($config['installedpackages']['snortglobal']['alertsblocks']['brefresh']=="on" || $config['installedpackages']['snortglobal']['alertsblocks']['brefresh']=='') echo "checked"; ?>> + <strong>Default</strong> is <strong>ON</strong>. <input + name="blertnumber" type="text" class="formfld" id="blertnumber" + size="5" value="<?=htmlspecialchars($bnentries);?>"> Enter the + number of blocked entries to view. <strong>Default</strong> is <strong>500</strong>. </form> </td> </tr> - </table> - - <!-- STOP MAIN AREA --> </table> + </div> + <br> </td> - </tr> - </table> - </td> </tr> -</table> -</div> + <table class="tabcont" width="100%" border="0" cellspacing="0" + cellpadding="0"> + <tr> + <td> + <table id="sortabletable1" class="sortable" width="100%" border="0" + cellpadding="0" cellspacing="0"> + <tr id="frheader"> + <td width="5%" class="listhdrr">Remove</td> + <td class="listhdrr">#</td> + <td class="listhdrr">IP</td> + <td class="listhdrr">Alert Description</td> + </tr> + <?php + + /* set the arrays */ + exec('/sbin/pfctl -t snort2c -T show > /tmp/snort_block.cache'); + $blocked_ips_array = str_replace(' ', '', array_filter(explode("\n", file_get_contents('/tmp/snort_block.cache')))); + foreach (glob("/var/log/snort/alert_*") as $alert) { + $alerts_array = array_reverse(explode("\n\n", file_get_contents("{$alert}"))); + + $logent = $bnentries; + + if ($blocked_ips_array[0] != '' && $alerts_array[0] != '') + { + + /* build the list and compare blocks to alerts */ + $counter = 0; + foreach($alerts_array as $fileline) + { + + $counter++; + + $alert_ip_src = get_snort_alert_ip_src($fileline); + $alert_ip_disc = get_snort_alert_disc($fileline); + $alert_ip_src_array[] = get_snort_alert_ip_src($fileline); + + if (in_array("$alert_ip_src", $blocked_ips_array)) + $input[] = "[$alert_ip_src] " . "[$alert_ip_disc]\n"; + } + + foreach($blocked_ips_array as $alert_block_ip) + { + + if (!in_array($alert_block_ip, $alert_ip_src_array)) + { + $input[] = "[$alert_block_ip] " . "[N\A]\n"; + } + } + + /* reduce double occurrences */ + $result = array_unique($input); + + /* buil final list, preg_match, buld html */ + $counter2 = 0; + + foreach($result as $fileline2) + { + if($logent <= $counter2) + continue; + + $counter2++; + + $alert_block_ip_str = get_snort_block_ip($fileline2); + + if($alert_block_ip_str != '') + { + $alert_block_ip_match = array('[',']'); + $alert_block_ip = str_replace($alert_block_ip_match, '', "$alert_block_ip_str"); + }else{ + $alert_block_ip = 'empty'; + } + + $alert_block_disc_str = get_snort_block_disc($fileline2); + + if($alert_block_disc_str != '') + { + $alert_block_disc_match = array('] [',']'); + $alert_block_disc = str_replace($alert_block_disc_match, '', "$alert_block_disc_str"); + }else{ + $alert_block_disc = 'empty'; + } + + /* use one echo to do the magic*/ + echo "<tr> + <td align=\"center\" valign=\"top\"'><a href='snort_blocked.php?todelete=" . trim(urlencode($alert_block_ip)) . "'> + <img title=\"Delete\" border=\"0\" name='todelete' id='todelete' alt=\"Delete\" src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\"></a></td> + <td> {$counter2}</td> + <td> {$alert_block_ip}</td> + <td> {$alert_block_disc}</td> + </tr>\n"; + + } + + }else{ + + /* if alerts file is empty and blocked table is not empty */ + $counter2 = 0; + + foreach($blocked_ips_array as $alert_block_ip) + { + if($logent <= $counter2) + continue; + + $counter2++; + + $alert_block_disc = 'N/A'; + + /* use one echo to do the magic*/ + echo "<tr> + <td align=\"center\" valign=\"top\"'><a href='snort_blocked.php?todelete=" . trim(urlencode($alert_block_ip)) . "'> + <img title=\"Delete\" border=\"0\" name='todelete' id='todelete' alt=\"Delete\" src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\"></a></td> + <td> {$counter2}</td> + <td> {$alert_block_ip}</td> + <td> {$alert_block_disc}</td> + </tr>\n"; + } + } + } + + echo '</table>' . "\n"; + + if (empty($blocked_ips_array[0])) + echo "\n<tr><td colspan='3' align=\"center\" valign=\"top\"><br><strong>There are currently no items being blocked by snort.</strong></td></tr>"; + else + echo "\n<tr><td colspan='3' align=\"center\" valign=\"top\">{$counter2} items listed.</td></tr>"; + + ?> + </td> + </tr> + </table> + </td> + </tr> + </table> + </div> + + <?php + + include("fend.inc"); -<!-- footer do not touch below --> -<?php -include("fend.inc"); echo $snort_custom_rnd_box; -?> +?> </body> </html> diff --git a/config/snort-dev/snort_check_cron_misc.inc b/config/snort-dev/snort_check_cron_misc.inc new file mode 100644 index 00000000..28d454b0 --- /dev/null +++ b/config/snort-dev/snort_check_cron_misc.inc @@ -0,0 +1,76 @@ +<?php +/* $Id$ */ +/* + snort_chk_log_dir_size.php + part of pfSense + + Modified for the Pfsense snort package v. 1.8+ + Copyright (C) 2009-2010 Robert Zelaya Developer + 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("/usr/local/pkg/snort/snort.inc"); + +// 'B' => 1, +// 'KB' => 1024, +// 'MB' => 1024 * 1024, +// 'GB' => 1024 * 1024 * 1024, +// 'TB' => 1024 * 1024 * 1024 * 1024, +// 'PB' => 1024 * 1024 * 1024 * 1024 * 1024, + + +/* chk if snort log dir is full if so clear it */ +$snortloglimit = $config['installedpackages']['snortglobal']['snortloglimit']; +$snortloglimitsize = $config['installedpackages']['snortglobal']['snortloglimitsize']; + +if ($g['booting']==true) + return; + +if ($snortloglimit == 'off') + return; + +$snortloglimitDSKsize = exec('/bin/df -k /var | grep -v "Filesystem" | awk \'{print $4}\''); + +$snortlogAlertsizeKB = snort_Getdirsize('/var/log/snort/alert'); +$snortloglimitAlertsizeKB = round($snortlogAlertsizeKB * .70); +$snortloglimitsizeKB = round($snortloglimitsize * 1024); + +/* do I need HUP kill ? */ +if (snort_Getdirsize('/var/log/snort/') >= $snortloglimitsizeKB ) { + + conf_mount_rw(); + if(file_exists('/var/log/snort/alert')) { + if ($snortlogAlertsizeKB >= $snortloglimitAlertsizeKB) { + exec('/bin/echo "" > /var/log/snort/alert'); + } + post_delete_logs(); + /* XXX: This is needed if snort is run as snort user */ + //mwexec('/usr/sbin/chown snort:snort /var/log/snort/*', true); + mwexec('/bin/chmod 660 /var/log/snort/*', true); + } + conf_mount_ro(); + +} + +?> diff --git a/config/snort-dev/snort_check_for_rule_updates.php b/config/snort-dev/snort_check_for_rule_updates.php new file mode 100644 index 00000000..41995e9d --- /dev/null +++ b/config/snort-dev/snort_check_for_rule_updates.php @@ -0,0 +1,690 @@ +<?php +/* + snort_check_for_rule_updates.php + Copyright (C) 2006 Scott Ullrich + Copyright (C) 2009 Robert Zelaya + Copyright (C) 2011 Ermal Luci + 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. + */ + +/* Setup enviroment */ + +/* TODO: review if include files are needed */ +require_once("functions.inc"); +require_once("service-utils.inc"); +require_once("/usr/local/pkg/snort/snort.inc"); + +$pkg_interface = "console"; + +$tmpfname = "/usr/local/etc/snort/tmp/snort_rules_up"; +$snortdir = "/usr/local/etc/snort"; +$snortdir_wan = "/usr/local/etc/snort"; +$snort_filename_md5 = "{$snort_rules_file}.md5"; +$snort_filename = "{$snort_rules_file}"; +$emergingthreats_filename_md5 = "emerging.rules.tar.gz.md5"; +$emergingthreats_filename = "emerging.rules.tar.gz"; +$pfsense_rules_filename_md5 = "pfsense_rules.tar.gz.md5"; +$pfsense_rules_filename = "pfsense_rules.tar.gz"; + +/* Time stamps define */ +$last_md5_download = $config['installedpackages']['snortglobal']['last_md5_download']; +$last_rules_install = $config['installedpackages']['snortglobal']['last_rules_install']; + +$up_date_time = date('l jS \of F Y h:i:s A'); +echo "\n"; +echo "#########################\n"; +echo "$up_date_time\n"; +echo "#########################\n"; +echo "\n\n"; + +/* define checks */ +$oinkid = $config['installedpackages']['snortglobal']['oinkmastercode']; +$snortdownload = $config['installedpackages']['snortglobal']['snortdownload']; +$emergingthreats = $config['installedpackages']['snortglobal']['emergingthreats']; + +if ($snortdownload == 'off' && $emergingthreats != 'on') + $snort_emrging_info = 'stop'; + +if ($oinkid == "" && $snortdownload != 'off') + $snort_oinkid_info = 'stop'; + +/* check if main rule directory is empty */ +$if_mrule_dir = "/usr/local/etc/snort/rules"; +$mfolder_chk = (count(glob("$if_mrule_dir/*")) === 0) ? 'empty' : 'full'; + +if (file_exists('/var/run/snort.conf.dirty')) + $snort_dirty_d = 'stop'; + +/* Start of code */ +conf_mount_rw(); + +if (!is_dir('/usr/local/etc/snort/tmp')) + exec('/bin/mkdir -p /usr/local/etc/snort/tmp'); + +$snort_md5_check_ok = 'off'; +$emerg_md5_check_ok = 'off'; +$pfsense_md5_check_ok = 'off'; + +/* Set user agent to Mozilla */ +ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)'); +ini_set("memory_limit","150M"); + +/* mark the time update started */ +$config['installedpackages']['snortglobal']['last_md5_download'] = date("Y-M-jS-h:i-A"); + +/* send current buffer */ +ob_flush(); + +/* send current buffer */ +ob_flush(); + +/* remove old $tmpfname files */ +if (is_dir("{$tmpfname}")) { + update_status(gettext("Removing old tmp files...")); + exec("/bin/rm -r {$tmpfname}"); + apc_clear_cache(); +} + +/* Make shure snortdir exits */ +exec("/bin/mkdir -p {$snortdir}"); +exec("/bin/mkdir -p {$snortdir}/rules"); +exec("/bin/mkdir -p {$snortdir}/signatures"); +exec("/bin/mkdir -p {$tmpfname}"); +exec("/bin/mkdir -p /usr/local/lib/snort/dynamicrules/"); + +/* send current buffer */ +ob_flush(); + +$pfsensedownload = 'on'; + +/* download md5 sig from snort.org */ +if ($snortdownload == 'on') +{ + if (file_exists("{$tmpfname}/{$snort_filename_md5}") && + filesize("{$tmpfname}/{$snort_filename_md5}") > 0) { + update_status(gettext("snort.org md5 temp file exists...")); + } else { + update_status(gettext("Downloading snort.org md5 file...")); + ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)'); + + //$image = @file_get_contents("http://www.mtest.local/pub-bin/oinkmaster.cgi/{$oinkid}/{$snort_filename_md5}"); + $image = @file_get_contents("http://www.snort.org/pub-bin/oinkmaster.cgi/{$oinkid}/{$snort_filename_md5}"); + @file_put_contents("{$tmpfname}/{$snort_filename_md5}", $image); + update_status(gettext("Done downloading snort.org md5")); + } +} + +/* download md5 sig from emergingthreats.net */ +if ($emergingthreats == 'on') +{ + update_status(gettext("Downloading emergingthreats md5 file...")); + ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)'); + // $image = @file_get_contents("http://www.mtest.local/pub-bin/oinkmaster.cgi/{$oinkid}/version.txt"); + $image = @file_get_contents('http://rules.emergingthreats.net/open/snort-2.9.0/emerging.rules.tar.gz.md5'); + @file_put_contents("{$tmpfname}/{$emergingthreats_filename_md5}", $image); + update_status(gettext("Done downloading emergingthreats md5")); +} + +/* download md5 sig from pfsense.org */ +if (file_exists("{$tmpfname}/{$pfsense_rules_filename_md5}")) { + update_status(gettext("pfsense md5 temp file exists...")); +} else { + update_status(gettext("Downloading pfsense md5 file...")); + ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)'); + //$image = @file_get_contents("http://www.mtest.local/pub-bin/oinkmaster.cgi/{$oinkid}/pfsense_rules.tar.gz.md5"); + $image = @file_get_contents("http://www.pfsense.com/packages/config/snort/pfsense_rules/pfsense_rules.tar.gz.md5"); + @file_put_contents("{$tmpfname}/pfsense_rules.tar.gz.md5", $image); + update_status(gettext("Done downloading pfsense md5.")); +} + +/* If md5 file is empty wait 15min exit */ +if ($snortdownload == 'on') +{ + if (0 == filesize("{$tmpfname}/{$snort_filename_md5}")) + { + update_status(gettext("Please wait... You may only check for New Rules every 15 minutes...")); + update_output_window(gettext("Rules are released every month from snort.org. You may download the Rules at any time.")); + $snortdownload = 'off'; + } +} + +/* If pfsense md5 file is empty wait 15min exit */ +if (0 == filesize("{$tmpfname}/$pfsense_rules_filename_md5")){ + update_status(gettext("Please wait... You may only check for New Pfsense Rules every 15 minutes...")); + update_output_window(gettext("Rules are released to support Pfsense packages.")); + $pfsensedownload = 'off'; +} + +/* Check if were up to date snort.org */ +if ($snortdownload == 'on') +{ + if (file_exists("{$snortdir}/{$snort_filename_md5}")) + { + $md5_check_new_parse = file_get_contents("{$tmpfname}/{$snort_filename_md5}"); + $md5_check_new = `/bin/echo "{$md5_check_new_parse}" | /usr/bin/awk '{ print $1 }'`; + $md5_check_old_parse = file_get_contents("{$snortdir}/{$snort_filename_md5}"); + $md5_check_old = `/bin/echo "{$md5_check_old_parse}" | /usr/bin/awk '{ print $1 }'`; + if ($md5_check_new == $md5_check_old) + { + update_status(gettext("Your rules are up to date...")); + update_output_window(gettext("You may start Snort now, check update.")); + $snort_md5_check_ok = 'on'; + } else { + update_status(gettext("Your rules are not up to date...")); + $snort_md5_check_ok = 'off'; + } + } +} + +/* Check if were up to date emergingthreats.net */ +if ($emergingthreats == 'on') +{ + if (file_exists("{$snortdir}/{$emergingthreats_filename_md5}")) + { + $emerg_md5_check_new_parse = file_get_contents("{$tmpfname}/{$emergingthreats_filename_md5}"); + $emerg_md5_check_new = `/bin/echo "{$emerg_md5_check_new_parse}" | /usr/bin/awk '{ print $1 }'`; + $emerg_md5_check_old_parse = file_get_contents("{$snortdir}/{$emergingthreats_filename_md5}"); + $emerg_md5_check_old = `/bin/echo "{$emerg_md5_check_old_parse}" | /usr/bin/awk '{ print $1 }'`; + if ($emerg_md5_check_new == $emerg_md5_check_old) + { + $emerg_md5_check_ok = 'on'; + } else + $emerg_md5_check_ok = 'off'; + } +} + +/* Check if were up to date pfsense.org */ +if ($pfsensedownload == 'on' && file_exists("{$snortdir}/pfsense_rules.tar.gz.md5")) +{ + $pfsense_check_new_parse = file_get_contents("{$tmpfname}/pfsense_rules.tar.gz.md5"); + $pfsense_md5_check_new = `/bin/echo "{$pfsense_md5_check_new_parse}" | /usr/bin/awk '{ print $1 }'`; + $pfsense_md5_check_old_parse = file_get_contents("{$snortdir}/pfsense_rules.tar.gz.md5"); + $pfsense_md5_check_old = `/bin/echo "{$pfsense_md5_check_old_parse}" | /usr/bin/awk '{ print $1 }'`; + if ($pfsense_md5_check_new == $pfsense_md5_check_old) + { + $pfsense_md5_check_ok = 'on'; + } else + $pfsense_md5_check_ok = 'off'; +} + +if ($snortdownload == 'on') { + if ($snort_md5_check_ok == 'on') + { + update_status(gettext("Your snort.org rules are up to date...")); + update_output_window(gettext("You may start Snort now...")); + $snortdownload = 'off'; + } +} +if ($emergingthreats == 'on') { + if ($emerg_md5_check_ok == 'on') + { + update_status(gettext("Your Emergingthreats rules are up to date...")); + update_output_window(gettext("You may start Snort now...")); + $emergingthreats = 'off'; + } +} + +/* download snortrules file */ +if ($snortdownload == 'on') +{ + if ($snort_md5_check_ok != 'on') { + if (file_exists("{$tmpfname}/{$snort_filename}")) { + update_status(gettext("Snortrule tar file exists...")); + } else { + update_status(gettext("There is a new set of Snort.org rules posted. Downloading...")); + update_output_window(gettext("May take 4 to 10 min...")); + download_file_with_progress_bar("http://www.snort.org/pub-bin/oinkmaster.cgi/{$oinkid}/{$snort_filename}", "{$tmpfname}/{$snort_filename}"); + update_all_status($static_output); + update_status(gettext("Done downloading rules file.")); + if (300000 > filesize("{$tmpfname}/$snort_filename")){ + update_status(gettext("Error with the snort rules download...")); + update_output_window(gettext("Snort rules file downloaded failed...")); + $snortdownload = 'off'; + } + } + } +} + +/* download emergingthreats rules file */ +if ($emergingthreats == "on") +{ + if ($emerg_md5_check_ok != 'on') + { + if (file_exists("{$tmpfname}/{$emergingthreats_filename}")) + { + update_status(gettext('Emergingthreats tar file exists...')); + }else{ + update_status(gettext("There is a new set of Emergingthreats rules posted. Downloading...")); + update_output_window(gettext("May take 4 to 10 min...")); + download_file_with_progress_bar('http://rules.emergingthreats.net/open/snort-2.9.0/emerging.rules.tar.gz', "{$tmpfname}/{$emergingthreats_filename}"); + update_status(gettext('Done downloading Emergingthreats rules file.')); + } + } +} + +/* download pfsense rules file */ +if ($pfsensedownload == 'on' && $pfsense_md5_check_ok != 'on') { + if (file_exists("{$tmpfname}/{$pfsense_rules_filename}")) { + update_status(gettext("Snortrule tar file exists...")); + } else { + update_status(gettext("There is a new set of Pfsense rules posted. Downloading...")); + update_output_window(gettext("May take 4 to 10 min...")); + download_file_with_progress_bar("http://www.pfsense.com/packages/config/snort/pfsense_rules/pfsense_rules.tar.gz", $tmpfname . "/{$pfsense_rules_filename}"); + update_all_status($static_output); + update_status(gettext("Done downloading rules file.")); + } +} + +/* Compair md5 sig to file sig */ + +//$premium_url_chk = $config['installedpackages']['snort']['config'][0]['subscriber']; +//if ($premium_url_chk == on) { +//$md5 = file_get_contents("{$tmpfname}/{$snort_filename_md5}"); +//$file_md5_ondisk = `/sbin/md5 {$tmpfname}/{$snort_filename} | /usr/bin/awk '{ print $4 }'`; +// if ($md5 == $file_md5_ondisk) { +// update_status(gettext("Valid md5 checksum pass...")); +//} else { +// update_status(gettext("The downloaded file does not match the md5 file...P is ON")); +// update_output_window(gettext("Error md5 Mismatch...")); +// return; +// } +//} + +//$premium_url_chk = $config['installedpackages']['snort']['config'][0]['subscriber']; +//if ($premium_url_chk != on) { +//$md55 = `/bin/cat {$tmpfname}/{$snort_filename_md5} | /usr/bin/awk '{ print $4 }'`; +//$file_md5_ondisk2 = `/sbin/md5 {$tmpfname}/{$snort_filename} | /usr/bin/awk '{ print $4 }'`; +// if ($md55 == $file_md5_ondisk2) { +// update_status(gettext("Valid md5 checksum pass...")); +//} else { +// update_status(gettext("The downloaded file does not match the md5 file...Not P")); +// update_output_window(gettext("Error md5 Mismatch...")); +// return; +// } +//} + +/* Untar snort rules file individually to help people with low system specs */ +if ($snortdownload == 'on') +{ + if ($snort_md5_check_ok != 'on') { + if (file_exists("{$tmpfname}/{$snort_filename}")) { + + if ($pfsense_stable == 'yes') + $freebsd_version_so = 'FreeBSD-7-2'; + else + $freebsd_version_so = 'FreeBSD-8-1'; + + update_status(gettext("Extracting Snort.org rules...")); + update_output_window(gettext("May take a while...")); + /* extract snort.org rules and add prefix to all snort.org files*/ + exec("/bin/rm -r {$snortdir}/rules"); + sleep(2); + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} rules/"); + chdir ("/usr/local/etc/snort/rules"); + sleep(2); + exec('/usr/local/bin/perl /usr/local/bin/snort_rename.pl s/^/snort_/ *.rules'); + + /* extract so rules */ + exec('/bin/mkdir -p /usr/local/lib/snort/dynamicrules/'); + if($snort_arch == 'x86'){ + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} so_rules/precompiled/$freebsd_version_so/i386/2.9.0.5/"); + exec("/bin/mv -f {$snortdir}/so_rules/precompiled/$freebsd_version_so/i386/2.9.0.5/* /usr/local/lib/snort/dynamicrules/"); + } else if ($snort_arch == 'x64') { + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} so_rules/precompiled/$freebsd_version_so/x86-64/2.9.0.5/"); + exec("/bin/mv -f {$snortdir}/so_rules/precompiled/$freebsd_version_so/x86-64/2.9.0.5/* /usr/local/lib/snort/dynamicrules/"); + } + /* extract so rules none bin and rename */ + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} so_rules/bad-traffic.rules/" . + " so_rules/chat.rules/" . + " so_rules/dos.rules/" . + " so_rules/exploit.rules/" . + " so_rules/icmp.rules/" . + " so_rules/imap.rules/" . + " so_rules/misc.rules/" . + " so_rules/multimedia.rules/" . + " so_rules/netbios.rules/" . + " so_rules/nntp.rules/" . + " so_rules/p2p.rules/" . + " so_rules/smtp.rules/" . + " so_rules/sql.rules/" . + " so_rules/web-activex.rules/" . + " so_rules/web-client.rules/" . + " so_rules/web-iis.rules/" . + " so_rules/web-misc.rules/"); + + exec("/bin/mv -f {$snortdir}/so_rules/bad-traffic.rules {$snortdir}/rules/snort_bad-traffic.so.rules"); + exec("/bin/mv -f {$snortdir}/so_rules/chat.rules {$snortdir}/rules/snort_chat.so.rules"); + exec("/bin/mv -f {$snortdir}/so_rules/dos.rules {$snortdir}/rules/snort_dos.so.rules"); + exec("/bin/mv -f {$snortdir}/so_rules/exploit.rules {$snortdir}/rules/snort_exploit.so.rules"); + exec("/bin/mv -f {$snortdir}/so_rules/icmp.rules {$snortdir}/rules/snort_icmp.so.rules"); + exec("/bin/mv -f {$snortdir}/so_rules/imap.rules {$snortdir}/rules/snort_imap.so.rules"); + exec("/bin/mv -f {$snortdir}/so_rules/misc.rules {$snortdir}/rules/snort_misc.so.rules"); + exec("/bin/mv -f {$snortdir}/so_rules/multimedia.rules {$snortdir}/rules/snort_multimedia.so.rules"); + exec("/bin/mv -f {$snortdir}/so_rules/netbios.rules {$snortdir}/rules/snort_netbios.so.rules"); + exec("/bin/mv -f {$snortdir}/so_rules/nntp.rules {$snortdir}/rules/snort_nntp.so.rules"); + exec("/bin/mv -f {$snortdir}/so_rules/p2p.rules {$snortdir}/rules/snort_p2p.so.rules"); + exec("/bin/mv -f {$snortdir}/so_rules/smtp.rules {$snortdir}/rules/snort_smtp.so.rules"); + exec("/bin/mv -f {$snortdir}/so_rules/sql.rules {$snortdir}/rules/snort_sql.so.rules"); + exec("/bin/mv -f {$snortdir}/so_rules/web-activex.rules {$snortdir}/rules/snort_web-activex.so.rules"); + exec("/bin/mv -f {$snortdir}/so_rules/web-client.rules {$snortdir}/rules/snort_web-client.so.rules"); + exec("/bin/mv -f {$snortdir}/so_rules/web-iis.rules {$snortdir}/rules/snort_web-iis.so.rules"); + exec("/bin/mv -f {$snortdir}/so_rules/web-misc.rules {$snortdir}/rules/snort_web-misc.so.rules"); + exec("/bin/rm -r {$snortdir}/so_rules"); + } + + /* extract base etc files */ + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} etc/"); + exec("/bin/mv -f {$snortdir}/etc/* {$snortdir}"); + exec("/bin/rm -r {$snortdir}/etc"); + + update_status(gettext("Done extracting Snort.org Rules.")); + }else{ + update_status(gettext("Error extracting Snort.org Rules...")); + update_output_window(gettext("Error Line 755")); + $snortdownload = 'off'; + } +} + +/* Untar emergingthreats rules to tmp */ +if ($emergingthreats == 'on') +{ + if ($emerg_md5_check_ok != 'on') + { + if (file_exists("{$tmpfname}/{$emergingthreats_filename}")) + { + update_status(gettext("Extracting rules...")); + update_output_window(gettext("May take a while...")); + exec("/usr/bin/tar xzf {$tmpfname}/{$emergingthreats_filename} -C {$snortdir} rules/"); + } + } +} + +/* Untar Pfsense rules to tmp */ +if ($pfsensedownload == 'on' && $pfsense_md5_check_ok != 'on') { + if (file_exists("{$tmpfname}/{$pfsense_rules_filename}")) { + update_status(gettext("Extracting Pfsense rules...")); + update_output_window(gettext("May take a while...")); + exec("/usr/bin/tar xzf {$tmpfname}/{$pfsense_rules_filename} -C {$snortdir} rules/"); + } +} + +/* Untar snort signatures */ +if ($snortdownload == 'on' && $snort_md5_check_ok != 'on') { + if (file_exists("{$tmpfname}/{$snort_filename}")) { + $signature_info_chk = $config['installedpackages']['snortglobal']['signatureinfo']; + if ($premium_url_chk == 'on') { + update_status(gettext("Extracting Signatures...")); + update_output_window(gettext("May take a while...")); + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} doc/signatures/"); + update_status(gettext("Done extracting Signatures.")); + } + } +} + +/* Copy md5 sig to snort dir */ +if ($snortdownload == 'on') +{ + if ($snort_md5_check_ok != 'on') { + if (file_exists("{$tmpfname}/$snort_filename_md5")) { + update_status(gettext("Copying md5 sig to snort directory...")); + exec("/bin/cp {$tmpfname}/$snort_filename_md5 {$snortdir}/$snort_filename_md5"); + }else{ + update_status(gettext("The md5 file does not exist...")); + update_output_window(gettext("Error copying config...")); + $snortdownload = 'off'; + } + } +} + +/* Copy emergingthreats md5 sig to snort dir */ +if ($emergingthreats == "on") +{ + if ($emerg_md5_check_ok != 'on') + { + if (file_exists("{$tmpfname}/$emergingthreats_filename_md5")) + { + update_status(gettext("Copying md5 sig to snort directory...")); + exec("/bin/cp {$tmpfname}/$emergingthreats_filename_md5 {$snortdir}/$emergingthreats_filename_md5"); + }else{ + update_status(gettext("The emergingthreats md5 file does not exist...")); + update_output_window(gettext("Error copying config...")); + $emergingthreats = 'off'; + } + } +} + +/* Copy Pfsense md5 sig to snort dir */ +if ($pfsensedownload == 'on' && $pfsense_md5_check_ok != 'on') { + if (file_exists("{$tmpfname}/$pfsense_rules_filename_md5")) { + update_status(gettext("Copying Pfsense md5 sig to snort directory...")); + exec("/bin/cp {$tmpfname}/$pfsense_rules_filename_md5 {$snortdir}/$pfsense_rules_filename_md5"); + } else { + update_status(gettext("The Pfsense md5 file does not exist...")); + update_output_window(gettext("Error copying config...")); + $pfsensedownload = 'off'; + } +} + +/* Copy signatures dir to snort dir */ +if ($snortdownload == 'on') +{ + if ($snort_md5_check_ok != 'on') + { + $signature_info_chk = $config['installedpackages']['snortglobal']['signatureinfo']; + if ($premium_url_chk == 'on') + { + if (file_exists("{$snortdir}/doc/signatures")) { + update_status(gettext("Copying signatures...")); + update_output_window(gettext("May take a while...")); + exec("/bin/mv -f {$snortdir}/doc/signatures {$snortdir}/signatures"); + exec("/bin/rm -r {$snortdir}/doc/signatures"); + update_status(gettext("Done copying signatures.")); + }else{ + update_status(gettext("Directory signatures exist...")); + update_output_window(gettext("Error copying signature...")); + $snortdownload = 'off'; + } + } + } +} + +/* double make shure cleanup emerg rules that dont belong */ +if (file_exists("/usr/local/etc/snort/rules/emerging-botcc-BLOCK.rules")) { + apc_clear_cache(); + @unlink("/usr/local/etc/snort/rules/emerging-botcc-BLOCK.rules"); + @unlink("/usr/local/etc/snort/rules/emerging-botcc.rules"); + @unlink("/usr/local/etc/snort/rules/emerging-compromised-BLOCK.rules"); + @unlink("/usr/local/etc/snort/rules/emerging-drop-BLOCK.rules"); + @unlink("/usr/local/etc/snort/rules/emerging-dshield-BLOCK.rules"); + @unlink("/usr/local/etc/snort/rules/emerging-rbn-BLOCK.rules"); + @unlink("/usr/local/etc/snort/rules/emerging-tor-BLOCK.rules"); +} + +if (file_exists("/usr/local/lib/snort/dynamicrules/lib_sfdynamic_example_rule.so")) { + exec("/bin/rm /usr/local/lib/snort/dynamicrules/lib_sfdynamic_example_rule.so"); + exec("/bin/rm /usr/local/lib/snort/dynamicrules/lib_sfdynamic_example\*"); +} + +/* make shure default rules are in the right format */ +exec("/usr/local/bin/perl -pi -e 's/#alert/# alert/g' /usr/local/etc/snort/rules/*.rules"); +exec("/usr/local/bin/perl -pi -e 's/##alert/# alert/g' /usr/local/etc/snort/rules/*.rules"); +exec("/usr/local/bin/perl -pi -e 's/## alert/# alert/g' /usr/local/etc/snort/rules/*.rules"); + +/* create a msg-map for snort */ +update_status(gettext("Updating Alert Messages...")); +update_output_window(gettext("Please Wait...")); +exec("/usr/local/bin/perl /usr/local/bin/create-sidmap.pl /usr/local/etc/snort/rules > /usr/local/etc/snort/sid-msg.map"); + + +////////////////// +/* open oinkmaster_conf for writing" function */ +function oinkmaster_conf($id, $if_real, $iface_uuid) +{ + global $config, $g, $snort_md5_check_ok, $emerg_md5_check_ok, $pfsense_md5_check_ok; + + @unlink("/usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/oinkmaster_{$iface_uuid}_{$if_real}.conf"); + + /* enable disable setting will carry over with updates */ + /* TODO carry signature changes with the updates */ + if ($snort_md5_check_ok != 'on' || $emerg_md5_check_ok != 'on' || $pfsense_md5_check_ok != 'on') { + + $selected_sid_on_section = ""; + $selected_sid_off_sections = ""; + + if (!empty($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_on'])) { + $enabled_sid_on = trim($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_on']); + $enabled_sid_on_array = split('\|\|', $enabled_sid_on); + foreach($enabled_sid_on_array as $enabled_item_on) + $selected_sid_on_sections .= "$enabled_item_on\n"; + } + + if (!empty($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_off'])) { + $enabled_sid_off = trim($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_off']); + $enabled_sid_off_array = split('\|\|', $enabled_sid_off); + foreach($enabled_sid_off_array as $enabled_item_off) + $selected_sid_off_sections .= "$enabled_item_off\n"; + } + + if (!empty($selected_sid_off_sections) || !empty($selected_sid_on_section)) { + $snort_sid_text = <<<EOD + +########################################### +# # +# this is auto generated on snort updates # +# # +########################################### + +path = /bin:/usr/bin:/usr/local/bin + +update_files = \.rules$|\.config$|\.conf$|\.txt$|\.map$ + +url = dir:///usr/local/etc/snort/rules + +$selected_sid_on_sections + +$selected_sid_off_sections + +EOD; + + /* open snort's oinkmaster.conf for writing */ + @file_put_contents("/usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/oinkmaster_{$iface_uuid}_{$if_real}.conf", $snort_sid_text); + } + } +} + +/* Run oinkmaster to snort_wan and cp configs */ +/* If oinkmaster is not needed cp rules normally */ +/* TODO add per interface settings here */ +function oinkmaster_run($id, $if_real, $iface_uuid) +{ + global $config, $g, $snortdir_wan, $snortdir, $snort_md5_check_ok, $emerg_md5_check_ok, $pfsense_md5_check_ok; + + if ($snort_md5_check_ok != 'on' || $emerg_md5_check_ok != 'on' || $pfsense_md5_check_ok != 'on') { + if (empty($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_on']) && empty($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_off'])) { + update_status(gettext("Your first set of rules are being copied...")); + update_output_window(gettext("May take a while...")); + exec("/bin/cp {$snortdir}/rules/* {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}/rules/"); + exec("/bin/cp {$snortdir}/classification.config {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/gen-msg.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/generators {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/reference.config {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/sid {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/sid-msg.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/unicode.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + } else { + update_status(gettext("Your enable and disable changes are being applied to your fresh set of rules...")); + update_output_window(gettext("May take a while...")); + exec("/bin/cp {$snortdir}/rules/* {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}/rules/"); + exec("/bin/cp {$snortdir}/classification.config {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/gen-msg.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/generators {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/reference.config {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/sid {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/sid-msg.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/unicode.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + + /* might have to add a sleep for 3sec for flash drives or old drives */ + exec("/usr/local/bin/perl /usr/local/bin/oinkmaster.pl -C /usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/oinkmaster_{$iface_uuid}_{$if_real}.conf -o /usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules > /usr/local/etc/snort/oinkmaster_{$iface_uuid}_{$if_real}.log"); + + } + } +} + +/* Start the proccess for every interface rule */ +/* TODO: try to make the code smother */ +if (is_array($config['installedpackages']['snortglobal']['rule'])) +{ + foreach ($config['installedpackages']['snortglobal']['rule'] as $id => $value) { + $result_lan = $value['interface']; + $if_real = snort_get_real_interface($result_lan); + $iface_uuid = $value['uuid']; + + /* make oinkmaster.conf for each interface rule */ + oinkmaster_conf($id, $if_real, $iface_uuid); + + /* run oinkmaster for each interface rule */ + oinkmaster_run($id, $if_real, $iface_uuid); + } +} + +////////////// + +/* mark the time update finnished */ +$config['installedpackages']['snortglobal']['last_rules_install'] = date("Y-M-jS-h:i-A"); + +/* remove old $tmpfname files */ +if (is_dir('/usr/local/etc/snort/tmp')) { + update_status(gettext("Cleaning up...")); + exec("/bin/rm -r /usr/local/etc/snort/tmp/snort_rules_up"); + sleep(2); + exec("/bin/rm -r /usr/local/etc/snort/tmp/rules_bk"); +} + +/* XXX: These are needed if snort is run as snort user +mwexec("/usr/sbin/chown -R snort:snort /var/log/snort", true); +mwexec("/usr/sbin/chown -R snort:snort /usr/local/etc/snort", true); +mwexec("/usr/sbin/chown -R snort:snort /usr/local/lib/snort", true); +*/ +/* make all dirs snorts */ +mwexec("/bin/chmod -R 755 /var/log/snort", true); +mwexec("/bin/chmod -R 755 /usr/local/etc/snort", true); +mwexec("/bin/chmod -R 755 /usr/local/lib/snort", true); + +if ($snortdownload == 'off' && $emergingthreats == 'off' && $pfsensedownload == 'off') + update_output_window(gettext("Finished...")); +else if ($snort_md5_check_ok == 'on' && $emerg_md5_check_ok == 'on' && $pfsense_md5_check_ok == 'on') + update_output_window(gettext("Finished...")); +else { + /* You are Not Up to date, always stop snort when updating rules for low end machines */; + update_status(gettext("You are NOT up to date...")); + exec("/bin/sh /usr/local/etc/rc.d/snort.sh start"); + update_status(gettext("The Rules update finished...")); + update_output_window(gettext("Snort has restarted with your new set of rules...")); + exec("/bin/rm /tmp/snort_download_halt.pid"); +} + +update_status(gettext("The Rules update finished...")); +conf_mount_ro(); + +?> diff --git a/config/snort-dev/snort_define_servers.php b/config/snort-dev/snort_define_servers.php index 05e7709e..497f0a79 100644 --- a/config/snort-dev/snort_define_servers.php +++ b/config/snort-dev/snort_define_servers.php @@ -1,19 +1,13 @@ <?php /* $Id$ */ /* - - part of pfSense - All rights reserved. + snort_define_servers.php + part of m0n0wall (http://m0n0.ch/wall) Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + Copyright (C) 2008-2009 Robert Zelaya. All rights reserved. - Pfsense Old snort GUI - Copyright (C) 2006 Scott Ullrich. - - Pfsense snort GUI - Copyright (C) 2008-2012 Robert Zelaya. - Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -24,10 +18,6 @@ notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - 3. Neither the name of the pfSense nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - 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 @@ -38,413 +28,514 @@ 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. - */ +/* + +TODO: Nov 12 09 +Clean this code up its ugly +Important add error checking + +*/ + +//require_once("globals.inc"); require_once("guiconfig.inc"); -require_once("/usr/local/pkg/snort/snort_new.inc"); require_once("/usr/local/pkg/snort/snort_gui.inc"); +require_once("/usr/local/pkg/snort/snort.inc"); -//Set no caching -header("Expires: Mon, 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"); - -// set page vars +global $g; -$uuid = $_GET['uuid']; -if (isset($_POST['uuid'])) -$uuid = $_POST['uuid']; +$id = $_GET['id']; +if (isset($_POST['id'])) + $id = $_POST['id']; +if (is_null($id)) { + header("Location: /snort/snort_interfaces.php"); + exit; +} -if ($uuid == '') { - echo 'error: no uuid'; - exit(0); +if (!is_array($config['installedpackages']['snortglobal']['rule'])) { + $config['installedpackages']['snortglobal']['rule'] = array(); +} +$a_nat = &$config['installedpackages']['snortglobal']['rule']; + +$pconfig = array(); +if (isset($id) && $a_nat[$id]) { + $pconfig = $a_nat[$id]; + + /* old options */ + $pconfig['def_dns_servers'] = $a_nat[$id]['def_dns_servers']; + $pconfig['def_dns_ports'] = $a_nat[$id]['def_dns_ports']; + $pconfig['def_smtp_servers'] = $a_nat[$id]['def_smtp_servers']; + $pconfig['def_smtp_ports'] = $a_nat[$id]['def_smtp_ports']; + $pconfig['def_mail_ports'] = $a_nat[$id]['def_mail_ports']; + $pconfig['def_http_servers'] = $a_nat[$id]['def_http_servers']; + $pconfig['def_www_servers'] = $a_nat[$id]['def_www_servers']; + $pconfig['def_http_ports'] = $a_nat[$id]['def_http_ports']; + $pconfig['def_sql_servers'] = $a_nat[$id]['def_sql_servers']; + $pconfig['def_oracle_ports'] = $a_nat[$id]['def_oracle_ports']; + $pconfig['def_mssql_ports'] = $a_nat[$id]['def_mssql_ports']; + $pconfig['def_telnet_servers'] = $a_nat[$id]['def_telnet_servers']; + $pconfig['def_telnet_ports'] = $a_nat[$id]['def_telnet_ports']; + $pconfig['def_snmp_servers'] = $a_nat[$id]['def_snmp_servers']; + $pconfig['def_snmp_ports'] = $a_nat[$id]['def_snmp_ports']; + $pconfig['def_ftp_servers'] = $a_nat[$id]['def_ftp_servers']; + $pconfig['def_ftp_ports'] = $a_nat[$id]['def_ftp_ports']; + $pconfig['def_ssh_servers'] = $a_nat[$id]['def_ssh_servers']; + $pconfig['def_ssh_ports'] = $a_nat[$id]['def_ssh_ports']; + $pconfig['def_pop_servers'] = $a_nat[$id]['def_pop_servers']; + $pconfig['def_pop2_ports'] = $a_nat[$id]['def_pop2_ports']; + $pconfig['def_pop3_ports'] = $a_nat[$id]['def_pop3_ports']; + $pconfig['def_imap_servers'] = $a_nat[$id]['def_imap_servers']; + $pconfig['def_imap_ports'] = $a_nat[$id]['def_imap_ports']; + $pconfig['def_sip_proxy_ip'] = $a_nat[$id]['def_sip_proxy_ip']; + $pconfig['def_sip_servers'] = $a_nat[$id]['def_sip_servers']; + $pconfig['def_sip_ports'] = $a_nat[$id]['def_sip_ports']; + $pconfig['def_sip_proxy_ports'] = $a_nat[$id]['def_sip_proxy_ports']; + $pconfig['def_auth_ports'] = $a_nat[$id]['def_auth_ports']; + $pconfig['def_finger_ports'] = $a_nat[$id]['def_finger_ports']; + $pconfig['def_irc_ports'] = $a_nat[$id]['def_irc_ports']; + $pconfig['def_nntp_ports'] = $a_nat[$id]['def_nntp_ports']; + $pconfig['def_rlogin_ports'] = $a_nat[$id]['def_rlogin_ports']; + $pconfig['def_rsh_ports'] = $a_nat[$id]['def_rsh_ports']; + $pconfig['def_ssl_ports'] = $a_nat[$id]['def_ssl_ports']; } +/* convert fake interfaces to real */ +$if_real = snort_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) { + + $natent = array(); + $natent = $pconfig; + + /* if no errors write to conf */ + if (!$input_errors) { + /* post new options */ + if ($_POST['def_dns_servers'] != "") { $natent['def_dns_servers'] = $_POST['def_dns_servers']; }else{ $natent['def_dns_servers'] = ""; } + if ($_POST['def_dns_ports'] != "") { $natent['def_dns_ports'] = $_POST['def_dns_ports']; }else{ $natent['def_dns_ports'] = ""; } + if ($_POST['def_smtp_servers'] != "") { $natent['def_smtp_servers'] = $_POST['def_smtp_servers']; }else{ $natent['def_smtp_servers'] = ""; } + if ($_POST['def_smtp_ports'] != "") { $natent['def_smtp_ports'] = $_POST['def_smtp_ports']; }else{ $natent['def_smtp_ports'] = ""; } + if ($_POST['def_mail_ports'] != "") { $natent['def_mail_ports'] = $_POST['def_mail_ports']; }else{ $natent['def_mail_ports'] = ""; } + if ($_POST['def_http_servers'] != "") { $natent['def_http_servers'] = $_POST['def_http_servers']; }else{ $natent['def_http_servers'] = ""; } + if ($_POST['def_www_servers'] != "") { $natent['def_www_servers'] = $_POST['def_www_servers']; }else{ $natent['def_www_servers'] = ""; } + if ($_POST['def_http_ports'] != "") { $natent['def_http_ports'] = $_POST['def_http_ports']; }else{ $natent['def_http_ports'] = ""; } + if ($_POST['def_sql_servers'] != "") { $natent['def_sql_servers'] = $_POST['def_sql_servers']; }else{ $natent['def_sql_servers'] = ""; } + if ($_POST['def_oracle_ports'] != "") { $natent['def_oracle_ports'] = $_POST['def_oracle_ports']; }else{ $natent['def_oracle_ports'] = ""; } + if ($_POST['def_mssql_ports'] != "") { $natent['def_mssql_ports'] = $_POST['def_mssql_ports']; }else{ $natent['def_mssql_ports'] = ""; } + if ($_POST['def_telnet_servers'] != "") { $natent['def_telnet_servers'] = $_POST['def_telnet_servers']; }else{ $natent['def_telnet_servers'] = ""; } + if ($_POST['def_telnet_ports'] != "") { $natent['def_telnet_ports'] = $_POST['def_telnet_ports']; }else{ $natent['def_telnet_ports'] = ""; } + if ($_POST['def_snmp_servers'] != "") { $natent['def_snmp_servers'] = $_POST['def_snmp_servers']; }else{ $natent['def_snmp_servers'] = ""; } + if ($_POST['def_snmp_ports'] != "") { $natent['def_snmp_ports'] = $_POST['def_snmp_ports']; }else{ $natent['def_snmp_ports'] = ""; } + if ($_POST['def_ftp_servers'] != "") { $natent['def_ftp_servers'] = $_POST['def_ftp_servers']; }else{ $natent['def_ftp_servers'] = ""; } + if ($_POST['def_ftp_ports'] != "") { $natent['def_ftp_ports'] = $_POST['def_ftp_ports']; }else{ $natent['def_ftp_ports'] = ""; } + if ($_POST['def_ssh_servers'] != "") { $natent['def_ssh_servers'] = $_POST['def_ssh_servers']; }else{ $natent['def_ssh_servers'] = ""; } + if ($_POST['def_ssh_ports'] != "") { $natent['def_ssh_ports'] = $_POST['def_ssh_ports']; }else{ $natent['def_ssh_ports'] = ""; } + if ($_POST['def_pop_servers'] != "") { $natent['def_pop_servers'] = $_POST['def_pop_servers']; }else{ $natent['def_pop_servers'] = ""; } + if ($_POST['def_pop2_ports'] != "") { $natent['def_pop2_ports'] = $_POST['def_pop2_ports']; }else{ $natent['def_pop2_ports'] = ""; } + if ($_POST['def_pop3_ports'] != "") { $natent['def_pop3_ports'] = $_POST['def_pop3_ports']; }else{ $natent['def_pop3_ports'] = ""; } + if ($_POST['def_imap_servers'] != "") { $natent['def_imap_servers'] = $_POST['def_imap_servers']; }else{ $natent['def_imap_servers'] = ""; } + if ($_POST['def_imap_ports'] != "") { $natent['def_imap_ports'] = $_POST['def_imap_ports']; }else{ $natent['def_imap_ports'] = ""; } + if ($_POST['def_sip_proxy_ip'] != "") { $natent['def_sip_proxy_ip'] = $_POST['def_sip_proxy_ip']; }else{ $natent['def_sip_proxy_ip'] = ""; } + if ($_POST['def_sip_proxy_ports'] != "") { $natent['def_sip_proxy_ports'] = $_POST['def_sip_proxy_ports']; }else{ $natent['def_sip_proxy_ports'] = ""; } + if ($_POST['def_sip_servers'] != "") { $natent['def_sip_servers'] = $_POST['def_sip_servers']; }else{ $natent['def_sip_servers'] = ""; } + if ($_POST['def_sip_ports'] != "") { $natent['def_sip_ports'] = $_POST['def_sip_ports']; }else{ $natent['def_sip_ports'] = ""; } + if ($_POST['def_auth_ports'] != "") { $natent['def_auth_ports'] = $_POST['def_auth_ports']; }else{ $natent['def_auth_ports'] = ""; } + if ($_POST['def_finger_ports'] != "") { $natent['def_finger_ports'] = $_POST['def_finger_ports']; }else{ $natent['def_finger_ports'] = ""; } + if ($_POST['def_irc_ports'] != "") { $natent['def_irc_ports'] = $_POST['def_irc_ports']; }else{ $natent['def_irc_ports'] = ""; } + if ($_POST['def_nntp_ports'] != "") { $natent['def_nntp_ports'] = $_POST['def_nntp_ports']; }else{ $natent['def_nntp_ports'] = ""; } + if ($_POST['def_rlogin_ports'] != "") { $natent['def_rlogin_ports'] = $_POST['def_rlogin_ports']; }else{ $natent['def_rlogin_ports'] = ""; } + if ($_POST['def_rsh_ports'] != "") { $natent['def_rsh_ports'] = $_POST['def_rsh_ports']; }else{ $natent['def_rsh_ports'] = ""; } + if ($_POST['def_ssl_ports'] != "") { $natent['def_ssl_ports'] = $_POST['def_ssl_ports']; }else{ $natent['def_ssl_ports'] = ""; } + + + if (isset($id) && $a_nat[$id]) + $a_nat[$id] = $natent; + else { + if (is_numeric($after)) + array_splice($a_nat, $after+1, 0, array($natent)); + else + $a_nat[] = $natent; + } + + write_config(); + + sync_snort_package_config(); + + /* after click go to this page */ + 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_define_servers.php?id=$id"); + exit; + } +} -$a_list = snortSql_fetchAllSettings('snortDB', 'SnortIfaces', 'uuid', $uuid); +$pgtitle = "Snort: Interface $id$if_real Define Servers"; +include_once("head.inc"); +?> +<body + link="#0000CC" vlink="#0000CC" alink="#0000CC"> - $pgtitle = "Snort: Interface Define Servers:"; - include("/usr/local/pkg/snort/snort_head.inc"); +<?php +include("fbegin.inc"); +if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';} +echo "{$snort_general_css}\n"; ?> -<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> - -<!-- loading msg --> -<div id="loadingWaiting"> - <div class="snortModal" style="top: 200px; left: 700px;"> - <div class="snortModalTop"> - <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> - </div> - <div class="snortModalTitle"> - <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> - </div> - <div> - <p class="loadingWaitingMessage"></p> - </div> - </div> -</div> - -<?php include("fbegin.inc"); ?> -<!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"> -<a href="../index.php" id="status-link2"> -<img src="./images/transparent.gif" border="0"></img> -</a> -</div> - -<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> +<form action="snort_define_servers.php" method="post" + enctype="multipart/form-data" name="iform" id="iform"><?php + + /* Display Alert message */ + + if ($input_errors) { + print_input_errors($input_errors); // TODO: add checks + } + + if ($savemsg) { + print_info_box2($savemsg); + } + + ?> <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td> - - <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> - <ul class="newtabmenu"> - <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> - <li><a href="/snort/snort_interfaces_edit.php?uuid=<?=$uuid;?>"><span>If Settings</span></a></li> - <li><a href="/snort/snort_rulesets.php?uuid=<?=$uuid;?>"><span>Categories</span></a></li> - <li><a href="/snort/snort_rules.php?uuid=<?=$uuid;?>"><span>Rules</span></a></li> - <li><a href="/snort/snort_rulesets_ips.php?uuid=<?=$uuid;?>"><span>Ruleset Ips</span></a></li> - <li class="newtabmenu_active"><a href="/snort/snort_define_servers.php?uuid=<?=$uuid;?>"><span>Servers</span></a></li> - <li><a href="/snort/snort_preprocessors.php?uuid=<?=$uuid;?>"><span>Preprocessors</span></a></li> - <li><a href="/snort/snort_barnyard.php?uuid=<?=$uuid;?>"><span>Barnyard2</span></a></li> - </ul> - </div> - - </td> - </tr> - <tr> - <td id="tdbggrey"> - <table width="100%" border="0" cellpadding="10px" cellspacing="0"> - <tr> - <td class="tabnavtbl"> +<tr><td> +<?php + $tab_array = array(); + $tabid = 0; + $tab_array[$tabid] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); + $tabid++; + $tab_array[$tabid] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Servers"), true, "/snort/snort_define_servers.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); + display_top_tabs($tab_array); +?> +</td></tr> +<tr> + <td class="tabcont"> <table width="100%" border="0" cellpadding="6" cellspacing="0"> - <!-- START MAIN AREA --> - - <form id="iform" > - <input type="hidden" name="snortSaveSettings" value="1" /> <!-- what to do, save --> - <input type="hidden" name="dbName" value="snortDB" /> <!-- what db--> - <input type="hidden" name="dbTable" value="SnortIfaces" /> <!-- what db table--> - <input type="hidden" name="ifaceTab" value="snort_define_servers" /> <!-- what interface tab --> - <input name="uuid" type="hidden" value="<?=$uuid; ?>"> - <tr> <td width="22%" valign="top"> </td> - <td width="78%"><span class="vexpl"> - <span class="red"><strong>Note:</strong></span><br> - Please save your settings before you click start.<br> - Please make sure there are <strong>no spaces</strong> in your definitions. - </td> + <td width="78%"><span class="vexpl"><span class="red"><strong>Note:</strong></span><br> + Please save your settings before you click start.<br> + Please make sure there are <strong>no spaces</strong> in your + definitions. </td> </tr> <tr> <td colspan="2" valign="top" class="listtopic">Define Servers</td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define DNS_SERVERS</td> - <td width="78%" class="vtable"> - <input name="def_dns_servers" type="text" class="formfld" id="def_dns_servers" size="40" value="<?=$a_list['def_dns_servers']; ?>"> - <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> - </td> + <td width="78%" class="vtable"><input name="def_dns_servers" + type="text" class="formfld" id="def_dns_servers" size="40" + value="<?=htmlspecialchars($pconfig['def_dns_servers']);?>"> <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave + blank to scan all networks.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define DNS_PORTS</td> - <td width="78%" class="vtable"> - <input name="def_dns_ports" type="text" class="formfld" id="def_dns_ports" size="40" value="<?=$a_list['def_dns_ports']; ?>"> - <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 53.</span> - </td> + <td width="78%" class="vtable"><input name="def_dns_ports" + type="text" class="formfld" id="def_dns_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_dns_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is 53.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define SMTP_SERVERS</td> - <td width="78%" class="vtable"> - <input name="def_smtp_servers" type="text" class="formfld" id="def_smtp_servers" size="40" value="<?=$a_list['def_smtp_servers']; ?>"> - <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> - </td> + <td width="78%" class="vtable"><input name="def_smtp_servers" + type="text" class="formfld" id="def_smtp_servers" size="40" + value="<?=htmlspecialchars($pconfig['def_smtp_servers']);?>"> <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave + blank to scan all networks.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define SMTP_PORTS</td> - <td width="78%" class="vtable"> - <input name="def_smtp_ports" type="text" class="formfld" id="def_smtp_ports" size="40" value="<?=$a_list['def_smtp_ports']; ?>"> - <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 25.</span> - </td> + <td width="78%" class="vtable"><input name="def_smtp_ports" + type="text" class="formfld" id="def_smtp_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_smtp_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is 25.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define Mail_Ports</td> - <td width="78%" class="vtable"> - <input name="def_mail_ports" type="text" class="formfld" id="def_mail_ports" size="40" value="<?=$a_list['def_mail_ports']; ?>"> - <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 25,143,465,691.</span> - </td> + <td width="78%" class="vtable"><input name="def_mail_ports" + type="text" class="formfld" id="def_mail_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_mail_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is 25,143,465,691.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define HTTP_SERVERS</td> - <td width="78%" class="vtable"> - <input name="def_http_servers" type="text" class="formfld" id="def_http_servers" size="40" value="<?=$a_list['def_http_servers']; ?>"> - <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> - </td> + <td width="78%" class="vtable"><input name="def_http_servers" + type="text" class="formfld" id="def_http_servers" size="40" + value="<?=htmlspecialchars($pconfig['def_http_servers']);?>"> <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave + blank to scan all networks.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define WWW_SERVERS</td> - <td width="78%" class="vtable"> - <input name="def_www_servers" type="text" class="formfld" id="def_www_servers" size="40" value="<?=$a_list['def_www_servers']; ?>"> - <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> - </td> + <td width="78%" class="vtable"><input name="def_www_servers" + type="text" class="formfld" id="def_www_servers" size="40" + value="<?=htmlspecialchars($pconfig['def_www_servers']);?>"> <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave + blank to scan all networks.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define HTTP_PORTS</td> - <td width="78%" class="vtable"> - <input name="def_http_ports" type="text" class="formfld" id="def_http_ports" size="40" value="<?=$a_list['def_http_ports']; ?>"> - <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 80.</span> - </td> + <td width="78%" class="vtable"><input name="def_http_ports" + type="text" class="formfld" id="def_http_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_http_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is 80.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define SQL_SERVERS</td> - <td width="78%" class="vtable"> - <input name="def_sql_servers" type="text" class="formfld" id="def_sql_servers" size="40" value="<?=$a_list['def_sql_servers']; ?>"> - <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> - </td> + <td width="78%" class="vtable"><input name="def_sql_servers" + type="text" class="formfld" id="def_sql_servers" size="40" + value="<?=htmlspecialchars($pconfig['def_sql_servers']);?>"> <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave + blank to scan all networks.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define ORACLE_PORTS</td> - <td width="78%" class="vtable"> - <input name="def_oracle_ports" type="text" class="formfld" id="def_oracle_ports" size="40" value="<?=$a_list['def_oracle_ports']; ?>"> - <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 1521.</span> - </td> + <td width="78%" class="vtable"><input name="def_oracle_ports" + type="text" class="formfld" id="def_oracle_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_oracle_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is 1521.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define MSSQL_PORTS</td> - <td width="78%" class="vtable"> - <input name="def_mssql_ports" type="text" class="formfld" id="def_mssql_ports" size="40" value="<?=$a_list['def_mssql_ports']; ?>"> - <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 1433.</span> - </td> + <td width="78%" class="vtable"><input name="def_mssql_ports" + type="text" class="formfld" id="def_mssql_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_mssql_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is 1433.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define TELNET_SERVERS</td> - <td width="78%" class="vtable"> - <input name="def_telnet_servers" type="text" class="formfld" id="def_telnet_servers" size="40" value="<?=$a_list['def_telnet_servers']; ?>"> - <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> - </td> + <td width="78%" class="vtable"><input name="def_telnet_servers" + type="text" class="formfld" id="def_telnet_servers" size="40" + value="<?=htmlspecialchars($pconfig['def_telnet_servers']);?>"> <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave + blank to scan all networks.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define TELNET_PORTS</td> - <td width="78%" class="vtable"> - <input name="def_telnet_ports" type="text" class="formfld" id="def_telnet_ports" size="40" value="<?=$a_list['def_telnet_ports']; ?>"> - <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 23.</span> - </td> + <td width="78%" class="vtable"><input name="def_telnet_ports" + type="text" class="formfld" id="def_telnet_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_telnet_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is 23.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define SNMP_SERVERS</td> - <td width="78%" class="vtable"> - <input name="def_snmp_servers" type="text" class="formfld" id="def_snmp_servers" size="40" value="<?=$a_list['def_snmp_servers']; ?>"> - <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> - </td> + <td width="78%" class="vtable"><input name="def_snmp_servers" + type="text" class="formfld" id="def_snmp_servers" size="40" + value="<?=htmlspecialchars($pconfig['def_snmp_servers']);?>"> <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave + blank to scan all networks.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define SNMP_PORTS</td> - <td width="78%" class="vtable"> - <input name="def_snmp_ports" type="text" class="formfld" id="def_snmp_ports" size="40" value="<?=$a_list['def_snmp_ports']; ?>"> - <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 161.</span></td> + <td width="78%" class="vtable"><input name="def_snmp_ports" + type="text" class="formfld" id="def_snmp_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_snmp_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is 161.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define FTP_SERVERS</td> - <td width="78%" class="vtable"> - <input name="def_ftp_servers" type="text" class="formfld" id="def_ftp_servers" size="40" value="<?=$a_list['def_ftp_servers']; ?>"> - <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> - </td> + <td width="78%" class="vtable"><input name="def_ftp_servers" + type="text" class="formfld" id="def_ftp_servers" size="40" + value="<?=htmlspecialchars($pconfig['def_ftp_servers']);?>"> <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave + blank to scan all networks.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define FTP_PORTS</td> - <td width="78%" class="vtable"> - <input name="def_ftp_ports" type="text" class="formfld" id="def_ftp_ports" size="40" value="<?=$a_list['def_ftp_ports']; ?>"> - <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 21.</span> - </td> + <td width="78%" class="vtable"><input name="def_ftp_ports" + type="text" class="formfld" id="def_ftp_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_ftp_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is 21.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define SSH_SERVERS</td> - <td width="78%" class="vtable"> - <input name="def_ssh_servers" type="text" class="formfld" id="def_ssh_servers" size="40" value="<?=$a_list['def_ssh_servers']; ?>"> - <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> - </td> + <td width="78%" class="vtable"><input name="def_ssh_servers" + type="text" class="formfld" id="def_ssh_servers" size="40" + value="<?=htmlspecialchars($pconfig['def_ssh_servers']);?>"> <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave + blank to scan all networks.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define SSH_PORTS</td> - <td width="78%" class="vtable"> - <input name="def_ssh_ports" type="text" class="formfld" id="def_ssh_ports" size="40" value="<?=$a_list['def_ssh_ports']; ?>"> - <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is Pfsense SSH port.</span> - </td> + <td width="78%" class="vtable"><input name="def_ssh_ports" + type="text" class="formfld" id="def_ssh_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_ssh_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is the firewall's SSH port.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define POP_SERVERS</td> - <td width="78%" class="vtable"> - <input name="def_pop_servers" type="text" class="formfld" id="def_pop_servers" size="40" value="<?=$a_list['def_pop_servers']; ?>"> - <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> - </td> + <td width="78%" class="vtable"><input name="def_pop_servers" + type="text" class="formfld" id="def_pop_servers" size="40" + value="<?=htmlspecialchars($pconfig['def_pop_servers']);?>"> <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave + blank to scan all networks.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define POP2_PORTS</td> - <td width="78%" class="vtable"> - <input name="def_pop2_ports" type="text" class="formfld" id="def_pop2_ports" size="40" value="<?=$a_list['def_pop2_ports']; ?>"> - <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 109.</span> - </td> + <td width="78%" class="vtable"><input name="def_pop2_ports" + type="text" class="formfld" id="def_pop2_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_pop2_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is 109.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define POP3_PORTS</td> - <td width="78%" class="vtable"> - <input name="def_pop3_ports" type="text" class="formfld" id="def_pop3_ports" size="40" value="<?=$a_list['def_pop3_ports']; ?>"> - <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 110.</span> - </td> + <td width="78%" class="vtable"><input name="def_pop3_ports" + type="text" class="formfld" id="def_pop3_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_pop3_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is 110.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define IMAP_SERVERS</td> - <td width="78%" class="vtable"> - <input name="def_imap_servers" type="text" class="formfld" id="def_imap_servers" size="40" value="<?=$a_list['def_imap_servers']; ?>"> - <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> - </td> + <td width="78%" class="vtable"><input name="def_imap_servers" + type="text" class="formfld" id="def_imap_servers" size="40" + value="<?=htmlspecialchars($pconfig['def_imap_servers']);?>"> <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave + blank to scan all networks.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define IMAP_PORTS</td> - <td width="78%" class="vtable"> - <input name="def_imap_ports" type="text" class="formfld" id="def_imap_ports" size="40" value="<?=$a_list['def_imap_ports']; ?>"> - <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 143.</span> - </td> + <td width="78%" class="vtable"><input name="def_imap_ports" + type="text" class="formfld" id="def_imap_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_imap_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is 143.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define SIP_PROXY_IP</td> - <td width="78%" class="vtable"> - <input name="def_sip_proxy_ip" type="text" class="formfld" id="def_sip_proxy_ip" size="40" value="<?=$a_list['def_sip_proxy_ip']; ?>"> - <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> - </td> + <td width="78%" class="vtable"><input name="def_sip_proxy_ip" + type="text" class="formfld" id="def_sip_proxy_ip" size="40" + value="<?=htmlspecialchars($pconfig['def_sip_proxy_ip']);?>"> <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave + blank to scan all networks.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define SIP_PROXY_PORTS</td> - <td width="78%" class="vtable"> - <input name="def_sip_proxy_ports" type="text" class="formfld" id="def_sip_proxy_ports" size="40" value="<?=$a_list['def_sip_proxy_ports']; ?>"> - <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 5060:5090,16384:32768.</span> - </td> - </tr> + <td width="78%" class="vtable"><input name="def_sip_proxy_ports" + type="text" class="formfld" id="def_sip_proxy_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_sip_proxy_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is 5060:5090,16384:32768.</span></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define SIP_SERVERS</td> + <td width="78%" class="vtable"><input name="def_sip_servers" + type="text" class="formfld" id="def_sip_servers" size="40" + value="<?=htmlspecialchars($pconfig['def_sip_servers']);?>"> <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave + blank to scan all networks.</span></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define SIP_PORTS</td> + <td width="78%" class="vtable"><input name="def_sip_ports" + type="text" class="formfld" id="def_sip_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_sip_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is 5060:5090,16384:32768.</span></td> + </tr> <tr> <td width="22%" valign="top" class="vncell2">Define AUTH_PORTS</td> - <td width="78%" class="vtable"> - <input name="def_auth_ports" type="text" class="formfld" id="def_auth_ports" size="40" value="<?=$a_list['def_auth_ports']; ?>"> - <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 113.</span> - </td> + <td width="78%" class="vtable"><input name="def_auth_ports" + type="text" class="formfld" id="def_auth_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_auth_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is 113.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define FINGER_PORTS</td> - <td width="78%" class="vtable"> - <input name="def_finger_ports" type="text" class="formfld" id="def_finger_ports" size="40" value="<?=$a_list['def_finger_ports']; ?>"> - <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 79.</span> - </td> + <td width="78%" class="vtable"><input name="def_finger_ports" + type="text" class="formfld" id="def_finger_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_finger_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is 79.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define IRC_PORTS</td> - <td width="78%" class="vtable"> - <input name="def_irc_ports" type="text" class="formfld" id="def_irc_ports" size="40" value="<?=$a_list['def_irc_ports']; ?>"> - <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 6665,6666,6667,6668,6669,7000.</span> - </td> + <td width="78%" class="vtable"><input name="def_irc_ports" + type="text" class="formfld" id="def_irc_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_irc_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is 6665,6666,6667,6668,6669,7000.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define NNTP_PORTS</td> - <td width="78%" class="vtable"> - <input name="def_nntp_ports" type="text" class="formfld" id="def_nntp_ports" size="40" value="<?=$a_list['def_nntp_ports']; ?>"> - <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 119.</span> - </td> + <td width="78%" class="vtable"><input name="def_nntp_ports" + type="text" class="formfld" id="def_nntp_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_nntp_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is 119.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define RLOGIN_PORTS</td> - <td width="78%" class="vtable"> - <input name="def_rlogin_ports" type="text" class="formfld" id="def_rlogin_ports" size="40" value="<?=$a_list['def_rlogin_ports']; ?>"> - <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 513.</span> - </td> + <td width="78%" class="vtable"><input name="def_rlogin_ports" + type="text" class="formfld" id="def_rlogin_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_rlogin_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is 513.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define RSH_PORTS</td> - <td width="78%" class="vtable"> - <input name="def_rsh_ports" type="text" class="formfld" id="def_rsh_ports" size="40" value="<?=$a_list['def_rsh_ports']; ?>"> - <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 514.</span> - </td> + <td width="78%" class="vtable"><input name="def_rsh_ports" + type="text" class="formfld" id="def_rsh_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_rsh_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is 514.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define SSL_PORTS</td> - <td width="78%" class="vtable"> - <input name="def_ssl_ports" type="text" class="formfld" id="def_ssl_ports" size="40" value="<?=$a_list['def_ssl_ports']; ?>"> - <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 25,443,465,636,993,995.</span> - </td> + <td width="78%" class="vtable"><input name="def_ssl_ports" + type="text" class="formfld" id="def_ssl_ports" size="40" + value="<?=htmlspecialchars($pconfig['def_ssl_ports']);?>"> <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports + betwen "5060:5090 . Default is 25,443,465,636,993,995.</span></td> </tr> <tr> <td width="22%" valign="top"> </td> <td width="78%"> <input name="Submit" type="submit" class="formbtn" value="Save"> - <input id="cancel" type="button" class="formbtn" value="Cancel"> + <input name="id" type="hidden" value="<?=$id;?>"> </td> </tr> <tr> <td width="22%" valign="top"> </td> - <td width="78%"> - <span class="vexpl"><span class="red"><strong>Note:</strong></span> - <br> - Please save your settings before you click start.</span> - </td> + <td width="78%"><span class="vexpl"><span class="red"><strong>Note:</strong></span> + <br> + Please save your settings before you click start. </td> </tr> - - - - - </form> - <!-- STOP MAIN AREA --> </table> - </td> - </tr> - </table> - </td> - </tr> -</table> -</div> - - -<!-- footer do not touch below --> -<?php -include("fend.inc"); -echo $snort_custom_rnd_box; -?> - +</table> +</form> +<?php include("fend.inc"); ?> </body> </html> diff --git a/config/snort-dev/snort_download_rules.php b/config/snort-dev/snort_download_rules.php new file mode 100644 index 00000000..521a7b0f --- /dev/null +++ b/config/snort-dev/snort_download_rules.php @@ -0,0 +1,776 @@ +<?php +/* + snort_download_rules.php + Copyright (C) 2006 Scott Ullrich + Copyright (C) 2009 Robert Zelaya + Copyright (C) 2011 Ermal Luci + 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. + */ + +/* Setup enviroment */ +require_once("guiconfig.inc"); +require_once("functions.inc"); +require_once("service-utils.inc"); +require_once("/usr/local/pkg/snort/snort.inc"); + +if ($_GET['return']) { + header("Location: /snort/snort_download_updates.php"); + exit; +} + +$tmpfname = "/usr/local/etc/snort/tmp/snort_rules_up"; +$snortdir = "/usr/local/etc/snort"; +$snortdir_wan = "/usr/local/etc/snort"; +$snort_filename_md5 = "{$snort_rules_file}.md5"; +$snort_filename = "{$snort_rules_file}"; +$emergingthreats_filename_md5 = "emerging.rules.tar.gz.md5"; +$emergingthreats_filename = "emerging.rules.tar.gz"; +$pfsense_rules_filename_md5 = "pfsense_rules.tar.gz.md5"; +$pfsense_rules_filename = "pfsense_rules.tar.gz"; + +/* Time stamps define */ +$last_md5_download = $config['installedpackages']['snortglobal']['last_md5_download']; +$last_rules_install = $config['installedpackages']['snortglobal']['last_rules_install']; + +/* define checks */ +$oinkid = $config['installedpackages']['snortglobal']['oinkmastercode']; +$snortdownload = $config['installedpackages']['snortglobal']['snortdownload']; +$emergingthreats = $config['installedpackages']['snortglobal']['emergingthreats']; + +if ($snortdownload == 'off' && $emergingthreats != 'on') + $snort_emrging_info = 'stop'; + +if ($oinkid == "" && $snortdownload != 'off') + $snort_oinkid_info = 'stop'; + +/* check if main rule directory is empty */ +$if_mrule_dir = "/usr/local/etc/snort/rules"; +$mfolder_chk = (count(glob("$if_mrule_dir/*")) === 0) ? 'empty' : 'full'; + +if (file_exists('/var/run/snort.conf.dirty')) + $snort_dirty_d = 'stop'; + +$pgtitle = "Services: Snort: Update Rules"; + +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"> +<table width="100%" border="0" cellpadding="0" cellspacing="0"> +<tr> + <td> + <div id="mainarea"> + <table class="tabcont" width="100%" border="0" cellpadding="6" cellspacing="0"> + <tr> + <td ><!-- progress bar --> + <table id="progholder" width='320' + style='border-collapse: collapse; border: 1px solid #000000;' + cellpadding='2' cellspacing='2'> + <tr> + <td><img border='0' + src='../themes/<?= $g['theme']; ?>/images/misc/progress_bar.gif' + width='280' height='23' name='progressbar' id='progressbar' + alt='' /> + </td> + </tr> + </table> + <br /> + <!-- status box --> <textarea cols="60" rows="2" name="status" id="status" wrap="hard"> + <?=gettext("Initializing...");?> + </textarea> + <!-- command output box --> <textarea cols="60" rows="2" name="output" id="output" wrap="hard"> + </textarea> + </td> + </tr> + </table> + </div> + </td> +</tr> +<tr><td><input type="submit" Value="Return"></td></tr> +</table> +</form> +<?php include("fend.inc");?> +</body> +</html> + +<?php +/* Start of code */ +conf_mount_rw(); + +if (!is_dir('/usr/local/etc/snort/tmp')) + exec('/bin/mkdir -p /usr/local/etc/snort/tmp'); + +$snort_md5_check_ok = 'off'; +$emerg_md5_check_ok = 'off'; +$pfsense_md5_check_ok = 'off'; + +/* Set user agent to Mozilla */ +ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)'); +ini_set("memory_limit","150M"); + +/* mark the time update started */ +$config['installedpackages']['snortglobal']['last_md5_download'] = date("Y-M-jS-h:i-A"); + +/* send current buffer */ +ob_flush(); + +/* hide progress bar */ +hide_progress_bar_status(); + +/* send current buffer */ +ob_flush(); + +/* remove old $tmpfname files */ +if (is_dir("{$tmpfname}")) { + update_status(gettext("Removing old tmp files...")); + exec("/bin/rm -r {$tmpfname}"); + apc_clear_cache(); +} + +/* Make shure snortdir exits */ +exec("/bin/mkdir -p {$snortdir}"); +exec("/bin/mkdir -p {$snortdir}/rules"); +exec("/bin/mkdir -p {$snortdir}/signatures"); +exec("/bin/mkdir -p {$tmpfname}"); +exec("/bin/mkdir -p /usr/local/lib/snort/dynamicrules/"); + +/* send current buffer */ +ob_flush(); + +/* unhide progress bar and lets end this party */ +unhide_progress_bar_status(); + +$pfsensedownload = 'on'; + +/* download md5 sig from snort.org */ +if ($snortdownload == 'on') +{ + if (file_exists("{$tmpfname}/{$snort_filename_md5}") && + filesize("{$tmpfname}/{$snort_filename_md5}") > 0) { + update_status(gettext("snort.org md5 temp file exists...")); + } else { + update_status(gettext("Downloading snort.org md5 file...")); + ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)'); + + //$image = @file_get_contents("http://www.mtest.local/pub-bin/oinkmaster.cgi/{$oinkid}/{$snort_filename_md5}"); + $image = @file_get_contents("http://www.snort.org/pub-bin/oinkmaster.cgi/{$oinkid}/{$snort_filename_md5}"); + @file_put_contents("{$tmpfname}/{$snort_filename_md5}", $image); + update_status(gettext("Done downloading snort.org md5")); + } +} + +/* download md5 sig from emergingthreats.net */ +if ($emergingthreats == 'on') +{ + update_status(gettext("Downloading emergingthreats md5 file...")); + ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)'); + // $image = @file_get_contents("http://www.mtest.local/pub-bin/oinkmaster.cgi/{$oinkid}/version.txt"); + $image = @file_get_contents('http://rules.emergingthreats.net/open/snort-2.9.0/emerging.rules.tar.gz.md5'); + @file_put_contents("{$tmpfname}/{$emergingthreats_filename_md5}", $image); + update_status(gettext("Done downloading emergingthreats md5")); +} + +/* download md5 sig from pfsense.org */ +if (file_exists("{$tmpfname}/{$pfsense_rules_filename_md5}")) { + update_status(gettext("pfsense md5 temp file exists...")); +} else { + update_status(gettext("Downloading pfsense md5 file...")); + ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)'); + //$image = @file_get_contents("http://www.mtest.local/pub-bin/oinkmaster.cgi/{$oinkid}/pfsense_rules.tar.gz.md5"); + $image = @file_get_contents("http://www.pfsense.com/packages/config/snort/pfsense_rules/pfsense_rules.tar.gz.md5"); + @file_put_contents("{$tmpfname}/pfsense_rules.tar.gz.md5", $image); + update_status(gettext("Done downloading pfsense md5.")); +} + +/* If md5 file is empty wait 15min exit */ +if ($snortdownload == 'on') +{ + if (0 == filesize("{$tmpfname}/{$snort_filename_md5}")) + { + update_status(gettext("Please wait... You may only check for New Rules every 15 minutes...")); + update_output_window(gettext("Rules are released every month from snort.org. You may download the Rules at any time.")); + hide_progress_bar_status(); + $snortdownload = 'off'; + } +} + +/* If pfsense md5 file is empty wait 15min exit */ +if (0 == filesize("{$tmpfname}/$pfsense_rules_filename_md5")){ + update_status(gettext("Please wait... You may only check for New Pfsense Rules every 15 minutes...")); + update_output_window(gettext("Rules are released to support Pfsense packages.")); + hide_progress_bar_status(); + $pfsensedownload = 'off'; +} + +/* Check if were up to date snort.org */ +if ($snortdownload == 'on') +{ + if (file_exists("{$snortdir}/{$snort_filename_md5}")) + { + $md5_check_new_parse = file_get_contents("{$tmpfname}/{$snort_filename_md5}"); + $md5_check_new = `/bin/echo "{$md5_check_new_parse}" | /usr/bin/awk '{ print $1 }'`; + $md5_check_old_parse = file_get_contents("{$snortdir}/{$snort_filename_md5}"); + $md5_check_old = `/bin/echo "{$md5_check_old_parse}" | /usr/bin/awk '{ print $1 }'`; + if ($md5_check_new == $md5_check_old) + { + update_status(gettext("Your rules are up to date...")); + update_output_window(gettext("You may start Snort now, check update.")); + hide_progress_bar_status(); + $snort_md5_check_ok = 'on'; + } else { + update_status(gettext("Your rules are not up to date...")); + $snort_md5_check_ok = 'off'; + } + } +} + +/* Check if were up to date emergingthreats.net */ +if ($emergingthreats == 'on') +{ + if (file_exists("{$snortdir}/{$emergingthreats_filename_md5}")) + { + $emerg_md5_check_new_parse = file_get_contents("{$tmpfname}/{$emergingthreats_filename_md5}"); + $emerg_md5_check_new = `/bin/echo "{$emerg_md5_check_new_parse}" | /usr/bin/awk '{ print $1 }'`; + $emerg_md5_check_old_parse = file_get_contents("{$snortdir}/{$emergingthreats_filename_md5}"); + $emerg_md5_check_old = `/bin/echo "{$emerg_md5_check_old_parse}" | /usr/bin/awk '{ print $1 }'`; + if ($emerg_md5_check_new == $emerg_md5_check_old) + { + hide_progress_bar_status(); + $emerg_md5_check_ok = 'on'; + } else + $emerg_md5_check_ok = 'off'; + } +} + +/* Check if were up to date pfsense.org */ +if ($pfsensedownload == 'on' && file_exists("{$snortdir}/pfsense_rules.tar.gz.md5")) +{ + $pfsense_check_new_parse = file_get_contents("{$tmpfname}/pfsense_rules.tar.gz.md5"); + $pfsense_md5_check_new = `/bin/echo "{$pfsense_md5_check_new_parse}" | /usr/bin/awk '{ print $1 }'`; + $pfsense_md5_check_old_parse = file_get_contents("{$snortdir}/pfsense_rules.tar.gz.md5"); + $pfsense_md5_check_old = `/bin/echo "{$pfsense_md5_check_old_parse}" | /usr/bin/awk '{ print $1 }'`; + if ($pfsense_md5_check_new == $pfsense_md5_check_old) + { + hide_progress_bar_status(); + $pfsense_md5_check_ok = 'on'; + } else + $pfsense_md5_check_ok = 'off'; +} + +if ($snortdownload == 'on') { + if ($snort_md5_check_ok == 'on') + { + update_status(gettext("Your snort.org rules are up to date...")); + update_output_window(gettext("You may start Snort now...")); + $snortdownload = 'off'; + } +} +if ($emergingthreats == 'on') { + if ($emerg_md5_check_ok == 'on') + { + update_status(gettext("Your Emergingthreats rules are up to date...")); + update_output_window(gettext("You may start Snort now...")); + $emergingthreats = 'off'; + } +} + +/* download snortrules file */ +if ($snortdownload == 'on') +{ + if ($snort_md5_check_ok != 'on') { + if (file_exists("{$tmpfname}/{$snort_filename}")) { + update_status(gettext("Snortrule tar file exists...")); + } else { + unhide_progress_bar_status(); + update_status(gettext("There is a new set of Snort.org rules posted. Downloading...")); + update_output_window(gettext("May take 4 to 10 min...")); + download_file_with_progress_bar("http://www.snort.org/pub-bin/oinkmaster.cgi/{$oinkid}/{$snort_filename}", "{$tmpfname}/{$snort_filename}"); + update_all_status($static_output); + update_status(gettext("Done downloading rules file.")); + if (150000 > filesize("{$tmpfname}/$snort_filename")){ + update_status(gettext("Error with the snort rules download...")); + + update_output_window(gettext("Snort rules file downloaded failed...")); + $snortdownload = 'off'; + } + } + } +} + +/* download emergingthreats rules file */ +if ($emergingthreats == "on") +{ + if ($emerg_md5_check_ok != 'on') + { + if (file_exists("{$tmpfname}/{$emergingthreats_filename}")) + { + update_status(gettext('Emergingthreats tar file exists...')); + }else{ + update_status(gettext("There is a new set of Emergingthreats rules posted. Downloading...")); + update_output_window(gettext("May take 4 to 10 min...")); + download_file_with_progress_bar('http://rules.emergingthreats.net/open/snort-2.9.0/emerging.rules.tar.gz', "{$tmpfname}/{$emergingthreats_filename}"); + update_status(gettext('Done downloading Emergingthreats rules file.')); + } + } +} + +/* download pfsense rules file */ +if ($pfsensedownload == 'on' && $pfsense_md5_check_ok != 'on') { + if (file_exists("{$tmpfname}/{$pfsense_rules_filename}")) { + update_status(gettext("Snortrule tar file exists...")); + } else { + unhide_progress_bar_status(); + update_status(gettext("There is a new set of Pfsense rules posted. Downloading...")); + update_output_window(gettext("May take 4 to 10 min...")); + download_file_with_progress_bar("http://www.pfsense.com/packages/config/snort/pfsense_rules/pfsense_rules.tar.gz", $tmpfname . "/{$pfsense_rules_filename}"); + update_all_status($static_output); + update_status(gettext("Done downloading rules file.")); + } +} + +/* Compair md5 sig to file sig */ + +//$premium_url_chk = $config['installedpackages']['snort']['config'][0]['subscriber']; +//if ($premium_url_chk == on) { +//$md5 = file_get_contents("{$tmpfname}/{$snort_filename_md5}"); +//$file_md5_ondisk = `/sbin/md5 {$tmpfname}/{$snort_filename} | /usr/bin/awk '{ print $4 }'`; +// if ($md5 == $file_md5_ondisk) { +// update_status(gettext("Valid md5 checksum pass...")); +//} else { +// update_status(gettext("The downloaded file does not match the md5 file...P is ON")); +// update_output_window(gettext("Error md5 Mismatch...")); +// return; +// } +//} + +//$premium_url_chk = $config['installedpackages']['snort']['config'][0]['subscriber']; +//if ($premium_url_chk != on) { +//$md55 = `/bin/cat {$tmpfname}/{$snort_filename_md5} | /usr/bin/awk '{ print $4 }'`; +//$file_md5_ondisk2 = `/sbin/md5 {$tmpfname}/{$snort_filename} | /usr/bin/awk '{ print $4 }'`; +// if ($md55 == $file_md5_ondisk2) { +// update_status(gettext("Valid md5 checksum pass...")); +//} else { +// update_status(gettext("The downloaded file does not match the md5 file...Not P")); +// update_output_window(gettext("Error md5 Mismatch...")); +// return; +// } +//} + +/* Untar snort rules file individually to help people with low system specs */ +if ($snortdownload == 'on' && $snort_md5_check_ok != 'on') { + if (file_exists("{$tmpfname}/{$snort_filename}")) { + + // find out if were in 1.2.3-RELEASE + $pfsense_ver_chk = exec('/bin/cat /etc/version'); + if ($pfsense_ver_chk === '1.2.3-RELEASE') { + $pfsense_stable = 'yes'; + }else{ + $pfsense_stable = 'no'; + } + + // get the system arch + $snort_arch_ck = exec('/usr/bin/uname -m'); + if ($snort_arch_ck === 'i386') { + $snort_arch = 'i386'; + }else{ + $snort_arch = 'x86-64'; // amd64 + } + + if ($pfsense_stable === 'yes') { + $freebsd_version_so = 'FreeBSD-7-3'; + }else{ + $freebsd_version_so = 'FreeBSD-8-1'; + } + + update_status(gettext("Extracting Snort.org rules...")); + update_output_window(gettext("May take a while...")); + /* extract snort.org rules and add prefix to all snort.org files*/ + exec("/bin/rm -r {$snortdir}/rules"); + sleep(2); + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} rules/"); + chdir ("/usr/local/etc/snort/rules"); + sleep(2); + + $snort_dirList = scandir("{$snortdir}/rules"); // Waning: only in php 5 + $snortrules_filterList = snortscandirfilter($snort_dirList, '/.*\.rules/', '/\.rules/', ''); + + if (!empty($snortrules_filterList)) { + foreach ($snortrules_filterList as $snort_rule_move) + { + exec("/bin/mv -f {$snortdir}/rules/{$snort_rule_move}.rules {$snortdir}/rules/snort_{$snort_rule_move}.rules"); + } + } + + /* extract so_rules */ + + // list so_rules and exclude dir + exec("/usr/bin/tar --exclude='precompiled' --exclude='src' -tf {$tmpfname}/{$snort_filename} so_rules", $so_rules_list); + + $so_rulesPattr = array('/\//', '/\.rules/'); + $so_rulesPattw = array('', ''); + + // build list of so_rules + $so_rules_filterList = snortscandirfilter($so_rules_list, '/\/.*\.rules/', $so_rulesPattr, $so_rulesPattw); + + if (!empty($so_rules_filterList)) { + // cp rule to so tmp dir + foreach ($so_rules_filterList as $so_rule) + { + + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} so_rules/{$so_rule}.rules"); + + } + // mv and rename so rules + foreach ($so_rules_filterList as $so_rule_move) + { + exec("/bin/mv -f {$snortdir}/so_rules/{$so_rule_move}.rules {$snortdir}/rules/snort_{$so_rule_move}.so.rules"); + } + } + + /* extract preproc_rules */ + + // list so_rules and exclude dir + exec("/usr/bin/tar --exclude='precompiled' --exclude='src' -tf {$tmpfname}/{$snort_filename} preproc_rules", $preproc_rules_list); + + $preproc_rules_filterList = snortscandirfilter($preproc_rules_list, '/\/.*\.rules/', $so_rulesPattr, $so_rulesPattw); + + if (!empty($preproc_rules_filterList)) { + // cp rule to so tmp dir + foreach ($preproc_rules_filterList as $preproc_rule) + { + + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} preproc_rules/{$preproc_rule}.rules"); + + } + // mv and rename preproc_rules + foreach ($preproc_rules_filterList as $preproc_rule_move) + { + exec("/bin/mv -f {$snortdir}/preproc_rules/{$preproc_rule_move}.rules {$snortdir}/rules/snort_{$preproc_rule_move}.preproc.rules"); + } + } + + /* extract base etc files */ + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} etc/"); + exec("/bin/mv -f {$snortdir}/etc/* {$snortdir}"); + exec("/bin/rm -r {$snortdir}/etc"); + + update_status(gettext("Done extracting Snort.org Rules.")); + }else{ + update_status(gettext("Error extracting Snort.org Rules...")); + update_output_window(gettext("Error Line 755")); + $snortdownload = 'off'; + } +} + +/* Untar emergingthreats rules to tmp */ +if ($emergingthreats == 'on') +{ + if ($emerg_md5_check_ok != 'on') + { + if (file_exists("{$tmpfname}/{$emergingthreats_filename}")) + { + update_status(gettext("Extracting rules...")); + update_output_window(gettext("May take a while...")); + exec("/usr/bin/tar xzf {$tmpfname}/{$emergingthreats_filename} -C {$snortdir} rules/"); + } + } +} + +/* Untar Pfsense rules to tmp */ +if ($pfsensedownload == 'on' && $pfsense_md5_check_ok != 'on') { + if (file_exists("{$tmpfname}/{$pfsense_rules_filename}")) { + update_status(gettext("Extracting Pfsense rules...")); + update_output_window(gettext("May take a while...")); + exec("/usr/bin/tar xzf {$tmpfname}/{$pfsense_rules_filename} -C {$snortdir} rules/"); + } +} + +/* Untar snort signatures */ +if ($snortdownload == 'on' && $snort_md5_check_ok != 'on') { + if (file_exists("{$tmpfname}/{$snort_filename}")) { + $signature_info_chk = $config['installedpackages']['snortglobal']['signatureinfo']; + if ($premium_url_chk == 'on') { + update_status(gettext("Extracting Signatures...")); + update_output_window(gettext("May take a while...")); + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} doc/signatures/"); + update_status(gettext("Done extracting Signatures.")); + } + } +} + +/* Copy md5 sig to snort dir */ +if ($snortdownload == 'on') +{ + if ($snort_md5_check_ok != 'on') { + if (file_exists("{$tmpfname}/$snort_filename_md5")) { + update_status(gettext("Copying md5 sig to snort directory...")); + exec("/bin/cp {$tmpfname}/$snort_filename_md5 {$snortdir}/$snort_filename_md5"); + }else{ + update_status(gettext("The md5 file does not exist...")); + update_output_window(gettext("Error copying config...")); + $snortdownload = 'off'; + } + } +} + +/* Copy emergingthreats md5 sig to snort dir */ +if ($emergingthreats == "on") +{ + if ($emerg_md5_check_ok != 'on') + { + if (file_exists("{$tmpfname}/$emergingthreats_filename_md5")) + { + update_status(gettext("Copying md5 sig to snort directory...")); + exec("/bin/cp {$tmpfname}/$emergingthreats_filename_md5 {$snortdir}/$emergingthreats_filename_md5"); + }else{ + update_status(gettext("The emergingthreats md5 file does not exist...")); + update_output_window(gettext("Error copying config...")); + $emergingthreats = 'off'; + } + } +} + +/* Copy Pfsense md5 sig to snort dir */ +if ($pfsensedownload == 'on' && $pfsense_md5_check_ok != 'on') { + if (file_exists("{$tmpfname}/$pfsense_rules_filename_md5")) { + update_status(gettext("Copying Pfsense md5 sig to snort directory...")); + exec("/bin/cp {$tmpfname}/$pfsense_rules_filename_md5 {$snortdir}/$pfsense_rules_filename_md5"); + } else { + update_status(gettext("The Pfsense md5 file does not exist...")); + update_output_window(gettext("Error copying config...")); + $pfsensedownload = 'off'; + } +} + +/* Copy signatures dir to snort dir */ +if ($snortdownload == 'on') +{ + if ($snort_md5_check_ok != 'on') + { + $signature_info_chk = $config['installedpackages']['snortglobal']['signatureinfo']; + if ($premium_url_chk == 'on') + { + if (file_exists("{$snortdir}/doc/signatures")) { + update_status(gettext("Copying signatures...")); + update_output_window(gettext("May take a while...")); + exec("/bin/mv -f {$snortdir}/doc/signatures {$snortdir}/signatures"); + exec("/bin/rm -r {$snortdir}/doc/signatures"); + update_status(gettext("Done copying signatures.")); + }else{ + update_status(gettext("Directory signatures exist...")); + update_output_window(gettext("Error copying signature...")); + $snortdownload = 'off'; + } + } + } +} + +/* double make shure cleanup emerg rules that dont belong */ +if (file_exists("/usr/local/etc/snort/rules/emerging-botcc-BLOCK.rules")) { + apc_clear_cache(); + @unlink("/usr/local/etc/snort/rules/emerging-botcc-BLOCK.rules"); + @unlink("/usr/local/etc/snort/rules/emerging-botcc.rules"); + @unlink("/usr/local/etc/snort/rules/emerging-compromised-BLOCK.rules"); + @unlink("/usr/local/etc/snort/rules/emerging-drop-BLOCK.rules"); + @unlink("/usr/local/etc/snort/rules/emerging-dshield-BLOCK.rules"); + @unlink("/usr/local/etc/snort/rules/emerging-rbn-BLOCK.rules"); + @unlink("/usr/local/etc/snort/rules/emerging-tor-BLOCK.rules"); +} + +if (file_exists("/usr/local/lib/snort/dynamicrules/lib_sfdynamic_example_rule.so")) { + exec("/bin/rm /usr/local/lib/snort/dynamicrules/lib_sfdynamic_example_rule.so"); + exec("/bin/rm /usr/local/lib/snort/dynamicrules/lib_sfdynamic_example\*"); +} + +/* make shure default rules are in the right format */ +exec("/usr/bin/sed -i '' 's/^[ \t]*//' /usr/local/etc/snort/rules/*.rules"); // remove white spaces from begining of line +exec("/usr/bin/sed -i '' 's/^#alert*/\# alert/' /usr/local/etc/snort/rules/*.rules"); +exec("/usr/bin/sed -i '' 's/^##alert*/\# alert/' /usr/local/etc/snort/rules/*.rules"); +exec("/usr/bin/sed -i '' 's/^## alert*/\# alert/' /usr/local/etc/snort/rules/*.rules"); + +/* create a msg-map for snort */ +update_status(gettext("Updating Alert Messages...")); +update_output_window(gettext("Please Wait...")); +exec("/usr/local/bin/perl /usr/local/bin/create-sidmap.pl /usr/local/etc/snort/rules > /usr/local/etc/snort/sid-msg.map"); + + +////////////////// + +/* open oinkmaster_conf for writing" function */ +function oinkmaster_conf($id, $if_real, $iface_uuid) +{ + global $config, $snort_md5_check_ok, $emerg_md5_check_ok, $pfsense_md5_check_ok; + + @unlink("/usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/oinkmaster_{$iface_uuid}_{$if_real}.conf"); + + /* enable disable setting will carry over with updates */ + /* TODO carry signature changes with the updates */ + if ($snort_md5_check_ok != 'on' || $emerg_md5_check_ok != 'on' || $pfsense_md5_check_ok != 'on') { + + $selected_sid_on_sections = ""; + $selected_sid_off_sections = ""; + + if (!empty($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_on'])) { + $enabled_sid_on = trim($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_on']); + $enabled_sid_on_array = split('\|\|', $enabled_sid_on); + foreach($enabled_sid_on_array as $enabled_item_on) + $selected_sid_on_sections .= "$enabled_item_on\n"; + } + + if (!empty($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_off'])) { + $enabled_sid_off = trim($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_off']); + $enabled_sid_off_array = split('\|\|', $enabled_sid_off); + foreach($enabled_sid_off_array as $enabled_item_off) + $selected_sid_off_sections .= "$enabled_item_off\n"; + } + + if (!empty($selected_sid_on_sections) || !empty($selected_sid_off_sections)) { + $snort_sid_text = <<<EOD + +########################################### +# # +# this is auto generated on snort updates # +# # +########################################### + +path = /bin:/usr/bin:/usr/local/bin + +update_files = \.rules$|\.config$|\.conf$|\.txt$|\.map$ + +url = dir:///usr/local/etc/snort/rules + +$selected_sid_on_sections + +$selected_sid_off_sections + +EOD; + + /* open snort's oinkmaster.conf for writing */ + @file_put_contents("/usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/oinkmaster_{$iface_uuid}_{$if_real}.conf", $snort_sid_text); + } + } +} + +/* Run oinkmaster to snort_wan and cp configs */ +/* If oinkmaster is not needed cp rules normally */ +/* TODO add per interface settings here */ +function oinkmaster_run($id, $if_real, $iface_uuid) +{ + global $config, $g, $snortdir_wan, $snortdir, $snort_md5_check_ok, $emerg_md5_check_ok, $pfsense_md5_check_ok; + + if ($snort_md5_check_ok != 'on' || $emerg_md5_check_ok != 'on' || $pfsense_md5_check_ok != 'on') { + if (empty($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_on']) && empty($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_off'])) { + update_status(gettext("Your first set of rules are being copied...")); + update_output_window(gettext("May take a while...")); + exec("/bin/cp {$snortdir}/rules/* {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}/rules/"); + exec("/bin/cp {$snortdir}/classification.config {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/gen-msg.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/generators {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/reference.config {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/sid {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/sid-msg.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/unicode.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + } else { + update_status(gettext("Your enable and disable changes are being applied to your fresh set of rules...")); + update_output_window(gettext("May take a while...")); + exec("/bin/cp {$snortdir}/rules/* {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}/rules/"); + exec("/bin/cp {$snortdir}/classification.config {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/gen-msg.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/generators {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/reference.config {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/sid {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/sid-msg.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + exec("/bin/cp {$snortdir}/unicode.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); + + /* might have to add a sleep for 3sec for flash drives or old drives */ + exec("/usr/local/bin/perl /usr/local/bin/oinkmaster.pl -C /usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/oinkmaster_{$iface_uuid}_{$if_real}.conf -o /usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules > /usr/local/etc/snort/oinkmaster_{$iface_uuid}_{$if_real}.log"); + } + } +} + +/* Start the proccess for every interface rule */ +/* TODO: try to make the code smother */ +if (is_array($config['installedpackages']['snortglobal']['rule'])) +{ + foreach ($config['installedpackages']['snortglobal']['rule'] as $id => $value) { + $result_lan = $value['interface']; + $if_real = snort_get_real_interface($result_lan); + $iface_uuid = $value['uuid']; + + /* make oinkmaster.conf for each interface rule */ + oinkmaster_conf($id, $if_real, $iface_uuid); + + /* run oinkmaster for each interface rule */ + oinkmaster_run($id, $if_real, $iface_uuid); + } +} + +////////////// + +/* mark the time update finnished */ +$config['installedpackages']['snortglobal']['last_rules_install'] = date("Y-M-jS-h:i-A"); + +/* remove old $tmpfname files */ +if (is_dir('/usr/local/etc/snort/tmp')) { + update_status(gettext("Cleaning up...")); + exec("/bin/rm -r /usr/local/etc/snort/tmp/snort_rules_up"); + sleep(2); + exec("/bin/rm -r /usr/local/etc/snort/tmp/rules_bk"); +} + +/* XXX: These are needed if snort is run as snort user +mwexec("/usr/sbin/chown -R snort:snort /var/log/snort", true); +mwexec("/usr/sbin/chown -R snort:snort /usr/local/etc/snort", true); +mwexec("/usr/sbin/chown -R snort:snort /usr/local/lib/snort", true); +*/ +/* make all dirs snorts */ +mwexec("/bin/chmod -R 755 /var/log/snort", true); +mwexec("/bin/chmod -R 755 /usr/local/etc/snort", true); +mwexec("/bin/chmod -R 755 /usr/local/lib/snort", true); + +/* hide progress bar and lets end this party */ +hide_progress_bar_status(); + +if ($snortdownload == 'off' && $emergingthreats == 'off' && $pfsensedownload == 'off') + update_output_window(gettext("Finished...")); +else if ($snort_md5_check_ok == 'on' && $emerg_md5_check_ok == 'on' && $pfsense_md5_check_ok == 'on') + update_output_window(gettext("Finished...")); +else { + /* You are Not Up to date, always stop snort when updating rules for low end machines */; + update_status(gettext("You are NOT up to date...")); + exec("/bin/sh /usr/local/etc/rc.d/snort.sh start"); + update_status(gettext("The Rules update finished...")); + update_output_window(gettext("Snort has restarted with your new set of rules...")); + exec("/bin/rm /tmp/snort_download_halt.pid"); +} + +update_status(gettext("The Rules update finished...")); +conf_mount_ro(); + +?> diff --git a/config/snort-dev/snort_download_updates.php b/config/snort-dev/snort_download_updates.php index 445671bd..e902cd64 100644 --- a/config/snort-dev/snort_download_updates.php +++ b/config/snort-dev/snort_download_updates.php @@ -1,19 +1,15 @@ <?php -/* $Id$ */ /* - + snort_download_updates.php part of pfSense + Copyright (C) 2004 Scott Ullrich + Copyright (C) 2011 Ermal Luci All rights reserved. + part of m0n0wall as reboot.php (http://m0n0.ch/wall) Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. All rights reserved. - Pfsense Old snort GUI - Copyright (C) 2006 Scott Ullrich. - - Pfsense snort GUI - Copyright (C) 2008-2012 Robert Zelaya. - Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -24,10 +20,6 @@ notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - 3. Neither the name of the pfSense nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - 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 @@ -38,328 +30,293 @@ 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. - */ -// disable csrf for downloads, progressbar did not work because of this -$nocsrf = true; - require_once("guiconfig.inc"); require_once("/usr/local/pkg/snort/snort_gui.inc"); -require_once("/usr/local/pkg/snort/snort_download_rules.inc"); - -//Set no caching -header("Expires: Mon, 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"); - -// set page vars -if (isset($_GET['updatenow'])) { - $updatenow = $_GET['updatenow']; -} - -header("Cache-Control: no-cache, must-revalidate"); -header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); - -// get dates of md5s - -$tmpSettingsSnort = 'N/A'; -$tmpSettingsSnortChk = snortSql_fetchAllSettings2('snortDBtemp', 'SnortDownloads', 'filename', 'snortrules-snapshot-2905.tar.gz'); -if (!empty($tmpSettingsSnortChk)) { - $tmpSettingsSnort = date('l jS \of F Y h:i:s A', $tmpSettingsSnortChk[date]); -} - -$tmpSettingsEmerging = 'N/A'; -$tmpSettingsEmergingChk = snortSql_fetchAllSettings2('snortDBtemp', 'SnortDownloads', 'filename', 'emerging.rules.tar.gz'); -if (!empty($tmpSettingsEmergingChk)) { - $tmpSettingsEmerging = date('l jS \of F Y h:i:s A', $tmpSettingsEmergingChk[date]); -} - -$tmpSettingsPfsense = 'N/A'; -$tmpSettingsPfsenseChk = snortSql_fetchAllSettings2('snortDBtemp', 'SnortDownloads', 'filename', 'pfsense_rules.tar.gz'); -if (!empty($tmpSettingsPfsenseChk)) { - $tmpSettingsPfsense = date('l jS \of F Y h:i:s A', $tmpSettingsPfsenseChk[date]); -} - -// get rule on stats -$generalSettings = snortSql_fetchAllSettings2('snortDB', 'SnortSettings', 'id', '1'); - -$snortMd5CurrentChk = @file_get_contents('/usr/local/etc/snort/snortDBrules/snort_rules/snortrules-snapshot-2905.tar.gz.md5'); - -$snortDownlodChkMark = ''; -if ($generalSettings[snortdownload] === 'on') { - $snortDownlodChkMark = 'checked="checked"'; -} - -$snortMd5Current = 'N/A'; -if (!empty($snortMd5CurrentChk)) { - preg_match('/^\".*\"/', $snortMd5CurrentChk, $snortMd5Current); - if (!empty($snortMd5Current[0])) { - $snortMd5Current = preg_replace('/\"/', '', $snortMd5Current[0]); - } -} - -$emergingMd5CurrentChk = @file_get_contents('/usr/local/etc/snort/snortDBrules/emerging_rules/emerging.rules.tar.gz.md5'); - -$emerginDownlodChkMark = ''; -if ($generalSettings[emergingthreatsdownload] !== 'off') { - $emerginDownlodChkMark = 'checked="checked"'; -} - -$emergingMd5Current = 'N/A'; -if (!empty($emergingMd5CurrentChk)) { - $emergingMd5Current = $emergingMd5CurrentChk; -} - -$pfsenseMd5CurrentChk = @file_get_contents('/usr/local/etc/snort/snortDBrules/pfsense_rules/pfsense_rules.tar.gz.md5'); - -$pfsenseMd5Current = 'N/A'; -if (!empty($pfsenseMd5CurrentChk)) { - preg_match('/^\".*\"/', $pfsenseMd5CurrentChk, $pfsenseMd5Current); - if (!empty($pfsenseMd5Current[0])) { - $pfsenseMd5Current = preg_replace('/\"/', '', $pfsenseMd5Current[0]); - } -} - - $pgtitle = 'Services: Snort: Updates'; - include("/usr/local/pkg/snort/snort_head.inc"); +require_once("/usr/local/pkg/snort/snort.inc"); -?> +global $g; - - -<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> +/* load only javascript that is needed */ +$snort_load_jquery = 'yes'; +$snort_load_jquery_colorbox = 'yes'; -<!-- loading update msg --> -<div id="loadingRuleUpadteGUI"> - <div class="snortModalUpdate"> - <div class="snortModalTopUpdate"> - <div class="snortModalTopClose"> - <!-- <a href="javascript:hideLoading('#loadingRuleUpadteGUI');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a> --> - </div> - </div> - <p id="UpdateMsg1" class="snortModalTitleUpdate snortModalTitleUpdateMsg1"> - </p> - <div class="snortModalTitleUpdate snortModalTitleUpdateBar"> - <table width="600px" height="43px" border="0" cellpadding="0" cellspacing="0"> - <tr><td><span class="progressBar" id="pb4"></span></td></tr> - </table> - </div> - <p id="UpdateMsg2" class="snortModalTitleUpdate snortModalTitleUpdateMsg2"> - </p> - </div> +/* quick md5s chk */ +$snort_org_sig_chk_local = 'N/A'; +if (file_exists("/usr/local/etc/snort/{$snort_rules_file}.md5")) + $snort_org_sig_chk_local = exec("/bin/cat /usr/local/etc/snort/{$snort_rules_file}.md5"); + +$emergingt_net_sig_chk_local = 'N/A'; +if(file_exists('/usr/local/etc/snort/emerging.rules.tar.gz.md5')) + $emergingt_net_sig_chk_local = exec('/bin/cat /usr/local/etc/snort/emerging.rules.tar.gz.md5'); + +$pfsense_org_sig_chk_local = 'N/A'; +if(file_exists('/usr/local/etc/snort/pfsense_rules.tar.gz.md5')) + $pfsense_org_sig_chk_local = exec('/bin/cat /usr/local/etc/snort/pfsense_rules.tar.gz.md5'); + +/* define checks */ +$oinkid = $config['installedpackages']['snortglobal']['oinkmastercode']; +$snortdownload = $config['installedpackages']['snortglobal']['snortdownload']; +$emergingthreats = $config['installedpackages']['snortglobal']['emergingthreats']; + +if ($snortdownload != 'on' && $emergingthreats != 'on') + $snort_emrging_info = 'stop'; + +if ($oinkid == '' && $snortdownload != 'off') + $snort_oinkid_info = 'stop'; + +if ($snort_emrging_info == 'stop' || $snort_oinkid_info == 'stop') + $error_stop = 'true'; + +/* check if main rule directory is empty */ +$if_mrule_dir = "/usr/local/etc/snort/rules"; +$mfolder_chk = (count(glob("$if_mrule_dir/*")) === 0) ? 'empty' : 'full'; + +/* check for logfile */ +$update_logfile_chk = 'no'; +if (file_exists('/usr/local/etc/snort/snort_update.log')) + $update_logfile_chk = 'yes'; + +header("snort_help_info.php"); +header( "Expires: Mon, 20 Dec 1998 01:00:00 GMT" ); +header( "Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT" ); +header( "Cache-Control: no-cache, must-revalidate" ); +header( "Pragma: no-cache" ); + + +$pgtitle = "Services: Snort: Updates"; +include_once("head.inc"); + +?> -</div> +<body link="#000000" vlink="#000000" alink="#000000"> +<?php +echo "{$snort_general_css}\n"; +echo "$snort_interfaces_css\n"; +?> <?php include("fbegin.inc"); ?> -<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> +<?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> + +<noscript> +<div class="alert" ALIGN=CENTER><img + src="../themes/<?php echo $g['theme']; ?>/images/icons/icon_alert.gif" /><strong>Please +enable JavaScript to view this content +</CENTER></div> +</noscript> <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> +<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"), true, "/snort/snort_download_updates.php"); + $tab_array[3] = array(gettext("Alerts"), false, "/snort/snort_alerts.php"); + $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); + $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); + $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Help"), false, "/snort/help_and_info.php"); + display_top_tabs($tab_array); +?> +</td></tr> +<tr> <td> + <div id="mainarea3"> + <table id="maintable4" class="tabcont" width="100%" border="0" + cellpadding="0" cellspacing="0"> + <tr> + <td><!-- grey line --> + <table height="12px" width="725px" border="0" cellpadding="5px" + cellspacing="0"> + <tr> + <td style='background-color: #eeeeee'> + <div height="12px" width="725px" style='background-color: #dddddd'> + </div> + </td> + </tr> + </table> - <div class="newtabmenu" style="margin: 1px 0px; width: 790px;"><!-- Tabbed bar code--> - <ul class="newtabmenu"> - <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> - <li><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> - <li class="newtabmenu_active"><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> - <li><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> - <li><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> - <li><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> - <li><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> - <li><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> - <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> - </ul> - </div> + <br> + + <table id="download_rules" height="32px" width="725px" border="0" + cellpadding="5px" cellspacing="0"> + <tr> + <td id="download_rules_td" style="background-color: #eeeeee"> + <div height="32" width="725px" style="background-color: #eeeeee"> + + <font color="#777777" size="1.5px"><b>INSTALLED SIGNATURE RULESET</b></font><br> + <br> + <p style="text-align: left; margin-left: 225px;"><font + color="#FF850A" size="1px"><b>SNORT.ORG >>></b></font><font + size="1px" color="#000000"> <? echo $snort_org_sig_chk_local; ?></font><br> + <font color="#FF850A" size="1px"><b>EMERGINGTHREATS.NET >>></b></font><font + size="1px" color="#000000"> <? echo $emergingt_net_sig_chk_local; ?></font><br> + <font color="#FF850A" size="1px"><b>PFSENSE.ORG >>></b></font><font + size="1px" color="#000000"> <? echo $pfsense_org_sig_chk_local; ?></font><br> + </p> + + </div> + </td> + </tr> + </table> - </td> - </tr> - <tr> - <td> + <br> + + <!-- grey line --> + <table height="12px" width="725px" border="0" cellpadding="5px" + cellspacing="0"> + <tr> + <td style='background-color: #eeeeee'> + <div height="12px" width="725px" style='background-color: #eeeeee'> + </div> + </td> + </tr> + </table> - <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> - <ul class="newtabmenu"> - <li class="newtabmenu_active"><a href="/snort/snort_download_rules.php"><span>Rule Update</span></a></li> - <!-- <li><a href="#"><span>Upload Custom Rules</span></a></li> --> - <!-- <li><a href="#"><span>Gui Update</span></a></li> --> - </ul> - </div> + <br> - </td> - </tr> - <tr> - <td id="tdbggrey"> - <div style="width:780px; margin-left: auto ; margin-right: auto ; padding-top: 10px; padding-bottom: 10px;"> - <!-- START MAIN AREA --> - - - <!-- start Interface Satus --> - <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr id="maintable77" > - <td colspan="2" valign="top" class="listtopic2"> - Rule databases that are ready to be updated. - </td> - <td width="6%" colspan="2" valign="middle" class="listtopic3" > - </td> - </tr> - </table> -<br> - - <!-- start User Interface --> - <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr id="maintable77" > - <td colspan="2" valign="top" class="listtopic">SIGNATURE RULESET DATABASES:</td> - </tr> - </table> - - - <table class="vncell2" width="100%" border="0" cellpadding="0" cellspacing="0"> - - <td class="list" ></td> - <td class="list" valign="middle" > - - <tr id="frheader" > - <td width="1%" class="listhdrr2">On</td> - <td width="25%" class="listhdrr2">Signature DB Name</td> - <td width="35%" class="listhdrr2">MD5 Version</td> - <td width="38%" class="listhdrr2">Last Rule DB Date</td> - <td width="1%" class="listhdrr2"> </td> - </tr> - - <!-- START javascript sid loop here --> - <tbody class="rulesetloopblock"> - -<tr id="fr0" valign="top"> -<td class="odd_ruleset2"> -<input class="domecheck" name="filenamcheckbox2[]" value="1292" <?=$snortDownlodChkMark;?> type="checkbox" disabled="disabled" > -</td> -<td class="odd_ruleset2" id="frd0">SNORT.ORG</td> -<td class="odd_ruleset2" id="frd0"><?=$snortMd5Current;?></td> -<td class="listbg" id="frd0"><font color="white"><?=$tmpSettingsSnort;?></font></td> -<td class="odd_ruleset2"> -<img src="/themes/pfsense_ng/images/icons/icon_alias_url_reload.gif" title="edit rule" width="17" border="0" height="17"> -</td> -</tr> - -<tr id="fr0" valign="top"> -<td class="odd_ruleset2"> -<input class="domecheck" name="filenamcheckbox2[]" value="1292" <?=$emerginDownlodChkMark;?> type="checkbox" disabled="disabled" > -</td> -<td class="odd_ruleset2" id="frd0">EMERGINGTHREATS.NET</td> -<td class="odd_ruleset2" id="frd0"><?=$emergingMd5Current;?></td> -<td class="listbg" id="frd0"><font color="white"><?=$tmpSettingsEmerging; ?></font></td> -<td class="odd_ruleset2"> -<img src="/themes/pfsense_ng/images/icons/icon_alias_url_reload.gif" title="edit rule" width="17" border="0" height="17"> -</td> -</tr> - -<tr id="fr0" valign="top"> -<td class="odd_ruleset2"> -<input class="domecheck" name="filenamcheckbox2[]" value="1292" checked="checked" type="checkbox" disabled="disabled" > -</td> -<td class="odd_ruleset2" id="frd0">PFSENSE.ORG</td> -<td class="odd_ruleset2" id="frd0"><?=$pfsenseMd5Current;?></td> -<td class="listbg" id="frd0"><font color="white"><?=$tmpSettingsPfsense;?></font></td> -<td class="odd_ruleset2"> -<img src="/themes/pfsense_ng/images/icons/icon_alias_url_reload.gif" title="edit rule" width="17" border="0" height="17"> -</td> -</tr> - - </tbody> - <!-- STOP javascript sid loop here --> - - </td> - <td class="list" colspan="8"></td> - - </table> - <br> - <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td> - <input id="openupdatebox" type="submit" class="formbtn" value="Update"> - </td> - </tr> - </table> - <br> - - <!-- stop snortsam --> - - <!-- STOP MAIN AREA --> - </div> - </td> - </tr> -</table> -</div> - -<!-- start info box --> + <table id="download_rules" height="32px" width="725px" border="0" + cellpadding="5px" cellspacing="0"> + <tr> + <td id="download_rules_td" style='background-color: #eeeeee'> + <div height="32" width="725px" style='background-color: #eeeeee'> -<br> + <font color='#777777' size='1.5px'><b>UPDATE YOUR RULES</b></font><br> + <br> -<div style="width:790px; background-color: #dddddd;" id="mainarea4"> -<div style="width:780px; margin-left: auto ; margin-right: auto ; padding-top: 10px; padding-bottom: 10px;"> -<table class="vncell2" width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr > - <td width="10%" valign="middle" > - <img style="vertical-align: middle;" src="/snort/images/icon_excli.png" width="40" height="32"> - </td> - <td width="90%" valign="middle" > - <span class="red"><strong>Note:</strong></span> - <strong> Snort.org and Emergingthreats.net will go down from time to time. Please be patient.</strong> - </td> - </tr> -</table> -</div> -</div> + <?php + if ($error_stop == 'true') { + echo ' + + <button class="sexybutton disabled" disabled="disabled"><span class="download">Update Rules </span></button><br/> + <p style="text-align:left; margin-left:150px;"> + <font color="#fc3608" size="2px"><b>WARNING:</b></font><font size="1px" color="#000000"> No rule types have been selected for download. "Global Settings Tab"</font><br>'; -<script type="text/javascript"> + if ($mfolder_chk == 'empty') { + echo ' + <font color="#fc3608" size="2px"><b>WARNING:</b></font><font size="1px" color="#000000"> The main rules directory is empty. /usr/local/etc/snort/rules</font>' ."\n"; + } -//prepare the form when the DOM is ready -jQuery(document).ready(function() { + echo '</p>' . "\n"; - jQuery('.closeupdatebox').live('click', function(){ - var url = '/snort/snort_download_updates.php'; - window.location = url; - }); + }else{ - jQuery('#openupdatebox').live('click', function(){ - var url = '/snort/snort_download_updates.php?updatenow=1'; - window.location = url; - }); + echo ' -}); // end of document ready + <a href="/snort/snort_download_rules.php"><button class="sexybutton disabled"><span class="download">Update Rules </span></button></a><br/>' . "\n"; -</script> + if ($mfolder_chk == 'empty') { -<?php + echo ' + <p style="text-align:left; margin-left:150px;"> + <font color="#fc3608" size="2px"><b>WARNING:</b></font><font size="1px" color="#000000"> The main rules directory is empty. /usr/local/etc/snort/rules</font> + </p>'; + } -if ($updatenow == 1) { - sendUpdateSnortLogDownload(''); // start main function - echo ' - <script type="text/javascript"> - jQuery(\'.snortModalTopClose\').append(\'<img class="icon_click closeupdatebox" src="/snort/images/close_9x9.gif" border="0" height="9" width="9">\'); - </script> - '; -} + } -?> + ?> <br> + </div> + </td> + </tr> + </table> -<!-- stop info box --> + <br> -<!-- footer do not touch below --> -<?php -include("fend.inc"); -echo $snort_custom_rnd_box; -?> + <table id="download_rules" height="32px" width="725px" border="0" + cellpadding="5px" cellspacing="0"> + <tr> + <td id="download_rules_td" style='background-color: #eeeeee'> + <div height="32" width="725px" style='background-color: #eeeeee'> + + <font color='#777777' size='1.5px'><b>VIEW UPDATE LOG</b></font><br> + <br> + + <?php + + if ($update_logfile_chk == 'yes') { + echo ' + <button class="sexybutton sexysimple example9" href="/snort/snort_rules_edit.php?openruleset=/usr/local/etc/snort/snort_update.log"><span class="pwhitetxt">Update Log </span></button>' . "\n"; + }else{ + echo ' + <button class="sexybutton disabled" disabled="disabled" href="/snort/snort_rules_edit.php?openruleset=/usr/local/etc/snort/snort_update.log"><span class="pwhitetxt">Update Log </span></button>' . "\n"; + } + + ?> <br> + <br> + + </div> + </td> + </tr> + </table> + + <br> + + <table height="12px" width="725px" border="0" cellpadding="5px" + cellspacing="0"> + <tr> + <td style='background-color: #eeeeee'> + <div height="12px" width="725px" style='background-color: #eeeeee'> + </div> + </td> + </tr> + </table> + + <br> + + <table id="download_rules" height="32px" width="725px" border="0" + cellpadding="5px" cellspacing="0"> + <tr> + <td id="download_rules_td" style='background-color: #eeeeee'> + <div height="32" width="725px" style='background-color: #eeeeee'> + + <img style='vertical-align: middle' + src="/snort/images/icon_excli.png" width="40" height="32"> <font + color='#FF850A' size='1px'><b>NOTE:</b></font><font size='1px' + color='#000000'> Snort.org and Emergingthreats.net + will go down from time to time. Please be patient.</font></div> + </td> + </tr> + </table> + + <br> + + <table height="12px" width="725px" border="0" cellpadding="5px" + cellspacing="0"> + <tr> + <td style='background-color: #eeeeee'> + <div height="12px" width="725px" style='background-color: #eeeeee'> + </div> + </td> + </tr> + </table> + + </td> + </tr> + </table> + </div> + + + + + + <br> + </td> + </tr> +</table> +<!-- end of final table --></div> + +<?php include("fend.inc"); ?> +<?php echo "$snort_custom_rnd_box\n"; ?> </body> </html> diff --git a/config/snort-dev/snort_gui.inc b/config/snort-dev/snort_gui.inc index d0a778ae..d2fd4e30 100644 --- a/config/snort-dev/snort_gui.inc +++ b/config/snort-dev/snort_gui.inc @@ -1,19 +1,12 @@ <?php /* $Id$ */ /* - + snort.inc + Copyright (C) 2006 Scott Ullrich + Copyright (C) 2006 Robert Zelaya part of pfSense All rights reserved. - Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. - All rights reserved. - - Pfsense Old snort GUI - Copyright (C) 2006 Scott Ullrich. - - Pfsense snort GUI - Copyright (C) 2008-2012 Robert Zelaya. - Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -24,10 +17,6 @@ notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - 3. Neither the name of the pfSense nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - 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 @@ -38,10 +27,9 @@ 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. - -*/ + */ -//include_once("/usr/local/pkg/snort/snort.inc"); +include_once("/usr/local/pkg/snort/snort.inc"); function print_info_box_np2($msg) { global $config, $g; @@ -74,10 +62,142 @@ function print_info_box_np2($msg) { } -if ($config['version'] >= 6) { - $helplink = '<li><a href="/snort/help_and_info.php"><span>Help</span></a>'; -}else{ - $helplink = ' <li><a class="example8" href="/snort/help_and_info.php"><span>Help</span></a></li>'; + +/* makes boxes round */ +/* load at bottom */ + +$snort_custom_rnd_box = ' +<script type="text/javascript"> +<!-- + + NiftyCheck(); + Rounded("div#mainarea2","bl br tr","#FFF","#dddddd","smooth"); + Rounded("div#mainarea3","bl br tr","#FFF","#dddddd","smooth"); + Rounded("div#mainarea4","all","#FFF","#dddddd","smooth"); + Rounded("div#mainarea5","all","#eeeeee","#dddddd","smooth"); + +//--> +</script>' . "\n"; + +/* general css code */ +$snort_general_css = ' + +<style type="text/css"> + +.alert { + position:absolute; + top:10px; + left:0px; + width:94%; + height:90%; + +background:#FCE9C0; +background-position: 15px; +border-top:2px solid #DBAC48; +border-bottom:2px solid #DBAC48; +padding: 15px 10px 85% 50px; +} + +.formpre { +font-family:arial; +font-size: 1.1em; +} + +#download_rules { +font-family: arial; +font-size: 13px; +font-weight: bold; +text-align: center +} + +#download_rules_td { +font-family: arial; +font-size: 13px; +font-weight: bold; +text-align: center +} + +body2 { +font-family:arial; +font-size:12px; +} + +.tabcont { +background-color: #dddddd; +padding-right: 12px; +padding-left: 12px; +padding-top: 12px; +padding-bottom: 12px; +} + +.tabcont2 { +background-color: #eeeeee; +padding-right: 12px; +padding-left: 12px; +padding-top: 12px; +padding-bottom: 12px; } +.vncell2 { + background-color: #eeeeee; + padding-right: 20px; + padding-left: 8px; + border-bottom: 1px solid #999999; +} + +/* global tab, white lil box */ +.vncell3 { + width: 50px; + background-color: #eeeeee; + padding-right: 2px; + padding-left: 2px; + border-bottom-width: 1px; + border-bottom-style: solid; + border-bottom-color: #999999; +} + +.vncellreq2 { +background-color: #eeeeee; +padding-right: 20px; +padding-left: 8px; +font-weight: bold; +border-bottom-width: 1px; +border-bottom-style: solid; +border-bottom-color: #999999; +} + +</style> ' . "\n"; + + +/* general css code for snort_interface.php */ +$snort_interfaces_css = ' + +<style type="text/css"> + +.listbg2 { + border-right: 1px solid #999999; + border-bottom: 1px solid #999999; + font-size: 11px; + background-color: #090; + color: #000; + padding-right: 16px; + padding-left: 6px; + padding-top: 4px; + padding-bottom: 4px; +} + +.listbg3 { + border-right: 1px solid #999999; + border-bottom: 1px solid #999999; + font-size: 11px; + background-color: #777777; + color: #000; + padding-right: 16px; + padding-left: 6px; + padding-top: 4px; + padding-bottom: 4px; +} + +</style>' . "\n"; + ?> diff --git a/config/snort-dev/snort_interfaces.php b/config/snort-dev/snort_interfaces.php index beb50f83..5ee7a176 100644 --- a/config/snort-dev/snort_interfaces.php +++ b/config/snort-dev/snort_interfaces.php @@ -2,413 +2,446 @@ /* $Id$ */ /* - part of pfSense - All rights reserved. - - Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. - All rights reserved. - - Pfsense Old snort GUI - Copyright (C) 2006 Scott Ullrich. - - Pfsense snort GUI - Copyright (C) 2008-2012 Robert Zelaya. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - 3. Neither the name of the pfSense nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - - 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. - +originally part of m0n0wall (http://m0n0.ch/wall) +Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. +Copyright (C) 2008-2009 Robert Zelaya. +Copyright (C) 2011 Ermal Luci +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. */ +//$nocsrf = true; require_once("guiconfig.inc"); -require_once("/usr/local/pkg/snort/snort_new.inc"); require_once("/usr/local/pkg/snort/snort_gui.inc"); +require_once("/usr/local/pkg/snort/snort.inc"); -//Set no caching -header("Expires: Mon, 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"); +global $g; -$new_ruleUUID = genAlphaNumMixFast(7, 8); +$id = $_GET['id']; +if (isset($_POST['id'])) + $id = $_POST['id']; -$a_interfaces = snortSql_fetchAllInterfaceRules('SnortIfaces', 'snortDB'); +if (!is_array($config['installedpackages']['snortglobal']['rule'])) + $config['installedpackages']['snortglobal']['rule'] = array(); +$a_nat = &$config['installedpackages']['snortglobal']['rule']; +$id_gen = count($config['installedpackages']['snortglobal']['rule']); +if (isset($_POST['del_x'])) { + /* delete selected rules */ + if (is_array($_POST['rule'])) { + conf_mount_rw(); + foreach ($_POST['rule'] as $rulei) { + + /* convert fake interfaces to real */ + $if_real = snort_get_real_interface($a_nat[$rulei]['interface']); + $snort_uuid = $a_nat[$rulei]['uuid']; - $pgtitle = "Services: Snort 2.9.0.5 pkg v. 2.0"; - include("/usr/local/pkg/snort/snort_head.inc"); + Running_Stop($snort_uuid,$if_real, $rulei); + + /* delete iface rule dirs */ + if (file_exists("/usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}")) { + exec("/bin/rm -r /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}"); + } + if (file_exists("/var/log/snort/{$snort_uuid}_{$if_real}")) { + exec("/bin/rm -r /var/log/snort/{$snort_uuid}_{$if_real}"); + } + if (file_exists("/var/log/snort/barnyard2/{$snort_uuid}_{$if_real}")) { + exec("/bin/rm -r /var/log/snort/barnyard2/{$snort_uuid}_{$if_real}"); + } + + unset($a_nat[$rulei]); + } + conf_mount_ro(); + + write_config(); + sleep(2); + + /* if there are no ifaces do not create snort.sh */ + if (!empty($config['installedpackages']['snortglobal']['rule'])) + create_snort_sh(); + else { + conf_mount_rw(); + exec('/bin/rm /usr/local/etc/rc.d/snort.sh'); + conf_mount_ro(); + } + + sync_snort_package_config(); + + 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; + } + +} + + +/* start/stop snort */ +if ($_GET['act'] == 'toggle' && is_numeric($id)) { + + $if_real = snort_get_real_interface($config['installedpackages']['snortglobal']['rule'][$id]['interface']); + $snort_uuid = $config['installedpackages']['snortglobal']['rule'][$id]['uuid']; + + /* Log Iface stop */ + exec("/usr/bin/logger -p daemon.info -i -t SnortStartup 'Toggle for {$snort_uuid}_{$if_real}...'"); + + sync_snort_package_config(); + + $snort_pgrep_chk_toggle = snortRunningChk('snort', $snort_uuid, $if_real); + + if (!empty($snort_pgrep_chk_toggle)) { + Running_Stop($snort_uuid, $if_real, $id); + + 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' ); + + } else { + Running_Start($snort_uuid, $if_real, $id); + + 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' ); + } + sleep(4); // So the GUI reports correctly + header("Location: /snort/snort_interfaces.php"); + exit; +} + + +$pgtitle = "Services: $snort_package_version"; +include_once("head.inc"); ?> - - -<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> - +<body link="#000000" vlink="#000000" alink="#000000"> -<!-- loading msg --> -<div id="loadingWaiting"> - <div class="snortModal" style="top: 200px; left: 700px;"> - <div class="snortModalTop"> - <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> - </div> - <div class="snortModalTitle"> - <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> - </div> - <div> - <p class="loadingWaitingMessage"></p> - </div> - </div> -</div> +<?php +echo "{$snort_general_css}\n"; +echo "$snort_interfaces_css\n"; -<?php include("fbegin.inc"); ?> -<!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"> -<a href="../index.php" id="status-link2"> -<img src="./images/transparent.gif" border="0"></img> -</a> -</div> +include_once("fbegin.inc"); +if ($pfsense_stable == 'yes') + echo '<p class="pgtitle">' . $pgtitle . '</p>'; +?> -<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> +<noscript> +<div class="alert" ALIGN=CENTER><img + src="../themes/<?php echo $g['theme']; ?>/images/icons/icon_alert.gif" /><strong>Please +enable JavaScript to view this content +</CENTER></div> +</noscript> -<form id="iform" > +<form action="snort_interfaces.php" method="post" enctype="multipart/form-data" name="iform" id="iform"> +<?php + /* Display Alert message */ + if ($input_errors) + print_input_errors($input_errors); // TODO: add checks + + if ($savemsg) + print_info_box2($savemsg); + + //if (file_exists($d_snortconfdirty_path)) { + if ($d_snortconfdirty_path_ls != '') { + echo '<p>'; + + if($savemsg) + print_info_box_np2("{$savemsg}"); + else { + print_info_box_np2(' + The Snort configuration has changed for one or more interfaces.<br> + You must apply the changes in order for them to take effect.<br> + '); + } + } +?> <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td> - - <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> - <ul class="newtabmenu"> - <li class="newtabmenu_active"><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> - <li><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> - <li><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> - <li><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> - <li><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> - <li><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> - <li><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> - <li><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> - <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> - </li> - </ul> - </div> +<tr><td> +<?php + $tab_array = array(); + $tab_array[0] = array(gettext("Snort Interfaces"), true, "/snort/snort_interfaces.php"); + $tab_array[1] = array(gettext("Global Settings"), false, "/snort/snort_interfaces_global.php"); + $tab_array[2] = array(gettext("Updates"), false, "/snort/snort_download_updates.php"); + $tab_array[3] = array(gettext("Alerts"), false, "/snort/snort_alerts.php"); + $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); + $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); + $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Help"), false, "/snort/help_and_info.php"); + display_top_tabs($tab_array); +?> +</td></tr> +<tr> + <td> + <div id="mainarea2"> + <table class="tabcont" width="100%" border="0" cellpadding="0" + cellspacing="0"> + <tr id="frheader"> + <td width="5%" class="list"> </td> + <td width="1%" class="list"> </td> + <td width="10%" class="listhdrr">If</td> + <td width="10%" class="listhdrr">Snort</td> + <td width="10%" class="listhdrr">Performance</td> + <td width="10%" class="listhdrr">Block</td> + <td width="10%" class="listhdrr">Barnyard2</td> + <td width="50%" class="listhdr">Description</td> + <td width="3%" class="list"> + <table border="0" cellspacing="0" cellpadding="1"> + <tr> + <td width="17"></td> + <td><a href="snort_interfaces_edit.php?id=<?php echo $id_gen;?>"><img + src="../themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" + width="17" height="17" border="0"></a></td> + </tr> + </table> + </td> + </tr> + <?php $nnats = $i = 0; foreach ($a_nat as $natent): ?> + <tr valign="top" id="fr<?=$nnats;?>"> + <?php - </td> - </tr> - <tr> - <td id="tdbggrey"> - <div style="width:750px; margin-left: auto ; margin-right: auto ; padding-top: 10px; padding-bottom: 10px;"> - <!-- START MAIN AREA --> + /* convert fake interfaces to real and check if iface is up */ + /* There has to be a smarter way to do this */ + $if_real = snort_get_real_interface($natent['interface']); + $snort_uuid = $natent['uuid']; - <!-- start snortsam --> - <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr id="maintable77" > - <td colspan="2" valign="top" class="listtopic">SnortSam Status</td> - </tr> - </table> - - <table class="vncell2" width="100%" border="0" cellpadding="0" cellspacing="0"> + $snort_pgrep_chk = snortRunningChk('snort', $snort_uuid, $if_real); + + if (empty($snort_pgrep_chk)) { + $iconfn = 'pass'; + $class_color_up = 'listbg'; + }else{ + $class_color_up = 'listbg2'; + $iconfn = 'block'; + } + + ?> + <td class="listt"> + <a href="?act=toggle&id=<?=$i;?>"> + <img src="../themes/<?= $g['theme']; ?>/images/icons/icon_<?=$iconfn;?>.gif" + width="13" height="13" border="0" + title="click to toggle start/stop snort"></a> + <input type="checkbox" id="frc<?=$nnats;?>" name="rule[]" value="<?=$i;?>" onClick="fr_bgcolor('<?=$nnats;?>')" style="margin: 0; padding: 0;"></td> + <td class="listt" align="center"></td> + <td class="<?=$class_color_up;?>" onClick="fr_toggle(<?=$nnats;?>)" + id="frd<?=$nnats;?>" + ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> + <?php + echo snort_get_friendly_interface($natent['interface']); + ?></td> + <td class="listr" onClick="fr_toggle(<?=$nnats;?>)" + id="frd<?=$nnats;?>" + ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> + <?php + $check_snort_info = $config['installedpackages']['snortglobal']['rule'][$nnats]['enable']; + if ($check_snort_info == "on") + { + $check_snort = enabled; + } else { + $check_snort = disabled; + } + ?> <?=strtoupper($check_snort);?></td> + <td class="listr" onClick="fr_toggle(<?=$nnats;?>)" + id="frd<?=$nnats;?>" + ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> + <?php + $check_performance_info = $config['installedpackages']['snortglobal']['rule'][$nnats]['performance']; + if ($check_performance_info != "") { + $check_performance = $check_performance_info; + }else{ + $check_performance = "lowmem"; + } + ?> <?=strtoupper($check_performance);?></td> + <td class="listr" onClick="fr_toggle(<?=$nnats;?>)" + id="frd<?=$nnats;?>" + ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> + <?php + $check_blockoffenders_info = $config['installedpackages']['snortglobal']['rule'][$nnats]['blockoffenders7']; + if ($check_blockoffenders_info == "on") + { + $check_blockoffenders = enabled; + } else { + $check_blockoffenders = disabled; + } + ?> <?=strtoupper($check_blockoffenders);?></td> + <?php + + $snort_pgrep_chkb = snortRunningChk('barnyard2', $snort_uuid, $if_real); + + if (!empty($snort_pgrep_chkb)) { + $class_color_upb = 'listbg2'; + }else{ + $class_color_upb = 'listbg'; + } + + ?> + <td class="<?=$class_color_upb;?>" onClick="fr_toggle(<?=$nnats;?>)" + id="frd<?=$nnats;?>" + ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> + <?php + $check_snortbarnyardlog_info = $config['installedpackages']['snortglobal']['rule'][$nnats]['barnyard_enable']; + if ($check_snortbarnyardlog_info == "on") + { + $check_snortbarnyardlog = strtoupper(enabled); + }else{ + $check_snortbarnyardlog = strtoupper(disabled); + } + ?> <?php echo "$check_snortbarnyardlog";?></td> + <td class="listbg3" onClick="fr_toggle(<?=$nnats;?>)" + ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> + <font color="#ffffff"> <?=htmlspecialchars($natent['descr']);?> + </td> + <td valign="middle" class="list" nowrap> + <table border="0" cellspacing="0" cellpadding="1"> + <tr> + <td><a href="snort_interfaces_edit.php?id=<?=$i;?>"><img + src="/themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" + width="17" height="17" border="0" title="edit rule"></a></td> + </tr> + </table> + </tr> + <?php $i++; $nnats++; endforeach; ?> + <tr> <td class="list" colspan="8"></td> <td class="list" valign="middle" nowrap> - - <tr id="frheader" > - <td width="3%" class="list"> </td> - <td width="10%" class="listhdrr2">SnortSam</td> - <td width="10%" class="listhdrr">Role</td> - <td width="10%" class="listhdrr">Port</td> - <td width="10%" class="listhdrr">Pass</td> - <td width="10%" class="listhdrr">Log</td> - <td width="50%" class="listhdr">Description</td> - <td width="5%" class="list"> </td> - <td width="5%" class="list"> </td> - - - <tr valign="top" id="fr0"> - <td class="listt"> - <a href="?act=toggle&id=0"><img src="/themes/<?= $g['theme']; ?>/images/icons/icon_pass.gif" width="13" height="13" border="0" title="click to toggle start/stop snortsam"></a> - </td> - <td class="listbg" id="frd0" ondblclick="document.location='snort_interfaces_edit.php?id=0';">DISABLED</td> - <td class="listr" id="frd0" ondblclick="document.location='snort_interfaces_edit.php?id=0';">MASTER</td> - <td class="listr" id="frd0" ondblclick="document.location='snort_interfaces_edit.php?id=0';">3526</td> - <td class="listr" id="frd0" ondblclick="document.location='snort_interfaces_edit.php?id=0';">ENABLED</td> - <td class="listr" id="frd0" ondblclick="document.location='snort_interfaces_edit.php?id=0';">DISABLED</td> - <td class="listbg3" ondblclick="document.location='snort_interfaces_edit.php?id=0';"><font color="#ffffff">Mster IPs </td> - <td></td> - <td> - <a href="snort_interfaces_edit.php?id=0"><img src="/themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" width="17" height="17" border="0" title="edit rule"></a> - </td> - - </tr> - </tr> - </td> - <td class="list" colspan="8"></td> - </table> - <!-- stop snortsam --> -<br> - <!-- start Interface Satus --> - <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr id="maintable77" > - <td colspan="2" valign="top" class="listtopic2">Interface Status</td> - <td width="6%" colspan="2" valign="middle" class="listtopic3" > - <a href="snort_interfaces_edit.php?uuid=<?=$new_ruleUUID;?>"> - <img style="padding-left:3px;" src="/themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" width="17" height="17" border="0" title="add rule"> - </a> - </td> - </tr> - </table> -<br> - <!-- start User Interface --> - <?php - foreach ($a_interfaces as $list) - { - // make caps - $list['interface'] = strtoupper($list['interface']); - $list['performance'] = strtoupper($list['performance']); - - // rename for GUI iface - $ifaceStat = ($list['enable'] == 'on' ? 'ENABLED' : 'DISABLED'); - $blockStat = ($list['blockoffenders7'] == 'on' ? 'ENABLED' : 'DISABLED'); - $logStat = ($list['snortunifiedlog'] == 'on' ? 'ENABLED' : 'DISABLED'); - $barnyard2Stat = ($list['barnyard_enable'] == 'on' ? 'ENABLED' : 'DISABLED'); - - - echo " - <div id=\"maintable_{$list['uuid']}\" data-options='{\"pagetable\":\"SnortIfaces\", \"pagedb\":\"snortDB\", \"DoPOST\":\"true\"}'> - "; - echo ' - <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr id="maintable77" > - '; - echo " - <td width=\"100%\" colspan=\"2\" valign=\"top\" class=\"listtopic\" >{$list['interface']} Interface Status ({$list['uuid']})</td> - "; - echo ' + <table border="0" cellspacing="0" cellpadding="1"> + <tr> + <td><?php if ($nnats == 0): ?><img + src="../themes/<?= $g['theme']; ?>/images/icons/icon_x_d.gif" + width="17" height="17" title="delete selected rules" border="0"><?php else: ?><input + name="del" type="image" + src="../themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" + width="17" height="17" title="delete selected mappings" + onclick="return confirm('Do you really want to delete the selected Snort Rule?')"><?php endif; ?></td> </tr> </table> - - <table class="vncell2" width="100%" border="0" cellpadding="0" cellspacing="0"> - - <td class="list" colspan="8"></td> - <td class="list" valign="middle" nowrap> - - <tr id="frheader" > - <td width="3%" class="list"> </td> - <td width="11%" class="listhdrr2">Snort</td> - <td width="10%" class="listhdrr">If</td> - <td width="10%" class="listhdrr">Performance</td> - <td width="10%" class="listhdrr">Block</td> - <td width="10%" class="listhdrr">Log</td> - <td width="50%" class="listhdr">Description</td> - <td width="5%" class="list"> </td> - <td width="5%" class="list"> </td> - - <tr valign="top" id="fr0"> - <td class="listt"> - '; - echo " - <a href=\"?act=toggle&id=0\"><img src=\"/themes/{$g['theme']}/images/icons/icon_pass.gif\" width=\"13\" height=\"13\" border=\"0\" title=\"click to toggle start/stop snort\"></a> - - </td> - <td class=\"listbg\" id=\"frd0\" ondblclick=\"document.location='snort_interfaces_edit.php?uuid={$list['uuid']}';\">{$ifaceStat}</td> - <td class=\"listr\" id=\"frd0\" ondblclick=\"document.location='snort_interfaces_edit.php?uuid={$list['uuid']}';\">{$list['interface']}</td> - <td class=\"listr\" id=\"frd0\" ondblclick=\"document.location='snort_interfaces_edit.php?uuid={$list['uuid']}';\">{$list['performance']}</td> - <td class=\"listr\" id=\"frd0\" ondblclick=\"document.location='snort_interfaces_edit.php?uuid={$list['uuid']}';\">{$blockStat}</td> - <td class=\"listr\" id=\"frd0\" ondblclick=\"document.location='snort_interfaces_edit.php?uuid={$list['uuid']}';\">{$logStat}</td> - <td class=\"listbg3\" ondblclick=\"document.location='snort_interfaces_edit.php?uuid={$list['uuid']}';\"><font color=\"#ffffff\">{$list['descr']}</td> - <td></td> - <td> - <a href=\"snort_interfaces_edit.php?uuid={$list['uuid']}\"><img src=\"/themes/{$g['theme']}/images/icons/icon_e.gif\" width=\"17\" height=\"17\" border=\"0\" title=\"edit rule\"></a> - "; - echo ' - </td> - - </tr> - </tr> - </td> - <td class="list" colspan="8"></td> - </table> - <table class="vncell2" width="100%" border="0" cellpadding="0" cellspacing="0"> - - <td class="list" colspan="8"></td> - <td class="list" valign="middle" nowrap> - - <tr id="frheader" > - <td width="3%" class="list"> </td> - <td width="10%" class="listhdrr2">Barnyard2</td> - <td width="10%" class="listhdrr">If</td> - <td width="10%" class="listhdrr">Sensor</td> - <td width="10%" class="listhdrr">Type</td> - <td width="10%" class="listhdrr">Log</td> - <td width="50%" class="listhdr">Description</td> - <td width="5%" class="list"> </td> - <td width="5%" class="list"> </td> - - - <tr valign="top" id="fr0"> - <td class="listt"> - '; - echo " - <a href=\"?act=toggle&id=0\"><img src=\"/themes/{$g['theme']}/images/icons/icon_pass.gif\" width=\"13\" height=\"13\" border=\"0\" title=\"click to toggle start/stop barnyard2\"></a> - </td> - <td class=\"listbg\" id=\"frd0\" ondblclick=\"document.location='snort_interfaces_edit.php?id=0';\">{$barnyard2Stat}</td> - <td class=\"listr\" id=\"frd0\" ondblclick=\"document.location='snort_interfaces_edit.php?id=0';\">{$list['interface']}</td> - <td class=\"listr\" id=\"frd0\" ondblclick=\"document.location='snort_interfaces_edit.php?id=0';\">{$list['uuid']}_{$list['interface']}</td> - <td class=\"listr\" id=\"frd0\" ondblclick=\"document.location='snort_interfaces_edit.php?id=0';\">unified2</td> - <td class=\"listr\" id=\"frd0\" ondblclick=\"document.location='snort_interfaces_edit.php?id=0';\">{$barnyard2Stat}</td> - <td class=\"listbg3\" ondblclick=\"document.location='snort_interfaces_edit.php?id=0';\"><font color=\"#ffffff\">Mster IPs </td> - <td></td> - <td> - <img id=\"icon_x_{$list['uuid']}\" class=\"icon_click icon_x\" src=\"/themes/{$g['theme']}/images/icons/icon_x.gif\" width=\"17\" height=\"17\" border=\"0\" title=\"delete rule\"> - "; - echo ' - </td> - - </tr> - </tr> - </td> - <td class="list" colspan="8"></td> - </table> - <br> - </div>'; - } // end of foreach main - ?> - <!-- stop User Interface --> - - <!-- stop Interface Sat --> - - <!-- STOP MAIN AREA --> - </div> - </td> + </td> + </tr> + </table> + </div> + </td> </tr> </table> -</form> -</div> - -<!-- start info box --> <br> - -<div style="background-color: #dddddd;" id="mainarea4"> -<div style="width:750px; margin-left: auto ; margin-right: auto ; padding-top: 10px; padding-bottom: 10px;"> -<table class="vncell2" width="100%" border="0" cellpadding="0" cellspacing="0"> +<table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> - <td> </td> - </tr> - <tr > - <td width="100%"> - <span class="red"><strong>Note:</strong></span> <br> - This is the <strong>Snort Menu</strong> where you can see an over view of all your interface settings. - Please edit the <strong>Global Settings</strong> tab before adding an interface. - <br> - <br> - <span class="red"><strong>Warning:</strong></span> - <br> - <strong>New settings will not take effect until interface restart.</strong> - <br> - <br> - <table> - <tr> - <td> - <strong>Click</strong> on the - <img src="/themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" width="17" height="17" border="0" title="Add Icon"> - icon to add a interface. - </td> - <td> - <strong>Click</strong> on the - <img src="/themes/<?= $g['theme']; ?>/images/icons/icon_pass.gif" width="13" height="13" border="0" title="Start Icon"> - icon to <strong>start</strong> snort or barnyard2. - </td> - </tr> - <tr> - <td> - <strong>Click</strong> on the - <img src="/themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" width="17" height="17" border="0" title="Edit Icon"> icon to edit a - interface and settings. - </td> - <td> - <strong>Click</strong> on the - <img src="/themes/<?= $g['theme']; ?>/images/icons/icon_block.gif" width="13" height="13" border="0" title="Stop Icon"> - icon to <strong>stop</strong> snort or barnyard2. - </td> - </tr> - <tr> - <td> - <strong> Click</strong> on the - <img src="/themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" width="17" height="17" border="0" title="Delete Icon"> - icon to delete a interface and settings. - </td> - </tr> - <tr> - <td> </td> + <td> + <div id="mainarea4"> + <table class="tabcont" width="100%" border="0" cellpadding="0" + cellspacing="0"> + <tr id="frheader"> + <td width="100%"><span class="red"><strong>Note:</strong></span> <br> + This is the <strong>Snort Menu</strong> where you can see an over + view of all your interface settings. <br> + Please edit the <strong>Global Settings</strong> tab before adding + an interface. <br> + <br> + <span class="red"><strong>Warning:</strong></span> <br> + <strong>New settings will not take effect until interface restart.</strong> + <br> + <br> + <strong>Click</strong> on the <img + src="../themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" + width="17" height="17" border="0" title="Add Icon"> icon to add a + interface.<strong> Click</strong> + on the <img + src="../themes/<?= $g['theme']; ?>/images/icons/icon_pass.gif" + width="13" height="13" border="0" title="Start Icon"> icon to <strong>start</strong> + snort and barnyard2. <br> + <strong>Click</strong> on the <img + src="../themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" + width="17" height="17" border="0" title="Edit Icon"> icon to edit a + interface and settings.<strong> Click</strong> + on the <img + src="../themes/<?= $g['theme']; ?>/images/icons/icon_block.gif" + width="13" height="13" border="0" title="Stop Icon"> icon to <strong>stop</strong> + snort and barnyard2. <br> + <strong> Click</strong> on the <img + src="../themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" + width="17" height="17" border="0" title="Delete Icon"> icon to + delete a interface and settings.</td> </tr> - </table> - </td> + </table> + </div> + </tr> + </td> </table> -</div> + + <?php + if ($pkg['tabs'] <> "") { + echo "</td></tr></table>"; + } + ?></form> </div> -<!-- stop info box --> +<br> +<br> +<br> -<!-- start snort footer --> +<style type="text/css"> +#footer2 { + position: relative; + background-color: transparent; + background-image: url("./images/logo22.png"); + background-repeat: no-repeat; + background-attachment: scroll; + background-position: 0% 0%; + top: 10px; + left: 0px; + width: 770px; + height: 60px; + color: #000000; + text-align: center; + font-size: 0.8em; + padding-top: 40px; + margin-bottom: -35px; + clear: both; +} +</style> + +<div id="footer2">SNORT registered � by Sourcefire, Inc, Barnyard2 +registered � by securixlive.com, Orion registered � by Robert Zelaya, +Emergingthreats registered � by emergingthreats.net, Mysql registered � +by Mysql.com</div> +<!-- Footer DIV --> -<br> + <?php -<div style="background-color: #dddddd;" id="mainarea6"> -<div style="width:750px; margin-left: auto ; margin-right: auto ; padding-top: 10px; padding-bottom: 10px;"> -<table class="vncell2" width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td> </td> - </tr> - <tr > - <td width="100%"> - <div id="footer2"> - <table> - <tr> - <td style="padding-top: 40px;"> - SNORT registered ® by Sourcefire, Inc, Barnyard2 registered ® by securixlive.com, Orion registered ® by Robert Zelaya, - Emergingthreats registered ® by emergingthreats.net, Mysql registered ® by Mysql.com - </td> - </tr> - </table> - </div> - </td> - </tr> - <tr> - <td> </td> - </tr> -</table> -</div> -</div> + include("fend.inc"); -<!-- stop snort footer --> + echo $snort_custom_rnd_box; + + ?> -<!-- footer do not touch below --> -<?php -include("fend.inc"); -echo $snort_custom_rnd_box; -?> </body> diff --git a/config/snort-dev/snort_interfaces_edit.php b/config/snort-dev/snort_interfaces_edit.php index ade5ade8..aee7bee1 100644 --- a/config/snort-dev/snort_interfaces_edit.php +++ b/config/snort-dev/snort_interfaces_edit.php @@ -1,19 +1,13 @@ <?php -/* $Id$ */ /* - - part of pfSense - All rights reserved. + snort_interfaces_edit.php + part of m0n0wall (http://m0n0.ch/wall) Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + Copyright (C) 2008-2009 Robert Zelaya. + Copyright (C) 2011 Ermal Luci All rights reserved. - Pfsense Old snort GUI - Copyright (C) 2006 Scott Ullrich. - - Pfsense snort GUI - Copyright (C) 2008-2012 Robert Zelaya. - Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -24,10 +18,6 @@ notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - 3. Neither the name of the pfSense nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - 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 @@ -38,499 +28,728 @@ 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_new.inc"); require_once("/usr/local/pkg/snort/snort_gui.inc"); +require_once("/usr/local/pkg/snort/snort.inc"); -//Set no caching -header("Expires: Mon, 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"); +global $g; -// set page vars +if (!is_array($config['installedpackages']['snortglobal']['rule'])) + $config['installedpackages']['snortglobal']['rule'] = array(); -$uuid = $_GET['uuid']; -if (isset($_POST['uuid'])) -$uuid = $_POST['uuid']; +$a_nat = &$config['installedpackages']['snortglobal']['rule']; -if ($uuid == '') { - echo 'error: no uuid'; - exit(0); +$id = $_GET['id']; +if (isset($_POST['id'])) + $id = $_POST['id']; +if (is_null($id)) { + header("Location: /snort/snort_interfaces.php"); + exit; } +if (isset($_GET['dup'])) { + $id = $_GET['dup']; + $after = $_GET['dup']; +} -$a_list = snortSql_fetchAllSettings('snortDB', 'SnortIfaces', 'uuid', $uuid); - -$a_rules = snortSql_fetchAllSettings('snortDBrules', 'Snortrules', 'All', ''); +/* always have a limit of (65535) numbers only or snort will not start do to id limits */ +/* TODO: When inline gets added make the uuid the port number lisstening */ +$pconfig = array(); -if (!is_array($a_list)) { - $a_list = array(); +/* gen uuid for each iface !inportant */ +if (empty($config['installedpackages']['snortglobal']['rule'][$id]['uuid'])) { + //$snort_uuid = gen_snort_uuid(strrev(uniqid(true))); + $snort_uuid = 0; + while ($snort_uuid > 65535 || $snort_uuid == 0) { + $snort_uuid = mt_rand(1, 65535); + $pconfig['uuid'] = $snort_uuid; + } +} else { + $snort_uuid = $a_nat[$id]['uuid']; + $pconfig['uuid'] = $snort_uuid; } -$a_whitelist = snortSql_fetchAllWhitelistTypes('SnortWhitelist', 'SnortWhitelistips'); +if (isset($id) && $a_nat[$id]) { + + /* old options */ + $pconfig['def_ssl_ports_ignore'] = $a_nat[$id]['def_ssl_ports_ignore']; + $pconfig['flow_depth'] = $a_nat[$id]['flow_depth']; + $pconfig['max_queued_bytes'] = $a_nat[$id]['max_queued_bytes']; + $pconfig['max_queued_segs'] = $a_nat[$id]['max_queued_segs']; + $pconfig['perform_stat'] = $a_nat[$id]['perform_stat']; + $pconfig['http_inspect'] = $a_nat[$id]['http_inspect']; + $pconfig['other_preprocs'] = $a_nat[$id]['other_preprocs']; + $pconfig['ftp_preprocessor'] = $a_nat[$id]['ftp_preprocessor']; + $pconfig['smtp_preprocessor'] = $a_nat[$id]['smtp_preprocessor']; + $pconfig['sf_portscan'] = $a_nat[$id]['sf_portscan']; + $pconfig['dce_rpc_2'] = $a_nat[$id]['dce_rpc_2']; + $pconfig['dns_preprocessor'] = $a_nat[$id]['dns_preprocessor']; + $pconfig['def_dns_servers'] = $a_nat[$id]['def_dns_servers']; + $pconfig['def_dns_ports'] = $a_nat[$id]['def_dns_ports']; + $pconfig['def_smtp_servers'] = $a_nat[$id]['def_smtp_servers']; + $pconfig['def_smtp_ports'] = $a_nat[$id]['def_smtp_ports']; + $pconfig['def_mail_ports'] = $a_nat[$id]['def_mail_ports']; + $pconfig['def_http_servers'] = $a_nat[$id]['def_http_servers']; + $pconfig['def_www_servers'] = $a_nat[$id]['def_www_servers']; + $pconfig['def_http_ports'] = $a_nat[$id]['def_http_ports']; + $pconfig['def_sql_servers'] = $a_nat[$id]['def_sql_servers']; + $pconfig['def_oracle_ports'] = $a_nat[$id]['def_oracle_ports']; + $pconfig['def_mssql_ports'] = $a_nat[$id]['def_mssql_ports']; + $pconfig['def_telnet_servers'] = $a_nat[$id]['def_telnet_servers']; + $pconfig['def_telnet_ports'] = $a_nat[$id]['def_telnet_ports']; + $pconfig['def_snmp_servers'] = $a_nat[$id]['def_snmp_servers']; + $pconfig['def_snmp_ports'] = $a_nat[$id]['def_snmp_ports']; + $pconfig['def_ftp_servers'] = $a_nat[$id]['def_ftp_servers']; + $pconfig['def_ftp_ports'] = $a_nat[$id]['def_ftp_ports']; + $pconfig['def_ssh_servers'] = $a_nat[$id]['def_ssh_servers']; + $pconfig['def_ssh_ports'] = $a_nat[$id]['def_ssh_ports']; + $pconfig['def_pop_servers'] = $a_nat[$id]['def_pop_servers']; + $pconfig['def_pop2_ports'] = $a_nat[$id]['def_pop2_ports']; + $pconfig['def_pop3_ports'] = $a_nat[$id]['def_pop3_ports']; + $pconfig['def_imap_servers'] = $a_nat[$id]['def_imap_servers']; + $pconfig['def_imap_ports'] = $a_nat[$id]['def_imap_ports']; + $pconfig['def_sip_proxy_ip'] = $a_nat[$id]['def_sip_proxy_ip']; + $pconfig['def_sip_servers'] = $a_nat[$id]['def_sip_servers']; + $pconfig['def_sip_ports'] = $a_nat[$id]['def_sip_ports']; + $pconfig['def_sip_proxy_ports'] = $a_nat[$id]['def_sip_proxy_ports']; + $pconfig['def_auth_ports'] = $a_nat[$id]['def_auth_ports']; + $pconfig['def_finger_ports'] = $a_nat[$id]['def_finger_ports']; + $pconfig['def_irc_ports'] = $a_nat[$id]['def_irc_ports']; + $pconfig['def_nntp_ports'] = $a_nat[$id]['def_nntp_ports']; + $pconfig['def_rlogin_ports'] = $a_nat[$id]['def_rlogin_ports']; + $pconfig['def_rsh_ports'] = $a_nat[$id]['def_rsh_ports']; + $pconfig['def_ssl_ports'] = $a_nat[$id]['def_ssl_ports']; + $pconfig['barnyard_enable'] = $a_nat[$id]['barnyard_enable']; + $pconfig['barnyard_mysql'] = $a_nat[$id]['barnyard_mysql']; + $pconfig['enable'] = $a_nat[$id]['enable']; + $pconfig['interface'] = $a_nat[$id]['interface']; + $pconfig['descr'] = $a_nat[$id]['descr']; + $pconfig['performance'] = $a_nat[$id]['performance']; + $pconfig['blockoffenders7'] = $a_nat[$id]['blockoffenders7']; + $pconfig['blockoffenderskill'] = $a_nat[$id]['blockoffenderskill']; + $pconfig['blockoffendersip'] = $a_nat[$id]['blockoffendersip']; + $pconfig['whitelistname'] = $a_nat[$id]['whitelistname']; + $pconfig['homelistname'] = $a_nat[$id]['homelistname']; + $pconfig['externallistname'] = $a_nat[$id]['externallistname']; + $pconfig['suppresslistname'] = $a_nat[$id]['suppresslistname']; + $pconfig['snortalertlogtype'] = $a_nat[$id]['snortalertlogtype']; + $pconfig['alertsystemlog'] = $a_nat[$id]['alertsystemlog']; + $pconfig['tcpdumplog'] = $a_nat[$id]['tcpdumplog']; + $pconfig['snortunifiedlog'] = $a_nat[$id]['snortunifiedlog']; + $pconfig['snortalertcvs'] = $a_nat[$id]['snortalertcvs']; + $pconfig['snortunifiedlogbasic'] = $a_nat[$id]['snortunifiedlogbasic']; + $pconfig['configpassthru'] = base64_decode($a_nat[$id]['configpassthru']); + $pconfig['barnconfigpassthru'] = $a_nat[$id]['barnconfigpassthru']; + $pconfig['rulesets'] = $a_nat[$id]['rulesets']; + $pconfig['rule_sid_off'] = $a_nat[$id]['rule_sid_off']; + $pconfig['rule_sid_on'] = $a_nat[$id]['rule_sid_on']; + + + if (!$pconfig['interface']) + $pconfig['interface'] = "wan"; + } else + $pconfig['interface'] = "wan"; + +/* convert fake interfaces to real */ +$if_real = snort_get_real_interface($pconfig['interface']); + +if (isset($_GET['dup'])) + unset($id); + + /* alert file */ + $d_snortconfdirty_path = "/var/run/snort_conf_{$snort_uuid}_{$if_real}.dirty"; + + if ($_POST["Submit"]) { + + if ($_POST['descr'] == '' && $pconfig['descr'] == '') { + $input_errors[] = "Please enter a description for your reference."; + } + + if ($id == "" && $config['installedpackages']['snortglobal']['rule'][0]['interface'] != "") { -if (!is_array($a_whitelist)) { - $a_whitelist = array(); -} - -$a_suppresslist = snortSql_fetchAllWhitelistTypes('SnortSuppress', ''); + $rule_array = $config['installedpackages']['snortglobal']['rule']; + foreach ($config['installedpackages']['snortglobal']['rule'] as $value) { -if (!is_array($a_suppresslist)) { - $a_suppresslist = array(); -} - + $result_lan = $value['interface']; + $if_real = snort_get_real_interface($result_lan); - $pgtitle = "Services: Snort: Interface Edit:"; - include("/usr/local/pkg/snort/snort_head.inc"); + if ($_POST['interface'] == $result_lan) + $input_errors[] = "Interface $result_lan is in use. Please select another interface."; + } + } -?> + /* XXX: Void code + * check for overlaps + foreach ($a_nat as $natent) { + if (isset($id) && ($a_nat[$id]) && ($a_nat[$id] === $natent)) + continue; + if ($natent['interface'] != $_POST['interface']) + continue; + } + */ + + /* if no errors write to conf */ + if (!$input_errors) { + $natent = array(); + + /* write to conf for 1st time or rewrite the answer */ + if ($_POST['interface']) + $natent['interface'] = $_POST['interface']; + + /* if post write to conf or rewite the answer */ + $natent['enable'] = $_POST['enable'] ? 'on' : 'off'; + $natent['uuid'] = $pconfig['uuid']; + $natent['descr'] = $_POST['descr'] ? $_POST['descr'] : $pconfig['descr']; + $natent['performance'] = $_POST['performance'] ? $_POST['performance'] : $pconfig['performance']; + /* if post = on use on off or rewrite the conf */ + if ($_POST['blockoffenders7'] == "on") + $natent['blockoffenders7'] = 'on'; + else + $natent['blockoffenders7'] = 'off'; + if ($_POST['blockoffenderskill'] == "on") + $natent['blockoffenderskill'] = 'on'; + if ($_POST['blockoffendersip']) + $natent['blockoffendersip'] = $_POST['blockoffendersip']; + + $natent['whitelistname'] = $_POST['whitelistname'] ? $_POST['whitelistname'] : $pconfig['whitelistname']; + $natent['homelistname'] = $_POST['homelistname'] ? $_POST['homelistname'] : $pconfig['homelistname']; + $natent['externallistname'] = $_POST['externallistname'] ? $_POST['externallistname'] : $pconfig['externallistname']; + $natent['suppresslistname'] = $_POST['suppresslistname'] ? $_POST['suppresslistname'] : $pconfig['suppresslistname']; + $natent['snortalertlogtype'] = $_POST['snortalertlogtype'] ? $_POST['snortalertlogtype'] : $pconfig['snortalertlogtype']; + if ($_POST['alertsystemlog'] == "on") { $natent['alertsystemlog'] = 'on'; }else{ $natent['alertsystemlog'] = 'off'; } + if ($_POST['enable']) { $natent['enable'] = 'on'; } else unset($natent['enable']); + if ($_POST['tcpdumplog'] == "on") { $natent['tcpdumplog'] = 'on'; }else{ $natent['tcpdumplog'] = 'off'; } + if ($_POST['snortunifiedlog'] == "on") { $natent['snortunifiedlog'] = 'on'; }else{ $natent['snortunifiedlog'] = 'off'; } + if ($_POST['snortalertcvs'] == "on") { $natent['snortalertcvs'] = 'on'; }else{ $natent['snortalertcvs'] = 'off'; } + if ($_POST['snortunifiedlogbasic'] == "on") { $natent['snortunifiedlogbasic'] = 'on'; }else{ $natent['snortunifiedlogbasic'] = 'off'; } + $natent['configpassthru'] = $_POST['configpassthru'] ? base64_encode($_POST['configpassthru']) : $pconfig['configpassthru']; + /* if optiion = 0 then the old descr way will not work */ + + /* rewrite the options that are not in post */ + /* make shure values are set befor repost or conf.xml will be broken */ + if ($pconfig['def_ssl_ports_ignore'] != "") { $natent['def_ssl_ports_ignore'] = $pconfig['def_ssl_ports_ignore']; } + if ($pconfig['flow_depth'] != "") { $natent['flow_depth'] = $pconfig['flow_depth']; } + if ($pconfig['max_queued_bytes'] != "") { $natent['max_queued_bytes'] = $pconfig['max_queued_bytes']; } + if ($pconfig['max_queued_segs'] != "") { $natent['max_queued_segs'] = $pconfig['max_queued_segs']; } + if ($pconfig['perform_stat'] != "") { $natent['perform_stat'] = $pconfig['perform_stat']; } + if ($pconfig['http_inspect'] != "") { $natent['http_inspect'] = $pconfig['http_inspect']; } + if ($pconfig['other_preprocs'] != "") { $natent['other_preprocs'] = $pconfig['other_preprocs']; } + if ($pconfig['ftp_preprocessor'] != "") { $natent['ftp_preprocessor'] = $pconfig['ftp_preprocessor']; } + if ($pconfig['smtp_preprocessor'] != "") { $natent['smtp_preprocessor'] = $pconfig['smtp_preprocessor']; } + if ($pconfig['sf_portscan'] != "") { $natent['sf_portscan'] = $pconfig['sf_portscan']; } + if ($pconfig['dce_rpc_2'] != "") { $natent['dce_rpc_2'] = $pconfig['dce_rpc_2']; } + if ($pconfig['dns_preprocessor'] != "") { $natent['dns_preprocessor'] = $pconfig['dns_preprocessor']; } + if ($pconfig['def_dns_servers'] != "") { $natent['def_dns_servers'] = $pconfig['def_dns_servers']; } + if ($pconfig['def_dns_ports'] != "") { $natent['def_dns_ports'] = $pconfig['def_dns_ports']; } + if ($pconfig['def_smtp_servers'] != "") { $natent['def_smtp_servers'] = $pconfig['def_smtp_servers']; } + if ($pconfig['def_smtp_ports'] != "") { $natent['def_smtp_ports'] = $pconfig['def_smtp_ports']; } + if ($pconfig['def_mail_ports'] != "") { $natent['def_mail_ports'] = $pconfig['def_mail_ports']; } + if ($pconfig['def_http_servers'] != "") { $natent['def_http_servers'] = $pconfig['def_http_servers']; } + if ($pconfig['def_www_servers'] != "") { $natent['def_www_servers'] = $pconfig['def_www_servers']; } + if ($pconfig['def_http_ports'] != "") { $natent['def_http_ports'] = $pconfig['def_http_ports']; } + if ($pconfig['def_sql_servers'] != "") { $natent['def_sql_servers'] = $pconfig['def_sql_servers']; } + if ($pconfig['def_oracle_ports'] != "") { $natent['def_oracle_ports'] = $pconfig['def_oracle_ports']; } + if ($pconfig['def_mssql_ports'] != "") { $natent['def_mssql_ports'] = $pconfig['def_mssql_ports']; } + if ($pconfig['def_telnet_servers'] != "") { $natent['def_telnet_servers'] = $pconfig['def_telnet_servers']; } + if ($pconfig['def_telnet_ports'] != "") { $natent['def_telnet_ports'] = $pconfig['def_telnet_ports']; } + if ($pconfig['def_snmp_servers'] != "") { $natent['def_snmp_servers'] = $pconfig['def_snmp_servers']; } + if ($pconfig['def_snmp_ports'] != "") { $natent['def_snmp_ports'] = $pconfig['def_snmp_ports']; } + if ($pconfig['def_ftp_servers'] != "") { $natent['def_ftp_servers'] = $pconfig['def_ftp_servers']; } + if ($pconfig['def_ftp_ports'] != "") { $natent['def_ftp_ports'] = $pconfig['def_ftp_ports']; } + if ($pconfig['def_ssh_servers'] != "") { $natent['def_ssh_servers'] = $pconfig['def_ssh_servers']; } + if ($pconfig['def_ssh_ports'] != "") { $natent['def_ssh_ports'] = $pconfig['def_ssh_ports']; } + if ($pconfig['def_pop_servers'] != "") { $natent['def_pop_servers'] = $pconfig['def_pop_servers']; } + if ($pconfig['def_pop2_ports'] != "") { $natent['def_pop2_ports'] = $pconfig['def_pop2_ports']; } + if ($pconfig['def_pop3_ports'] != "") { $natent['def_pop3_ports'] = $pconfig['def_pop3_ports']; } + if ($pconfig['def_imap_servers'] != "") { $natent['def_imap_servers'] = $pconfig['def_imap_servers']; } + if ($pconfig['def_imap_ports'] != "") { $natent['def_imap_ports'] = $pconfig['def_imap_ports']; } + if ($pconfig['def_sip_proxy_ip'] != "") { $natent['def_sip_proxy_ip'] = $pconfig['def_sip_proxy_ip']; } + if ($pconfig['def_sip_servers'] != "") { $natent['def_sip_servers'] = $pconfig['def_sip_servers']; }else{ $natent['def_sip_servers'] = ""; } + if ($pconfig['def_sip_ports'] != "") { $natent['def_sip_ports'] = $pconfig['def_sip_ports']; }else{ $natent['def_sip_ports'] = ""; } + if ($pconfig['def_sip_proxy_ports'] != "") { $natent['def_sip_proxy_ports'] = $pconfig['def_sip_proxy_ports']; } + if ($pconfig['def_auth_ports'] != "") { $natent['def_auth_ports'] = $pconfig['def_auth_ports']; } + if ($pconfig['def_finger_ports'] != "") { $natent['def_finger_ports'] = $pconfig['def_finger_ports']; } + if ($pconfig['def_irc_ports'] != "") { $natent['def_irc_ports'] = $pconfig['def_irc_ports']; } + if ($pconfig['def_nntp_ports'] != "") { $natent['def_nntp_ports'] = $pconfig['def_nntp_ports']; } + if ($pconfig['def_rlogin_ports'] != "") { $natent['def_rlogin_ports'] = $pconfig['def_rlogin_ports']; } + if ($pconfig['def_rsh_ports'] != "") { $natent['def_rsh_ports'] = $pconfig['def_rsh_ports']; } + if ($pconfig['def_ssl_ports'] != "") { $natent['def_ssl_ports'] = $pconfig['def_ssl_ports']; } + if ($pconfig['barnyard_enable'] != "") { $natent['barnyard_enable'] = $pconfig['barnyard_enable']; } + if ($pconfig['barnyard_mysql'] != "") { $natent['barnyard_mysql'] = $pconfig['barnyard_mysql']; } + if ($pconfig['barnconfigpassthru'] != "") { $natent['barnconfigpassthru'] = $pconfig['barnconfigpassthru']; } + if ($pconfig['rulesets'] != "") { $natent['rulesets'] = $pconfig['rulesets']; } + if ($pconfig['rule_sid_off'] != "") { $natent['rule_sid_off'] = $pconfig['rule_sid_off']; } + if ($pconfig['rule_sid_on'] != "") { $natent['rule_sid_on'] = $pconfig['rule_sid_on']; } + + + $if_real = snort_get_real_interface($natent['interface']); + + if (isset($id) && $a_nat[$id]) { + if ($natent['interface'] != $a_nat[$id]['interface']) + Running_Stop($snort_uuid, $if_real, $id); + $a_nat[$id] = $natent; + } else { + if (is_numeric($after)) + array_splice($a_nat, $after+1, 0, array($natent)); + else + $a_nat[] = $natent; + } -<!-- START page custom script --> -<script language="JavaScript"> + write_config(); -// start a jQuery sand box -jQuery(document).ready(function() { - - // misc call after a good save - jQuery.fn.miscTabCall = function () { - jQuery('.hide_newtabmenu').show(); - jQuery('#interface').attr("disabled", true); - }; - - // START disable option for snort_interfaces_edit.php - endis = !(jQuery('input[name=enable]:checked').val()); - - disableInputs=new Array( - "descr", - "performance", - "blockoffenders7", - "alertsystemlog", - "externallistname", - "homelistname", - "suppresslistname", - "tcpdumplog", - "snortunifiedlog", - "configpassthru" - ); - <?php - - if ($a_list['interface'] != '') { - echo ' - jQuery(\'[name=interface]\').attr(\'disabled\', \'true\'); - '; - } - - // disable tabs if nothing in database - if ($a_list['uuid'] == '') { - echo ' - jQuery(\'.hide_newtabmenu\').hide(); - '; - } - - ?> - - if (endis) { - for (var i = 0; i < disableInputs.length; i++) - { - jQuery('[name=' + disableInputs[i] + ']').attr('disabled', 'true'); + sync_snort_package_config(); + sleep(1); + + /* if snort.sh crashed this will remove the pid */ + exec('/bin/rm /tmp/snort.sh.pid'); + + 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; } } - jQuery("input[name=enable]").live('click', function() { + if ($_POST["Submit2"]) { - endis = !(jQuery('input[name=enable]:checked').val()); + sync_snort_package_config(); + sleep(1); - if (endis) { - for (var i = 0; i < disableInputs.length; i++) - { - jQuery('[name=' + disableInputs[i] + ']').attr('disabled', 'true'); - } - }else{ - for (var i = 0; i < disableInputs.length; i++) - { - jQuery('[name=' + disableInputs[i] + ']').removeAttr('disabled'); - } - } + Running_Start($snort_uuid, $if_real, $id); - - }); - // STOP disable option for snort_interfaces_edit.php - - -}); // end of on ready + 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_edit.php?id=$id"); + exit; + } -</script> +$pgtitle = "Snort: Interface Edit: $id $snort_uuid $if_real"; +include_once("head.inc"); +?> <body link="#0000CC" vlink="#0000CC" alink="#0000CC"> +<?php + include("fbegin.inc"); + echo "{$snort_general_css}\n"; +?> + +<noscript> +<div class="alert" ALIGN=CENTER><img + src="/themes/<?php echo $g['theme']; ?>/images/icons/icon_alert.gif" /><strong>Please +enable JavaScript to view this content</strong></div> +</noscript> +<script language="JavaScript"> +<!-- -<!-- loading msg --> -<div id="loadingWaiting"> - <div class="snortModal" style="top: 200px; left: 700px;"> - <div class="snortModalTop"> - <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> - </div> - <div class="snortModalTitle"> - <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> - </div> - <div> - <p class="loadingWaitingMessage"></p> - </div> - </div> -</div> - -<?php include("fbegin.inc"); ?> -<!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"> -<a href="../index.php" id="status-link2"> -<img src="./images/transparent.gif" border="0"></img> -</a> -</div> - -<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> +function enable_blockoffenders() { + var endis = !(document.iform.blockoffenders7.checked); + document.iform.blockoffenderskill.disabled=endis; + document.iform.blockoffendersip.disabled=endis; +} + +function enable_change(enable_change) { + endis = !(document.iform.enable.checked || enable_change); + // make shure a default answer is called if this is envoked. + endis2 = (document.iform.enable); + document.iform.performance.disabled = endis; + document.iform.blockoffenders7.disabled = endis; + document.iform.alertsystemlog.disabled = endis; + document.iform.externallistname.disabled = endis; + document.iform.homelistname.disabled = endis; + document.iform.suppresslistname.disabled = endis; + document.iform.tcpdumplog.disabled = endis; + document.iform.snortunifiedlog.disabled = endis; + document.iform.snortalertcvs.disabled = endis; + document.iform.snortunifiedlogbasic.disabled = endis; + document.iform.configpassthru.disabled = endis; +} +//--> +</script> + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + +<form method="post" enctype="multipart/form-data" name="iform" id="iform"> +<?php + /* Display Alert message */ + if ($input_errors) { + print_input_errors($input_errors); // TODO: add checks + } + + if ($savemsg) { + print_info_box2($savemsg); + } + + //if (file_exists($d_snortconfdirty_path)) { + if (file_exists($d_snortconfdirty_path) || file_exists("/var/run/snort_conf_{$snort_uuid}_.dirty")) { + echo '<p>'; + + if($savemsg) + print_info_box_np2("{$savemsg}"); + else { + print_info_box_np2(' + The Snort configuration has changed and snort needs to be restarted on this interface.<br> + You must apply the changes in order for them to take effect.<br> + '); + } + } +?> <table width="100%" border="0" cellpadding="0" cellspacing="0"> +<tr><td> +<?php + $tab_array = array(); + $tabid = 0; + $tab_array[$tabid] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); + $tabid++; + $tab_array[$tabid] = array(gettext("If Settings"), true, "/snort/snort_interfaces_edit.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Servers"), false, "/snort/snort_define_servers.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); + display_top_tabs($tab_array); +?> +</td></tr> <tr> - <td> - <div class="newtabmenu" style="margin: 1px 0px; width: 790px;"><!-- Tabbed bar code--> - <ul class="newtabmenu"> - <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> - <li class="newtabmenu_active"><a href="/snort/snort_interfaces_edit.php?uuid=<?=$uuid;?>"><span>If Settings</span></a></li> - <li class="hide_newtabmenu"><a href="/snort/snort_rulesets.php?uuid=<?=$uuid;?>"><span>Categories</span></a></li> - <li class="hide_newtabmenu"><a href="/snort/snort_rules.php?uuid=<?=$uuid;?>"><span>Rules</span></a></li> - <li class="hide_newtabmenu"><a href="/snort/snort_rulesets_ips.php?uuid=<?=$uuid;?>"><span>Ruleset Ips</span></a></li> - <li class="hide_newtabmenu"><a href="/snort/snort_define_servers.php?uuid=<?=$uuid;?>"><span>Servers</span></a></li> - <li class="hide_newtabmenu"><a href="/snort/snort_preprocessors.php?uuid=<?=$uuid;?>"><span>Preprocessors</span></a></li> - <li class="hide_newtabmenu"><a href="/snort/snort_barnyard.php?uuid=<?=$uuid;?>"><span>Barnyard2</span></a></li> - </ul> - </div> + <td class="tabnavtbl"> + <?php + if ($a_nat[$id]['interface'] != '') { + /* get the interface name */ + $snortInterfaces = array(); /* -gtm */ + + $if_list = $config['installedpackages']['snortglobal']['rule'][$id]['interface']; + $if_array = split(',', $if_list); + if($if_array) { + foreach($if_array as $iface2) { + /* build a list of user specified interfaces -gtm */ + $if2 = snort_get_real_interface($iface2); + if ($if2) + array_push($snortInterfaces, $if2); + } + + if (count($snortInterfaces) < 1) + log_error("Snort will not start. You must select an interface for it to listen on."); + } + + } + ?> </td> </tr> <tr> - <td id="tdbggrey"> - <table width="100%" border="0" cellpadding="10px" cellspacing="0"> - <tr> - <td class="tabnavtbl"> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> - <!-- START MAIN AREA --> - - <form id="iform" name="iform" > - <input type="hidden" name="snortSaveSettings" value="1" /> <!-- what to do, save --> - <input type="hidden" name="dbName" value="snortDB" /> <!-- what db--> - <input type="hidden" name="dbTable" value="SnortIfaces" /> <!-- what db table--> - <input type="hidden" name="ifaceTab" value="snort_interfaces_edit" /> <!-- what interface tab --> - <input name="uuid" type="hidden" value="<?=$uuid; ?>" > - + <td class="tabcont"> <table width="100%" border="0" cellpadding="6" cellspacing="0"> <tr> <td colspan="2" valign="top" class="listtopic">General Settings</td> </tr> <tr> - <td width="22%" valign="top" class="vncellreq2">Interface</td> - <td width="22%" valign="top" class="vtable"> - - <input name="enable" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['enable'] == 'on' || $a_list['enable'] == '' ? 'checked' : '';?> "> - <span class="vexpl">Enable or Disable</span> - </td> + <td width="22%" valign="top" class="vncellreq2">Enable</td> + <td width="22%" valign="top" class="vtable"> <?php + // <input name="enable" type="checkbox" value="yes" checked onClick="enable_change(false)"> + // care with spaces + if ($pconfig['enable'] == "on") + $checked = checked; + + $onclick_enable = "onClick=\"enable_change(false)\">"; + + echo " + <input name=\"enable\" type=\"checkbox\" value=\"on\" $checked $onclick_enable + Enable or Disable</td>\n\n"; + ?></td> </tr> <tr> <td width="22%" valign="top" class="vncellreq2">Interface</td> <td width="78%" class="vtable"> - <select id="interface" name="interface" class="formfld"> - - <?php - /* add group interfaces */ - /* needs to be watched, dont know if new interfces will work */ - if (is_array($config['ifgroups']['ifgroupentry'])) - foreach($config['ifgroups']['ifgroupentry'] as $ifgen) - if (have_ruleint_access($ifgen['ifname'])) - $interfaces[$ifgen['ifname']] = $ifgen['ifname']; - $ifdescs = get_configured_interface_with_descr(); - foreach ($ifdescs as $ifent => $ifdesc) - if(have_ruleint_access($ifent)) - $interfaces[$ifent] = $ifdesc; - if ($config['l2tp']['mode'] == "server") - if(have_ruleint_access("l2tp")) - $interfaces['l2tp'] = "L2TP VPN"; - if ($config['pptpd']['mode'] == "server") - if(have_ruleint_access("pptp")) - $interfaces['pptp'] = "PPTP VPN"; - - if (is_pppoe_server_enabled() && have_ruleint_access("pppoe")) - $interfaces['pppoe'] = "PPPoE VPN"; - /* add ipsec interfaces */ - if (isset($config['ipsec']['enable']) || isset($config['ipsec']['client']['enable'])) - if(have_ruleint_access("enc0")) - $interfaces["enc0"] = "IPsec"; - /* add openvpn/tun interfaces */ - if ($config['openvpn']["openvpn-server"] || $config['openvpn']["openvpn-client"]) - $interfaces["openvpn"] = "OpenVPN"; - $selected_interfaces = explode(",", $pconfig['interface']); - foreach ($interfaces as $iface => $ifacename) - { - echo "\n" . "<option value=\"$iface\""; - if ($a_list['interface'] == strtolower($ifacename)){echo " selected ";} - echo '>' . $ifacename . '</option>' . "\r"; + <select name="interface" class="formfld"> + <?php + if (function_exists('get_configured_interface_with_descr')) + $interfaces = get_configured_interface_with_descr(); + else { + $interfaces = array('wan' => 'WAN', 'lan' => 'LAN'); + for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++) { + $interfaces['opt' . $i] = $config['interfaces']['opt' . $i]['descr']; } - ?> - </select> - <br> - <span class="vexpl">Choose which interface this rule applies to.<br> - Hint: in most cases, you'll want to use WAN here.</span> - </td> + } + foreach ($interfaces as $iface => $ifacename): ?> + <option value="<?=$iface;?>" + <?php if ($iface == $pconfig['interface']) echo "selected"; ?>><?=htmlspecialchars($ifacename);?> + </option> + <?php endforeach; ?> + </select><br> + <span class="vexpl">Choose which interface this rule applies to.<br> + Hint: in most cases, you'll want to use WAN here.</span></td> </tr> <tr> <td width="22%" valign="top" class="vncellreq2">Description</td> - <td width="78%" class="vtable"> - <input name="descr" type="text" class="formfld" id="descr" size="40" value="<?=$a_list['descr']?>"> - <br> - <span class="vexpl">You may enter a description here for your reference (not parsed).</span> - </td> + <td width="78%" class="vtable"><input name="descr" type="text" + class="formfld" id="descr" size="40" + value="<?=htmlspecialchars($pconfig['descr']);?>"> <br> + <span class="vexpl">You may enter a description here for your + reference (not parsed).</span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Memory Performance</td> - <td width="78%" class="vtable"> - <select name="performance" class="formfld" id="performance"> - - <?php - $memoryPerfList = array('ac-bnfa' => 'AC-BNFA', 'lowmem' => 'LOWMEM', 'aclowmem-std' => 'AC-STD', 'ac' => 'AC', 'ac-banded' => 'AC-BANDED', 'ac-sparsebands' => 'AC-SPARSEBANDS', 'acs' => 'ACS'); - snortDropDownList($memoryPerfList, $a_list['performance']); - ?> - - </select> - <br> - <span class="vexpl">Lowmem and ac-bnfa are recommended for low end systems, Ac: high memory, best performance, ac-std: moderate - memory,high performance, acs: small memory, moderateperformance, ac-banded: small memory,moderate performance, ac-sparsebands: small memory, high performance.</span> - <br> - </td> + <td width="78%" class="vtable"><select name="performance" + class="formfld" id="performance"> + <?php + $interfaces2 = array('ac-bnfa' => 'AC-BNFA', 'lowmem' => 'LOWMEM', 'ac-std' => 'AC-STD', 'ac' => 'AC', 'ac-banded' => 'AC-BANDED', 'ac-sparsebands' => 'AC-SPARSEBANDS', 'acs' => 'ACS'); + foreach ($interfaces2 as $iface2 => $ifacename2): ?> + <option value="<?=$iface2;?>" + <?php if ($iface2 == $pconfig['performance']) echo "selected"; ?>> + <?=htmlspecialchars($ifacename2);?></option> + <?php endforeach; ?> + </select><br> + <span class="vexpl">Lowmem and ac-bnfa are recommended for low end + systems, Ac: high memory, best performance, ac-std: moderate + memory,high performance, acs: small memory, moderateperformance, + ac-banded: small memory,moderate performance, ac-sparsebands: small + memory, high performance.<br> + </span></td> </tr> <tr> - <td colspan="2" valign="top" class="listtopic">Choose the rule DB snort should use.</td> + <td colspan="2" valign="top" class="listtopic">Choose the networks + snort should inspect and whitelist.</td> </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Rule DB</td> - <td width="78%" class="vtable"> - <select name="ruledbname" class="formfld" id="ruledbname"> - - <?php - // find ruleDB names and value by uuid - $selected = ''; - if ($a_list['ruledbname'] == 'default') { - $selected = 'selected'; + <td width="22%" valign="top" class="vncell2">Home net</td> + <td width="78%" class="vtable"><select name="homelistname" + class="formfld" id="homelistname"> + <?php + echo "<option value='default' >default</option>"; + /* find whitelist names and filter by type */ + if (is_array($config['installedpackages']['snortglobal']['whitelist']['item'])) { + foreach ($config['installedpackages']['snortglobal']['whitelist']['item'] as $value) { + if ($value['snortlisttype'] == 'netlist') { + $ilistname = $value['name']; + if ($ilistname == $pconfig['homelistname']) + echo "<option value='$ilistname' selected>"; + else + echo "<option value='$ilistname'>"; + echo htmlspecialchars($ilistname) . '</option>'; + } } - echo "\n" . '<option value="default" ' . $selected . ' >DEFAULT</option>' . "\r"; - foreach ($a_rules as $value) - { - $selected = ''; - if ($value['uuid'] == $a_list['ruledbname']) { - $selected = 'selected'; + } + ?> + </select><br> + <span class="vexpl">Choose the home net you will like this rule to + use. </span> <br/><span class="red">Note:</span> Default home + net adds only local networks.<br> + <span class="red">Hint:</span> Most users add a list of + friendly ips that the firewall cant see.</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">External net</td> + <td width="78%" class="vtable"><select name="externallistname" + class="formfld" id="externallistname"> + <?php + echo "<option value='default' >default</option>"; + /* find whitelist names and filter by type */ + if (is_array($config['installedpackages']['snortglobal']['whitelist']['item'])) { + foreach ($config['installedpackages']['snortglobal']['whitelist']['item'] as $value) { + if ($value['snortlisttype'] == 'netlist') { + $ilistname = $value['name']; + if ($ilistname == $pconfig['externallistname']) + echo "<option value='$ilistname' selected>"; + else + echo "<option value='$ilistname'>"; + echo htmlspecialchars($ilistname) . '</option>'; } - - echo "\n" . '<option value="' . $value['uuid'] . '" ' . $selected . ' >' . strtoupper($value['ruledbname']) . '</option>' . "\r"; } - ?> - - </select> - <br> - <span class="vexpl">Choose the rule database to use. <span class="red">Note:</span> Cahnges to this database are global. - <br> - <span class="red">WARNING:</span> Never change this when snort is running.</span> - </td> - </tr> - + } + ?> + </select><br/> + <span class="vexpl">Choose the external net you will like this rule + to use. </span> <br/><span class="red">Note:</span> Default + external net, networks that are not home net.<br> + <span class="red">Hint:</span> Most users should leave this + setting at default.</td> + </tr> <tr> - <td colspan="2" valign="top" class="listtopic">Choose the networks snort should inspect and whitelist.</td> + <td width="22%" valign="top" class="vncell2">Block offenders</td> + <td width="78%" class="vtable"> + <input name="blockoffenders7" id="blockoffenders7" type="checkbox" value="on" + <?php if ($pconfig['blockoffenders7'] == "on") echo "checked"; ?> + onClick="enable_blockoffenders()"><br> + Checking this option will automatically block hosts that generate a + Snort alert.</td> </tr> <tr> - <td width="22%" valign="top" class="vncell2">Home net</td> + <td width="22%" valign="top" class="vncell2">Kill states</td> <td width="78%" class="vtable"> - <select name="homelistname" class="formfld" id="homelistname"> - - <?php - /* find homelist names and filter by type */ - $selected = ''; - if ($a_list['homelistname'] == 'default'){$selected = 'selected';} - echo "\n" . '<option value="default" ' . $selected . ' >DEFAULT</option>' . "\r"; - foreach ($a_whitelist as $value) - { - $selected = ''; - if ($value['filename'] == $a_list['homelistname']){$selected = 'selected';}; - if ($value['snortlisttype'] == 'netlist') // filter - { - - echo "\n" . '<option value="' . $value['filename'] . '" ' . $selected . ' >' . strtoupper($value['filename']) . '</option>' . "\r"; - - } - } - ?> - - </select> - <br> - <span class="vexpl">Choose the home net you will like this rule to use. <span class="red">Note:</span> Default homenet adds only local networks. - <br> - <span class="red">Hint:</span> Most users add a list offriendly ips that the firewall cant see.</span> + <input name="blockoffenderskill" id="blockoffenderskill" type="checkbox" value="on" <?php if ($pconfig['blockoffenderskill'] == "on") echo "checked"; ?>> + <br/>Should firewall states be killed for the blocked ip </td> </tr> <tr> - <td width="22%" valign="top" class="vncell2">External net</td> + <td width="22%" valign="top" class="vncell2">Which ip to block</td> <td width="78%" class="vtable"> - <select name="externallistname" class="formfld" id="externallistname"> - - <?php - /* find externallist names and filter by type */ - $selected = ''; - if ($a_list['externallistname'] == 'default'){$selected = 'selected';} - echo "\n" . '<option value="default" ' . $selected . ' >DEFAULT</option>' . "\r"; - foreach ($a_whitelist as $value) - { - $selected = ''; - if ($value['filename'] == $a_list['externallistname']){$selected = 'selected';} - if ($value['snortlisttype'] == 'netlist') // filter - { - - echo "\n" . '<option value="' . $value['filename'] . '" ' . $selected . ' >' . strtoupper($value['filename']) . '</option>' . "\r"; - - } - } - ?> - + <select name="blockoffendersip" class="formfld" id="blockoffendersip"> + <?php + foreach (array("src", "dst", "both") as $btype) { + if ($btype == $pconfig['blockoffendersip']) + echo "<option value='{$btype}' selected>"; + else + echo "<option value='{$btype}'>"; + echo htmlspecialchars($btype) . '</option>'; + } + ?> </select> - <br> - <span class="vexpl">Choose the external net you will like this rule to use. <span class="red">Note:</span> Default external net, networks that are not home net. - <br> - <span class="red">Hint:</span> Most users should leave this setting at default.</span> + <br/> Which ip extracted from the packet you want to block </td> </tr> <tr> - <td width="22%" valign="top" class="vncell2">Block offenders</td> + <td width="22%" valign="top" class="vncell2">Whitelist</td> <td width="78%" class="vtable"> - <input name="blockoffenders7" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['blockoffenders7'] == 'on' ? 'checked' : '';?> > - <br> - <span class="vexpl">Checking this option will automatically block hosts that generate a Snort alerts with SnortSam.</span> + <select name="whitelistname" class="formfld" id="whitelistname"> + <?php + /* find whitelist names and filter by type, make sure to track by uuid */ + echo "<option value='default' >default</option>\n"; + if (is_array($config['installedpackages']['snortglobal']['whitelist']['item'])) { + foreach ($config['installedpackages']['snortglobal']['whitelist']['item'] as $value) { + if ($value['snortlisttype'] == 'whitelist') { + if ($value['name'] == $pconfig['whitelistname']) + echo "<option value='{$value['name']}' selected>"; + else + echo "<option value='{$value['name']}'>"; + echo htmlspecialchars($value['name']) . '</option>'; + } + } + } + ?> + </select><br> + <span class="vexpl">Choose the whitelist you will like this rule to + use. </span> <br/><span class="red">Note:</span> Default + whitelist adds only local networks.<br/> + <span class="red">Note:</span> This option will only be used when block offenders is on. </td> </tr> <tr> - <td width="22%" valign="top" class="vncell2">Suppression and filtering</td> + <td width="22%" valign="top" class="vncell2">Suppression and + filtering</td> <td width="78%" class="vtable"> <select name="suppresslistname" class="formfld" id="suppresslistname"> - - <?php - /* find suppresslist names and filter by type */ - $selected = ''; - if ($a_list['suppresslistname'] == 'default'){$selected = 'selected';} - - echo "\n" . '<option value="default" ' . $selected . ' >DEFAULT</option>' . "\r"; - - foreach ($a_suppresslist as $value) - { - $selected = ''; - if ($value['filename'] == $a_list['suppresslistname']){$selected = 'selected';} - - echo "\n" . '<option value="' . $value['filename'] . '" ' . $selected . ' >' . strtoupper($value['filename']) . '</option>' . "\r"; + <?php + echo "<option value='default' >default</option>\n"; + if (is_array($config['installedpackages']['snortglobal']['suppress']['item'])) { + $slist_select = $config['installedpackages']['snortglobal']['suppress']['item']; + foreach ($slist_select as $value) { + $ilistname = $value['name']; + if ($ilistname == $pconfig['suppresslistname']) + echo "<option value='$ilistname' selected>"; + else + echo "<option value='$ilistname'>"; + echo htmlspecialchars($ilistname) . '</option>'; } - ?> - - </select> - <br> - <span class="vexpl">Choose the suppression or filtering file you will like this rule to use. <span class="red"> - Note:</span> Default option disables suppression and filtering.</span> - </td> - </tr> - <tr> - <td colspan="2" valign="top" class="listtopic">Choose the types of logs snort should create.</td> + } + ?> + </select><br> + <span class="vexpl">Choose the suppression or filtering file you + will like this rule to use. </span> <br/><span class="red">Note:</span> Default + option disables suppression and filtering.</td> </tr> + <tr> - <td width="22%" valign="top" class="vncell2">Type of Unified Logging</td> - <td width="78%" class="vtable"> - <select name="snortalertlogtype" class="formfld" id="snortalertlogtype"> - - <?php - $snortalertlogtypePerfList = array('full' => 'FULL', 'fast' => 'FAST', 'disable' => 'DISABLE'); - snortDropDownList($snortalertlogtypePerfList, $a_list['snortalertlogtype']); - ?> - - </select> - <br> - <span class="vexpl">Snort will log Alerts to a file in the UNIFIED format. Full is a requirement for the snort wigdet.</span> - </td> - </tr> + <td colspan="2" valign="top" class="listtopic">Choose the types of + logs snort should create.</td> + </tr> <tr> - <td width="22%" valign="top" class="vncell2">Send alerts to mainSystem logs</td> - <td width="78%" class="vtable"> - <input name="alertsystemlog" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['alertsystemlog'] == 'on' ? 'checked' : '';?> > - <br> - <span class="vexpl">Snort will send Alerts to the Pfsense system logs.</span> - </td> + <td width="22%" valign="top" class="vncell2">Send alerts to main + System logs</td> + <td width="78%" class="vtable"><input name="alertsystemlog" + type="checkbox" value="on" + <?php if ($pconfig['alertsystemlog'] == "on") echo "checked"; ?> + onClick="enable_change(false)"><br> + Snort will send Alerts to the firewall's system logs.</td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Log to a Tcpdump file</td> + <td width="78%" class="vtable"><input name="tcpdumplog" + type="checkbox" value="on" + <?php if ($pconfig['tcpdumplog'] == "on") echo "checked"; ?> + onClick="enable_change(false)"><br> + Snort will log packets to a tcpdump-formatted file. The file then + can be analyzed by an application such as Wireshark which + understands pcap file formats. <span class="red"><strong>WARNING:</strong></span> + File may become large.</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Log Alerts to a snort unified file</td> <td width="78%" class="vtable"> - <input name="tcpdumplog" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['tcpdumplog'] == 'on' ? 'checked' : '';?> > - <br> - <span class="vexpl">Snort will log packets to a tcpdump-formatted file. The file then can be analyzed by an application such as Wireshark which understands pcap file formats. - <span class="red"><strong>WARNING:</strong></span> File may become large.</span> + <input name="snortunifiedlogbasic" type="checkbox" value="on" <?php if ($pconfig['snortunifiedlogbasic'] == "on") echo "checked"; ?> onClick="enable_change(false)"> + <br> + Snort will log Alerts to a file in the UNIFIED format. </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Log Alerts to a snort + unified2 file</td> + <td width="78%" class="vtable"><input name="snortunifiedlog" + type="checkbox" value="on" + <?php if ($pconfig['snortunifiedlog'] == "on") echo "checked"; ?> + onClick="enable_change(false)"><br> + Snort will log Alerts to a file in the UNIFIED2 format. This is a + requirement for barnyard2.</td> </tr> <tr> - <td width="22%" valign="top" class="vncell2">Log Alerts to a snort unified2 file</td> + <td width="22%" valign="top" class="vncell2">Log Alerts to a snort cvs file</td> <td width="78%" class="vtable"> - <input name="snortunifiedlog" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['snortunifiedlog'] == 'on' ? 'checked' : '';?> > - <br> - <span class="vexpl">Snort will log Alerts to a file in the UNIFIED2 format. This is a requirement for barnyard2.</span> + <input name="snortalertcvs" type="checkbox" value="on" <?php if ($pconfig['snortalertcvs'] == "on") echo "checked"; ?> onClick="enable_change(false)"> + <br> + Snort will log Alerts to a file in the CVS format. </td> - </tr> + </tr> <tr> - <td colspan="2" valign="top" class="listtopic">Arguments here will be automatically inserted into the snort configuration.</td> + <td colspan="2" valign="top" class="listtopic">Arguments here will + be automatically inserted into the snort configuration.</td> </tr> <tr> - <td width="22%" valign="top" class="vncell2">Advanced configuration pass through</td> - <td width="78%" class="vtable"> - <textarea wrap="off" name="configpassthru" cols="75" rows="12" id="configpassthru" class="formpre2"><?=base64_decode($a_list['configpassthru']); ?></textarea> + <td width="22%" valign="top" class="vncell2">Advanced configuration + pass through</td> + <td width="78%" class="vtable"><textarea wrap="off" + name="configpassthru" cols="75" rows="12" id="configpassthru" + class="formpre2"><?=htmlspecialchars($pconfig['configpassthru']);?></textarea> </td> </tr> <tr> <td width="22%" valign="top"></td> - <td width="78%"> - <input name="Submit" type="submit" class="formbtn" value="Save"> - <input name="Submit2" type="submit" class="formbtn" value="Start"> - <input id="cancel" type="button" class="formbtn" value="Cancel"> - </td> + <td width="78%"><input name="Submit" type="submit" class="formbtn" value="Save"> + <?php if (isset($id) && $a_nat[$id]): ?> + <input name="id" type="hidden" value="<?=$id;?>"> + <?php endif; ?></td> </tr> <tr> <td width="22%" valign="top"> </td> - <td width="78%"> - <span class="vexpl"><span class="red"><strong>Note:</strong></span> - Please save your settings before you click start.</span> - </td> + <td width="78%"><span class="vexpl"><span class="red"><strong>Note:</strong></span> + <br> + Please save your settings before you click start. </td> </tr> </table> - </form> - - <!-- STOP MAIN AREA --> - </table> - </td> - </tr> - </table> - </td> - </tr> -</table> -</div> +</table> +</form> -<!-- footer do not touch below --> -<?php -include("fend.inc"); -echo $snort_custom_rnd_box; -?> - +<script language="JavaScript"> +<!-- +enable_change(false); +enable_blockoffenders(); +//--> +</script> +<?php include("fend.inc"); ?> </body> </html> diff --git a/config/snort-dev/snort_interfaces_global.php b/config/snort-dev/snort_interfaces_global.php index fd9d27d4..a267f561 100644 --- a/config/snort-dev/snort_interfaces_global.php +++ b/config/snort-dev/snort_interfaces_global.php @@ -1,19 +1,16 @@ <?php -/* $Id$ */ /* + snort_interfaces_global.php + part of m0n0wall (http://m0n0.ch/wall) - part of pfSense + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + Copyright (C) 2011 Ermal Luci All rights reserved. - Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + Copyright (C) 2008-2009 Robert Zelaya + Modified for the Pfsense snort package. All rights reserved. - Pfsense Old snort GUI - Copyright (C) 2006 Scott Ullrich. - - Pfsense snort GUI - Copyright (C) 2008-2012 Robert Zelaya. - Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -24,10 +21,6 @@ notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - 3. Neither the name of the pfSense nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - 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 @@ -38,244 +31,317 @@ 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_new.inc"); require_once("/usr/local/pkg/snort/snort_gui.inc"); +require_once("/usr/local/pkg/snort/snort.inc"); + +global $g; + +$d_snort_global_dirty_path = '/var/run/snort_global.dirty'; + +/* make things short */ +$pconfig['snortdownload'] = $config['installedpackages']['snortglobal']['snortdownload']; +$pconfig['oinkmastercode'] = $config['installedpackages']['snortglobal']['oinkmastercode']; +$pconfig['emergingthreats'] = $config['installedpackages']['snortglobal']['emergingthreats']; +$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['snortalertlogtype'] = $config['installedpackages']['snortglobal']['snortalertlogtype']; +$pconfig['forcekeepsettings'] = $config['installedpackages']['snortglobal']['forcekeepsettings']; + +/* if no errors move foward */ +if (!$input_errors) { + + if ($_POST["Submit"]) { + + $config['installedpackages']['snortglobal']['snortdownload'] = $_POST['snortdownload']; + $config['installedpackages']['snortglobal']['oinkmastercode'] = $_POST['oinkmastercode']; + $config['installedpackages']['snortglobal']['emergingthreats'] = $_POST['emergingthreats'] ? 'on' : 'off'; + $config['installedpackages']['snortglobal']['rm_blocked'] = $_POST['rm_blocked']; + if ($_POST['snortloglimitsize']) { + $config['installedpackages']['snortglobal']['snortloglimit'] = $_POST['snortloglimit']; + $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']; + $config['installedpackages']['snortglobal']['snortalertlogtype'] = $_POST['snortalertlogtype']; + $config['installedpackages']['snortglobal']['forcekeepsettings'] = $_POST['forcekeepsettings'] ? 'on' : 'off'; + + $retval = 0; + + $snort_snortloglimit_info_ck = $config['installedpackages']['snortglobal']['snortloglimit']; + snort_snortloglimit_install_cron($snort_snortloglimit_info_ck == 'ok' ? true : false); + + /* set the snort block hosts time IMPORTANT */ + $snort_rm_blocked_info_ck = $config['installedpackages']['snortglobal']['rm_blocked']; + if ($snort_rm_blocked_info_ck == "never_b") + $snort_rm_blocked_false = false; + else + $snort_rm_blocked_false = true; + + snort_rm_blocked_install_cron($snort_rm_blocked_false); + + /* set the snort rules update time */ + $snort_rules_up_info_ck = $config['installedpackages']['snortglobal']['autorulesupdate7']; + if ($snort_rules_up_info_ck == "never_up") + $snort_rules_up_false = false; + else + $snort_rules_up_false = true; + + snort_rules_up_install_cron($snort_rules_up_false); + + configure_cron(); + write_config(); + + /* create whitelist and homenet file then sync files */ + sync_snort_package_config(); + + /* 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_interfaces_global.php"); + exit; + } +} + + +if ($_POST["Reset"]) { + + function snort_deinstall_settings() { + global $config, $g, $id, $if_real; + + exec("/usr/usr/bin/killall snort"); + sleep(2); + exec("/usr/usr/bin/killall -9 snort"); + sleep(2); + exec("/usr/usr/bin/killall barnyard2"); + sleep(2); + exec("/usr/usr/bin/killall -9 barnyard2"); + sleep(2); + + /* Remove snort cron entries Ugly code needs smoothness*/ + if (!function_exists('snort_deinstall_cron')) { + function snort_deinstall_cron($cronmatch) { + global $config, $g; + + + if(!$config['cron']['item']) + return; + + $x=0; + $is_installed = false; + foreach($config['cron']['item'] as $item) { + if (strstr($item['command'], $cronmatch)) { + $is_installed = true; + break; + } + $x++; + } + if($is_installed == true) + unset($config['cron']['item'][$x]); + + configure_cron(); + } + } + + snort_deinstall_cron("snort2c"); + snort_deinstall_cron("snort_check_for_rule_updates.php"); + + + /* Unset snort registers in conf.xml IMPORTANT snort will not start with out this */ + /* Keep this as a last step */ + unset($config['installedpackages']['snortglobal']); + + /* remove all snort iface dir */ + exec('rm -r /usr/local/etc/snort/snort_*'); + exec('rm /var/log/snort/*'); + } + + snort_deinstall_settings(); + write_config(); /* XXX */ + + 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_global.php"); + exit; +} + +$pgtitle = 'Services: Snort: Global Settings'; +include_once("head.inc"); -//Set no caching -header("Expires: Mon, 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"); - -// set page vars - -$generalSettings = snortSql_fetchAllSettings('snortDB', 'SnortSettings', 'id', '1'); - -$snortdownload_off = ($generalSettings['snortdownload'] == 'off' ? 'checked' : ''); -$snortdownload_on = ($generalSettings['snortdownload'] == 'on' ? 'checked' : ''); -$oinkmastercode = $generalSettings['oinkmastercode']; - -$emergingthreatsdownload_off = ($generalSettings['emergingthreatsdownload'] == 'off' ? 'checked' : ''); -$emergingthreatsdownload_basic = ($generalSettings['emergingthreatsdownload'] == 'basic' ? 'checked' : ''); -$emergingthreatsdownload_pro = ($generalSettings['emergingthreatsdownload'] == 'pro' ? 'checked' : ''); -$emergingthreatscode = $generalSettings['emergingthreatscode']; - -$updaterules = $generalSettings['updaterules']; - -$rm_blocked = $generalSettings['rm_blocked']; - -$snortloglimit_off = ($generalSettings['snortloglimit'] == 'off' ? 'checked' : ''); -$snortloglimit_on = ($generalSettings['snortloglimit'] == 'on' ? 'checked' : ''); - -$snortloglimitsize = $generalSettings['snortloglimitsize']; - -$snortalertlogtype = $generalSettings['snortalertlogtype']; - -$forcekeepsettings_on = ($generalSettings['forcekeepsettings'] == 'on' ? 'checked' : ''); +?> -$snortlogCurrentDSKsize = round(exec('df -k /var | grep -v "Filesystem" | awk \'{print $4}\'') / 1024); +<body link="#000000" vlink="#000000" alink="#000000"> +<?php +echo "{$snort_general_css}\n"; +echo "$snort_interfaces_css\n"; - $pgtitle = "Services: Snort: Global Settings"; - include("/usr/local/pkg/snort/snort_head.inc"); +include_once("fbegin.inc"); +if($pfsense_stable == 'yes') + echo '<p class="pgtitle">' . $pgtitle . '</p>'; ?> - - -<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> - -<!-- loading msg --> -<div id="loadingWaiting"> - <div class="snortModal"> - <div class="snortModalTop"> - <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> - </div> - <div class="snortModalTitle"> - <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> - </div> - <div> - <p class="loadingWaitingMessage"></p> - </div> - </div> -</div> - -<?php include("fbegin.inc"); ?> -<!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"> -<a href="../index.php" id="status-link2"> -<img src="./images/transparent.gif" border="0"></img> -</a> -</div> +<noscript> +<div class="alert" ALIGN=CENTER><img + src="../themes/<?php echo $g['theme']; ?>/images/icons/icon_alert.gif" /><strong>Please +enable JavaScript to view this content +</CENTER></div> +</noscript> -<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> +<form action="snort_interfaces_global.php" method="post" enctype="multipart/form-data" name="iform" id="iform"> +<?php + /* Display Alert message, under form tag or no refresh */ + if ($input_errors) + print_input_errors($input_errors); // TODO: add checks + + if (!$input_errors) { + if (file_exists($d_snort_global_dirty_path)) { + print_info_box_np2(' + The Snort configuration has changed and snort needs to be restarted on this interface.<br> + You must apply the changes in order for them to take effect.<br> + '); + } + } +?> <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td> - - <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> - <ul class="newtabmenu"> - <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> - <li class="newtabmenu_active"><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> - <li><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> - <li><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> - <li><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> - <li><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> - <li><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> - <li><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> - <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> - </ul> - </div> - - </td> - </tr> - <tr> - <td id="tdbggrey"> - <table width="100%" border="0" cellpadding="10px" cellspacing="0"> - <tr> - <td class="tabnavtbl"> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> - <!-- START MAIN AREA --> - - <form id="iform" > - <input type="hidden" name="snortSaveSettings" value="1" /> <!-- what to do, save --> - <input type="hidden" name="dbName" value="snortDB" /> <!-- what db --> - <input type="hidden" name="dbTable" value="SnortSettings" /> <!-- what db table --> - <input type="hidden" name="ifaceTab" value="snort_interfaces_global" /> <!-- what interface tab --> - - <tr id="maintable" data-options='{"pagetable":"SnortSettings"}'> <!-- db to lookup --> - <td colspan="2" valign="top" class="listtopic">Please Choose The Type Of Rules You Wish To Download</td> - </tr> +<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"), true, "/snort/snort_interfaces_global.php"); + $tab_array[2] = array(gettext("Updates"), false, "/snort/snort_download_updates.php"); + $tab_array[3] = array(gettext("Alerts"), false, "/snort/snort_alerts.php"); + $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); + $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); + $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Help"), false, "/snort/help_and_info.php"); + display_top_tabs($tab_array); +?> +</td></tr> +<tr> + <td class="tabcont"> + <table id="maintable2" width="100%" border="0" cellpadding="6" + cellspacing="0"> <tr> + <tr> + <td colspan="2" valign="top" class="listtopic">Please Choose The + Type Of Rules You Wish To Download</td> + </tr> <td width="22%" valign="top" class="vncell2">Install Snort.org rules</td> <td width="78%" class="vtable"> <table cellpadding="0" cellspacing="0"> <tr> - <td colspan="2"> - <input name="snortdownload" type="radio" id="snortdownloadoff" value="off" <?=$snortdownload_off;?> > - <span class="vexpl">Do <strong>NOT</strong> Install</span> - </td> + <td colspan="2"><input name="snortdownload" type="radio" + id="snortdownload" value="off" onClick="enable_change(false)" + <?php if($pconfig['snortdownload']=='off' || $pconfig['snortdownload']=='') echo 'checked'; ?>> + Do <strong>NOT</strong> Install</td> </tr> <tr> - <td colspan="2"> - <input name="snortdownload" type="radio" id="snortdownloadon" value="on" <?=$snortdownload_on;?> > - <span class="vexpl">Install Basic Rules or Premium rules</span> <br> - </td> + <td colspan="2"><input name="snortdownload" type="radio" + id="snortdownload" value="on" onClick="enable_change(false)" + <?php if($pconfig['snortdownload']=='on') echo 'checked'; ?>> Install + Basic Rules or Premium rules <br> + <a + href="https://www.snort.org/signup" target="_blank">Sign Up for a + Basic Rule Account</a><br> + <a + href="http://www.snort.org/vrt/buy-a-subscription" + target="_blank">Sign Up for Sourcefire VRT Certified Premium + Rules. This Is Highly Recommended</a></td> </tr> - </table> - <table STYLE="padding-top: 5px"> <tr> - <td colspan="2"> - <a class="vncell2" href="https://www.snort.org/signup" target="_blank" alt="Basic rules are free but 30 days old."> - Sign Up for a Basic Rule Account - </a><br><br> - <a class="vncell2" href="http://www.snort.org/vrt/buy-a-subscription" target="_blank" alt="Premium users receive rules 30 days faster than basic users."> - Sign Up for Sourcefire VRT Certified Premium Rules. This Is Highly Recommended - </a> - </td> + <td> </td> </tr> </table> <table width="100%" border="0" cellpadding="6" cellspacing="0"> <tr> - <td colspan="2" valign="top"><span class="vexpl">Oinkmaster code</span></td> + <td colspan="2" valign="top" class="optsect_t2">Oinkmaster code</td> </tr> <tr> - <td class="vncell2" valign="top"><span class="vexpl">Code</span></td> - <td class="vtable"> - <input name="oinkmastercode" type="text"class="formfld2" id="oinkmastercode" size="52" value="<?=$oinkmastercode;?>" > <br> - <span class="vexpl">Obtain a snort.org Oinkmaster code and paste here.</span> - </td> - </table> - </tr> + <td class="vncell2" valign="top">Code</td> + <td class="vtable"><input name="oinkmastercode" type="text" + class="formfld" id="oinkmastercode" size="52" + value="<?=htmlspecialchars($pconfig['oinkmastercode']);?>"><br> + Obtain a snort.org Oinkmaster code and paste here.</td> + + </table> + </tr> <tr> - <td width="22%" valign="top" class="vncell2">Install Emergingthreats rules</td> - <td width="78%" class="vtable"> - <table cellpadding="0" cellspacing="0"> - <tr> - <td colspan="2"> - <input name="emergingthreatsdownload" type="radio" id="emergingthreatsdownloadoff" value="off" <?=$emergingthreatsdownload_off;?> > - <span class="vexpl">Do <strong>NOT</strong> Install</span> - </td> - </tr> - <tr> - <td colspan="2"> - <input name="emergingthreatsdownload" type="radio" id="emergingthreatsdownloadon" value="basic" <?=$emergingthreatsdownload_basic;?> > - <span class="vexpl">Install <b>Basic</b> Rules: No need to register</span> <br> - </td> - </tr> - <tr> - <td colspan="2"> - <input name="emergingthreatsdownload" type="radio" id="emergingthreatsprodownloadon" value="pro" <?=$emergingthreatsdownload_pro;?> > - <span class="vexpl">Install <b>Pro</b> rules: You need to register</span> <br> - </td> - </tr> - </table> - <table STYLE="padding-top: 5px"> - <tr> - <td colspan="2"> - <a class="vncell2" href="http://www.emergingthreatspro.com" target="_blank" alt="Premium users receive rules 30 days faster than basic users."> - Sign Up for Emerging Threats Pro Certified Premium Rules. This Is Highly Recommended - </a> - </td> - </tr> - </table> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> - <tr> - <td colspan="2" valign="top"><span class="vexpl">Pro rules code</span></td> - </tr> - <tr> - <td class="vncell2" valign="top"><span class="vexpl">Code</span></td> - <td class="vtable"> - <input name="emergingthreatscode" type="text"class="formfld2" id="emergingthreatscode" size="52" value="<?=$emergingthreatscode;?>" > <br> - <span class="vexpl">Obtain a emergingthreatspro.com Pro rules code and paste here.</span> - </td> - </table> + <td width="22%" valign="top" class="vncell2">Install <strong>Emergingthreats</strong> + rules</td> + <td width="78%" class="vtable"><input name="emergingthreats" + type="checkbox" value="yes" + <?php if ($config['installedpackages']['snortglobal']['emergingthreats']=="on") echo "checked"; ?> + onClick="enable_change(false)"><br> + Emerging Threats is an open source community that produces fastest + moving and diverse Snort Rules.</td> </tr> - <tr> - <td width="22%" valign="top" class="vncell2"><span>Update rules automatically</span></td> - <td width="78%" class="vtable"> - <select name="updaterules" class="formfld2" id="updaterules"> - <?php - $updateDaysList = array('never' => 'NEVER', '6h_up' => '6 HOURS', '12h_up' => '12 HOURS', '1d_up' => '1 DAY', '4d_up' => '4 DAYS', '7d_up' => '7 DAYS', '28d_up' => '28 DAYS'); - snortDropDownList($updateDaysList, $updaterules); - ?> + <td width="22%" valign="top" class="vncell2">Update rules + automatically</td> + <td width="78%" class="vtable"><select name="autorulesupdate7" + class="formfld" id="autorulesupdate7"> + <?php + $interfaces3 = array('never_up' => 'NEVER', '6h_up' => '6 HOURS', '12h_up' => '12 HOURS', '1d_up' => '1 DAY', '4d_up' => '4 DAYS', '7d_up' => '7 DAYS', '28d_up' => '28 DAYS'); + foreach ($interfaces3 as $iface3 => $ifacename3): ?> + <option value="<?=$iface3;?>" + <?php if ($iface3 == $pconfig['autorulesupdate7']) echo "selected"; ?>> + <?=htmlspecialchars($ifacename3);?></option> + <?php endforeach; ?> </select><br> - <span class="vexpl"> - Please select the update times for rules.<br> Hint: in most cases, every 12 hours is a good choice. - </span> - </td> + <span class="vexpl">Please select the update times for rules.<br> + Hint: in most cases, every 12 hours is a good choice.</span></td> </tr> <tr> - <td colspan="2" valign="top" class="listtopic"><span>General Settings</span></td> + <td colspan="2" valign="top" class="listtopic">General Settings</td> </tr> + <tr> - <td width="22%" valign="top" class="vncell2"><span>Log Directory SizeLimit</span><br> - <br><br><br><br><br> - <span class="red"><strong>Note:</strong><br>Available space is <strong><?=$snortlogCurrentDSKsize; ?>MB</strong></span> - </td> + <?php $snortlogCurrentDSKsize = round(exec('df -k /var | grep -v "Filesystem" | awk \'{print $4}\'') / 1024); ?> + <td width="22%" valign="top" class="vncell2">Log Directory Size + Limit<br> + <br> + <br> + <br> + <br> + <br> + <span class="red"><strong>Note</span>:</strong><br> + 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="snortloglimiton" value="on" <?=$snortloglimit_on;?> > - <span class="vexpl"><strong>Enable</strong> directory size limit (Default)</span> - </td> + <td colspan="2"><input name="snortloglimit" type="radio" + id="snortloglimit" value="on" onClick="enable_change(false)" + <?php if($pconfig['snortloglimit']=='on') echo 'checked'; ?>> + <strong>Enable</strong> directory size limit (<strong>Default</strong>)</td> </tr> <tr> - <td colspan="2"> - <input name="snortloglimit" type="radio" id="snortloglimitoff" value="off" <?=$snortloglimit_off ?> > - <span class="vexpl"><strong>Disable </strong>directory size limit</span><br><br> - <span class="vexpl red"><strong>Warning:</strong> Pfsense Nanobsd should use no more than 10MB of space.</span> - </td> + <td colspan="2"><input name="snortloglimit" type="radio" + id="snortloglimit" value="off" onClick="enable_change(false)" + <?php if($pconfig['snortloglimit']=='off') echo 'checked'; ?>> <strong>Disable</strong> + directory size limit<br> + <br> + <span class="red"><strong>Warning</span>:</strong> Nanobsd + should use no more than 10MB of space.</td> </tr> <tr> <td> </td> @@ -283,85 +349,89 @@ $snortlogCurrentDSKsize = round(exec('df -k /var | grep -v "Filesystem" | awk \' </table> <table width="100%" border="0" cellpadding="6" cellspacing="0"> <tr> - <td class="vncell3"><span>Size in <strong>MB</strong></span></td> - <td class="vtable"> - <input name="snortloglimitsize" type="text" class="formfld2" id="snortloglimitsize" size="7" value="<?=$snortloglimitsize;?>"> - <span class="vexpl">Default is <strong>20%</strong> of available space.</span> - </td> - </table> + <td class="vncell3">Size in <strong>MB</strong></td> + <td class="vtable"><input name="snortloglimitsize" type="text" + class="formfld" id="snortloglimitsize" size="7" + value="<?=htmlspecialchars($pconfig['snortloglimitsize']);?>"> + Default is <strong>20%</strong> of available space.</td> + + </table> + </tr> + <tr> - <td width="22%" valign="top" class="vncell2"><span>Remove blocked hosts every</span></td> - <td width="78%" class="vtable"> - <select name="rm_blocked" class="formfld2" id="rm_blocked"> - <?php - $BlockTimeReset = array('never' => 'NEVER', '1h_b' => '1 HOUR', '3h_b' => '3 HOURS', '6h_b' => '6 HOURS', '12h_b' => '12 HOURS', '1d_b' => '1 DAY', '4d_b' => '4 DAYS', '7d_b' => '7 DAYS', '28d_b' => '28 DAYS'); - snortDropDownList($BlockTimeReset, $rm_blocked); - ?> - </select><br> - <span class="vexpl">Please select the amount of time you would likehosts to be blocked for.<br>Hint: in most cases, 1 hour is a good choice.</span> - </td> + <td width="22%" valign="top" class="vncell2">Remove blocked hosts + every</td> + <td width="78%" class="vtable"><select name="rm_blocked" + class="formfld" id="rm_blocked"> + <?php + $interfaces3 = array('never_b' => 'NEVER', '1h_b' => '1 HOUR', '3h_b' => '3 HOURS', '6h_b' => '6 HOURS', '12h_b' => '12 HOURS', '1d_b' => '1 DAY', '4d_b' => '4 DAYS', '7d_b' => '7 DAYS', '28d_b' => '28 DAYS'); + foreach ($interfaces3 as $iface3 => $ifacename3): ?> + <option value="<?=$iface3;?>" + <?php if ($iface3 == $pconfig['rm_blocked']) echo "selected"; ?>> + <?=htmlspecialchars($ifacename3);?></option> + <?php endforeach; ?> + </select><br> + <span class="vexpl">Please select the amount of time you would like + hosts to be blocked for.<br> + Hint: in most cases, 1 hour is a good choice.</span></td> </tr> <tr> - <td width="22%" valign="top" class="vncell2"><span>Alerts file descriptiontype</span></td> - <td width="78%" class="vtable"> - <select name="snortalertlogtype" class="formfld2" id="snortalertlogtype"> + <td width="22%" valign="top" class="vncell2">Alerts file description + type</td> + <td width="78%" class="vtable"><select name="snortalertlogtype" + class="formfld" id="snortalertlogtype"> <?php - // TODO: make this option a check box with all log types - $alertLogTypeList = array('full' => 'FULL', 'fast' => 'SHORT'); - snortDropDownList($alertLogTypeList, $snortalertlogtype) - ?> + $interfaces4 = array('full' => 'FULL', 'fast' => 'SHORT'); + foreach ($interfaces4 as $iface4 => $ifacename4): ?> + <option value="<?=$iface4;?>" + <?php if ($iface4 == $pconfig['snortalertlogtype']) echo "selected"; ?>> + <?=htmlspecialchars($ifacename4);?></option> + <?php endforeach; ?> </select><br> - <span class="vexpl">Please choose the type of Alert logging you will like see in your alert file.<br> Hint: Best pratice is to chose full logging.</span> - <span class="red"><strong>WARNING:</strong></span> <strong>On change, alert file will be cleared.</strong> - </td> + <span class="vexpl">Please choose the type of Alert logging you will + like see in your alert file.<br> + Hint: Best pratice is to chose full logging.</span> <span + class="red"><strong>WARNING:</strong></span> <strong>On + change, alert file will be cleared.</strong></td> </tr> <tr> - <td width="22%" valign="top" class="vncell2"><span>Keep snort settings after deinstall</span></td> - <td width="22%" class="vtable"> - <input name="forcekeepsettings" id="forcekeepsettings" type="checkbox" value="on" <?=$forcekeepsettings_on;?> > - <span class="vexpl">Settings will not be removed during deinstall.</span> - </td> + <td width="22%" valign="top" class="vncell2">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"; ?> + onClick="enable_change(false)"><br> + Settings will not be removed during deinstall.</td> </tr> <tr> - <td width="22%" valign="top" class="vncell2"><span>Save Settings</span></td> - <td width="30%" class="vtable"> - <input name="Submit" type="submit" class="formbtn" value="Save"> - <input id="cancel" type="button" class="formbtn" value="Cancel"> + <td width="22%" valign="top"><input name="Reset" type="submit" + class="formbtn" value="Reset" + onclick="return confirm('Do you really want to delete all global and interface settings?')"><span + class="red"><strong> WARNING:</strong><br> + This will reset all global and interface settings.</span></td> + <td width="78%"><input name="Submit" type="submit" class="formbtn" + value="Save" onClick="enable_change(true)"> </td> </tr> - </form> - <form id="iform2" > <tr> - <td width="22%" valign="top" class="vncell2"> - <input name="Reset" type="submit" class="formbtn" value="Reset" onclick="return confirm('Do you really want to remove all your settings ? All Snort Settings will be reset !')" > - <input type="hidden" name="reset_snortgeneralsettings" value="1" /> - <span class="vexpl red"><strong> WARNING:</strong><br> This will reset all global and interface settings.</span> - </td> - <td class="vtable"> - <span class="vexpl red"><strong>Note:</strong></span><br> - <span class="vexpl">Changing any settings on this page will affect all interfaces. Please, double check if your oink code is correct and the type of snort.org account you hold.</span> - </td> + <td width="22%" valign="top"> </td> + <td width="78%"><span class="vexpl"><span class="red"><strong>Note:<br> + </strong></span> Changing any settings on this page will affect all + interfaces. Please, double check if your oink code is correct and + the type of snort.org account you hold.</span></td> </tr> - </form> - - <!-- STOP MAIN AREA --> </table> </td> - </tr> - </table> - </td> </tr> </table> -</div> +</form> +</div> -<!-- footer do not touch below --> -<?php -include("fend.inc"); -echo $snort_custom_rnd_box; -?> + <?php include("fend.inc"); ?> + <?php echo "$snort_custom_rnd_box\n"; ?> </body> </html> diff --git a/config/snort-dev/snort_interfaces_suppress.php b/config/snort-dev/snort_interfaces_suppress.php index 977dcf2d..4eeed42d 100644 --- a/config/snort-dev/snort_interfaces_suppress.php +++ b/config/snort-dev/snort_interfaces_suppress.php @@ -1,18 +1,17 @@ <?php /* $Id$ */ /* - - part of pfSense + Copyright (C) 2004 Scott Ullrich + Copyright (C) 2011 Ermal Luci All rights reserved. + originially part of m0n0wall (http://m0n0.ch/wall) Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. All rights reserved. - Pfsense Old snort GUI - Copyright (C) 2006 Scott Ullrich. - - Pfsense snort GUI - Copyright (C) 2008-2012 Robert Zelaya. + modified for the pfsense snort package + Copyright (C) 2009-2010 Robert Zelaya. + All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -24,10 +23,6 @@ notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - 3. Neither the name of the pfSense nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - 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 @@ -38,174 +33,139 @@ 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_new.inc"); require_once("/usr/local/pkg/snort/snort_gui.inc"); +require_once("/usr/local/pkg/snort/snort.inc"); + -//Set no caching -header("Expires: Mon, 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"); +if (!is_array($config['installedpackages']['snortglobal']['suppress'])) + $config['installedpackages']['snortglobal']['suppress'] = array(); +if (!is_array($config['installedpackages']['snortglobal']['suppress']['item'])) + $config['installedpackages']['snortglobal']['suppress']['item'] = array(); +$a_suppress = &$config['installedpackages']['snortglobal']['suppress']['item']; +$id_gen = count($config['installedpackages']['snortglobal']['suppress']['item']); +$d_suppresslistdirty_path = '/var/run/snort_suppress.dirty'; -$a_suppress = snortSql_fetchAllWhitelistTypes('SnortSuppress', ''); +if ($_GET['act'] == "del") { + if ($a_suppress[$_GET['id']]) { + /* make sure rule is not being referenced by any nat or filter rules */ - if (!is_array($a_suppress)) - { - $a_suppress = array(); + unset($a_suppress[$_GET['id']]); + write_config(); + filter_configure(); + header("Location: /snort/snort_interfaces_suppress.php"); + exit; } +} +$pgtitle = "Services: Snort: Suppression"; +include_once("head.inc"); - if ($a_suppress == 'Error') - { - echo 'Error'; - exit(0); - } +?> - $pgtitle = "Services: Snort: Suppression"; - include("/usr/local/pkg/snort/snort_head.inc"); +<body link="#000000" vlink="#000000" alink="#000000"> +<?php +include_once("fbegin.inc"); +echo $snort_general_css; ?> - - -<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> - -<!-- loading msg --> -<div id="loadingWaiting"> - <div class="snortModal" style="top: 200px; left: 700px;"> - <div class="snortModalTop"> - <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> - </div> - <div class="snortModalTitle"> - <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> - </div> - <div> - <p class="loadingWaitingMessage"></p> - </div> - </div> -</div> -<?php include("fbegin.inc"); ?> -<!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"> -<a href="../index.php" id="status-link2"> -<img src="./images/transparent.gif" border="0"></img> -</a> -</div> +<div class="body2"><?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> -<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> +<form action="/snort/snort_interfaces_suppress.php" method="post"><?php if ($savemsg) print_info_box($savemsg); ?> +<?php if (file_exists($d_suppresslistdirty_path)): ?> +<p><?php print_info_box_np("The white list has been changed.<br>You must apply the changes in order for them to take effect.");?> +<?php endif; ?> <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("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); + $tab_array[6] = array(gettext("Suppress"), true, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Help"), false, "/snort/help_and_info.php"); + display_top_tabs($tab_array); +?> + </td> + </tr> <tr> - <td> - - <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> - <ul class="newtabmenu"> - <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> - <li><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> - <li><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> - <li><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> - <li><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> - <li><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> - <li><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> - <li class="newtabmenu_active"><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> - <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> - </li> - </ul> - </div> + <td class="tabcont"> - </td> - </tr> - <tr> - <td id="tdbggrey"> - <table width="100%" border="0" cellpadding="10px" cellspacing="0"> - <tr> - <td class="tabnavtbl"> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> - <!-- START MAIN AREA --> - - <tr> <!-- db to lookup --> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + + <tr> <td width="30%" class="listhdrr">File Name</td> <td width="70%" class="listhdr">Description</td> + <td width="10%" class="list"></td> </tr> - <?php foreach ($a_suppress as $list): ?> - <tr id="maintable_<?=$list['uuid']?>" data-options='{"pagetable":"SnortSuppress", "pagedb":"snortDB", "DoPOST":"true"}' > - <td class="listlr" ondblclick="document.location='snort_interfaces_suppress_edit.php?uuid=<?=$list['uuid'];?>'"><?=$list['filename'];?></td> - <td class="listbg" ondblclick="document.location='snort_interfaces_suppress_edit.php?uuid=<?=$list['uuid'];?>'"> - <font color="#FFFFFF"> <?=htmlspecialchars($list['description']);?> + <?php $i = 0; foreach ($a_suppress as $list): ?> + <tr> + <td class="listlr" + ondblclick="document.location='snort_interfaces_suppress_edit.php?id=<?=$i;?>';"> + <?=htmlspecialchars($list['name']);?></td> + <td class="listbg" + ondblclick="document.location='snort_interfaces_suppress_edit.php?id=<?=$i;?>';"> + <font color="#FFFFFF"> <?=htmlspecialchars($list['descr']);?> </td> - <td></td> + <td valign="middle" nowrap class="list"> <table border="0" cellspacing="0" cellpadding="1"> <tr> - <td valign="middle"> - <a href="snort_interfaces_suppress_edit.php?uuid=<?=$list['uuid'];?>"><img src="/themes/<?= $g['theme']; ?>/images/icons/icon_e.gif"width="17" height="17" border="0" title="edit suppress list"></a> - </td> - <td> - <img id="icon_x_<?=$list['uuid'];?>" class="icon_click icon_x" src="/themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" width="17" height="17" border="0" title="delete list" > - </a> - </td> + <td valign="middle"><a + href="snort_interfaces_suppress_edit.php?id=<?=$i;?>"><img + src="/themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" + width="17" height="17" border="0" title="edit whitelist"></a></td> + <td><a + href="/snort/snort_interfaces_suppress.php?act=del&id=<?=$i;?>" + onclick="return confirm('Do you really want to delete this whitelist? All elements that still use it will become invalid (e.g. snort rules will fall back to the default whitelist)!')"><img + src="/themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" + width="17" height="17" border="0" title="delete whitelist"></a></td> </tr> </table> </td> </tr> <?php $i++; endforeach; ?> <tr> - <td class="list" colspan="3"></td> + <td class="list" colspan="2"></td> <td class="list"> <table border="0" cellspacing="0" cellpadding="1"> - <tr> - <td valign="middle" width="17"> </td> - <td valign="middle"><a href="snort_interfaces_suppress_edit.php?uuid=<?=genAlphaNumMixFast(28, 28);?> "><img src="/themes/nervecenter/images/icons/icon_plus.gif" width="17" height="17" border="0" title="add a new list"></a></td> + <tr> + <td valign="middle" width="17"> </td> + <td valign="middle"><a + href="snort_interfaces_suppress_edit.php?id=<?php echo $id_gen;?> "><img + src="/themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" + width="17" height="17" border="0" title="add a new list"></a></td> </tr> </table> </td> </tr> - </table> - </td> - </tr> - - <!-- STOP MAIN AREA --> </table> </td> - </tr> - - </table> - </td> </tr> </table> - -<!-- 2nd box note --> <br> -<div id=mainarea4> -<table class="tabcont" width="100%" border="0" cellpadding="0" cellspacing="0"> - <td width="100%"> - <span class="vexpl"> - <span class="red"><strong>Note:</strong></span> - <p><span class="vexpl"> - Here you can create event filtering and suppression for your snort package rules.<br> - Please note that you must restart a running rule so that changes can take effect.<br> - </span></p> - </td> +<table class="tabcont" width="100%" border="0" cellpadding="0" + cellspacing="0"> + <td width="100%"><span class="vexpl"><span class="red"><strong>Note:</strong></span> + <p><span class="vexpl">Here you can create event filtering and + suppression for your snort package rules.<br> + Please note that you must restart a running rule so that changes can + take effect.</span></p></td> </table> -</div> - -</div> +</form> -<!-- footer do not touch below --> -<?php -include("fend.inc"); -echo $snort_custom_rnd_box; -?> - +</div> +<?php include("fend.inc"); ?> </body> </html> diff --git a/config/snort-dev/snort_interfaces_suppress_edit.php b/config/snort-dev/snort_interfaces_suppress_edit.php index e9f23254..7303349f 100644 --- a/config/snort-dev/snort_interfaces_suppress_edit.php +++ b/config/snort-dev/snort_interfaces_suppress_edit.php @@ -1,18 +1,17 @@ <?php /* $Id$ */ /* - - part of pfSense + firewall_aliases_edit.php + Copyright (C) 2004 Scott Ullrich All rights reserved. + originially part of m0n0wall (http://m0n0.ch/wall) Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. All rights reserved. - Pfsense Old snort GUI - Copyright (C) 2006 Scott Ullrich. - - Pfsense snort GUI - Copyright (C) 2008-2012 Robert Zelaya. + modified for the pfsense snort package + Copyright (C) 2009-2010 Robert Zelaya. + All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -24,10 +23,6 @@ notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - 3. Neither the name of the pfSense nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - 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 @@ -38,194 +33,263 @@ 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_new.inc"); require_once("/usr/local/pkg/snort/snort_gui.inc"); +require_once("/usr/local/pkg/snort/snort.inc"); + +if (!is_array($config['installedpackages']['snortglobal']['suppress'])) + $config['installedpackages']['snortglobal']['suppress'] = array(); +if (!is_array($config['installedpackages']['snortglobal']['suppress']['item'])) + $config['installedpackages']['snortglobal']['suppress']['item'] = array(); +$a_suppress = &$config['installedpackages']['snortglobal']['suppress']['item']; + +$id = $_GET['id']; +if (isset($_POST['id'])) + $id = $_POST['id']; +if (!is_numeric($id)) + $id = 0; // XXX: safety belt + + +/* gen uuid for each iface */ +if (is_array($config['installedpackages']['snortglobal']['suppress']['item'][$id])) { + if ($config['installedpackages']['snortglobal']['suppress']['item'][$id]['uuid'] == '') { + //$snort_uuid = gen_snort_uuid(strrev(uniqid(true))); + $suppress_uuid = 0; + while ($suppress_uuid > 65535 || $suppress_uuid == 0) { + $suppress_uuid = mt_rand(1, 65535); + $pconfig['uuid'] = $suppress_uuid; + } + } else if ($config['installedpackages']['snortglobal']['suppress']['item'][$id]['uuid'] != '') { + $suppress_uuid = $config['installedpackages']['snortglobal']['suppress']['item'][$id]['uuid']; + } +} -//Set no caching -header("Expires: Mon, 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"); +$d_snort_suppress_dirty_path = '/var/run/snort_suppress.dirty'; -// set page vars +/* returns true if $name is a valid name for a whitelist file name or ip */ +function is_validwhitelistname($name) { + if (!is_string($name)) + return false; -$uuid = $_GET['uuid']; -if (isset($_POST['uuid'])) -$uuid = $_POST['uuid']; + if (!preg_match("/[^a-zA-Z0-9\.\/]/", $name)) + return true; -if ($uuid == '') { - echo 'error: no uuid'; - exit(0); + return false; } -$a_list = snortSql_fetchAllSettings('snortDB', 'SnortSuppress', 'uuid', $uuid); +if (isset($id) && $a_suppress[$id]) { + /* old settings */ + $pconfig['name'] = $a_suppress[$id]['name']; + $pconfig['uuid'] = $a_suppress[$id]['uuid']; + $pconfig['descr'] = $a_suppress[$id]['descr']; + $pconfig['suppresspassthru'] = base64_decode($a_suppress[$id]['suppresspassthru']); +} -// $a_list returns empty use defaults -if ($a_list == '') -{ - - $a_list = array( - 'id' => '', - 'date' => date(U), - 'uuid' => $uuid, - 'filename' => '', - 'description' => '', - 'suppresspassthru' => '' +if ($_POST['submit']) { - ); - -} + unset($input_errors); + $pconfig = $_POST; + do_input_validation($_POST, $reqdfields, $reqdfieldsn, &$input_errors); + if(strtolower($_POST['name']) == "defaultwhitelist") + $input_errors[] = "Whitelist file names may not be named defaultwhitelist."; + $x = is_validwhitelistname($_POST['name']); + if (!isset($x)) { + $input_errors[] = "Reserved word used for whitelist file name."; + } else { + if (is_validwhitelistname($_POST['name']) == false) + $input_errors[] = "Whitelist file name may only consist of the characters a-z, A-Z and 0-9 _. Note: No Spaces. Press Cancel to reset."; + } - $pgtitle = 'Services: Snort: Suppression: Edit'; - include('/usr/local/pkg/snort/snort_head.inc'); -?> - - -<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + /* check for name conflicts */ + foreach ($a_suppress as $s_list) { + if (isset($id) && ($a_suppress[$id]) && ($a_suppress[$id] === $s_list)) + continue; -<!-- loading msg --> -<div id="loadingWaiting"> - <div class="snortModal" style="top: 200px; left: 700px;"> - <div class="snortModalTop"> - <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> - </div> - <div class="snortModalTitle"> - <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> - </div> - <div> - <p class="loadingWaitingMessage"></p> - </div> - </div> -</div> + if ($s_list['name'] == $_POST['name']) { + $input_errors[] = "A whitelist file name with this name already exists."; + break; + } + } -<?php include("fbegin.inc"); ?> -<!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"> -<a href="../index.php" id="status-link2"> -<img src="./images/transparent.gif" border="0"></img> -</a> -</div> -<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> + if (!$input_errors) { + $s_list = array(); + $s_list['name'] = $_POST['name']; + $s_list['uuid'] = $suppress_uuid; + $s_list['descr'] = mb_convert_encoding($_POST['descr'],"HTML-ENTITIES","auto"); + $s_list['suppresspassthru'] = base64_encode($_POST['suppresspassthru']); + + if (isset($id) && $a_suppress[$id]) + $a_suppress[$id] = $s_list; + else + $a_suppress[] = $s_list; + + write_config(); + + sync_snort_package_config(); + + header("Location: /snort/snort_interfaces_suppress.php"); + exit; + } + +} + +$pgtitle = "Services: Snort: Suppression: Edit $suppress_uuid"; +include_once("head.inc"); + +?> + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + +<?php +include("fbegin.inc"); +echo $snort_general_css; +?> -<form id="iform"> +<div class="body2"><?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> + +<?php if ($input_errors) print_input_errors($input_errors); ?> +<div id="inputerrors"></div> + +<form action="/snort/snort_interfaces_suppress_edit.php?id=<?=$id?>" + method="post" name="iform" id="iform"><?php + /* Display Alert message */ + if ($input_errors) { + print_input_errors($input_errors); // TODO: add checks + } + + if ($savemsg) { + print_info_box2($savemsg); + } + + //if (file_exists($d_snortconfdirty_path)) { + if (file_exists($d_snort_suppress_dirty_path)) { + echo '<p>'; + + if($savemsg) { + print_info_box_np2("{$savemsg}"); + }else{ + print_info_box_np2(' + The Snort configuration has changed and snort needs to be restarted on this interface.<br> + You must apply the changes in order for them to take effect.<br> + '); + } + } + ?> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> - <td> + <td class="tabnavtbl"> <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> <ul class="newtabmenu"> <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> - <li><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> + <li><a href="/snort/snort_interfaces_global.php"><span>Global + Settings</span></a></li> <li><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> - <li><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> <li><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> <li><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> <li><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> - <li class="newtabmenu_active"><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> - <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> - </li> + <li class="newtabmenu_active"><a + href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> + <li><a class="example8" href="/snort/help_and_info.php"><span>Help</span></a></li> </ul> </div> </td> </tr> + <tr> - <td id="tdbggrey"> - <table width="100%" border="0" cellpadding="10px" cellspacing="0"> - <tr> - <td class="tabnavtbl"> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> - <!-- START MAIN AREA --> - - <!-- table point --> - <input name="snortSaveSuppresslist" type="hidden" value="1" /> - <input name="ifaceTab" type="hidden" value="snort_interfaces_suppress_edit" /> - <input type="hidden" name="dbName" value="snortDB" /> <!-- what db --> - <input type="hidden" name="dbTable" value="SnortSuppress" /> <!-- what db table --> - <input name="date" type="hidden" value="<?=$a_list['date'];?>" /> - <input name="uuid" type="hidden" value="<?=$a_list['uuid'];?>" /> - + <td class="tabcont"> <table width="100%" border="0" cellpadding="6" cellspacing="0"> <tr> - <td colspan="2" valign="top" class="listtopic">Add the name anddescription of the file.</td> + <td colspan="2" valign="top" class="listtopic">Add the name and + description of the file.</td> </tr> <tr> <td valign="top" class="vncellreq2">Name</td> - <td class="vtable"> - <input class="formfld2" name="filename" type="text" id="filename" size="40" value="<?=$a_list['filename'] ?>" /> <br /> - <span class="vexpl"> The list name may only consist of the characters a-z, A-Z and 0-9. <span class="red">Note: </span> No Spaces. </span> - </td> + <td class="vtable"><input name="name" type="text" id="name" + size="40" value="<?=htmlspecialchars($pconfig['name']);?>" /> <br /> + <span class="vexpl"> The list name may only consist of the + characters a-z, A-Z and 0-9. <span class="red">Note: </span> No + Spaces. </span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Description</td> - <td width="78%" class="vtable"> - <input class="formfld2" name="description" type="text" id="description" size="40" value="<?=$a_list['description'] ?>" /> <br /> - <span class="vexpl"> You may enter a description here for your reference (not parsed). </span> - </td> - </tr> - <tr> - <td colspan="2" valign="top" class="listtopic"> - Examples: - </td> - </tr> - <tr> - <td colspan="2" valign="top" class="vncell2"> - <b>Example 1;</b> suppress gen_id 1, sig_id 1852, track by_src, ip 10.1.1.54<br> - <b>Example 2;</b> event_filter gen_id 1, sig_id 1851, type limit,track by_src, count 1, seconds 60<br> - <b>Example 3;</b> rate_filter gen_id 135, sig_id 1, track by_src, count 100, seconds 1, new_action log, timeout 10 - </td> + <td width="78%" class="vtable"><input name="descr" type="text" + id="descr" size="40" value="<?=$pconfig['descr'];?>" /> <br /> + <span class="vexpl"> You may enter a description here for your + reference (not parsed). </span></td> </tr> </table> - <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td colspan="2" valign="top" class="listtopic"> - Apply suppression or filters to rules. Valid keywords are 'suppress', 'event_filter' and 'rate_filter'. - </td> - </tr> - <tr> - <td colspan="2" valign="top" class="vncelltextbox"> - <textarea wrap="off" name="suppresspassthru" cols="101" rows="28" id="suppresspassthru" class="formfld2"><?=base64_decode($a_list['suppresspassthru']); ?></textarea> - </td> - </tr> - </table> - <tr> - <td style="padding-left: 160px;"> - <input name="Submit" type="submit" class="formbtn" value="Save"> - <input id="cancel" type="button" class="formbtn" value="Cancel"> - </td> - </tr> - </form> - - <!-- STOP MAIN AREA --> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <table height="32" width="100%"> + <tr> + <td> + <div style='background-color: #E0E0E0' id='redbox'> + <table width='100%'> + <tr> + <td width='8%'> <img + style='vertical-align: middle' + src="/snort/images/icon_excli.png" width="40" height="32"></td> + <td width='70%'><font size="2" color='#FF850A'><b>NOTE:</b></font> + <font size="2" color='#000000'> The threshold keyword + is deprecated as of version 2.8.5. Use the event_filter keyword + instead.</font></td> + </tr> + </table> + </div> + </td> + </tr> + <script type="text/javascript"> + NiftyCheck(); + Rounded("div#redbox","all","#FFF","#E0E0E0","smooth"); + Rounded("td#blackbox","all","#FFF","#000000","smooth"); + </script> + <tr> + <td colspan="2" valign="top" class="listtopic">Apply suppression or + filters to rules. Valid keywords are 'suppress', 'event_filter' and + 'rate_filter'.</td> + </tr> + <tr> + <td colspan="2" valign="top" class="vncell"><b>Example 1;</b> + suppress gen_id 1, sig_id 1852, track by_src, ip 10.1.1.54<br> + <b>Example 2;</b> event_filter gen_id 1, sig_id 1851, type limit, + track by_src, count 1, seconds 60<br> + <b>Example 3;</b> rate_filter gen_id 135, sig_id 1, track by_src, + count 100, seconds 1, new_action log, timeout 10</td> + </tr> + <tr> + <td width="100%" class="vtable"><textarea wrap="off" + name="suppresspassthru" cols="142" rows="28" id="suppresspassthru" + class="formpre"><?=htmlspecialchars($pconfig['suppresspassthru']);?></textarea> + </td> + </tr> + <tr> + <td width="78%"><input id="submit" name="submit" type="submit" + class="formbtn" value="Save" /> <input id="cancelbutton" + name="cancelbutton" type="button" class="formbtn" value="Cancel" + onclick="history.back()" /> <?php if (isset($id) && $a_suppress[$id]): ?> + <input name="id" type="hidden" value="<?=$id;?>" /> <?php endif; ?> + </td> + </tr> + </table> </table> </td> - </tr> - </table> - </td> </tr> </table> -</div> - +</form> -<!-- footer do not touch below --> -<?php -include("fend.inc"); -echo $snort_custom_rnd_box; -?> +</div> + <?php include("fend.inc"); ?> </body> </html> diff --git a/config/snort-dev/snort_interfaces_whitelist.php b/config/snort-dev/snort_interfaces_whitelist.php index 3167b65f..2dc2d491 100644 --- a/config/snort-dev/snort_interfaces_whitelist.php +++ b/config/snort-dev/snort_interfaces_whitelist.php @@ -1,18 +1,18 @@ <?php /* $Id$ */ /* - - part of pfSense + firewall_aliases.php + Copyright (C) 2004 Scott Ullrich + Copyright (C) 2011 Ermal Luci All rights reserved. + originially part of m0n0wall (http://m0n0.ch/wall) Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. All rights reserved. - Pfsense Old snort GUI - Copyright (C) 2006 Scott Ullrich. - - Pfsense snort GUI - Copyright (C) 2008-2012 Robert Zelaya. + modified for the pfsense snort package + Copyright (C) 2009-2010 Robert Zelaya. + All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -24,10 +24,6 @@ notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - 3. Neither the name of the pfSense nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - 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 @@ -38,148 +34,117 @@ 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_new.inc"); require_once("/usr/local/pkg/snort/snort_gui.inc"); +require_once("/usr/local/pkg/snort/snort.inc"); -//Set no caching -header("Expires: Mon, 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"); +if (!is_array($config['installedpackages']['snortglobal']['whitelist']['item'])) +$config['installedpackages']['snortglobal']['whitelist']['item'] = array(); -$a_whitelist = snortSql_fetchAllWhitelistTypes('SnortWhitelist', 'SnortWhitelistips'); +//aliases_sort(); << what ? +$a_whitelist = &$config['installedpackages']['snortglobal']['whitelist']['item']; - if (!is_array($a_whitelist)) - { - $a_whitelist = array(); - } +if (isset($config['installedpackages']['snortglobal']['whitelist']['item'])) { + $id_gen = count($config['installedpackages']['snortglobal']['whitelist']['item']); +}else{ + $id_gen = '0'; +} - if ($a_whitelist == 'Error') - { - echo 'Error'; - exit(0); +$d_whitelistdirty_path = '/var/run/snort_whitelist.dirty'; + +if ($_GET['act'] == "del") { + if ($a_whitelist[$_GET['id']]) { + /* make sure rule is not being referenced by any nat or filter rules */ + + unset($a_whitelist[$_GET['id']]); + write_config(); + filter_configure(); + header("Location: /snort/snort_interfaces_whitelist.php"); + exit; } +} - $pgtitle = "Services: Snort: Whitelist"; - include("/usr/local/pkg/snort/snort_head.inc"); +$pgtitle = "Services: Snort: Whitelist"; +include_once("head.inc"); ?> - - + <body link="#0000CC" vlink="#0000CC" alink="#0000CC"> -<!-- loading msg --> -<div id="loadingWaiting"> - <div class="snortModal" style="top: 200px; left: 700px;"> - <div class="snortModalTop"> - <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> - </div> - <div class="snortModalTitle"> - <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> - </div> - <div> - <p class="loadingWaitingMessage"></p> - </div> - </div> -</div> +<?php +include_once("fbegin.inc"); +echo $snort_general_css; +?> -<?php include("fbegin.inc"); ?> -<!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"> -<a href="../index.php" id="status-link2"> -<img src="./images/transparent.gif" border="0"></img> -</a> -</div> +<div class="body2"><?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> -<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> +<form action="/snort/snort_interfaces_whitelist.php" method="post"><?php if ($savemsg) print_info_box($savemsg); ?> +<?php if (file_exists($d_whitelistdirty_path)): ?> +<p><?php print_info_box_np("The white list has been changed.<br>You must apply the changes in order for them to take effect.");?> +<?php endif; ?> <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td> - - <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> - <ul class="newtabmenu"> - <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> - <li><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> - <li><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> - <li><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> - <li><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> - <li><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> - <li class="newtabmenu_active"><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> - <li><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> - <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> - </li> - </ul> - </div> - +<tr><td> +<?php + $tab_array = array(); + $tab_array[0] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); + $tab_array[1] = array(gettext("Global Settings"), false, "/snort/snort_interfaces_global.php"); + $tab_array[2] = array(gettext("Updates"), false, "/snort/snort_download_updates.php"); + $tab_array[3] = array(gettext("Alerts"), false, "/snort/snort_alerts.php"); + $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); + $tab_array[5] = array(gettext("Whitelists"), true, "/snort/snort_interfaces_whitelist.php"); + $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Help"), false, "/snort/help_and_info.php"); + display_top_tabs($tab_array); +?> </td> </tr> <tr> - <td id="tdbggrey"> - <table width="100%" border="0" cellpadding="10px" cellspacing="0"> - <tr> - <td class="tabnavtbl"> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> - <!-- START MAIN AREA --> - - <tr> <!-- db to lookup --> + <td class="tabcont"> + + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + + <tr> <td width="20%" class="listhdrr">File Name</td> - <td width="45%" class="listhdrr">Values</td> - <td width="35%" class="listhdr">Description</td> + <td width="40%" class="listhdrr">Values</td> + <td width="40%" class="listhdr">Description</td> <td width="10%" class="list"></td> </tr> - <?php foreach ($a_whitelist as $list): ?> - <tr id="maintable_<?=$list['uuid']?>" data-options='{"pagetable":"SnortWhitelist", "pagedb":"snortDB", "DoPOST":"true"}' > - <td class="listlr" ondblclick="document.location='snort_interfaces_whitelist_edit.php?uuid=<?=$list['uuid'];?>'"><?=$list['filename'];?></td> - <td class="listr" ondblclick="document.location='snort_interfaces_whitelist_edit.php?uuid=<?=$list['uuid'];?>'"> - <?php - $a = 0; - $countList = count($list['list']); - foreach ($list['list'] as $value) - { - - $a++; - - if ($a != $countList || $countList == 1) - { - echo $value['ip']; - } - - if ($a > 0 && $a != $countList) - { - echo ',' . ' '; - }else{ - echo ' '; - } - - } // end foreach - - if ($a > 3) - { - echo '...'; - } - ?> - </td> - <td class="listbg" ondblclick="document.location='snort_interfaces_whitelist_edit.php?uuid=<?=$list['uuid'];?>'"> - <font color="#FFFFFF"> <?=htmlspecialchars($list['description']);?> + <?php $i = 0; foreach ($a_whitelist as $list): ?> + <tr> + <td class="listlr" + ondblclick="document.location='snort_interfaces_whitelist_edit.php?id=<?=$i;?>';"> + <?=htmlspecialchars($list['name']);?></td> + <td class="listr" + ondblclick="document.location='snort_interfaces_whitelist_edit.php?id=<?=$i;?>';"> + <?php + $addresses = implode(", ", array_slice(explode(" ", $list['address']), 0, 10)); + echo $addresses; + if(count($addresses) < 10) { + echo " "; + } else { + echo "..."; + } + ?></td> + <td class="listbg" + ondblclick="document.location='snort_interfaces_whitelist_edit.php?id=<?=$i;?>';"> + <font color="#FFFFFF"> <?=htmlspecialchars($list['descr']);?> </td> <td valign="middle" nowrap class="list"> <table border="0" cellspacing="0" cellpadding="1"> <tr> - <td valign="middle"> - <a href="snort_interfaces_whitelist_edit.php?uuid=<?=$list['uuid'];?>"><img src="/themes/<?= $g['theme']; ?>/images/icons/icon_e.gif"width="17" height="17" border="0" title="edit whitelist"></a> - </td> - <td> - <img id="icon_x_<?=$list['uuid'];?>" class="icon_click icon_x" src="/themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" width="17" height="17" border="0" title="delete list" > - </a> - </td> + <td valign="middle"><a + href="snort_interfaces_whitelist_edit.php?id=<?=$i;?>"><img + src="/themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" + width="17" height="17" border="0" title="edit whitelist"></a></td> + <td><a + href="/snort/snort_interfaces_whitelist.php?act=del&id=<?=$i;?>" + onclick="return confirm('Do you really want to delete this whitelist? All elements that still use it will become invalid (e.g. snort rules will fall back to the default whitelist)!')"><img + src="/themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" + width="17" height="17" border="0" title="delete whitelist"></a></td> </tr> </table> </td> @@ -189,53 +154,36 @@ $a_whitelist = snortSql_fetchAllWhitelistTypes('SnortWhitelist', 'SnortWhitelist <td class="list" colspan="3"></td> <td class="list"> <table border="0" cellspacing="0" cellpadding="1"> - <tr> - <td valign="middle" width="17"> </td> - <td valign="middle"><a href="snort_interfaces_whitelist_edit.php?uuid=<?=genAlphaNumMixFast(28, 28);?> "><img src="/themes/nervecenter/images/icons/icon_plus.gif" width="17" height="17" border="0" title="add a new list"></a></td> + <tr> + <td valign="middle" width="17"> </td> + <td valign="middle"><a + href="snort_interfaces_whitelist_edit.php?id=<?php echo $id_gen;?> "><img + src="/themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" + width="17" height="17" border="0" title="add a new list"></a></td> </tr> </table> </td> </tr> - </table> - </td> - </tr> - - <!-- STOP MAIN AREA --> </table> </td> - </tr> - - </table> - </td> </tr> </table> - -<!-- 2nd box note --> <br> -<div id=mainarea4> -<table class="tabcont" width="100%" border="0" cellpadding="0" cellspacing="0"> - <td width="100%"> - <span class="vexpl"> - <span class="red"><strong>Note:</strong></span> - <p><span class="vexpl"> - Here you can create whitelist files for your snort package rules.<br> - Please add all the ips or networks you want to protect against snort block decisions.<br> +<table class="tabcont" width="100%" border="0" cellpadding="0" + cellspacing="0"> + <td width="100%"><span class="vexpl"><span class="red"><strong>Note:</strong></span> + <p><span class="vexpl">Here you can create whitelist files for your + snort package rules.<br> + Please add all the ips or networks you want to protect against snort + block decisions.<br> Remember that the default whitelist only includes local networks.<br> - Be careful, it is very easy to get locked out of you system. - </span></p> - </td> + Be careful, it is very easy to get locked out of you system.</span></p></td> </table> -</div> - -</div> +</form> -<!-- footer do not touch below --> -<?php -include("fend.inc"); -echo $snort_custom_rnd_box; -?> - +</div> +<?php include("fend.inc"); ?> </body> </html> diff --git a/config/snort-dev/snort_interfaces_whitelist_edit.php b/config/snort-dev/snort_interfaces_whitelist_edit.php index dbdbb649..ef930eb9 100644 --- a/config/snort-dev/snort_interfaces_whitelist_edit.php +++ b/config/snort-dev/snort_interfaces_whitelist_edit.php @@ -1,18 +1,18 @@ <?php /* $Id$ */ /* - - part of pfSense + firewall_aliases_edit.php + Copyright (C) 2004 Scott Ullrich + Copyright (C) 2011 Ermal Luci All rights reserved. + originially part of m0n0wall (http://m0n0.ch/wall) Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. All rights reserved. - Pfsense Old snort GUI - Copyright (C) 2006 Scott Ullrich. - - Pfsense snort GUI - Copyright (C) 2008-2012 Robert Zelaya. + modified for the pfsense snort package + Copyright (C) 2009-2010 Robert Zelaya. + All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -24,10 +24,6 @@ notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - 3. Neither the name of the pfSense nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - 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 @@ -38,304 +34,461 @@ 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_new.inc'); -require_once('/usr/local/pkg/snort/snort_gui.inc'); +require_once("guiconfig.inc"); +require_once("/usr/local/pkg/snort/snort_gui.inc"); +require_once("/usr/local/pkg/snort/snort.inc"); -//Set no caching -header("Expires: Mon, 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"); +if (!is_array($config['installedpackages']['snortglobal']['whitelist']['item'])) + $config['installedpackages']['snortglobal']['whitelist']['item'] = array(); -//$GLOBALS['csrf']['rewrite-js'] = false; +$a_whitelist = &$config['installedpackages']['snortglobal']['whitelist']['item']; -$uuid = $_GET['uuid']; -if (isset($_POST['uuid'])) -$uuid = $_POST['uuid']; - -if ($uuid == '') { - echo 'error: no uuid'; - exit(0); +$id = $_GET['id']; +if (isset($_POST['id'])) + $id = $_POST['id']; +if (is_null($id)) { + header("Location: /snort/snort_interfaces_whitelist.php"); + exit; } -$a_list = snortSql_fetchAllSettings('snortDB', 'SnortWhitelist', 'uuid', $uuid); - -// $a_list returns empty use defaults -if ($a_list == '') -{ - - $a_list = array( - 'id' => '', - 'date' => date(U), - 'uuid' => $uuid, - 'filename' => '', - 'snortlisttype' => 'whitelist', - 'description' => '', - 'wanips' => 'on', - 'wangateips' => 'on', - 'wandnsips' => 'on', - 'vips' => 'on', - 'vpnips' => 'on' - ); - +/* gen uuid for each iface !inportant */ +if ($config['installedpackages']['snortglobal']['whitelist']['item'][$id]['uuid'] == '') { + $whitelist_uuid = 0; + while ($whitelist_uuid > 65535 || $whitelist_uuid == 0) { + $whitelist_uuid = mt_rand(1, 65535); + $pconfig['uuid'] = $whitelist_uuid; + } +} else if ($config['installedpackages']['snortglobal']['whitelist']['item'][$id]['uuid'] != '') { + $whitelist_uuid = $config['installedpackages']['snortglobal']['whitelist']['item'][$id]['uuid']; } -$listFilename = $a_list['filename']; +$d_snort_whitelist_dirty_path = '/var/run/snort_whitelist.dirty'; + +/* returns true if $name is a valid name for a whitelist file name or ip */ +function is_validwhitelistname($name, $type) { + if (!is_string($name)) + return false; -$a_list['list'] = snortSql_fetchAllSettingsList('SnortWhitelistips', $listFilename); + if ($type === 'name' && !preg_match("/[^a-zA-Z0-9\_]/", $name)) + return true; + + if ($type === 'ip' && !preg_match("/[^a-zA-Z0-9\:\,\.\/]/", $name)) + return true; + + if ($type === 'detail' && !preg_match("/[^a-zA-Z0-9\:\,\.\+\s\-\']/", $name)) + return true; -$wanips_chk = $a_list['wanips']; -$wanips_on = ($wanips_chk == 'on' ? 'checked' : ''); + return false; +} -$wangateips_chk = $a_list['wangateips']; -$wangateips_on = ($wangateips_chk == 'on' ? 'checked' : ''); +if (isset($id) && $a_whitelist[$id]) { + + /* old settings */ + $pconfig = array(); + $pconfig['name'] = $a_whitelist[$id]['name']; + $pconfig['uuid'] = $a_whitelist[$id]['uuid']; + $pconfig['detail'] = $a_whitelist[$id]['detail']; + $pconfig['addressuuid'] = $a_whitelist[$id]['addressuuid']; + $pconfig['snortlisttype'] = $a_whitelist[$id]['snortlisttype']; + $pconfig['address'] = $a_whitelist[$id]['address']; + $pconfig['descr'] = html_entity_decode($a_whitelist[$id]['descr']); + $pconfig['wanips'] = $a_whitelist[$id]['wanips']; + $pconfig['wangateips'] = $a_whitelist[$id]['wangateips']; + $pconfig['wandnsips'] = $a_whitelist[$id]['wandnsips']; + $pconfig['vips'] = $a_whitelist[$id]['vips']; + $pconfig['vpnips'] = $a_whitelist[$id]['vpnips']; + $addresses = explode(' ', $pconfig['address']); + $address = explode(" ", $addresses[0]); +} -$wandnsips_chk = $a_list['wandnsips']; -$wandnsips_on = ($wandnsips_chk == 'on' ? 'checked' : ''); +if ($_POST['submit']) { -$vips_chk = $a_list['vips']; -$vips_on = ($vips_chk == 'on' ? 'checked' : ''); + conf_mount_rw(); -$vpnips_chk = $a_list['vpnips']; -$vpnips_on = ($vpnips_chk == 'on' ? 'checked' : ''); + unset($input_errors); + $pconfig = $_POST; + //input validation + $reqdfields = explode(" ", "name"); // post name required + $reqdfieldsn = explode(",", "Name"); // error msg name + do_input_validation($_POST, $reqdfields, $reqdfieldsn, &$input_errors); - $pgtitle = "Services: Snort: Whitelist Edit"; - include("/usr/local/pkg/snort/snort_head.inc"); + if(strtolower($_POST['name']) == "defaultwhitelist") + $input_errors[] = "Whitelist file names may not be named defaultwhitelist."; -?> + if (is_validwhitelistname($_POST['name'], 'name') == false) + $input_errors[] = "Whitelist name may only consist of the characters a-z, A-Z and 0-9. Note: No Spaces."; + + if (is_validwhitelistname($_POST['descr'], 'detail') == false) + $input_errors[] = "Whitelist description name may only consist of the characters [a-z, A-Z 0-9 + , :]. Note: No Spaces."; + + // check for name conflicts + foreach ($a_whitelist as $w_list) { + if (isset($id) && ($a_whitelist[$id]) && ($a_whitelist[$id] === $w_list)) + continue; + + if ($w_list['name'] == $_POST['name']) { + $input_errors[] = "A whitelist file name with this name already exists."; + break; + } + } + + // build string lists + if (!empty($pconfig[addresses])) { + $countArray = count($pconfig[addresses]); + $i = 0; + + foreach ($pconfig[addresses] as $address) { + + $i++; + + if (is_validwhitelistname($address[address], 'ip') == false) { + $input_errors[] = "List of IPs may only consist of the characters [. : 0-9]. Note: No Spaces."; + } + + if (is_validwhitelistname($address[detail], 'detail') == false) { + $input_errors[] = "List of IP descriptions may only consist of the characters [a-z, A-Z 0-9 + , : ' -]."; + } + + if (!empty($address[address]) && !empty($address[uuid])) { + + $final_address_ip .= $address[address]; + + $final_address_uuid .= $address[uuid]; + + if (empty($address[detail])) { + $final_address_details .= "Entry added " . date('r'); + }else{ + $final_address_details .= $address[detail]; + } + + if($i < $countArray){ + $final_address_ip .= ','; + $final_address_details .= '||'; + $final_address_uuid .= '||'; + } + } + } + } + + $w_list = array(); + // post user input + $w_list['name'] = $_POST['name']; + $w_list['descr'] = mb_convert_encoding($_POST['descr'],"HTML-ENTITIES","auto"); + $w_list['uuid'] = $whitelist_uuid; + $w_list['snortlisttype'] = $_POST['snortlisttype']; + $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['addressuuid'] = $final_address_uuid; + $w_list['address'] = $final_address_ip; + $w_list['detail'] = $final_address_details; -<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> - -<!-- loading msg --> -<div id="loadingWaiting"> - <div class="snortModal" style="top: 200px; left: 700px;"> - <div class="snortModalTop"> - <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> - </div> - <div class="snortModalTitle"> - <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> - </div> - <div> - <p class="loadingWaitingMessage"></p> - </div> - </div> -</div> - -<?php include("fbegin.inc"); ?> -<!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"> -<a href="../index.php" id="status-link2"> -<img src="./images/transparent.gif" border="0"></img> -</a> -</div> - -<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> - -<form id="iform"> + if (empty($final_address_ip) && $w_list['wanips'] === 'no' && $w_list['wangateips'] === 'no' && $w_list['wandnsips'] === 'no' && $w_list['vips'] === 'no' && $w_list['vpnips'] === 'no') + $input_errors[] = "You must add a \"auto generated ip\" or a \"custom ip\"! "; + + if (!$input_errors) { + if (isset($id) && $a_whitelist[$id]) + $a_whitelist[$id] = $w_list; + else + $a_whitelist[] = $w_list; -<table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td> - - <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> - <ul class="newtabmenu"> - <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> - <li><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> - <li><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> - <li><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> - <li><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> - <li><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> - <li class="newtabmenu_active"><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> - <li><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> - <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> - </ul> - </div> + write_config(); + + // create whitelist and homenet file then sync files + sync_snort_package_config(); + + header("Location: /snort/snort_interfaces_whitelist.php"); + exit; + } else { + + $pconfig['wanips'] = $a_whitelist[$id]['wanips']; + $pconfig['wangateips'] = $a_whitelist[$id]['wangateips']; + $pconfig['wandnsips'] = $a_whitelist[$id]['wandnsips']; + $pconfig['vips'] = $a_whitelist[$id]['vips']; + $pconfig['vpnips'] = $a_whitelist[$id]['vpnips']; + + $pconfig['descr'] = mb_convert_encoding($_POST['descr'],"HTML-ENTITIES","auto"); + $pconfig['address'] = $final_address_ip; + $pconfig['detail'] = $final_address_details; + $pconfig['addressuuid'] = $final_address_uuid; + + $input_errors[] = 'Press Cancel to reset.'; + } + +} + +$pgtitle = "Services: Snort: Whitelist: Edit $whitelist_uuid"; +include_once("head.inc"); + +?> + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC" > + +<?php +include("fbegin.inc"); +echo $snort_general_css; +?> + +<?php + /* Display Alert message */ + if ($input_errors) + print_input_errors($input_errors); // TODO: add checks + + if ($savemsg) + print_info_box($savemsg); + +?> +<div id="inputerrors"></div> + +<form action="snort_interfaces_whitelist_edit.php?id=<?=$id?>" method="post" name="iform" id="iform"> +<table width="100%" border="0" cellpadding="0" cellspacing="0"> +<tr><td> +<?php + $tab_array = array(); + $tab_array[0] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); + $tab_array[1] = array(gettext("Global Settings"), false, "/snort/snort_interfaces_global.php"); + $tab_array[2] = array(gettext("Updates"), false, "/snort/snort_download_updates.php"); + $tab_array[3] = array(gettext("Alerts"), false, "/snort/snort_alerts.php"); + $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); + $tab_array[5] = array(gettext("Whitelists"), true, "/snort/snort_interfaces_whitelist.php"); + $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + $tab_array[7] = array(gettext("Help"), false, "/snort/help_and_info.php"); + display_top_tabs($tab_array); +?> </td> - </tr> +</tr> <tr> - <td id="tdbggrey"> - <table width="100%" border="0" cellpadding="10px" cellspacing="0"> - <tr> - <td class="tabnavtbl"> + <td class="tabcont"> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> - <!-- START MAIN AREA --> - - <!-- table point --> - <input name="snortSaveWhitelist" type="hidden" value="1" /> - <input name="ifaceTab" type="hidden" value="snort_interfaces_whitelist_edit" /> - <input type="hidden" name="dbName" value="snortDB" /> <!-- what db --> - <input type="hidden" name="dbTable" value="SnortWhitelist" /> <!-- what db table --> - <input name="date" type="hidden" value="<?=$a_list['date'];?>" /> - <input name="uuid" type="hidden" value="<?=$a_list['uuid'];?>" /> - <tr> - <td colspan="2" valign="top" class="listtopic">Add the name and description of the file.</td> - + <td colspan="2" valign="top" class="listtopic">Add the name and + description of the file.</td> </tr> - <tr id="filename" data-options='{"filename":"<?=$listFilename; ?>"}' > + <tr> <td valign="top" class="vncellreq2">Name</td> - <td class="vtable"> - <input class="formfld2" name="filename" type="text" id="name" size="40" value="<?=$listFilename; ?>" /> <br /> - <span class="vexpl"> The list name may only consist of the characters a-z, A-Z and 0-9. <span class="red">Note: </span> No Spaces. </span> - </td> + <td class="vtable"><input name="name" type="text" id="name" + size="40" value="<?=htmlspecialchars($pconfig['name']);?>" /> <br /> + <span class="vexpl"> The list name may only consist of the + characters a-z, A-Z and 0-9. <span class="red">Note: </span> No + Spaces. </span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Description</td> - <td width="78%" class="vtable"> - <input class="formfld2" name="description" type="text" id="descr" size="40" value="<?=$a_list['description']; ?>" /> <br /> - <span class="vexpl"> You may enter a description here for your reference (not parsed). </span> - </td> + <td width="78%" class="vtable"><input name="descr" type="text" + id="descr" size="40" value="<?=$pconfig['descr'];?>" /> <br /> + <span class="vexpl"> You may enter a description here for your + reference (not parsed). </span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">List Type</td> <td width="78%" class="vtable"> - <div style="padding: 5px; margin-top: 16px; margin-bottom: 16px; border: 1px dashed #ff3333; background-color: #eee; color: #000; font-size: 8pt;"id="itemhelp"> - <strong>WHITELIST:</strong> This list specifies addresses that Snort Package should not block.<br><br> - <strong>NETLIST:</strong> This list is for defining addresses as $HOME_NET or $EXTERNAL_NET in the snort.conf file. - </div> - <select name="snortlisttype" class="formfld2" id="snortlisttype"> + + <div + style="padding: 5px; margin-top: 16px; margin-bottom: 16px; border: 1px dashed #ff3333; background-color: #eee; color: #000; font-size: 8pt;" + id="itemhelp"><strong>WHITELIST:</strong> This + list specifies addresses that Snort Package should not block.<br> + <br> + <strong>NETLIST:</strong> This list is for defining + addresses as $HOME_NET or $EXTERNAL_NET in the snort.conf file.</div> + + <select name="snortlisttype" class="formfld" id="snortlisttype"> <?php - $updateDaysList = array('whitelist' => 'WHITELIST', 'netlist' => 'NETLIST'); - snortDropDownList($updateDaysList, $a_list['snortlisttype']); - ?> - </select> - <span class="vexpl"> Choose the type of list you will like see in your <span class="red">Interface Edit Tab</span>.</span> - </td> + $interfaces4 = array('whitelist' => 'WHITELIST', 'netlist' => 'NETLIST'); + foreach ($interfaces4 as $iface4 => $ifacename4): ?> + <option value="<?=$iface4;?>" + <?php if ($iface4 == $pconfig['snortlisttype']) echo "selected"; ?>> + <?=htmlspecialchars($ifacename4);?></option> + <?php endforeach; ?> + </select> <span class="vexpl"> Choose the type of + list you will like see in your <span class="red">Interface Edit Tab</span>. + </span></td> </tr> <tr> - <td colspan="2" valign="top" class="listtopic">Add auto generated ips.</td> + <td colspan="2" valign="top" class="listtopic">Add auto generated + ips.</td> </tr> <tr> <td width="22%" valign="top" class="vncell2">WAN IPs</td> - <td width="78%" class="vtable"> - <input name="wanips" type="checkbox" id="wanips" size="40" value="on" <?=$wanips_on; ?> /> - <span class="vexpl"> Add WAN IPs to the list. </span> - </td> + <td width="78%" class="vtable"><input name="wanips" type="checkbox" + id="wanips" size="40" value="yes" + <?php if($pconfig['wanips'] == 'yes'){ echo "checked";} if($pconfig['wanips'] == ''){ echo "checked";} ?> /> + <span class="vexpl"> Add WAN IPs to the list. </span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Wan Gateways</td> - <td width="78%" class="vtable"> - <input name="wangateips" type="checkbox" id="wangateips" size="40" value="on" <?=$wangateips_on; ?> /> - <span class="vexpl"> Add WAN Gateways to the list. </span> - </td> + <td width="78%" class="vtable"><input name="wangateips" + type="checkbox" id="wangateips" size="40" value="yes" + <?php if($pconfig['wangateips'] == 'yes'){ echo "checked";} if($pconfig['wangateips'] == ''){ echo "checked";} ?> /> + <span class="vexpl"> Add WAN Gateways to the list. </span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Wan DNS servers</td> - <td width="78%" class="vtable"> - <input name="wandnsips" type="checkbox" id="wandnsips" size="40" value="on" <?=$wandnsips_on; ?> /> - <span class="vexpl"> Add WAN DNS servers to the list. </span> - </td> + <td width="78%" class="vtable"><input name="wandnsips" + type="checkbox" id="wandnsips" size="40" value="yes" + <?php if($pconfig['wandnsips'] == 'yes'){ echo "checked";} if($pconfig['wandnsips'] == ''){ echo "checked";} ?> /> + <span class="vexpl"> Add WAN DNS servers to the list. </span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Virtual IP Addresses</td> - <td width="78%" class="vtable"> - <input name="vips" type="checkbox" id="vips" size="40" value="on" <?=$vips_on; ?> /> - <span class="vexpl"> Add Virtual IP Addresses to the list. </span> - </td> + <td width="78%" class="vtable"><input name="vips" type="checkbox" + id="vips" size="40" value="yes" + <?php if($pconfig['vips'] == 'yes'){ echo "checked";} if($pconfig['vips'] == ''){ echo "checked";} ?> /> + <span class="vexpl"> Add Virtual IP Addresses to the list. </span></td> </tr> <tr> <td width="22%" valign="top" class="vncell2">VPNs</td> - <td width="78%" class="vtable"> - <input name="vpnips" type="checkbox" id="vpnips" size="40" value="on" <?=$vpnips_on; ?> /> - <span class="vexpl"> Add VPN Addresses to the list. </span> - </td> + <td width="78%" class="vtable"><input name="vpnips" type="checkbox" + id="vpnips" size="40" value="yes" + <?php if($pconfig['vpnips'] == 'yes'){ echo "checked";} if($pconfig['vpnips'] == ''){ echo "checked";} ?> /> + <span class="vexpl"> Add VPN Addresses to the list. </span></td> </tr> <tr> - <td colspan="2" valign="top" class="listtopic">Add your own custom ips.</td> + <td colspan="2" valign="top" class="listtopic">Add your own custom + ips.</td> </tr> <tr> <td width="22%" valign="top" class="vncellreq2"> <div id="addressnetworkport">IP or CIDR items</div> </td> <td width="78%" class="vtable"> - <table > - <tbody class="insertrow"> + <table id="maintable"> + <tbody> <tr> <td colspan="4"> - <div style="width:550px; padding: 5px; margin-top: 16px; margin-bottom: 16px; border: 1px dashed #ff3333; background-color: #eee; color: #000; font-size: 8pt;"id="itemhelp"> - For <strong>WHITELIST's</strong> enter <strong>ONLY IPs not CIDRs</strong>. Example: 192.168.4.1<br><br> - For <strong>NETLIST's</strong> you may enter <strong>IPs and CIDRs</strong>. Example: 192.168.4.1 or 192.168.4.0/24 - </div> - </td> - </tr> - <tr> - <td> - <div id="onecolumn" style="width:175px;"><span class="vexpl">IP or CIDR</span></div> - </td> - <td> - <div id="threecolumn"><span class="vexpl">Add a Description or leave blank and a date will be added.</span></div> - </td> - </tr> - </tbody> - <!-- Start of js loop --> - <tbody id="listloopblock" class="insertrow"> - <?php echo "\r"; $i = 0; foreach ($a_list['list'] as $list): ?> - <tr id="maintable_<?=$list['uuid']?>" data-options='{"pagetable":"SnortWhitelist", "pagedb":"snortDB", "DoPOST":"false"}' > - <td> - <input class="formfld2" name="list[<?=$i; ?>][ip]" type="text" id="address" size="30" value="<?=$list['ip']; ?>" /> - </td> - <td> - <input class="formfld2" name="list[<?=$i; ?>][description]" type="text" id="detail" size="50" value="<?=$list['description'] ?>" /> + <div + style="padding: 5px; margin-top: 16px; margin-bottom: 16px; border: 1px dashed #ff3333; background-color: #eee; color: #000; font-size: 8pt;" + id="itemhelp">For <strong>WHITELIST's</strong> enter <strong>ONLY + IPs not CIDRs</strong>. Example: 192.168.4.1<br> + <br> + For <strong>NETLIST's</strong> you may enter <strong>IPs and + CIDRs</strong>. Example: 192.168.4.1 or 192.168.4.0/24</div> </td> - <td> - <img id="icon_x_<?=$list['uuid'];?>" class="icon_click icon_x" src="/themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" width="17" height="17" border="0" title="delete list" > - </td> - <input name="list[<?=$i; ?>][uuid]" type="hidden" value="<?=$list['uuid'];?>" /> </tr> - <?php echo "\r"; $i++; endforeach; ?> - </tbody> - <!-- End of js loop --> - <tbody> <tr> <td> + <div id="onecolumn">IP or CIDR</div> </td> <td> - </td> - <td> - <img id="iconplus_<?=$i;?>" class="icon_click icon_plus" src="/themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" width="17" height="17" border="0" title="add list" > + <div id="threecolumn">Add a Description or leave blank and a date + will be added.</div> </td> </tr> + + <?php + /* cleanup code */ + $counter = 0; + if (!empty($pconfig['address'])): + + $addressArray = explode(',', $pconfig['address']); + $detailArray = explode('||', $pconfig['detail']); + $RowUUIDArray = explode('||', $pconfig['addressuuid']); + + foreach($addressArray as $address): + if (!empty($address)): + $detail = $detailArray[$counter]; + $rowaddressuuid= $RowUUIDArray[$counter]; + ?> + <tr id="<?=$rowaddressuuid?>"> + <td><input autocomplete="off" name="addresses[<?=$rowaddressuuid;?>][address]" class="formfld unknown" size="30" value="<?=$address;?>" type="text"></td> + <td><input autocomplete="off" name="addresses[<?=$rowaddressuuid;?>][detail]" class="formfld unknown" size="50" value="<?=$detail;?>" type="text"></td> + <td><img id="<?=$rowaddressuuid;?>" class="icon_x removeRow" src="/themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" alt="" title="remove entry" border="0"></td> + <td><input name="addresses[<?=$rowaddressuuid;?>][uuid]" value="<?=$rowaddressuuid;?>" type="hidden"></td> + </tr> + + <?php + $counter++; + endif; + endforeach; + endif; + ?> </tbody> </table> - </td> + <img id="addNewRow" class="icon_x" border="0" src="/themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" alt="" title="add another entry" /></td> </tr> <tr> <td width="22%" valign="top"> </td> <td width="78%"> - <input id="submit" name="submit" type="submit" class="formbtn" value="Save" /> - <input id="cancel" name="cancel" type="button" class="formbtn" value="Cancel"> + <input id="submit" name="submit" type="submit" class="formbtn" value="Save" /> + <input id="cancelbutton" name="cancelbutton" type="button" class="formbtn" value="Cancel" onclick="history.back()" /> + <input name="id" type="hidden" value="<?=$id;?>" /> </td> </tr> - </form> - - - <!-- STOP MAIN AREA --> </table> </td> - </tr> - </table> - </td> </tr> </table> -</div> - - -<!-- footer do not touch below --> -<?php -include("fend.inc"); -echo $snort_custom_rnd_box; -?> +</form> + +<script type="text/javascript"> + + +/*! Needs to be watched not my code <- IMPORTANT +* JavaScript UUID Generator, v0.0.1 +* +* Copyright (c) 2009 Massimo Lombardo. +* Dual licensed under the MIT and the GNU GPL licenses. +*/ + +function genUUID() { + var uuid = (function () { + var i, + c = "89ab", + u = []; + for (i = 0; i < 36; i += 1) { + u[i] = (Math.random() * 16 | 0).toString(16); + } + u[8] = u[13] = u[18] = u[23] = ""; + u[14] = "4"; + u[19] = c.charAt(Math.random() * 4 | 0); + return u.join(""); + })(); + return { + toString: function () { + return uuid; + }, + valueOf: function () { + return uuid; + } + } +}; + + + jQuery(".icon_x").live('mouseover', function() { + jQuery(this).css('cursor', 'pointer'); + }); + + jQuery('#addNewRow').live("click", function(){ + + var addRowCount = genUUID(); + + jQuery('#maintable > tbody').append( + "\n" + '<tr id="' + addRowCount + '">' + "\n" + + '<td><input autocomplete="off" name="addresses[' + addRowCount + '][address]" class="formfld unknown" size="30" value="" type="text"></td>' + "\n" + + '<td><input autocomplete="off" name="addresses[' + addRowCount + '][detail]" class="formfld unknown" size="50" value="" type="text"></td>' + "\n" + + '<td><img id="' + addRowCount + '" class="icon_x removeRow" border="0" src="/themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" alt="" title="remove entry" /></td>' + "\n" + + '<td><input name="addresses[' + addRowCount + '][uuid]" type="hidden" value="' + addRowCount + '" /></td>' + "\n" + + '</tr>' + "\n" + ); + }); + + + jQuery(".removeRow").live('click', function(){ + jQuery("#" + this.id).remove(); + }); + +</script> +<?php include("fend.inc"); ?> </body> </html> diff --git a/config/snort-dev/snort_preprocessors.php b/config/snort-dev/snort_preprocessors.php index d99f7f75..7f89d433 100644 --- a/config/snort-dev/snort_preprocessors.php +++ b/config/snort-dev/snort_preprocessors.php @@ -1,19 +1,14 @@ <?php /* $Id$ */ /* - - part of pfSense - All rights reserved. + snort_preprocessors.php + part of m0n0wall (http://m0n0.ch/wall) Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + Copyright (C) 2008-2009 Robert Zelaya. + Copyright (C) 2011 Ermal Luci All rights reserved. - Pfsense Old snort GUI - Copyright (C) 2006 Scott Ullrich. - - Pfsense snort GUI - Copyright (C) 2008-2012 Robert Zelaya. - Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -24,10 +19,6 @@ notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - 3. Neither the name of the pfSense nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - 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 @@ -38,147 +29,234 @@ 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_new.inc"); require_once("/usr/local/pkg/snort/snort_gui.inc"); +require_once("/usr/local/pkg/snort/snort.inc"); -//Set no caching -header("Expires: Mon, 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"); +global $g; -// set page vars +if (!is_array($config['installedpackages']['snortglobal']['rule'])) { + $config['installedpackages']['snortglobal']['rule'] = array(); +} +$a_nat = &$config['installedpackages']['snortglobal']['rule']; + +$id = $_GET['id']; +if (isset($_POST['id'])) + $id = $_POST['id']; +if (is_null($id)) { + header("Location: /snort/snort_interfaces.php"); + exit; +} -$uuid = $_GET['uuid']; -if (isset($_POST['uuid'])) -$uuid = $_POST['uuid']; +$pconfig = array(); +if (isset($id) && $a_nat[$id]) { + $pconfig = $a_nat[$id]; + + /* new options */ + $pconfig['perform_stat'] = $a_nat[$id]['perform_stat']; + $pconfig['def_ssl_ports_ignore'] = $a_nat[$id]['def_ssl_ports_ignore']; + $pconfig['flow_depth'] = $a_nat[$id]['flow_depth']; + $pconfig['max_queued_bytes'] = $a_nat[$id]['max_queued_bytes']; + $pconfig['max_queued_segs'] = $a_nat[$id]['max_queued_segs']; + $pconfig['perform_stat'] = $a_nat[$id]['perform_stat']; + $pconfig['http_inspect'] = $a_nat[$id]['http_inspect']; + $pconfig['other_preprocs'] = $a_nat[$id]['other_preprocs']; + $pconfig['ftp_preprocessor'] = $a_nat[$id]['ftp_preprocessor']; + $pconfig['smtp_preprocessor'] = $a_nat[$id]['smtp_preprocessor']; + $pconfig['sf_portscan'] = $a_nat[$id]['sf_portscan']; + $pconfig['dce_rpc_2'] = $a_nat[$id]['dce_rpc_2']; + $pconfig['dns_preprocessor'] = $a_nat[$id]['dns_preprocessor']; +} -if ($uuid == '') { - echo 'error: no uuid'; - exit(0); +/* convert fake interfaces to real */ +$if_real = snort_get_real_interface($pconfig['interface']); +$snort_uuid = $pconfig['uuid']; + +/* alert file */ +$d_snortconfdirty_path = "/var/run/snort_conf_{$snort_uuid}_{$if_real}.dirty"; + +if ($_POST) { + + $natent = array(); + $natent = $pconfig; + + /* if no errors write to conf */ + if (!$input_errors) { + /* post new options */ + $natent['perform_stat'] = $_POST['perform_stat']; + if ($_POST['def_ssl_ports_ignore'] != "") { $natent['def_ssl_ports_ignore'] = $_POST['def_ssl_ports_ignore']; }else{ $natent['def_ssl_ports_ignore'] = ""; } + if ($_POST['flow_depth'] != "") { $natent['flow_depth'] = $_POST['flow_depth']; }else{ $natent['flow_depth'] = ""; } + if ($_POST['max_queued_bytes'] != "") { $natent['max_queued_bytes'] = $_POST['max_queued_bytes']; }else{ $natent['max_queued_bytes'] = ""; } + if ($_POST['max_queued_segs'] != "") { $natent['max_queued_segs'] = $_POST['max_queued_segs']; }else{ $natent['max_queued_segs'] = ""; } + + $natent['perform_stat'] = $_POST['perform_stat'] ? 'on' : 'off'; + $natent['http_inspect'] = $_POST['http_inspect'] ? 'on' : 'off'; + $natent['other_preprocs'] = $_POST['other_preprocs'] ? 'on' : 'off'; + $natent['ftp_preprocessor'] = $_POST['ftp_preprocessor'] ? 'on' : 'off'; + $natent['smtp_preprocessor'] = $_POST['smtp_preprocessor'] ? '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'; + + if (isset($id) && $a_nat[$id]) + $a_nat[$id] = $natent; + else { + if (is_numeric($after)) + array_splice($a_nat, $after+1, 0, array($natent)); + else + $a_nat[] = $natent; + } + + write_config(); + + $if_real = snort_get_real_interface($pconfig['interface']); + sync_snort_package_config(); + + /* after click go to this page */ + 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_preprocessors.php?id=$id"); + exit; + } } +$pgtitle = "Snort: Interface $id$if_real Preprocessors and Flow"; +include_once("head.inc"); -$a_list = snortSql_fetchAllSettings('snortDB', 'SnortIfaces', 'uuid', $uuid); +?> +<body + link="#0000CC" vlink="#0000CC" alink="#0000CC"> - $pgtitle = "Snort: Interface Preprocessors and Flow"; - include("/usr/local/pkg/snort/snort_head.inc"); +<?php include("fbegin.inc"); ?> +<?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> +<?php +echo "{$snort_general_css}\n"; ?> -<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> - -<!-- loading msg --> -<div id="loadingWaiting"> - <div class="snortModal" style="top: 200px; left: 700px;"> - <div class="snortModalTop"> - <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> - </div> - <div class="snortModalTitle"> - <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> - </div> - <div> - <p class="loadingWaitingMessage"></p> - </div> - </div> -</div> +<div class="body2"> -<?php include("fbegin.inc"); ?> -<!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"> -<a href="../index.php" id="status-link2"> -<img src="./images/transparent.gif" border="0"></img> -</a> -</div> +<noscript> +<div class="alert" ALIGN=CENTER><img + src="../themes/<?php echo $g['theme']; ?>/images/icons/icon_alert.gif" /><strong>Please +enable JavaScript to view this content +</CENTER></div> +</noscript> -<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> -<table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td> - - <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> - <ul class="newtabmenu"> - <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> - <li><a href="/snort/snort_interfaces_edit.php?uuid=<?=$uuid;?>"><span>If Settings</span></a></li> - <li><a href="/snort/snort_rulesets.php?uuid=<?=$uuid;?>"><span>Categories</span></a></li> - <li><a href="/snort/snort_rules.php?uuid=<?=$uuid;?>"><span>Rules</span></a></li> - <li><a href="/snort/snort_rulesets_ips.php?uuid=<?=$uuid;?>"><span>Ruleset Ips</span></a></li> - <li><a href="/snort/snort_define_servers.php?uuid=<?=$uuid;?>"><span>Servers</span></a></li> - <li class="newtabmenu_active"><a href="/snort/snort_preprocessors.php?uuid=<?=$uuid;?>"><span>Preprocessors</span></a></li> - <li><a href="/snort/snort_barnyard.php?uuid=<?=$uuid;?>"><span>Barnyard2</span></a></li> - </ul> - </div> - - </td> - </tr> - <tr> - <td id="tdbggrey"> - <table width="100%" border="0" cellpadding="10px" cellspacing="0"> - <tr> - <td class="tabnavtbl"> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> - <!-- START MAIN AREA --> - - <form id="iform" > - <input type="hidden" name="snortSaveSettings" value="1" /> <!-- what to do, save --> - <input type="hidden" name="dbName" value="snortDB" /> <!-- what db--> - <input type="hidden" name="dbTable" value="SnortIfaces" /> <!-- what db table--> - <input type="hidden" name="ifaceTab" value="snort_preprocessors" /> <!-- what interface tab --> - <input name="uuid" type="hidden" value="<?=$a_list['uuid']; ?>"> +<form action="snort_preprocessors.php" method="post" + enctype="multipart/form-data" name="iform" id="iform"><?php + + /* Display Alert message */ + + if ($input_errors) { + print_input_errors($input_errors); // TODO: add checks + } + if ($savemsg) { + print_info_box2($savemsg); + } + ?> +<table width="100%" border="0" cellpadding="0" cellspacing="0"> +<tr><td> +<?php + $tab_array = array(); + $tabid = 0; + $tab_array[$tabid] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); + $tabid++; + $tab_array[$tabid] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Servers"), false, "/snort/snort_define_servers.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Preprocessors"), true, "/snort/snort_preprocessors.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); + display_top_tabs($tab_array); +?> +</td></tr> + <tr> + <td class="tabcont"> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <?php + /* display error code if there is no id */ + if($id == "") + { + echo " + <style type=\"text/css\"> + .noid { + position:absolute; + top:10px; + left:0px; + width:94%; + background:#FCE9C0; + background-position: 15px; + border-top:2px solid #DBAC48; + border-bottom:2px solid #DBAC48; + padding: 15px 10px 85% 50px; + } + </style> + <div class=\"alert\" ALIGN=CENTER><img src=\"../themes/{$g['theme']}/images/icons/icon_alert.gif\"/><strong>You can not edit options without an interface ID.</CENTER></div>\n"; + + } + ?> <tr> <td width="22%" valign="top"> </td> - <td width="78%"><span class="vexpl"> - <span class="red"><strong>Note:</strong></span> - <br> - <span class="vexpl">Rules may be dependent on preprocessors!<br> - Defaults will be used when there is no user input.</span><br> - </td> + <td width="78%"><span class="vexpl"><span class="red"><strong>Note: + </strong></span><br> + Rules may be dependent on preprocessors!<br> + Defaults will be used when there is no user input.<br></td> </tr> <tr> - <td colspan="2" valign="top" class="listtopic">Performance Statistics</td> + <td colspan="2" valign="top" class="listtopic">Performance + Statistics</td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Enable</td> - <td width="78%" class="vtable"> - <input name="perform_stat" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['perform_stat'] == 'on' || $a_list['perform_stat'] == '' ? 'checked' : '';?> > - <span class="vexpl">Performance Statistics for this interface.</span> - </td> + <td width="78%" class="vtable"><input name="perform_stat" + type="checkbox" value="on" + <?php if ($pconfig['perform_stat']=="on") echo "checked"; ?> + onClick="enable_change(false)"> Performance Statistics for this + interface.</td> </tr> <tr> <td colspan="2" valign="top" class="listtopic">HTTP Inspect Settings</td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Enable</td> - <td width="78%" class="vtable"> - <input name="http_inspect" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['http_inspect'] == 'on' || $a_list['http_inspect'] == '' ? 'checked' : '';?> > - <span class="vexpl">Use HTTP Inspect to Normalize/Decode and detect HTTP traffic and protocol anomalies.</span> - </td> + <td width="78%" class="vtable"><input name="http_inspect" + type="checkbox" value="on" + <?php if ($pconfig['http_inspect']=="on") echo "checked"; ?> + onClick="enable_change(false)"> Use HTTP Inspect to + Normalize/Decode and detect HTTP traffic and protocol anomalies.</td> </tr> <tr> <td valign="top" class="vncell2">HTTP server flow depth</td> <td class="vtable"> - <table cellpadding="0" cellspacing="0"> - <tr> - <td> - <input name="flow_depth" type="text" class="formfld" id="flow_depth" size="5" value="<?=$a_list['flow_depth']; ?>"> - <span class="vexpl"><strong>-1</strong> to <strong>1460</strong> (<strong>-1</strong> disables HTTP inspect, <strong>0</strong> enables all HTTP inspect)</span> - </td> - </tr> - </table> - <span class="vexpl">Amount of HTTP server response payload to inspect. Snort's performance may increase by adjusting this value. - <br> - Setting this value too low may cause false negatives. Values above 0 are specified in bytes. Default value is <strong>0</strong></span> - <br> + <table cellpadding="0" cellspacing="0"> + <tr> + <td><input name="flow_depth" type="text" class="formfld" + id="flow_depth" size="5" + value="<?=htmlspecialchars($pconfig['flow_depth']);?>"> <strong>-1</strong> + to <strong>1460</strong> (<strong>-1</strong> disables HTTP + inspect, <strong>0</strong> enables all HTTP inspect)</td> + </tr> + </table> + Amount of HTTP server response payload to inspect. Snort's + performance may increase by adjusting this value.<br> + Setting this value too low may cause false negatives. Values above 0 + are specified in bytes. Default value is <strong>0</strong><br> </td> </tr> <tr> @@ -187,151 +265,127 @@ $a_list = snortSql_fetchAllSettings('snortDB', 'SnortIfaces', 'uuid', $uuid); <tr> <td valign="top" class="vncell2">Max Queued Bytes</td> <td class="vtable"> - <table cellpadding="0" cellspacing="0"> - <tr> - <td> - <input name="max_queued_bytes" type="text" class="formfld" id="max_queued_bytes" size="5" value="<?=$a_list['max_queued_bytes']; ?>"> - <span class="vexpl">Minimum is <strong>1024</strong>, Maximum is <strong>1073741824</strong> ( default value is <strong>1048576</strong>, <strong>0</strong>means Maximum )</span> - </td> - </tr> - </table> - <span class="vexpl">The number of bytes to be queued for reassembly for TCP sessions in memory. Default value is <strong>1048576</strong></span> - <br> + <table cellpadding="0" cellspacing="0"> + <tr> + <td><input name="max_queued_bytes" type="text" class="formfld" + id="max_queued_bytes" size="5" + value="<?=htmlspecialchars($pconfig['max_queued_bytes']);?>"> + Minimum is <strong>1024</strong>, Maximum is <strong>1073741824</strong> + ( default value is <strong>1048576</strong>, <strong>0</strong> + means Maximum )</td> + </tr> + </table> + The number of bytes to be queued for reassembly for TCP sessions in + memory. Default value is <strong>1048576</strong><br> </td> </tr> <tr> <td valign="top" class="vncell2">Max Queued Segs</td> <td class="vtable"> - <table cellpadding="0" cellspacing="0"> - <tr> - <td> - <input name="max_queued_segs" type="text" class="formfld" id="max_queued_segs" size="5" value="<?=$a_list['max_queued_segs']; ?>" > - <span class="vexpl">Minimum is <strong>2</strong>, Maximum is <strong>1073741824</strong> ( default value is <strong>2621</strong>, <strong>0</strong> means Maximum )</span> - </td> - </tr> - </table> - <span class="vexpl">The number of segments to be queued for reassembly for TCP sessions in memory. Default value is <strong>2621</strong></span> - <br> + <table cellpadding="0" cellspacing="0"> + <tr> + <td><input name="max_queued_segs" type="text" class="formfld" + id="max_queued_segs" size="5" + value="<?=htmlspecialchars($pconfig['max_queued_segs']);?>"> + Minimum is <strong>2</strong>, Maximum is <strong>1073741824</strong> + ( default value is <strong>2621</strong>, <strong>0</strong> means + Maximum )</td> + </tr> + </table> + The number of segments to be queued for reassembly for TCP sessions + in memory. Default value is <strong>2621</strong><br> </td> </tr> <tr> - <td colspan="2" valign="top" class="listtopic">General Preprocessor Settings</td> + <td colspan="2" valign="top" class="listtopic">General Preprocessor + Settings</td> </tr> <tr> - <td width="22%" valign="top" class="vncell2"> - Enable <br> - RPC Decode and Back Orifice detector - </td> - <td width="78%" class="vtable"> - <input name="other_preprocs" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['other_preprocs'] == 'on' || $a_list['other_preprocs'] == '' ? 'checked' : '';?> > - <br> - <span class="vexpl">Normalize/Decode RPC traffic and detects Back Orifice traffic on the network.</span> - </td> + <td width="22%" valign="top" class="vncell2">Enable <br> + RPC Decode and Back Orifice detector</td> + <td width="78%" class="vtable"><input name="other_preprocs" + type="checkbox" value="on" + <?php if ($pconfig['other_preprocs']=="on") echo "checked"; ?> + onClick="enable_change(false)"><br> + Normalize/Decode RPC traffic and detects Back Orifice traffic on the + network.</td> </tr> <tr> - <td width="22%" valign="top" class="vncell2"> - Enable - <br> - FTP and Telnet Normalizer - </td> - <td width="78%" class="vtable"> - <input name="ftp_preprocessor" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['ftp_preprocessor'] == 'on' || $a_list['ftp_preprocessor'] == '' ? 'checked' : '';?> > - <br> - <span class="vexpl">Normalize/Decode FTP and Telnet traffic and protocol anomalies.</span> - </td> + <td width="22%" valign="top" class="vncell2">Enable <br> + FTP and Telnet Normalizer</td> + <td width="78%" class="vtable"><input name="ftp_preprocessor" + type="checkbox" value="on" + <?php if ($pconfig['ftp_preprocessor']=="on") echo "checked"; ?> + onClick="enable_change(false)"><br> + Normalize/Decode FTP and Telnet traffic and protocol anomalies.</td> </tr> <tr> - <td width="22%" valign="top" class="vncell2"> - Enable - <br> - SMTP Normalizer - </td> - <td width="78%" class="vtable"> - <input name="smtp_preprocessor" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['smtp_preprocessor'] == 'on' || $a_list['smtp_preprocessor'] == '' ? 'checked' : '';?> > - <br> - <span class="vexpl">Normalize/Decode SMTP protocol for enforcement and buffer overflows.</span> - </td> + <td width="22%" valign="top" class="vncell2">Enable <br> + SMTP Normalizer</td> + <td width="78%" class="vtable"><input name="smtp_preprocessor" + type="checkbox" value="on" + <?php if ($pconfig['smtp_preprocessor']=="on") echo "checked"; ?> + onClick="enable_change(false)"><br> + Normalize/Decode SMTP protocol for enforcement and buffer overflows.</td> </tr> <tr> - <td width="22%" valign="top" class="vncell2"> - Enable - <br> - Portscan Detection - </td> - <td width="78%" class="vtable"> - <input name="sf_portscan" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['sf_portscan'] == 'on' || $a_list['sf_portscan'] == '' ? 'checked' : '';?> > - <br> - <span class="vexpl">Detects various types of portscans and portsweeps.</span> - </td> + <td width="22%" valign="top" class="vncell2">Enable <br> + Portscan Detection</td> + <td width="78%" class="vtable"><input name="sf_portscan" + type="checkbox" value="on" + <?php if ($pconfig['sf_portscan']=="on") echo "checked"; ?> + onClick="enable_change(false)"><br> + Detects various types of portscans and portsweeps.</td> </tr> <tr> - <td width="22%" valign="top" class="vncell2"> - Enable - <br> - DCE/RPC2 Detection - </td> - <td width="78%" class="vtable"> - <input name="dce_rpc_2" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['dce_rpc_2'] == 'on' || $a_list['dce_rpc_2'] == '' ? 'checked' : '';?> > - <br> - <span class="vexpl">The DCE/RPC preprocessor detects and decodes SMB and DCE/RPC traffic.</span> - </td> + <td width="22%" valign="top" class="vncell2">Enable <br> + DCE/RPC2 Detection</td> + <td width="78%" class="vtable"><input name="dce_rpc_2" + type="checkbox" value="on" + <?php if ($pconfig['dce_rpc_2']=="on") echo "checked"; ?> + onClick="enable_change(false)"><br> + The DCE/RPC preprocessor detects and decodes SMB and DCE/RPC + traffic.</td> </tr> <tr> - <td width="22%" valign="top" class="vncell2"> - Enable - <br> - DNS Detection - </td> - <td width="78%" class="vtable"> - <input name="dns_preprocessor" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['dns_preprocessor'] == 'on' || $a_list['dns_preprocessor'] == '' ? 'checked' : '';?> > - <br> - <span class="vexpl">The DNS preprocessor decodes DNS Response traffic and detects some vulnerabilities.</span> - </td> + <td width="22%" valign="top" class="vncell2">Enable <br> + DNS Detection</td> + <td width="78%" class="vtable"><input name="dns_preprocessor" + type="checkbox" value="on" + <?php if ($pconfig['dns_preprocessor']=="on") echo "checked"; ?> + onClick="enable_change(false)"><br> + The DNS preprocessor decodes DNS Response traffic and detects some + vulnerabilities.</td> </tr> <tr> <td width="22%" valign="top" class="vncell2">Define SSL_IGNORE</td> - <td width="78%" class="vtable"> - <input name="def_ssl_ports_ignore" type="text" class="formfld" id="def_ssl_ports_ignore" size="40" value="<?=$a_list['def_ssl_ports_ignore']; ?>" > - <br> - <span class="vexpl">Encrypted traffic should be ignored by Snort for both performance reasons and to reduce false positives. - <br> - Default: "443 465 563 636 989 990 992 993 994 995". <strong>Please use spaces and not commas.</strong></span> - </td> + <td width="78%" class="vtable"><input name="def_ssl_ports_ignore" + type="text" class="formfld" id="def_ssl_ports_ignore" size="40" + value="<?=htmlspecialchars($pconfig['def_ssl_ports_ignore']);?>"> <br> + <span class="vexpl"> Encrypted traffic should be ignored by Snort + for both performance reasons and to reduce false positives.<br> + Default: "443 465 563 636 989 990 992 993 994 995".</span> <strong>Please + use spaces and not commas.</strong></td> </tr> <tr> <td width="22%" valign="top"> </td> <td width="78%"> - <input name="Submit" type="submit" class="formbtn" value="Save"> - <input id="cancel" type="button" class="formbtn" value="Cancel" > - </td> + <input name="Submit" type="submit" class="formbtn" value="Save"> + <input name="id" type="hidden" value="<?=$id;?>"></td> </tr> - <tr> <td width="22%" valign="top"> </td> - <td width="78%"><span class="vexpl"> - <span class="vexpl"><span class="red"><strong>Note:</strong></span> Please save your settings before you click Start.</span> - </td> + <td width="78%"><span class="vexpl"><span class="red"><strong>Note:</strong></span> + <br> + Please save your settings before you click Start. </td> </tr> - - - </form> - <!-- STOP MAIN AREA --> - </table> - </td> - </tr> </table> - </td> - </tr> -</table> -</div> - -<!-- footer do not touch below --> -<?php -include("fend.inc"); -echo $snort_custom_rnd_box; -?> +</table> +</form> +</div> + <?php include("fend.inc"); ?> </body> </html> diff --git a/config/snort-dev/snort_rules.php b/config/snort-dev/snort_rules.php index fd102538..871eb39e 100644 --- a/config/snort-dev/snort_rules.php +++ b/config/snort-dev/snort_rules.php @@ -1,19 +1,11 @@ <?php -/* $Id$ */ /* - - part of pfSense - All rights reserved. - - Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + snort_rules.php + Copyright (C) 2004, 2005 Scott Ullrich + Copyright (C) 2008, 2009 Robert Zelaya + Copyright (C) 2011 Ermal Luci All rights reserved. - Pfsense Old snort GUI - Copyright (C) 2006 Scott Ullrich. - - Pfsense snort GUI - Copyright (C) 2008-2012 Robert Zelaya. - Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -24,10 +16,6 @@ notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - 3. Neither the name of the pfSense nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - 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 @@ -38,563 +26,433 @@ 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_new.inc"); require_once("/usr/local/pkg/snort/snort_gui.inc"); +require_once("/usr/local/pkg/snort/snort.inc"); -//Set no caching -header("Expires: Mon, 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"); +global $g; -// set page vars +if (!is_array($config['installedpackages']['snortglobal']['rule'])) + $config['installedpackages']['snortglobal']['rule'] = array(); +$a_nat = &$config['installedpackages']['snortglobal']['rule']; -if (isset($_GET['uuid']) && isset($_GET['rdbuuid'])) { - echo 'Error: more than one uuid'; - exit(0); +$id = $_GET['id']; +if (isset($_POST['id'])) + $id = $_POST['id']; +if (is_null($id)) { + header("Location: /snort/snort_interfaces.php"); + exit; } -if (isset($_GET['uuid'])) { - $uuid = $_GET['uuid']; +if (isset($id) && $a_nat[$id]) { + $pconfig['enable'] = $a_nat[$id]['enable']; + $pconfig['interface'] = $a_nat[$id]['interface']; + $pconfig['rulesets'] = $a_nat[$id]['rulesets']; } -if (isset($_GET['rdbuuid'])) { - $rdbuuid = $_GET['rdbuuid']; -}else{ - $ruledbname_pre1 = snortSql_fetchAllSettings('snortDB', 'SnortIfaces', 'uuid', $uuid); - $rdbuuid = $ruledbname_pre1['ruledbname']; +/* convert fake interfaces to real */ +$if_real = snort_get_real_interface($pconfig['interface']); +$iface_uuid = $a_nat[$id]['uuid']; + +/* Check if the rules dir is empy if so warn the user */ +/* TODO give the user the option to delete the installed rules rules */ +if (!is_dir("/usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules")) + exec("/bin/mkdir -p /usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules"); + +$isrulesfolderempty = exec("ls -A /usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules/*.rules"); +if ($isrulesfolderempty == "") { + $isrulesfolderempty = exec("ls -A /usr/local/etc/snort/rules/*.rules"); + if ($isrulesfolderempty == "") { + include_once("head.inc"); + include_once("fbegin.inc"); + + echo "<body link=\"#000000\" vlink=\"#000000\" alink=\"#000000\">"; + + if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';} + + echo "<table width=\"99%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n + <tr>\n + <td>\n"; + + $tab_array = array(); + $tabid = 0; + $tab_array[$tabid] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); + $tabid++; + $tab_array[$tabid] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Rules"), true, "/snort/snort_rules.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Servers"), false, "/snort/snort_define_servers.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); + display_top_tabs($tab_array); + echo "</td>\n + </tr>\n + <tr>\n + <td>\n + <div id=\"mainarea\">\n + <table id=\"maintable\" class=\"tabcont\" width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n + <tr>\n + <td>\n + # The rules directory is empty.\n + </td>\n + </tr>\n + </table>\n + </div>\n + </td>\n + </tr>\n + </table>\n + \n + </form>\n + \n + <p>\n\n"; + + echo "Please click on the Update Rules tab to install your selected rule sets."; + include("fend.inc"); + + echo "</body>"; + echo "</html>"; + + exit(0); + } else { + /* Make sure that we have the rules */ + mwexec("/bin/cp /usr/local/etc/snort/rules/*.rules /usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules", true); + } } -// unset Session tmp on page load -unset($_SESSION['snort']['tmp']); +function get_middle($source, $beginning, $ending, $init_pos) { + $beginning_pos = strpos($source, $beginning, $init_pos); + $middle_pos = $beginning_pos + strlen($beginning); + $ending_pos = strpos($source, $ending, $beginning_pos); + $middle = substr($source, $middle_pos, $ending_pos - $middle_pos); + return $middle; +} -// list rules in the default dir -$a_list = snortSql_fetchAllSettings('snortDBrules', 'Snortrules', 'uuid', $rdbuuid); +function write_rule_file($content_changed, $received_file) +{ + @file_put_contents($received_file, implode("\n", $content_changed)); +} -$snortRuleDir = '/usr/local/etc/snort/snortDBrules/DB/' . $rdbuuid; +function load_rule_file($incoming_file) +{ + //read file into string, and get filesize + $contents = @file_get_contents($incoming_file); - // list rules in the default dir - $filterDirList = array(); - $filterDirList = snortScanDirFilter($snortRuleDir . '/rules', '\.rules'); + //split the contents of the string file into an array using the delimiter + return explode("\n", $contents); +} - // START read rule file - if ($_GET['openruleset']) { - $rulefile = $_GET['openruleset']; - }else{ - $rulefile = $filterDirList[0]; +$ruledir = "/usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules/"; +//$ruledir = "/usr/local/etc/snort/rules/"; +$dh = opendir($ruledir); +while (false !== ($filename = readdir($dh))) +{ + //only populate this array if its a rule file + $isrulefile = strstr($filename, ".rules"); + if ($isrulefile !== false) + $files[] = basename($filename); +} +sort($files); + +if ($_GET['openruleset']) + $rulefile = $_GET['openruleset']; +else + $rulefile = $ruledir.$files[0]; + +//Load the rule file +$splitcontents = load_rule_file($rulefile); + +if ($_GET['act'] == "toggle" && $_GET['ids']) { + + $lineid= $_GET['ids']; + + //copy rule contents from array into string + $tempstring = $splitcontents[$lineid]; + + //explode rule contents into an array, (delimiter is space) + $rule_content = explode(' ', $tempstring); + + $findme = "# alert"; //find string for disabled alerts + $disabled = strstr($tempstring, $findme); + + //if find alert is false, then rule is disabled + if ($disabled !== false) { + //rule has been enabled + $tempstring = substr($tempstring, 2); + } else + $tempstring = "# ". $tempstring; + + //copy string into array for writing + $splitcontents[$lineid] = $tempstring; + + //write the new .rules file + write_rule_file($splitcontents, $rulefile); + + //write disable/enable sid to config.xml + $sid = get_middle($tempstring, 'sid:', ';', 0); + if (is_numeric($sid)) { + // rule_sid_on registers + if (!empty($a_nat[$id]['rule_sid_on'])) + $a_nat[$id]['rule_sid_on'] = str_replace("||enablesid $sid", "", $a_nat[$id]['rule_sid_on']); + if (!empty($a_nat[$id]['rule_sid_on'])) + $a_nat[$id]['rule_sid_off'] = str_replace("||disablesid $sid", "", $a_nat[$id]['rule_sid_off']); + if ($disabled === false) + $a_nat[$id]['rule_sid_off'] = "||disablesid $sid_off" . $a_nat[$id]['rule_sid_off']; + else + $a_nat[$id]['rule_sid_on'] = "||enablesid $sid_on" . $a_nat[$id]['rule_sid_on']; } - // path of rule file - $workingFile = $snortRuleDir . '/rules/' . $rulefile; - -function load_rule_file($incoming_file, $splitcontents) -{ - $pattern = '/(^alert |^# alert )/'; - foreach ( $splitcontents as $val ) - { - // remove whitespaces - $rmWhitespaces = preg_replace('/\s\s+/', ' ', $val); - - // filter none alerts - if (preg_match($pattern, $rmWhitespaces)) - { - $splitcontents2[] = $val; - } - - } - unset($splitcontents); - - return $splitcontents2; + write_config(); + header("Location: /snort/snort_rules.php?id={$id}&openruleset={$rulefile}"); + exit; } - - // Load the rule file - // split the contents of the string file into an array using the delimiter - // used by rule gui edit and table build code - if (filesize($workingFile) > 0) { - $splitcontents = split_rule_file($workingFile); - - $splitcontents2 = load_rule_file($workingFile, $splitcontents); - - $countSig = count($splitcontents2); - - if ($countSig > 0) { - $newFilterRuleSigArray = newFilterRuleSig($splitcontents2); - } - } - - /* - * SET GLOBAL ARRAY $_SESSION['snort'] - * Use SESSION instead POST for security because were writing to files. - */ - - $_SESSION['snort']['tmp']['snort_rules']['dbName'] = 'snortDBrules'; - $_SESSION['snort']['tmp']['snort_rules']['dbTable'] = 'SnortruleSigs'; - $_SESSION['snort']['tmp']['snort_rules']['rdbuuid'] = $rdbuuid; - $_SESSION['snort']['tmp']['snort_rules']['rulefile'] = $rulefile; - - -// find ./ -name test.txt | xargs grep "^disablesid 127 " - - $pgtitle = "Snort: Category: rule: $rulefile"; - include("/usr/local/pkg/snort/snort_head.inc"); -?> +$currentruleset = basename($rulefile); - - -<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> - -<!-- loading msg --> -<div id="loadingWaiting"> - <div class="snortModal" style="top: 200px; left: 700px;"> - <div class="snortModalTop"> - <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> - </div> - <div class="snortModalTitle"> - <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> - </div> - <div> - <p class="loadingWaitingMessage"></p> - </div> - </div> -</div> - -<!-- hidden div --> -<div id="loadingRuleEditGUI"> - - <div class="loadingRuleEditGUIDiv"> - <form id="iform2" action=""> - <input type="hidden" name="snortSidRuleEdit" value="1" /> - <input type="hidden" name="snortSidRuleDBuuid" value="<?=$rdbuuid;?>" /> <!-- what to do, save --> - <input type="hidden" name="snortSidRuleFile" value="<?=$rulefile; ?>" /> <!-- what to do, save --> - <input type="hidden" name="snortSidNum" value="" /> <!-- what to do, save --> - <table width="100%" cellpadding="9" cellspacing="9" bgcolor="#eeeeee"> - <tr> - <td> - <input name="save" type="submit" class="formbtn" id="save" value="Save" /> - <input type="button" class="formbtn closeRuleEditGUI" value="Close" > - </td> - </tr> - <tr> - <td> - <textarea id="sidstring" name="sidstring" wrap="off" style="width: 98%; margin: 7px;" rows="1" cols="" ></textarea> <!-- SID to EDIT --> - </td> - </tr> - <tr> - <td> - <textarea wrap="off" style="width: 98%; margin: 7px;" rows="<?php if(count($splitcontents) > 24){echo 24;}else{echo count($splitcontents);} ?>" cols="" disabled > - - <?php - - echo "\n"; - - foreach ($splitcontents as $sidLineGui) - - echo $sidLineGui . "\n"; - - - - ?> - </textarea> <!-- Display rule file --> - </td> - </tr> - </table> - <table width="100%" cellpadding="9" cellspacing="9" bgcolor="#eeeeee"> - <tr> - <td> - <input name="save" type="submit" class="formbtn" id="save" value="Save" /> - <input type="button" class="formbtn closeRuleEditGUI" value="Close" > - </td> - </tr> - </table> - </form> - </div> +$ifname = strtoupper($pconfig['interface']); +require_once("guiconfig.inc"); +include_once("head.inc"); -</div> +$pgtitle = "Snort: $id $iface_uuid $if_real Category: $currentruleset"; +?> -<?php include("fbegin.inc"); ?> +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> +<?php +include("fbegin.inc"); +if ($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';} -<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> +echo "{$snort_general_css}\n"; +?> +<form action="snort_rules.php" method="post" name="iform" id="iform"> + +<script language="javascript" type="text/javascript"> +function go() +{ + var box = document.iform.selectbox; + destination = box.options[box.selectedIndex].value; + if (destination) + location.href = destination; +} +function popup(url) +{ + params = 'width='+screen.width; + params += ', height='+screen.height; + params += ', top=0, left=0' + params += ', fullscreen=yes'; + + newwin=window.open(url,'windowname4', params); + if (window.focus) {newwin.focus()} + return false; +} +</script> -<table width="100%" border="0" cellpadding="0" cellspacing="0"> - <?php - if (!empty($uuid)) { - echo ' +<table style="table-layout:fixed;" width="99%" border="0" cellpadding="0" cellspacing="0"> +<tr><td> +<?php + $tab_array = array(); + $tabid = 0; + $tab_array[$tabid] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); + $tabid++; + $tab_array[$tabid] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Rules"), true, "/snort/snort_rules.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Servers"), false, "/snort/snort_define_servers.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); + display_top_tabs($tab_array); +?> +</td></tr> +<tr> + <td> + <div id="mainarea2"> + <table id="maintable" class="tabcont" width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> - <td> - <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> - <ul class="newtabmenu"> - <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> - <li><a href="/snort/snort_interfaces_edit.php?uuid=' . $uuid . '"><span>If Settings</span></a></li> - <li><a href="/snort/snort_rulesets.php?uuid=' . $uuid . '"><span>Categories</span></a></li> - <li class="newtabmenu_active"><a href="/snort/snort_rules.php?uuid=' . $uuid . '"><span>Rules</span></a></li> - <li><a href="/snort/snort_rulesets_ips.php?uuid=' . $uuid . '"><span>Ruleset Ips</span></a></li> - <li><a href="/snort/snort_define_servers.php?uuid=' . $uuid . '"><span>Servers</span></a></li> - <li><a href="/snort/snort_preprocessors.php?uuid=' . $uuid . '"><span>Preprocessors</span></a></li> - <li><a href="/snort/snort_barnyard.php?uuid=' . $uuid . '"><span>Barnyard2</span></a></li> - </ul> - </div> + <td class="listt" colspan="8"> + <br>Category: + <select id="selectbox" name="selectbox" class="formfld" onChange="go()"> + <?php + foreach ($files as $value) { + echo "<option value='?id={$id}&openruleset={$ruledir}{$value}' "; + if ($value === $currentruleset) + echo "selected"; + echo ">{$value}</option>\n"; + } + ?> + </select> + </td> + </tr> + <tr id="frheader"> + <td width="3%" class="list"> </td> + <td width="5%" class="listhdr">SID</td> + <td width="6%" class="listhdrr">Proto</td> + <td width="15%" class="listhdrr">Source</td> + <td width="10%" class="listhdrr">Port</td> + <td width="15%" class="listhdrr">Destination</td> + <td width="10%" class="listhdrr">Port</td> + <td width="32%" class="listhdrr">Message</td> + </tr> + <?php + foreach ( $splitcontents as $counter => $value ) + { + $disabled = "False"; + $comments = "False"; + $findme = "# alert"; //find string for disabled alerts + $disabled_pos = strstr($value, $findme); + + $counter2 = 1; + $sid = get_middle($value, 'sid:', ';', 0); + //check to see if the sid is numberical + if (!is_numeric($sid)) + continue; + + //if find alert is false, then rule is disabled + if ($disabled_pos !== false){ + $counter2 = $counter2+1; + $textss = "<span class=\"gray\">"; + $textse = "</span>"; + $iconb = "icon_block_d.gif"; + + $ischecked = ""; + } else { + $textss = $textse = ""; + $iconb = "icon_block.gif"; + + $ischecked = "checked"; + } + + $rule_content = explode(' ', $value); + + $protocol = $rule_content[$counter2];//protocol location + $counter2++; + $source = substr($rule_content[$counter2], 0, 20) . "...";//source location + $counter2++; + $source_port = $rule_content[$counter2];//source port location + $counter2 = $counter2+2; + $destination = substr($rule_content[$counter2], 0, 20) . "...";//destination location + $counter2++; + $destination_port = $rule_content[$counter2];//destination port location + + if (strstr($value, 'msg: "')) + $message = get_middle($value, 'msg: "', '";', 0); + else if (strstr($value, 'msg:"')) + $message = get_middle($value, 'msg:"', '";', 0); + + echo "<tr><td class=\"listt\"> $textss\n"; + ?> + <a href="?id=<?=$id;?>&openruleset=<?=$rulefile;?>&act=toggle&ids=<?=$counter;?>"><img + src="../themes/<?= $g['theme']; ?>/images/icons/<?=$iconb;?>" + width="10" height="10" border="0" + title="click to toggle enabled/disabled status"></a> + <!-- <input name="enable" type="checkbox" value="yes" <?= $ischecked; ?> onClick="enable_change(false)"> --> + <!-- TODO: add checkbox and save so that that disabling is nicer --> + <?php + echo "$textse + </td> + <td width='5%' class=\"listlr\"> + $textss + $sid + $textse + </td> + <td width='6%' class=\"listlr\"> + $textss + $protocol"; + echo "$textse + </td> + <td width='20%' class=\"listlr\"> + $textss + $source + $textse + </td> + <td width='5%' class=\"listlr\"> + $textss + $source_port + $textse + </td> + <td width='20%' class=\"listlr\"> + $textss + $destination + $textse + </td> + <td width='5%' class=\"listlr\"> + $textss + $destination_port + $textse + </td> + <td width='30%' class=\"listbg\"><font color=\"white\"> + $textss + $message + $textse + </td>"; + ?> + <td valign="middle" nowrap class="list"> + <table border="0" cellspacing="0" cellpadding="1"> + <tr> + <td><a href="javascript: void(0)" + onclick="popup('snort_rules_edit.php?id=<?=$id;?>&openruleset=<?=$rulefile;?>&ids=<?=$counter;?>')"><img + src="../themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" + title="edit rule" width="17" height="17" border="0"></a></td> + <!-- Codes by Quackit.com --> + </tr> + </table> + </td> + <?php + } + ?> + + </table> </td> </tr> - '; - }else{ - echo ' <tr> - <td> - <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> - <ul class="newtabmenu"> - <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> - <li><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> - <li><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> - <li class="newtabmenu_active"><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> - <li><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> - <li><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> - <li><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> - <li><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> - <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> - </ul> - </div> + <td class="listlr"> + <?php echo " <strong><span class='red'>There are {$counter} rules in this category. <br/><br/></span></strong>"; ?> </td> </tr> <tr> <td> - <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> - <ul class="newtabmenu"> - <li class="hide_newtabmenu"><a href="/snort/snort_interfaces_rules_edit.php?rdbuuid=' . $rdbuuid . '"><span>Rules DB Edit</span></a></li> - <li class="hide_newtabmenu"><a href="/snort/snort_rulesets.php?rdbuuid=' . $rdbuuid . '"><span>Categories</span></a></li> - <li class="hide_newtabmenu newtabmenu_active"><a href="/snort/snort_rules.php?rdbuuid=' . $rdbuuid . '"><span>Rules</span></a></li> - <li><a href="/snort/snort_rulesets_ips.php?rdbuuid=' . $rdbuuid . '"><span>Ruleset Ips</span></a></li> - </ul> - </div> - </td> - </tr> - '; - } - ?> - <tr> - <td id="tdbggrey"> - <div style="width:780px; margin-left: auto ; margin-right: auto ; padding-top: 10px; padding-bottom: 10px;"> - <!-- START MAIN AREA --> - - - <!-- start Interface Satus --> - <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr id="maintable77" > - <td colspan="2" valign="top" class="listtopic2"> - Category: - <select name="selectbox" class="formfld" > - <?php - if(isset($_GET['uuid'])) { - $urlUuid = "&uuid=$uuid"; - } - - if(isset($_GET['rdbuuid'])) { - $urlUuid = "&rdbuuid=$rdbuuid"; - } - - $i=0; - foreach ($filterDirList as $value) - { - $selectedruleset = ''; - if ($value === $rulefile) { - $selectedruleset = 'selected'; - } - - echo "\n" . '<option value="?&openruleset=' . $ruledir . $value . $urlUuid . '" ' . $selectedruleset . ' >' . $value . '</option>' . "\r"; - - $i++; - - } - ?> - </select> - There are <?=$countSig; ?> rules in this category. - </td> - <td width="6%" colspan="2" valign="middle" class="listtopic3" > - <a href="snort_interfaces_edit.php?uuid=<?=$new_ruleUUID;?>"> - <img style="padding-left:3px;" src="/themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" width="17" height="17" border="0" title="add rule"> - </a> - </td> + <table class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="0"> + <tr> + <td width="16"><img + src="../themes/<?= $g['theme']; ?>/images/icons/icon_block.gif" + width="11" height="11"></td> + <td>Rule Enabled</td> </tr> - </table> -<br> - - <!-- Save all inputs --> - <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td> - <input id="select_all" type="button" class="formbtn" value="Select All" > - <input id="deselect_all" type="button" class="formbtn" value="Deselect All" > - </td> - </tr> - </table> - -<br> - - <!-- start User Interface --> - - - <form id="iform" action=""> - <input type="hidden" name="snortSaveRuleSets" value="1" /> <!-- what to do, save --> - <input type="hidden" name="ifaceTab" value="snort_rules" /> <!-- what interface tab --> - - <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr id="maintable77" > - <td colspan="2" valign="top" class="listtopic">Snort Signatures:</td> + <tr> + <td><img + src="../themes/<?= $g['theme']; ?>/images/icons/icon_block_d.gif" + width="11" height="11"></td> + <td nowrap>Rule Disabled</td> + </tr> + <tr> + <!-- TODO: add save and cancel for checkbox options --> + <!-- <td><pre><input name="Submit" type="submit" class="formbtn" value="Save"> <input type="button" class="formbtn" value="Cancel" onclick="history.back()"><pre></td> --> + </tr> + <tr> + <td colspan="10"> + <p><!--<strong><span class="red">Warning:<br/> </span></strong>Editing these r</p>--> + </td> </tr> - </table> - - <table id="mainCreateTable" width="100%" border="0" cellpadding="0" cellspacing="0"> - - <tr id="frheader" > - <td class="listhdrr2">On</td> - <td class="listhdrr2">Sid</td> - <td class="listhdrr2">Proto</td> - <td class="listhdrr2">Src</td> - <td class="listhdrr2">Port</td> - <td class="listhdrr2">Dst</td> - <td class="listhdrr2">Port</td> - <td class="listhdrr2">Message</td> - <td class="listhdrr2"> </td> - </tr> - <tr> - <!-- START javascript sid loop here --> - <tbody class="rulesetloopblock"> - - - - </tbody> - <!-- STOP javascript sid loop here --> - </tr> - - </table> - <br> - <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td> - <input name="Submit" type="submit" class="formbtn" value="Save"> - <input id="cancel" type="button" class="formbtn" value="Cancel"> - </td> - </tr> </table> - </form> - <br> - - <!-- stop snortsam --> - - <!-- STOP MAIN AREA --> - </div> + </td> + </tr> + </table> </td> - </tr> +</tr> </table> </form> -</div> - -<!-- start info box --> - -<br> - -<div style="width:790px; background-color: #dddddd;" id="mainarea4"> -<div style="width:780px; margin-left: auto ; margin-right: auto ; padding-top: 10px; padding-bottom: 10px;"> -<table class="vncell2" width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td> </td> - </tr> - <tr > - <td width="100%"> - <span class="red"><strong>Note:</strong></span> <br> - This is the <strong>Snort Rule Signature Viewer</strong>. - Please make sure not to add a <strong>whitespace</strong> before <strong>alert</strong> or <strong>#alert</strong>. - <br> - <br> - <span class="red"><strong>Warning:</strong></span> - <br> - <strong>New settings will not take effect until interface restart.</strong> - <br><br> - </td> - </tr> -</table> -</div> -</div> - - -<script type="text/javascript"> - - -//prepare the form when the DOM is ready -jQuery(document).ready(function() { - - // NOTE: needs to be watched - // change url on selected dropdown rule - jQuery('select[name=selectbox]').change(function() { - window.location.replace(jQuery(this).val()); - }); - -<?php - - /* - * NOTE: - * I could have used a php loop to build the table but I wanted to see if off loading to client is faster. - * Seems to be faster on embeded systems with low specs. On higher end systems there is no difference that I can see. - * WARNING: - * If Json string is to long browsers start asking to terminate javascript. - * FIX: - * Use julienlecomte()net/blog/2007/10/28/, the more reading I do about this subject it seems that off loading to a client is not recomended. - */ - if (!empty($newFilterRuleSigArray)) - { - $countSigList = count($newFilterRuleSigArray); - - echo "\n"; - - echo 'var snortObjlist = ['; - $i = 0; - foreach ($newFilterRuleSigArray as $val3) - { - - $i++; - - // NOTE: escapeJsonString; foward slash has added spaces on each side, ie and chrome were giving issues with tablw widths - if( $i !== $countSigList ) { - echo '{"sid":"' . $val3['sid'] . '","enable":"' . $val3['enable'] . '","proto":"' . $val3['proto'] . '","src":"' . $val3['src'] . '","srcport":"' . $val3['srcport'] . '","dst":"' . $val3['dst'] . '", "dstport":"' . $val3['dstport'] . '","msg":"' . escapeJsonString($val3['msg']) . '"},'; - }else{ - echo '{"sid":"' . $val3['sid'] . '","enable":"' . $val3['enable'] . '","proto":"' . $val3['proto'] . '","src":"' . $val3['src'] . '","srcport":"' . $val3['srcport'] . '","dst":"' . $val3['dst'] . '", "dstport":"' . $val3['dstport'] . '","msg":"' . escapeJsonString($val3['msg']) . '"}'; - } - } - - echo '];' . "\n"; - } - - - - if (!empty($countSig)) { - echo 'var countRowAppend = ' . $countSig . ';' . "\n"; - }else{ - echo 'var countRowAppend = 0;' . "\n"; - } - -?> - -if(typeof escapeHtmlEntities == 'undefined') { - escapeHtmlEntities = function (text) { - return text.replace(/[\u00A0-\u2666<>\&]/g, function(c) { return '&' + - escapeHtmlEntities.entityTable[c.charCodeAt(0)] || '#'+c.charCodeAt(0) + ';'; }); - }; - - // all HTML4 entities as defined here: http://www.w3.org/TR/html4/sgml/entities.html - // added: amp, lt, gt, quot and apos - escapeHtmlEntities.entityTable = { 34 : 'quot', 38 : 'amp', 39 : 'apos', 47 : 'slash', 60 : 'lt', 62 : 'gt', 160 : 'nbsp', 161 : 'iexcl', 162 : 'cent', 163 : 'pound', 164 : 'curren', 165 : 'yen', 166 : 'brvbar', 167 : 'sect', 168 : 'uml', 169 : 'copy', 170 : 'ordf', 171 : 'laquo', 172 : 'not', 173 : 'shy', 174 : 'reg', 175 : 'macr', 176 : 'deg', 177 : 'plusmn', 178 : 'sup2', 179 : 'sup3', 180 : 'acute', 181 : 'micro', 182 : 'para', 183 : 'middot', 184 : 'cedil', 185 : 'sup1', 186 : 'ordm', 187 : 'raquo', 188 : 'frac14', 189 : 'frac12', 190 : 'frac34', 191 : 'iquest', 192 : 'Agrave', 193 : 'Aacute', 194 : 'Acirc', 195 : 'Atilde', 196 : 'Auml', 197 : 'Aring', 198 : 'AElig', 199 : 'Ccedil', 200 : 'Egrave', 201 : 'Eacute', 202 : 'Ecirc', 203 : 'Euml', 204 : 'Igrave', 205 : 'Iacute', 206 : 'Icirc', 207 : 'Iuml', 208 : 'ETH', 209 : 'Ntilde', 210 : 'Ograve', 211 : 'Oacute', 212 : 'Ocirc', 213 : 'Otilde', 214 : 'Ouml', 215 : 'times', 216 : 'Oslash', 217 : 'Ugrave', 218 : 'Uacute', 219 : 'Ucirc', 220 : 'Uuml', 221 : 'Yacute', 222 : 'THORN', 223 : 'szlig', 224 : 'agrave', 225 : 'aacute', 226 : 'acirc', 227 : 'atilde', 228 : 'auml', 229 : 'aring', 230 : 'aelig', 231 : 'ccedil', 232 : 'egrave', 233 : 'eacute', 234 : 'ecirc', 235 : 'euml', 236 : 'igrave', 237 : 'iacute', 238 : 'icirc', 239 : 'iuml', 240 : 'eth', 241 : 'ntilde', 242 : 'ograve', 243 : 'oacute', 244 : 'ocirc', 245 : 'otilde', 246 : 'ouml', 247 : 'divide', 248 : 'oslash', 249 : 'ugrave', 250 : 'uacute', 251 : 'ucirc', 252 : 'uuml', 253 : 'yacute', 254 : 'thorn', 255 : 'yuml', 402 : 'fnof', 913 : 'Alpha', 914 : 'Beta', 915 : 'Gamma', 916 : 'Delta', 917 : 'Epsilon', 918 : 'Zeta', 919 : 'Eta', 920 : 'Theta', 921 : 'Iota', 922 : 'Kappa', 923 : 'Lambda', 924 : 'Mu', 925 : 'Nu', 926 : 'Xi', 927 : 'Omicron', 928 : 'Pi', 929 : 'Rho', 931 : 'Sigma', 932 : 'Tau', 933 : 'Upsilon', 934 : 'Phi', 935 : 'Chi', 936 : 'Psi', 937 : 'Omega', 945 : 'alpha', 946 : 'beta', 947 : 'gamma', 948 : 'delta', 949 : 'epsilon', 950 : 'zeta', 951 : 'eta', 952 : 'theta', 953 : 'iota', 954 : 'kappa', 955 : 'lambda', 956 : 'mu', 957 : 'nu', 958 : 'xi', 959 : 'omicron', 960 : 'pi', 961 : 'rho', 962 : 'sigmaf', 963 : 'sigma', 964 : 'tau', 965 : 'upsilon', 966 : 'phi', 967 : 'chi', 968 : 'psi', 969 : 'omega', 977 : 'thetasym', 978 : 'upsih', 982 : 'piv', 8226 : 'bull', 8230 : 'hellip', 8242 : 'prime', 8243 : 'Prime', 8254 : 'oline', 8260 : 'frasl', 8472 : 'weierp', 8465 : 'image', 8476 : 'real', 8482 : 'trade', 8501 : 'alefsym', 8592 : 'larr', 8593 : 'uarr', 8594 : 'rarr', 8595 : 'darr', 8596 : 'harr', 8629 : 'crarr', 8656 : 'lArr', 8657 : 'uArr', 8658 : 'rArr', 8659 : 'dArr', 8660 : 'hArr', 8704 : 'forall', 8706 : 'part', 8707 : 'exist', 8709 : 'empty', 8711 : 'nabla', 8712 : 'isin', 8713 : 'notin', 8715 : 'ni', 8719 : 'prod', 8721 : 'sum', 8722 : 'minus', 8727 : 'lowast', 8730 : 'radic', 8733 : 'prop', 8734 : 'infin', 8736 : 'ang', 8743 : 'and', 8744 : 'or', 8745 : 'cap', 8746 : 'cup', 8747 : 'int', 8756 : 'there4', 8764 : 'sim', 8773 : 'cong', 8776 : 'asymp', 8800 : 'ne', 8801 : 'equiv', 8804 : 'le', 8805 : 'ge', 8834 : 'sub', 8835 : 'sup', 8836 : 'nsub', 8838 : 'sube', 8839 : 'supe', 8853 : 'oplus', 8855 : 'otimes', 8869 : 'perp', 8901 : 'sdot', 8968 : 'lceil', 8969 : 'rceil', 8970 : 'lfloor', 8971 : 'rfloor', 9001 : 'lang', 9002 : 'rang', 9674 : 'loz', 9824 : 'spades', 9827 : 'clubs', 9829 : 'hearts', 9830 : 'diams', 34 : 'quot', 38 : 'amp', 60 : 'lt', 62 : 'gt', 338 : 'OElig', 339 : 'oelig', 352 : 'Scaron', 353 : 'scaron', 376 : 'Yuml', 710 : 'circ', 732 : 'tilde', 8194 : 'ensp', 8195 : 'emsp', 8201 : 'thinsp', 8204 : 'zwnj', 8205 : 'zwj', 8206 : 'lrm', 8207 : 'rlm', 8211 : 'ndash', 8212 : 'mdash', 8216 : 'lsquo', 8217 : 'rsquo', 8218 : 'sbquo', 8220 : 'ldquo', 8221 : 'rdquo', 8222 : 'bdquo', 8224 : 'dagger', 8225 : 'Dagger', 8240 : 'permil', 8249 : 'lsaquo', 8250 : 'rsaquo', 8364 : 'euro' }; -} - - // if rowcount is not empty do this - if (countRowAppend > 0){ - - // if rowcount is more than 300 - if (countRowAppend > 200){ - // call to please wait - showLoading('#loadingWaiting'); - } - - - // Break up append row adds by chunks of 300 - // NOTE: ie9 is still giving me issues on deleted.rules 6000 sigs. I should break up the json code above into smaller parts. - incrementallyProcess(function (i){ - // loop code goes in here - //console.log('loop: ', i); - - if (isEven(i) === true){ - var rowIsEvenOdd = 'odd_ruleset2'; - }else{ - var rowIsEvenOdd = 'even_ruleset2'; - } - - if (snortObjlist[i].enable === 'on'){ - var rulesetChecked = 'checked'; - }else{ - var rulesetChecked = ''; - } - - jQuery('.rulesetloopblock').append( - - "\n" + '<tr valign="top" id="fr0">' + "\n" + - '<td class="' + rowIsEvenOdd + '">' + "\n" + - '<input class="domecheck" type="checkbox" name="filenamcheckbox2[]" value="' + snortObjlist[i].sid + '" ' + rulesetChecked + ' >' + "\n" + - '</td>' + "\n" + - '<td class="' + rowIsEvenOdd + '" id="frd0" >' + snortObjlist[i].sid + '</td>' + "\n" + - '<td class="' + rowIsEvenOdd + '" id="frd0" >' + snortObjlist[i].proto + '</td>' + "\n" + - '<td class="' + rowIsEvenOdd + '" id="frd0" >' + snortObjlist[i].src + '</td>' + "\n" + - '<td class="' + rowIsEvenOdd + '" id="frd0" >' + snortObjlist[i].srcport + '</td>' + "\n" + - '<td class="' + rowIsEvenOdd + '" id="frd0" >' + snortObjlist[i].dst + '</td>' + "\n" + - '<td class="' + rowIsEvenOdd + '" id="frd0" >' + snortObjlist[i].dstport + '</td>' + "\n" + - '<td class="listbg" id="frd0" ><font color="white">' + escapeHtmlEntities(snortObjlist[i].msg) + '</font></td>' + "\n" + - '<td class="' + rowIsEvenOdd+ '">' + "\n" + - '<img id="' + snortObjlist[i].sid + '" class="icon_click showeditrulegui" src="/themes/<?=$g['theme']; ?>/images/icons/icon_e.gif" width="17" height="17" border="0" title="edit rule">' + "\n" + - '</td>' + "\n" + - '</tr>' + "\n" - - ); - - }, - snortObjlist, // Object to work with the case Json object - 500, // chunk size - 200, // how many secs to wait - function (){ - // things that happen after the processing is done go here - // console.log('done!'); - - // if rowcount is more than 300 - if (countRowAppend > 200){ - // call to please wait - hideLoading('#loadingWaiting'); - } - - }); - } // end of if stopRowAppend - - - // On click show rule edit GUI - jQuery('.showeditrulegui').live('click', function(){ - - // Get sid - jQuery.getJSON('/snort/snort_json_get.php', - { - "snortGetSidString": "1", - "snortIface": "<?=$uuid . '_' . $a_list['interface']; ?>", - "snortRuleFile": "<?=$rulefile; ?>", - "sid": jQuery(this).attr('id') - }, - function(data){ - jQuery("textarea#sidstring").val(data.sidstring); // add string to textarea - jQuery("input[name=snortSidNum]").val(data.sid); // add sid to input - showLoading('#loadingRuleEditGUI'); - }); - }); - - jQuery('.closeRuleEditGUI').live('click', function(){ - hideLoading('#loadingRuleEditGUI'); - }); - - -}); // end of document ready - -</script> - - -<!-- stop info box --> - -<!-- footer do not touch below --> -<?php -include("fend.inc"); -echo $snort_custom_rnd_box; -?> - - +<?php include("fend.inc"); ?> </body> </html> diff --git a/config/snort-dev/snort_rules_edit.php b/config/snort-dev/snort_rules_edit.php new file mode 100644 index 00000000..330630f4 --- /dev/null +++ b/config/snort-dev/snort_rules_edit.php @@ -0,0 +1,188 @@ +<?php +/* + snort_rules_edit.php + Copyright (C) 2004, 2005 Scott Ullrich + Copyright (C) 2011 Ermal Luci + All rights reserved. + + Adapted for FreeNAS by Volker Theile (votdev@gmx.de) + Copyright (C) 2006-2009 Volker Theile + + Adapted for Pfsense Snort package by Robert Zelaya + Copyright (C) 2008-2009 Robert Zelaya + + Using dp.SyntaxHighlighter for syntax highlighting + http://www.dreamprojections.com/SyntaxHighlighter + Copyright (C) 2004-2006 Alex Gorbatchev. 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"); +require_once("/usr/local/pkg/snort/snort_gui.inc"); + +if (!is_array($config['installedpackages']['snortglobal']['rule'])) { + $config['installedpackages']['snortglobal']['rule'] = array(); +} +$a_nat = &$config['installedpackages']['snortglobal']['rule']; + +$id = $_GET['id']; +if (isset($_POST['id'])) + $id = $_POST['id']; + +$ids = $_GET['ids']; +if (isset($_POST['ids'])) + $ids = $_POST['ids']; + +if (isset($id) && $a_nat[$id]) { + $pconfig['enable'] = $a_nat[$id]['enable']; + $pconfig['interface'] = $a_nat[$id]['interface']; + $pconfig['rulesets'] = $a_nat[$id]['rulesets']; +} + +//get rule id +$lineid = $_GET['ids']; +if (isset($_POST['ids'])) + $lineid = $_POST['ids']; + +$file = $_GET['openruleset']; +if (isset($_POST['openruleset'])) + $file = $_POST['openruleset']; + +//read file into string, and get filesize also chk for empty files +$contents = ''; +if (filesize($file) > 0 ) + $contents = file_get_contents($file); + +//delimiter for each new rule is a new line +$delimiter = "\n"; + +//split the contents of the string file into an array using the delimiter +$splitcontents = explode($delimiter, $contents); +$findme = "# alert"; //find string for disabled alerts +$highlight = "yes"; +if (strstr($splitcontents[$lineid], $findme)) + $highlight = "no"; +if ($highlight == "no") + $splitcontents[$lineid] = substr($splitcontents[$lineid], 2); + +if (!function_exists('get_middle')) { + function get_middle($source, $beginning, $ending, $init_pos) { + $beginning_pos = strpos($source, $beginning, $init_pos); + $middle_pos = $beginning_pos + strlen($beginning); + $ending_pos = strpos($source, $ending, $beginning_pos); + $middle = substr($source, $middle_pos, $ending_pos - $middle_pos); + return $middle; + } +} + +if ($_POST) { + if ($_POST['save']) { + + //copy string into file array for writing + if ($_POST['highlight'] == "yes") + $splitcontents[$lineid] = $_POST['code']; + else + $splitcontents[$lineid] = "# " . $_POST['code']; + + //write disable/enable sid to config.xml + $sid = get_middle($splitcontents[$lineid], 'sid:', ';', 0); + if (is_numeric($sid)) { + // rule_sid_on registers + if (!empty($a_nat[$id]['rule_sid_on'])) + $a_nat[$id]['rule_sid_on'] = str_replace("||enablesid $sid", "", $a_nat[$id]['rule_sid_on']); + if (!empty($a_nat[$id]['rule_sid_on'])) + $a_nat[$id]['rule_sid_off'] = str_replace("||disablesid $sid", "", $a_nat[$id]['rule_sid_off']); + if ($_POST['highlight'] == "yes") + $a_nat[$id]['rule_sid_on'] = "||enablesid $sid" . $a_nat[$id]['rule_sid_on']; + else + $a_nat[$id]['rule_sid_off'] = "||disablesid $sid" . $a_nat[$id]['rule_sid_off']; + } + + //write the new .rules file + @file_put_contents($file, implode($delimiter, $splitcontents)); + + write_config(); + + echo "<script> opener.window.location.reload(); window.close(); </script>"; + exit; + } +} + +$pgtitle = array(gettext("Advanced"), gettext("File Editor")); + +?> + +<?php include("head.inc");?> + +<body link="#000000" vlink="#000000" alink="#000000"> +<form action="snort_rules_edit.php" method="post"> + <?php if ($savemsg) print_info_box($savemsg); ?> +<table width="100%" border="0" cellpadding="0" cellspacing="0"> +<tr> + <td class="tabcont"> + + + <table width="100%" cellpadding="9" cellspacing="9" bgcolor="#eeeeee"> + <tr> + <td> + <input name="save" type="submit" class="formbtn" id="save" value="save" /> + <input type='hidden' name='id' value='<?=$id;?>' /> + <input type='hidden' name='ids' value='<?=$ids;?>' /> + <input type='hidden' name='openruleset' value='<?=$file;?>' /> + <input type="button" class="formbtn" value="Cancel" onclick="window.close()"> + <hr noshade="noshade" /> + Disable original rule :<br/> + + <input id="highlighting_enabled" name="highlight2" type="radio" value="yes" <?php if($highlight == "yes") echo " checked=\"checked\""; ?> /> + <label for="highlighting_enabled"><?=gettext("Enabled");?> </label> + <input id="highlighting_disabled" name="highlight2" type="radio" value="no" <?php if($highlight == "no") echo " checked=\"checked\""; ?> /> + <label for="highlighting_disabled"> <?=gettext("Disabled");?></label> + </td> + </tr> + <tr> + <td valign="top" class="label"> + <textarea wrap="off" style="width: 98%; margin: 7px;" + class="<?php echo $language; ?>:showcolumns" rows="3" + cols="66" name="code"><?=$splitcontents[$lineid];?></textarea> + </div> + </td> + </tr> + <tr> + <td valign="top" class="label"> + <div style="background: #eeeeee;" id="textareaitem"><!-- NOTE: The opening *and* the closing textarea tag must be on the same line. --> + <textarea disabled + wrap="off" style="width: 98%; margin: 7px;" + class="<?php echo $language; ?>:showcolumns" rows="33" + cols="66" name="code2"><?=$contents;?></textarea> + </div> + </td> + </tr> + </table> + </td> +</tr> +</table> +</form> +<?php include("fend.inc");?> +</body> +</html> diff --git a/config/snort-dev/snort_rulesets.php b/config/snort-dev/snort_rulesets.php index a2e4f7f3..313daea2 100644 --- a/config/snort-dev/snort_rulesets.php +++ b/config/snort-dev/snort_rulesets.php @@ -1,19 +1,12 @@ <?php /* $Id$ */ /* - - part of pfSense - All rights reserved. - - Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + snort_rulesets.php + Copyright (C) 2006 Scott Ullrich + Copyright (C) 2009 Robert Zelaya + Copyright (C) 2011 Ermal Luci All rights reserved. - Pfsense Old snort GUI - Copyright (C) 2006 Scott Ullrich. - - Pfsense snort GUI - Copyright (C) 2008-2012 Robert Zelaya. - Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -24,10 +17,6 @@ notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - 3. Neither the name of the pfSense nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - 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 @@ -38,310 +27,287 @@ 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_new.inc"); require_once("/usr/local/pkg/snort/snort_gui.inc"); +require_once("/usr/local/pkg/snort/snort.inc"); -//Set no caching -header("Expires: Mon, 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"); +global $g; -if (isset($_GET['uuid']) && isset($_GET['rdbuuid'])) { - echo 'Error: more than one uuid'; - exit(0); +if (!is_array($config['installedpackages']['snortglobal']['rule'])) { + $config['installedpackages']['snortglobal']['rule'] = array(); } - -// set page vars -if (isset($_GET['uuid'])) { - $uuid = $_GET['uuid']; +$a_nat = &$config['installedpackages']['snortglobal']['rule']; + +$id = $_GET['id']; +if (isset($_POST['id'])) + $id = $_POST['id']; +if (is_null($id)) { + header("Location: /snort/snort_interfaces.php"); + exit; } -if (isset($_GET['rdbuuid'])) { - $rdbuuid = $_GET['rdbuuid']; -}else{ - $ruledbname_pre1 = snortSql_fetchAllSettings('snortDB', 'SnortIfaces', 'uuid', $uuid); - $rdbuuid = $ruledbname_pre1['ruledbname']; +if (isset($id) && $a_nat[$id]) { + $pconfig['enable'] = $a_nat[$id]['enable']; + $pconfig['interface'] = $a_nat[$id]['interface']; + $pconfig['rulesets'] = $a_nat[$id]['rulesets']; + + /* convert fake interfaces to real */ + $if_real = snort_get_real_interface($pconfig['interface']); + + $iface_uuid = $a_nat[$id]['uuid']; } -//$a_list = snortSql_fetchAllSettings('snortDBrules', 'SnortIfaces', 'uuid', $uuid); - - // list rules in the default dir - $filterDirList = array(); - $filterDirList = snortScanDirFilter('/usr/local/etc/snort/snortDBrules/DB/' . $rdbuuid . '/rules', '\.rules'); - - // list rules in db that are on in a array - $listOnRules = array(); - $listOnRules = snortSql_fetchAllSettings('snortDBrules', 'SnortRuleSets', 'rdbuuid', $rdbuuid); - - if (!empty($listOnRules)) { - foreach ( $listOnRules as $val2 ) - { - if ($val2['enable'] == 'on') { - $rulesetOn[] = $val2['rulesetname']; - } - } - unset($listOnRules); +$pgtitle = "Snort: Interface $id $iface_uuid $if_real Categories"; + + +/* Check if the rules dir is empy if so warn the user */ +/* TODO give the user the option to delete the installed rules rules */ +$isrulesfolderempty = exec("ls -A /usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules/*.rules"); +if ($isrulesfolderempty == "") { + $isrulesfolderempty = exec("ls -A /usr/local/etc/snort/rules/*.rules"); + if ($isrulesfolderempty == "") { + include_once("head.inc"); + include("fbegin.inc"); + + echo "<p class=\"pgtitle\">"; + if($pfsense_stable == 'yes'){echo $pgtitle;} + echo "</p>\n"; + + echo "<body link=\"#000000\" vlink=\"#000000\" alink=\"#000000\">"; + + echo " + <table width=\"99%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n + <tr><td>\n"; + + $tab_array = array(); + $tabid = 0; + $tab_array[$tabid] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); + $tabid++; + $tab_array[$tabid] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Categories"), true, "/snort/snort_rulesets.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Servers"), false, "/snort/snort_define_servers.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); + display_top_tabs($tab_array); + echo " + </td></tr> + <tr>\n + <td>\n + <div id=\"mainarea\">\n + <table id=\"maintable\" class=\"tabcont\" width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n + <tr>\n + <td>\n + # The rules directory is empty. /usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules \n + </td>\n + </tr>\n + </table>\n + </div>\n + </td>\n + </tr>\n + </table>\n + \n + </form>\n + \n + <p>\n\n"; + + echo "Please click on the Update Rules tab to install your selected rule sets. $isrulesfolderempty"; + include("fend.inc"); + + echo "</body>"; + echo "</html>"; + + exit(0); + } else { + /* Make sure that we have the rules */ + mwexec("/bin/cp /usr/local/etc/snort/rules/*.rules /usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules", true); } - - $pgtitle = "Snort: Interface Rule Categories"; - include("/usr/local/pkg/snort/snort_head.inc"); +} + +/* alert file */ +$d_snortconfdirty_path = "/var/run/snort_conf_{$iface_uuid}_{$if_real}.dirty"; +if ($_POST["Submit"]) { + $enabled_items = ""; + $isfirst = true; + if (is_array($_POST['toenable'])) + $enabled_items = implode("||", $_POST['toenable']); + else + $enabled_items = $_POST['toenable']; + $a_nat[$id]['rulesets'] = $enabled_items; + + write_config(); + sync_snort_package_config(); + + 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_rulesets.php?id=$id"); + exit; +} + +$enabled_rulesets = $a_nat[$id]['rulesets']; +if($enabled_rulesets) + $enabled_rulesets_array = split("\|\|", $enabled_rulesets); + +include_once("head.inc"); ?> +<body link="#000000" vlink="#000000" alink="#000000"> +<?php include("fbegin.inc"); ?> +<?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> +<?php +echo "{$snort_general_css}\n"; +?> -<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> - -<script type="text/javascript"> - -//prepare the form when the DOM is ready -jQuery(document).ready(function() { - - <?php - /* - * NOTE: I could have used a php loop to build the table but off loading to client is faster - * use jQuery jason parse, make sure its in one line - */ - if (!empty($filterDirList)) { - - $countDirList = count($filterDirList); - - echo "\n"; - - echo 'var snortObjlist = jQuery.parseJSON(\' { "ruleSets": [ '; - $i = 0; - foreach ($filterDirList as $val3) - { - - $i++; - - // if list ruleset is in the db ON mark it checked - $rulesetOnChecked = 'off'; - if(!empty($rulesetOn)) - { - if (in_array($val3, $rulesetOn)) - { - $rulesetOnChecked = 'on'; - } - } - - if ( $i !== $countDirList ) - { - echo '{"rule": ' . '"' . $val3 . '", ' . '"enable": ' . '"' . $rulesetOnChecked . '"' . '}, '; - }else{ - echo '{"rule": "' . $val3 . '", ' . '"enable": ' . '"' . $rulesetOnChecked . '"' . '} '; - } - } - - echo ' ]}\');' . "\n"; - - }else{ - - echo 'var snortObjlist = jQuery.parseJSON(\' { "ruleSets": [] } \');' . "\n"; - - } - - - ?> - - // loop through object, dont use .each in jQuery as its slow - if(snortObjlist.ruleSets.length > 0) { - for (var i = 0; i < snortObjlist.ruleSets.length; i++) { - - if (isEven(i) === true) { - var rowIsEvenOdd = 'even_ruleset'; - }else{ - var rowIsEvenOdd = 'odd_ruleset'; - } - - if (snortObjlist.ruleSets[i].enable === 'on') { - var rulesetChecked = 'checked'; - }else{ - var rulesetChecked = ''; - } - - jQuery('.rulesetloopblock').append( - "\n" + '<tr>' + "\n" + - '<td class="' + rowIsEvenOdd + '" align="center" valign="top" width="9%">' + "\n" + - ' <input class="domecheck" name="filenamcheckbox[]" value="' + snortObjlist.ruleSets[i].rule + '" type="checkbox" ' + rulesetChecked + ' >' + "\n" + - '</td>' + "\n" + - '<td class="' + rowIsEvenOdd + '">' + "\n" + - ' <a href="/snort/snort_rules.php?openruleset=' + snortObjlist.ruleSets[i].rule + '<?php if(isset($uuid)){echo "&uuid=$uuid";}else{echo "&rdbuuid=$rdbuuid";}?>' + '">' + snortObjlist.ruleSets[i].rule + '</a>' + "\n" + - '</td>' + "\n" + - '</tr>' + "\n\n" - ); - }; - } +<div class="body2"> - -}); // end of document ready +<noscript> +<div class="alert" ALIGN=CENTER><img + src="../themes/<?php echo $g['theme']; ?>/images/icons/icon_alert.gif" /><strong>Please +enable JavaScript to view this content +</CENTER></div> +</noscript> -</script> +<?php -<!-- loading msg --> -<div id="loadingWaiting"> - <div class="snortModal" style="top: 200px; left: 700px;"> - <div class="snortModalTop"> - <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> - </div> - <div class="snortModalTitle"> - <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> - </div> - <div> - <p class="loadingWaitingMessage"></p> - </div> - </div> -</div> +echo "<form action=\"snort_rulesets.php?id={$id}\" method=\"post\" name=\"iform\" id=\"iform\">"; -<?php include("fbegin.inc"); ?> +?> <?php + +/* Display message */ + +if ($input_errors) { + print_input_errors($input_errors); // TODO: add checks +} + +if ($savemsg) { + print_info_box2($savemsg); +} -<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> -<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0" alt="transgif" ></img></a></div> - -<table width="100%" border="0" cellpadding="0" cellspacing="0"> - <?php - if (!empty($uuid)) { - echo ' - <tr> - <td> - <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> - <ul class="newtabmenu"> - <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> - <li><a href="/snort/snort_interfaces_edit.php?uuid=' . $uuid . '"><span>If Settings</span></a></li> - <li class="newtabmenu_active"><a href="/snort/snort_rulesets.php?uuid=' . $uuid . '"><span>Categories</span></a></li> - <li><a href="/snort/snort_rules.php?uuid=' . $uuid . '"><span>Rules</span></a></li> - <li><a href="/snort/snort_rulesets_ips.php?uuid=' . $uuid . '"><span>Ruleset Ips</span></a></li> - <li><a href="/snort/snort_define_servers.php?uuid=' . $uuid . '"><span>Servers</span></a></li> - <li><a href="/snort/snort_preprocessors.php?uuid=' . $uuid . '"><span>Preprocessors</span></a></li> - <li><a href="/snort/snort_barnyard.php?uuid=' . $uuid . '"><span>Barnyard2</span></a></li> - </ul> - </div> - </td> - </tr> - '; +if (file_exists($d_snortconfdirty_path)) { + echo '<p>'; + + if($savemsg) { + print_info_box_np2("{$savemsg}"); }else{ - echo ' - <tr> - <td> - <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> - <ul class="newtabmenu"> - <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> - <li><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> - <li><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> - <li class="newtabmenu_active"><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> - <li><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> - <li><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> - <li><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> - <li><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> - <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> - </ul> - </div> - </td> - </tr> - <tr> - <td> - <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> - <ul class="newtabmenu"> - <li class="hide_newtabmenu"><a href="/snort/snort_interfaces_rules_edit.php?rdbuuid=' . $rdbuuid . '"><span>Rules DB Edit</span></a></li> - <li class="hide_newtabmenu newtabmenu_active"><a href="/snort/snort_rulesets.php?rdbuuid=' . $rdbuuid . '"><span>Categories</span></a></li> - <li class="hide_newtabmenu"><a href="/snort/snort_rules.php?rdbuuid=' . $rdbuuid . '"><span>Rules</span></a></li> - <li><a href="/snort/snort_rulesets_ips.php?rdbuuid=' . $rdbuuid . '"><span>Ruleset Ips</span></a></li> - </ul> - </div> - </td> - </tr> - '; + print_info_box_np2(' + The Snort configuration has changed and snort needs to be restarted on this interface.<br> + You must apply the changes in order for them to take effect.<br> + '); } - ?> +} + +?> + +<table width="99%" border="0" cellpadding="0" cellspacing="0"> +<tr><td> +<?php + $tab_array = array(); + $tabid = 0; + $tab_array[$tabid] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); + $tabid++; + $tab_array[$tabid] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Categories"), true, "/snort/snort_rulesets.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Servers"), false, "/snort/snort_define_servers.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); + $tabid++; + $tab_array[$tabid] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); + display_top_tabs($tab_array); +?> +</td></tr> <tr> - <td id="tdbggrey"> - <table width="100%" border="0" cellpadding="10px" cellspacing="0"> - <tr> - <td class="tabnavtbl"> - <table width="100%" border="0" cellpadding="6" cellspacing="0" > - <!-- START MAIN AREA --> - - - - <table width="100%" border="0" cellpadding="0" cellspacing="0" > - <tr> - <td> - </td> - <td> - <input id="select_all" type="button" class="formbtn" value="Select All" > - <input id="deselect_all" type="button" class="formbtn" value="Deselect All" > - </td> - </tr> - </table> - - <div id="checkboxdo" style="width: 100%; margin-left: auto ; margin-right: auto ; padding-top: 10px; padding-bottom: 0px;"> - <form id="iform" action="" > - <input type="hidden" name="snortSaveRuleSets" value="1" /> <!-- what to do, save --> - <input type="hidden" name="dbName" value="snortDBrules" /> <!-- what db--> - <input type="hidden" name="dbTable" value="SnortruleSets" /> <!-- what db table--> - <input type="hidden" name="ifaceTab" value="snort_rulesets" /> <!-- what interface tab --> - <input type="hidden" name="rdbuuid" value="<?=$rdbuuid;?>" /> <!-- what interface to save for --> - <input type="hidden" name="uuid" value="<?=$uuid;?>" /> <!-- create snort.conf --> - - <table width="100%" border="0" cellpadding="0" cellspacing="0"> - - <tr > - <td width="5%" class="listtopic">Enabled</td> - <td class="listtopic">Ruleset: Rules that end with "so.rules" are shared object rules.</td> - </tr> - <table class="rulesetbkg" width="100%"> - - <tbody class="rulesetloopblock" > - <!-- javscript loop table build here --> - </tbody> - - </table> - <table class="vncell1" width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td class="listtopic" >Check the rulesets that you would like Snort to load at startup.</td> - </tr> - </table> - <tr> - <td> - <input name="Submit" type="submit" class="formbtn" value="Save"> - <input id="cancel" type="button" class="formbtn" value="Cancel"> - </td> - </tr> + <td> + <div id="mainarea2"> + <table id="maintable" class="tabcont" width="100%" border="0" + cellpadding="0" cellspacing="0"> <tr> - <td width="78%"> - <span class="vexpl"><span class="red"><strong>Note:</strong></span> - Please save your settings before you click start.</span> + <td> + <table id="sortabletable1" class="sortable" width="100%" border="0" + cellpadding="0" cellspacing="0"> + <tr id="frheader"> + <td width="5%" class="listhdrr">Enabled</td> + <td class="listhdrr"><?php if($snort_arch == 'x86'){echo 'Ruleset: Rules that end with "so.rules" are shared object rules.';}else{echo 'Shared object rules are "so.rules" and not available on 64 bit architectures.';}?></td> + <!-- <td class="listhdrr">Description</td> --> + </tr> + <?php + $dir = "/usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules/"; + $dh = opendir($dir); + while (false !== ($filename = readdir($dh))) { + $files[] = basename($filename); + } + sort($files); + foreach($files as $file) { + if(!stristr($file, ".rules")) + continue; + echo "<tr>\n"; + echo "<td align=\"center\" valign=\"top\">"; + if(is_array($enabled_rulesets_array)) + if(in_array($file, $enabled_rulesets_array)) { + $CHECKED = " checked=\"checked\""; + } else { + $CHECKED = ""; + } + else + $CHECKED = ""; + echo " \n<input type='checkbox' name='toenable[]' value='$file' {$CHECKED} />\n"; + echo "</td>\n"; + echo "<td>\n"; + echo "<a href='snort_rules.php?id={$id}&openruleset=/usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules/" . urlencode($file) . "'>{$file}</a>\n"; + echo "</td>\n</tr>\n\n"; + //echo "<td>"; + //echo "description"; + //echo "</td>"; + } + + ?> + </table> </td> </tr> - - </table> - </form> - </div> - - <!-- STOP MAIN AREA --> + <tr> + <td> </td> + </tr> + <tr> + <td>Check the rulesets that you would like Snort to load at startup.</td> + </tr> + <tr> + <td> </td> + </tr> + <tr> + <td><input value="Save" type="submit" name="Submit" id="Submit" /></td> + </tr> </table> + </div> </td> - </tr> - </table> - </td> </tr> </table> + +</form> + +<p><b>NOTE:</b> You can click on a ruleset name to edit the ruleset.</p> + </div> -<!-- footer do not touch below --> -<?php -include("fend.inc"); +<?php +include("fend.inc"); echo $snort_custom_rnd_box; ?> - </body> </html> - diff --git a/config/snort-dev/snort_startstop.php b/config/snort-dev/snort_startstop.php new file mode 100644 index 00000000..c006ced9 --- /dev/null +++ b/config/snort-dev/snort_startstop.php @@ -0,0 +1,93 @@ +#!/usr/local/bin/php -f + +<?php +/* + snort_startstop.php + Copyright (C) 2009-2010 Robert Zelaya + 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. + */ + + +require_once("/usr/local/pkg/snort/snort.inc"); +require_once("/etc/inc/config.inc"); + +if (empty($argv) || file_exists("/tmp/snort_startstop.php.pid")) { + exit(); +} + +if (!empty($_GET[snortstart]) && !empty($_GET[snortstop]) || empty($_GET[snortstart]) && empty($_GET[snortstop]) ) { + exit(); +} + + // make shure there are no dup starts + exec("/bin/echo 'Starting snort_startstop.php' > /tmp/snort_startstop.php.pid"); + + // wait until boot is done + $snort_bootupWait = function() use(&$_GET, &$g) { + $i = 0; + exec("/bin/echo {$i} > /tmp/snort_testing.sh.pid"); + while(isset($g['booting']) || file_exists("{$g['varrun_path']}/booting")) { + $i++; + exec("/usr/bin/logger -p daemon.info -i -t SnortBoot 'Snort Boot count...{$i}'"); + exec("/bin/echo {$i} > /tmp/snort_testing.sh.pid"); // remove when finnished testing + sleep(2); + } + }; + $snort_bootupWait(); + + + $snort_bootupCleanStartStop = function($type) use(&$_GET, &$g) { + + $snortstartArray = explode(',', $_GET[$type]); + + foreach($snortstartArray as $iface_pre) { + + if (!empty($iface_pre)) { + $iface = explode('_', $iface_pre); + + if( !empty($iface[0]) && !empty($iface[1]) && is_numeric($iface[2]) ) { + + if($type === 'snortstart') { Running_Start($iface[0], $iface[1], $iface[2]); } + + if($type === 'snortstop') { Running_Stop($iface[0], $iface[1], $iface[2]); } + + } + } + } + }; + + + if (!empty($_GET[snortstart])) { + $snort_bootupCleanStartStop('snortstart'); + } + if (!empty($_GET[snortstop])) { + $snort_bootupCleanStartStop('snortstop'); + } + + // important + @exec("/bin/rm /tmp/snort_startstop.php.pid"); + exit(); + +?> diff --git a/config/snort-dev/css/new_tab_menu.css b/config/snort-dev/snortsam-package-code/css/new_tab_menu.css index 1592be9f..1592be9f 100644 --- a/config/snort-dev/css/new_tab_menu.css +++ b/config/snort-dev/snortsam-package-code/css/new_tab_menu.css diff --git a/config/snort-dev/css/style_snort2.css b/config/snort-dev/snortsam-package-code/css/style_snort2.css index 16b2e327..16b2e327 100644 --- a/config/snort-dev/css/style_snort2.css +++ b/config/snort-dev/snortsam-package-code/css/style_snort2.css diff --git a/config/snort/images/alert.jpg b/config/snort-dev/snortsam-package-code/images/alert.jpg Binary files differindex 96c24e35..96c24e35 100644 --- a/config/snort/images/alert.jpg +++ b/config/snort-dev/snortsam-package-code/images/alert.jpg diff --git a/config/snort/images/arrow_down.png b/config/snort-dev/snortsam-package-code/images/arrow_down.png Binary files differindex 2c4e2793..2c4e2793 100644 --- a/config/snort/images/arrow_down.png +++ b/config/snort-dev/snortsam-package-code/images/arrow_down.png diff --git a/config/snort/images/awesome-overlay-sprite.png b/config/snort-dev/snortsam-package-code/images/awesome-overlay-sprite.png Binary files differindex c3af7dd9..c3af7dd9 100644 --- a/config/snort/images/awesome-overlay-sprite.png +++ b/config/snort-dev/snortsam-package-code/images/awesome-overlay-sprite.png diff --git a/config/snort-dev/images/close_9x9.gif b/config/snort-dev/snortsam-package-code/images/close_9x9.gif Binary files differindex 326f5fa5..326f5fa5 100644 --- a/config/snort-dev/images/close_9x9.gif +++ b/config/snort-dev/snortsam-package-code/images/close_9x9.gif diff --git a/config/snort-dev/images/controls.png b/config/snort-dev/snortsam-package-code/images/controls.png Binary files differindex e1e97982..e1e97982 100644 --- a/config/snort-dev/images/controls.png +++ b/config/snort-dev/snortsam-package-code/images/controls.png diff --git a/config/snort/images/down.gif b/config/snort-dev/snortsam-package-code/images/down.gif Binary files differindex 2b3c99fc..2b3c99fc 100644 --- a/config/snort/images/down.gif +++ b/config/snort-dev/snortsam-package-code/images/down.gif diff --git a/config/snort/images/down2.gif b/config/snort-dev/snortsam-package-code/images/down2.gif Binary files differindex 71bf92eb..71bf92eb 100644 --- a/config/snort/images/down2.gif +++ b/config/snort-dev/snortsam-package-code/images/down2.gif diff --git a/config/snort/images/footer.jpg b/config/snort-dev/snortsam-package-code/images/footer.jpg Binary files differindex 4af05707..4af05707 100644 --- a/config/snort/images/footer.jpg +++ b/config/snort-dev/snortsam-package-code/images/footer.jpg diff --git a/config/snort/images/footer2.jpg b/config/snort-dev/snortsam-package-code/images/footer2.jpg Binary files differindex 3332e085..3332e085 100644 --- a/config/snort/images/footer2.jpg +++ b/config/snort-dev/snortsam-package-code/images/footer2.jpg diff --git a/config/snort/images/icon-table-sort-asc.png b/config/snort-dev/snortsam-package-code/images/icon-table-sort-asc.png Binary files differindex 0c127919..0c127919 100644 --- a/config/snort/images/icon-table-sort-asc.png +++ b/config/snort-dev/snortsam-package-code/images/icon-table-sort-asc.png diff --git a/config/snort/images/icon-table-sort-desc.png b/config/snort-dev/snortsam-package-code/images/icon-table-sort-desc.png Binary files differindex 5c52f2d0..5c52f2d0 100644 --- a/config/snort/images/icon-table-sort-desc.png +++ b/config/snort-dev/snortsam-package-code/images/icon-table-sort-desc.png diff --git a/config/snort/images/icon-table-sort.png b/config/snort-dev/snortsam-package-code/images/icon-table-sort.png Binary files differindex 3cae604b..3cae604b 100644 --- a/config/snort/images/icon-table-sort.png +++ b/config/snort-dev/snortsam-package-code/images/icon-table-sort.png diff --git a/config/snort/images/icon_excli.png b/config/snort-dev/snortsam-package-code/images/icon_excli.png Binary files differindex 4b54fa31..4b54fa31 100644 --- a/config/snort/images/icon_excli.png +++ b/config/snort-dev/snortsam-package-code/images/icon_excli.png diff --git a/config/snort-dev/images/loading.gif b/config/snort-dev/snortsam-package-code/images/loading.gif Binary files differindex cbc00f09..cbc00f09 100644 --- a/config/snort-dev/images/loading.gif +++ b/config/snort-dev/snortsam-package-code/images/loading.gif diff --git a/config/snort/images/logo.jpg b/config/snort-dev/snortsam-package-code/images/logo.jpg Binary files differindex fa01d818..fa01d818 100644 --- a/config/snort/images/logo.jpg +++ b/config/snort-dev/snortsam-package-code/images/logo.jpg diff --git a/config/snort/images/logo22.png b/config/snort-dev/snortsam-package-code/images/logo22.png Binary files differindex 64ed9d75..64ed9d75 100644 --- a/config/snort/images/logo22.png +++ b/config/snort-dev/snortsam-package-code/images/logo22.png diff --git a/config/snort-dev/images/new_tab_menu.png b/config/snort-dev/snortsam-package-code/images/new_tab_menu.png Binary files differindex f0e4cbeb..f0e4cbeb 100644 --- a/config/snort-dev/images/new_tab_menu.png +++ b/config/snort-dev/snortsam-package-code/images/new_tab_menu.png diff --git a/config/snort/images/page_white_text.png b/config/snort-dev/snortsam-package-code/images/page_white_text.png Binary files differindex 813f712f..813f712f 100644 --- a/config/snort/images/page_white_text.png +++ b/config/snort-dev/snortsam-package-code/images/page_white_text.png diff --git a/config/snort-dev/images/progress_bar2.gif b/config/snort-dev/snortsam-package-code/images/progress_bar2.gif Binary files differindex 81766a93..81766a93 100644 --- a/config/snort-dev/images/progress_bar2.gif +++ b/config/snort-dev/snortsam-package-code/images/progress_bar2.gif diff --git a/config/snort-dev/images/progressbar.gif b/config/snort-dev/snortsam-package-code/images/progressbar.gif Binary files differindex 6d167f5b..6d167f5b 100644 --- a/config/snort-dev/images/progressbar.gif +++ b/config/snort-dev/snortsam-package-code/images/progressbar.gif diff --git a/config/snort-dev/images/top_modal_bar_lil.jpg b/config/snort-dev/snortsam-package-code/images/top_modal_bar_lil.jpg Binary files differindex f0049de8..f0049de8 100644 --- a/config/snort-dev/images/top_modal_bar_lil.jpg +++ b/config/snort-dev/snortsam-package-code/images/top_modal_bar_lil.jpg diff --git a/config/snort-dev/images/transparent.gif b/config/snort-dev/snortsam-package-code/images/transparent.gif Binary files differindex e7ccd741..e7ccd741 100644 --- a/config/snort-dev/images/transparent.gif +++ b/config/snort-dev/snortsam-package-code/images/transparent.gif diff --git a/config/snort-dev/images/transparentbg.png b/config/snort-dev/snortsam-package-code/images/transparentbg.png Binary files differindex 86918930..86918930 100644 --- a/config/snort-dev/images/transparentbg.png +++ b/config/snort-dev/snortsam-package-code/images/transparentbg.png diff --git a/config/snort/images/up.gif b/config/snort-dev/snortsam-package-code/images/up.gif Binary files differindex 89596771..89596771 100644 --- a/config/snort/images/up.gif +++ b/config/snort-dev/snortsam-package-code/images/up.gif diff --git a/config/snort/images/up2.gif b/config/snort-dev/snortsam-package-code/images/up2.gif Binary files differindex 21c5a254..21c5a254 100644 --- a/config/snort/images/up2.gif +++ b/config/snort-dev/snortsam-package-code/images/up2.gif diff --git a/config/snort-dev/javascript/jquery-1.6.2.min.js b/config/snort-dev/snortsam-package-code/javascript/jquery-1.6.2.min.js index 48590ecb..48590ecb 100644 --- a/config/snort-dev/javascript/jquery-1.6.2.min.js +++ b/config/snort-dev/snortsam-package-code/javascript/jquery-1.6.2.min.js diff --git a/config/snort-dev/javascript/jquery.form.js b/config/snort-dev/snortsam-package-code/javascript/jquery.form.js index 2b853df4..2b853df4 100644 --- a/config/snort-dev/javascript/jquery.form.js +++ b/config/snort-dev/snortsam-package-code/javascript/jquery.form.js diff --git a/config/snort-dev/javascript/jquery.progressbar.min.js b/config/snort-dev/snortsam-package-code/javascript/jquery.progressbar.min.js index e85e1120..e85e1120 100644 --- a/config/snort-dev/javascript/jquery.progressbar.min.js +++ b/config/snort-dev/snortsam-package-code/javascript/jquery.progressbar.min.js diff --git a/config/snort-dev/javascript/snort_globalsend.js b/config/snort-dev/snortsam-package-code/javascript/snort_globalsend.js index dc92efba..dc92efba 100644 --- a/config/snort-dev/javascript/snort_globalsend.js +++ b/config/snort-dev/snortsam-package-code/javascript/snort_globalsend.js diff --git a/config/snort-dev/patches/SnortSam/TODAO.txt b/config/snort-dev/snortsam-package-code/patches/SnortSam/TODAO.txt index 3abf0303..3abf0303 100644 --- a/config/snort-dev/patches/SnortSam/TODAO.txt +++ b/config/snort-dev/snortsam-package-code/patches/SnortSam/TODAO.txt diff --git a/config/snort-dev/patches/SnortSam/snortsam-2.8.6.1.diff b/config/snort-dev/snortsam-package-code/patches/SnortSam/snortsam-2.8.6.1.diff index 983165e1..983165e1 100644 --- a/config/snort-dev/patches/SnortSam/snortsam-2.8.6.1.diff +++ b/config/snort-dev/snortsam-package-code/patches/SnortSam/snortsam-2.8.6.1.diff diff --git a/config/snort-dev/patches/inlinemode_options_flags.txt b/config/snort-dev/snortsam-package-code/patches/inlinemode_options_flags.txt index e69de29b..e69de29b 100644 --- a/config/snort-dev/patches/inlinemode_options_flags.txt +++ b/config/snort-dev/snortsam-package-code/patches/inlinemode_options_flags.txt diff --git a/config/snort-dev/patches/spoink_patch/2.8.6/Makefile.am b/config/snort-dev/snortsam-package-code/patches/spoink_patch/2.8.6/Makefile.am index 0879c6e3..0879c6e3 100644 --- a/config/snort-dev/patches/spoink_patch/2.8.6/Makefile.am +++ b/config/snort-dev/snortsam-package-code/patches/spoink_patch/2.8.6/Makefile.am diff --git a/config/snort-dev/patches/spoink_patch/2.8.6/Makefile.in b/config/snort-dev/snortsam-package-code/patches/spoink_patch/2.8.6/Makefile.in index 3f06cc31..3f06cc31 100644 --- a/config/snort-dev/patches/spoink_patch/2.8.6/Makefile.in +++ b/config/snort-dev/snortsam-package-code/patches/spoink_patch/2.8.6/Makefile.in diff --git a/config/snort-dev/patches/spoink_patch/2.8.6/plugbase.c b/config/snort-dev/snortsam-package-code/patches/spoink_patch/2.8.6/plugbase.c index 31f381a8..31f381a8 100644 --- a/config/snort-dev/patches/spoink_patch/2.8.6/plugbase.c +++ b/config/snort-dev/snortsam-package-code/patches/spoink_patch/2.8.6/plugbase.c diff --git a/config/snort-dev/patches/spoink_patch/2.8.6/util.c b/config/snort-dev/snortsam-package-code/patches/spoink_patch/2.8.6/util.c index b2d3b38b..b2d3b38b 100644 --- a/config/snort-dev/patches/spoink_patch/2.8.6/util.c +++ b/config/snort-dev/snortsam-package-code/patches/spoink_patch/2.8.6/util.c diff --git a/config/snort-dev/patches/spoink_patch/spo_pf.c b/config/snort-dev/snortsam-package-code/patches/spoink_patch/spo_pf.c index 121920fc..121920fc 100644 --- a/config/snort-dev/patches/spoink_patch/spo_pf.c +++ b/config/snort-dev/snortsam-package-code/patches/spoink_patch/spo_pf.c diff --git a/config/snort-dev/patches/spoink_patch/spo_pf.h b/config/snort-dev/snortsam-package-code/patches/spoink_patch/spo_pf.h index af07dacd..af07dacd 100644 --- a/config/snort-dev/patches/spoink_patch/spo_pf.h +++ b/config/snort-dev/snortsam-package-code/patches/spoink_patch/spo_pf.h diff --git a/config/snort-dev/snortsam-package-code/snort.xml b/config/snort-dev/snortsam-package-code/snort.xml new file mode 100644 index 00000000..207fae8b --- /dev/null +++ b/config/snort-dev/snortsam-package-code/snort.xml @@ -0,0 +1,272 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + part of pfSense (http://www.pfsense.com) + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + All rights reserved. + */ +/* ========================================================================== */ +/* + + Pfsense Old snort GUI + Copyright (C) 2006 Scott Ullrich. + + Pfsense snort GUI + Copyright (C) 2008-2012 Robert Zelaya. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the pfSense nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>Orion</name> + <version>2.9.1</version> + <title>Services:2.9.1 pkg v. 2.0</title> + <include_file>/usr/local/pkg/snort/snort_install.inc</include_file> + <menu> + <name>Orion</name> + <tooltiptext>Setup snort specific settings</tooltiptext> + <section>Services</section> + <url>/snort/snort_interfaces.php</url> + </menu> + <service> + <name>snort</name> + <rcfile>snort.sh</rcfile> + <executable>snort</executable> + <description>Snort is the most widely deployed IDS/IPS technology worldwide.</description> + </service> + <tabs> + </tabs> + <additional_files_needed> + <prefix>/usr/local/pkg/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snortDB</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snortDBrules</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snortDBtemp</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_build.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_download_rules.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_gui.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_head.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_headbase.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_install.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_new.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_alerts.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_barnyard.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_blocked.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_define_servers.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_download_updates.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_help_info.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_edit.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_global.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_rules.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_rules_edit.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_suppress.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_suppress_edit.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_whitelist.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_interfaces_whitelist_edit.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_json_get.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_json_post.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_preprocessors.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_rules.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_rulesets.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_rules_ips.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/snort/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort-dev/snort_rulesets_ips.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/bin/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort/bin/oinkmaster_contrib/create-sidmap.pl</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/bin/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort/bin/oinkmaster_contrib/make_snortsam_map.pl</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/bin/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort/bin/oinkmaster_contrib/oinkmaster.pl</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/bin/</prefix> + <chmod>077</chmod> + <item>http://www.pfsense.com/packages/config/snort/bin/oinkmaster_contrib/snort_rename.pl</item> + </additional_files_needed> + <fields> + </fields> + <custom_add_php_command> + </custom_add_php_command> + <custom_php_resync_config_command> + sync_snort_package(); + </custom_php_resync_config_command> + <custom_php_install_command> + snort_postinstall(); + </custom_php_install_command> + <custom_php_deinstall_command> + snort_deinstall(); + </custom_php_deinstall_command> +</packagegui> diff --git a/config/snort-dev/snortDB b/config/snort-dev/snortsam-package-code/snortDB Binary files differindex c685a368..c685a368 100644 --- a/config/snort-dev/snortDB +++ b/config/snort-dev/snortsam-package-code/snortDB diff --git a/config/snort-dev/snortDBrules b/config/snort-dev/snortsam-package-code/snortDBrules Binary files differindex 829a589b..829a589b 100644 --- a/config/snort-dev/snortDBrules +++ b/config/snort-dev/snortsam-package-code/snortDBrules diff --git a/config/snort-dev/snortDBtemp b/config/snort-dev/snortsam-package-code/snortDBtemp Binary files differindex 56ab2842..56ab2842 100644 --- a/config/snort-dev/snortDBtemp +++ b/config/snort-dev/snortsam-package-code/snortDBtemp diff --git a/config/snort-dev/snortsam-package-code/snort_alerts.php b/config/snort-dev/snortsam-package-code/snort_alerts.php new file mode 100644 index 00000000..3cb79c5c --- /dev/null +++ b/config/snort-dev/snortsam-package-code/snort_alerts.php @@ -0,0 +1,189 @@ +<?php +/* $Id$ */ +/* + + part of pfSense + All rights reserved. + + Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + All rights reserved. + + Pfsense Old snort GUI + Copyright (C) 2006 Scott Ullrich. + + Pfsense snort GUI + Copyright (C) 2008-2012 Robert Zelaya. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the pfSense nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + + 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_new.inc"); +require_once("/usr/local/pkg/snort/snort_gui.inc"); + +//Set no caching +header("Expires: Mon, 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"); + +$generalSettings = snortSql_fetchAllSettings('snortDB', 'SnortSettings', 'id', '1'); + +$alertnumber = $generalSettings['alertnumber']; + +$arefresh_on = ($generalSettings['arefresh'] == 'on' ? 'checked' : ''); + + $pgtitle = "Services: Snort: Alerts"; + include("/usr/local/pkg/snort/snort_head.inc"); + +?> + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + +<!-- loading msg --> +<div id="loadingWaiting"> + <div class="snortModal" style="top: 200px; left: 700px;"> + <div class="snortModalTop"> + <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> + </div> + <div class="snortModalTitle"> + <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> + </div> + <div> + <p class="loadingWaitingMessage"></p> + </div> + </div> +</div> + +<?php include("fbegin.inc"); ?> +<!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"> +<a href="../index.php" id="status-link2"> +<img src="./images/transparent.gif" border="0"></img> +</a> +</div> + +<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> + +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td> + + <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> + <ul class="newtabmenu"> + <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> + <li><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> + <li><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> + <li><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> + <li class="newtabmenu_active"><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> + <li><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> + <li><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> + <li><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> + <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> + </ul> + </div> + + </td> + </tr> + <tr> + <td id="tdbggrey"> + <table width="100%" border="0" cellpadding="10px" cellspacing="0"> + <tr> + <td class="tabnavtbl"> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <!-- START MAIN AREA --> + + <tr id="maintable" data-options='{"pagetable":"SnortSettings"}'> <!-- db to lookup --> + <td colspan="2" valign="top" class="listtopic" width="21%">Last 255 Alert Entries</td> + <td colspan="2" valign="top" class="listtopic">Latest Alert Entries Are Listed First</td> + </tr> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <tr> + <td class="vncell2" valign="center" width="21%"><span class="vexpl">Save or Remove Logs</span></td> + <td class="vtable" width="40%"> + <form id="iform" > + <input name="snortlogsdownload" type="submit" class="formbtn" value="Download" > + <input type="hidden" name="snortlogsdownload" value="1" /> + <span class="vexpl">Save All Log Files.</span> + </form> + </td> + <td class="vtable"> + <form id="iform2" > + <input name="snortlogsdelete" type="submit" class="formbtn" value="Clear" onclick="return confirm('Do you really want to remove all your logs ? All Snort Logs will be removed !')" > + <input type="hidden" name="snortlogsdelete" value="1" /> + <span class="vexpl red"><strong>Warning:</strong></span><span class="vexpl"> all logs will be deleted.</span> + </form> + </td> + <div class="hiddendownloadlink"></div> + </tr> + <tr> + <td class="vncell2" valign="center"><span class="vexpl">Auto Refresh and Log View</span></td> + <td class="vtable"> + <form id="iform3" > + <input name="save" type="submit" class="formbtn" value="Save"> + <input id="cancel" type="button" class="formbtn" value="Cancel"> + <input name="arefresh" id="arefresh" type="checkbox" value="on" <?=htmlspecialchars($arefresh_on);?> > + <span class="vexpl">Auto Refresh</span> + <span class="vexpl"><strong>Default ON</strong>.</span> + </td> + <td class="vtable"> + <input name="alertnumber" type="text" class="formfld2" id="alertnumber" size="5" value="<?=htmlspecialchars($alertnumber);?>" > + <span class="vexpl">Limit entries to view. <strong>Default 250</strong>.</span> + + <input type="hidden" name="snortSaveSettings" value="1" /> <!-- what to do, save --> + <input type="hidden" name="dbName" value="snortDB" /> <!-- what db --> + <input type="hidden" name="dbTable" value="SnortSettings" /> <!-- what db table --> + <input type="hidden" name="ifaceTab" value="snort_alerts" /> <!-- what interface tab --> + + </form> + </td> + </tr> + </table> + + + <!-- STOP MAIN AREA --> + </table> + </td> + </tr> + </table> + </td> + </tr> +</table> +</div> + + +<!-- footer do not touch below --> +<?php +include("fend.inc"); +echo $snort_custom_rnd_box; +?> + + +</body> +</html> diff --git a/config/snort-dev/snortsam-package-code/snort_barnyard.php b/config/snort-dev/snortsam-package-code/snort_barnyard.php new file mode 100644 index 00000000..1cd2113b --- /dev/null +++ b/config/snort-dev/snortsam-package-code/snort_barnyard.php @@ -0,0 +1,289 @@ +<?php +/* $Id$ */ +/* + + part of pfSense + All rights reserved. + + Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + All rights reserved. + + Pfsense Old snort GUI + Copyright (C) 2006 Scott Ullrich. + + Pfsense snort GUI + Copyright (C) 2008-2012 Robert Zelaya. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the pfSense nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + + 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_new.inc"); +require_once("/usr/local/pkg/snort/snort_gui.inc"); + +//Set no caching +header("Expires: Mon, 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"); + +// set page vars + +$uuid = $_GET['uuid']; +if (isset($_POST['uuid'])) +$uuid = $_POST['uuid']; + +if ($uuid == '') { + echo 'error: no uuid'; + exit(0); +} + + +$a_list = snortSql_fetchAllSettings('snortDB', 'SnortIfaces', 'uuid', $uuid); + + if (!is_array($a_list)) + { + $a_list = array(); + } + + + + $pgtitle = "Snort: Interface: Barnyard2 Edit"; + include("/usr/local/pkg/snort/snort_head.inc"); + +?> + + +<!-- START page custom script --> +<script language="JavaScript"> + +// start a jQuery sand box +jQuery(document).ready(function() { + + // START disable option for snort_interfaces_edit.php + endis = !(jQuery('input[name=barnyard_enable]:checked').val()); + + disableInputs=new Array( + "barnyard_mysql", + "barnconfigpassthru", + "dce_rpc", + "dns_preprocessor", + "ftp_preprocessor", + "http_inspect", + "other_preprocs", + "perform_stat", + "sf_portscan", + "smtp_preprocessor" + ); + + + jQuery('[name=interface]').attr('disabled', 'true'); + + + if (endis) + { + for (var i = 0; i < disableInputs.length; i++) + { + jQuery('[name=' + disableInputs[i] + ']').attr('disabled', 'true'); + } + } + + jQuery("input[name=barnyard_enable]").live('click', function() { + + endis = !(jQuery('input[name=barnyard_enable]:checked').val()); + + if (endis) + { + for (var i = 0; i < disableInputs.length; i++) + { + jQuery('[name=' + disableInputs[i] + ']').attr('disabled', 'true'); + } + }else{ + for (var i = 0; i < disableInputs.length; i++) + { + jQuery('[name=' + disableInputs[i] + ']').removeAttr('disabled'); + } + } + + + }); + // STOP disable option for snort_interfaces_edit.php + + +}); // end of on ready + +</script> + + + + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + +<!-- loading msg --> +<div id="loadingWaiting"> + <div class="snortModal" style="top: 200px; left: 700px;"> + <div class="snortModalTop"> + <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> + </div> + <div class="snortModalTitle"> + <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> + </div> + <div> + <p class="loadingWaitingMessage"></p> + </div> + </div> +</div> + +<?php include("fbegin.inc"); ?> +<!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"> +<a href="../index.php" id="status-link2"> +<img src="./images/transparent.gif" border="0"></img> +</a> +</div> + +<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> + +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td> + + <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> + <ul class="newtabmenu"> + <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> + <li><a href="/snort/snort_interfaces_edit.php?uuid=<?=$uuid;?>"><span>If Settings</span></a></li> + <li><a href="/snort/snort_rulesets.php?uuid=<?=$uuid;?>"><span>Categories</span></a></li> + <li><a href="/snort/snort_rules.php?uuid=<?=$uuid;?>"><span>Rules</span></a></li> + <li><a href="/snort/snort_rulesets_ips.php?uuid=<?=$uuid;?>"><span>Ruleset Ips</span></a></li> + <li><a href="/snort/snort_define_servers.php?uuid=<?=$uuid;?>"><span>Servers</span></a></li> + <li><a href="/snort/snort_preprocessors.php?uuid=<?=$uuid;?>"><span>Preprocessors</span></a></li> + <li class="newtabmenu_active"><a href="/snort/snort_barnyard.php?uuid=<?=$uuid;?>"><span>Barnyard2</span></a></li> + </ul> + </div> + + </td> + </tr> + <tr> + <td id="tdbggrey"> + <table width="100%" border="0" cellpadding="10px" cellspacing="0"> + <tr> + <td class="tabnavtbl"> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <!-- START MAIN AREA --> + + <form id="iform" > + <input type="hidden" name="snortSaveSettings" value="1" /> <!-- what to do, save --> + <input type="hidden" name="dbName" value="snortDB" /> <!-- what db--> + <input type="hidden" name="dbTable" value="SnortIfaces" /> <!-- what db table--> + <input type="hidden" name="ifaceTab" value="snort_barnyard" /> <!-- what interface tab --> + <input name="uuid" type="hidden" value="<?=$uuid; ?>"> + + + <tr> + <td colspan="2" valign="top" class="listtopic">General Barnyard2 Settings</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncellreq2">Enable</td> + <td width="78%" class="vtable"> + <input name="barnyard_enable" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['barnyard_enable'] == 'on' || $a_list['barnyard_enable'] == '' ? 'checked' : '';?> > + <span class="vexpl"><strong>Enable Barnyard2 on this Interface</strong><br> + This will enable barnyard2 for this interface. You will also have to set the database credentials.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Interface</td> + <td width="78%" class="vtable"> + <select name="interface" class="formfld" > + <option value="wan" selected><?=strtoupper($a_list['interface']); ?></option> + </select> + <br> + <span class="vexpl">Choose which interface this rule applies to.<br> + Hint: in most cases, you'll want to use WAN here.</span></span> + </td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic">Mysql Settings</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Log to a Mysql Database</td> + <td width="78%" class="vtable"> + <input name="barnyard_mysql" type="text" class="formfld" id="barnyard_mysql" size="100" value="<?=$a_list['barnyard_mysql']; ?>"> + <br> + <span class="vexpl">Example: output database: alert, mysql, dbname=snort user=snort host=localhost password=xyz<br> + Example: output database: log, mysql, dbname=snort user=snort host=localhost password=xyz</span> + </td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic">Advanced Settings</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Advanced configuration pass through</td> + <td width="78%" class="vtable"> + <textarea name="barnconfigpassthru" cols="75" rows="12" id="barnconfigpassthru" class="formpre2"><?=$a_list['barnconfigpassthru']; ?></textarea> + <br> + <span class="vexpl">Arguments here will be automatically inserted into the running barnyard2 configuration.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top"> </td> + <td width="78%"> + <input name="Submit" type="submit" class="formbtn" value="Save"> + <input type="button" class="formbtn" value="Cancel" > + </td> + </tr> + <tr> + <td width="22%" valign="top"> </td> + <td width="78%"> + <span class="vexpl"><span class="red"><strong>Note:</strong></span> + Please save your settings befor you click start.</span> + </td> + </tr> + + + </form> + <!-- STOP MAIN AREA --> + </table> + </td> + </tr> + </table> + </td> + </tr> +</table> +</div> + + +<!-- footer do not touch below --> +<?php +include("fend.inc"); +echo $snort_custom_rnd_box; +?> + + +</body> +</html> diff --git a/config/snort-dev/snortsam-package-code/snort_blocked.php b/config/snort-dev/snortsam-package-code/snort_blocked.php new file mode 100644 index 00000000..fdc12480 --- /dev/null +++ b/config/snort-dev/snortsam-package-code/snort_blocked.php @@ -0,0 +1,193 @@ +<?php +/* $Id$ */ +/* + + part of pfSense + All rights reserved. + + Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + All rights reserved. + + Pfsense Old snort GUI + Copyright (C) 2006 Scott Ullrich. + + Pfsense snort GUI + Copyright (C) 2008-2012 Robert Zelaya. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the pfSense nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + + 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_new.inc"); +require_once("/usr/local/pkg/snort/snort_gui.inc"); + +//Set no caching +header("Expires: Mon, 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"); + + +$generalSettings = snortSql_fetchAllSettings('snortDB', 'SnortSettings', 'id', '1'); + +$blertnumber = $generalSettings['blertnumber']; + +$brefresh_on = ($generalSettings['brefresh'] == 'on' ? 'checked' : ''); + + $pgtitle = "Services: Snort Blocked Hosts"; + include("/usr/local/pkg/snort/snort_head.inc"); + +?> + + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + +<!-- loading msg --> +<div id="loadingWaiting"> + <div class="snortModal" style="top: 200px; left: 700px;"> + <div class="snortModalTop"> + <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> + </div> + <div class="snortModalTitle"> + <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> + </div> + <div> + <p class="loadingWaitingMessage"></p> + </div> + </div> +</div> + +<?php include("fbegin.inc"); ?> +<!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"> +<a href="../index.php" id="status-link2"> +<img src="./images/transparent.gif" border="0"></img> +</a> +</div> + +<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> + +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td> + + <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> + <ul class="newtabmenu"> + <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> + <li><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> + <li><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> + <li><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> + <li><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> + <li class="newtabmenu_active"><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> + <li><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> + <li><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> + <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> + </ul> + </div> + + </td> + </tr> + <tr> + <td id="tdbggrey"> + <table width="100%" border="0" cellpadding="10px" cellspacing="0"> + <tr> + <td class="tabnavtbl"> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <!-- START MAIN AREA --> + + <tr id="maintable" data-options='{"pagetable":"SnortSettings"}'> <!-- db to lookup --> + <td width="22%" colspan="0" class="listtopic">Last 500 Blocked.</td> + <td class="listtopic">This page lists hosts that have been blocked by Snort. Hosts are removed every <strong>hour</strong>.</td> + </tr> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <tr> + <td class="vncell2" valign="center" width="22%"><span class="vexpl">Save or Remove Hosts</span></td> + <td width="40%" class="vtable"> + <form id="iform" > + <input name="snortblockedlogsdownload" type="submit" class="formbtn" value="Download" > + <input type="hidden" name="snortblockedlogsdownload" value="1" /> + <span class="vexpl">Save All Blocked Hosts</span> + </form> + </td> + <td class="vtable"> + <form id="iform2" > + <input name="remove" type="submit" class="formbtn" value="Clear" onclick="return confirm('Do you really want to remove all blocked hosts ? All Blocked Hosts will be removed !')" > + <input type="hidden" name="snortflushpftable" value="1" /> + <span class="vexpl red"><strong>Warning:</strong></span><span class="vexpl"> all hosts will be removed.</span> + </form> + </td> + + <div class="hiddendownloadlink"> + </div> + + </tr> + <tr> + <td class="vncell2" valign="center"><span class="vexpl">Auto Refresh and Log View</span></td> + <td class="vtable"> + <form id="iform3" > + <input name="save" type="submit" class="formbtn" value="Save"> + <input id="cancel" type="button" class="formbtn" value="Cancel"> + <span class="vexpl">Auto Refresh</span> + <input name="brefresh" id="brefresh" type="checkbox" value="on" <?=$brefresh_on; ?> > + <span class="vexpl"><strong>Default ON</strong>.</span> + </td> + <td class="vtable"> + <input name="blertnumber" type="text" class="formfld2" id="blertnumber" size="5" value="<?=$blertnumber;?>" > + <span class="vexpl">Limit entries to view. <strong>Default 500</strong>.</span> + + <input type="hidden" name="snortSaveSettings" value="1" /> <!-- what to do, save --> + <input type="hidden" name="dbName" value="snortDB" /> <!-- what db --> + <input type="hidden" name="dbTable" value="SnortSettings" /> <!-- what db table --> + <input type="hidden" name="ifaceTab" value="snort_blocked" /> <!-- what interface tab --> + + </form> + </td> + </tr> + </table> + + <!-- STOP MAIN AREA --> + </table> + </td> + </tr> + </table> + </td> + </tr> +</table> +</div> + + +<!-- footer do not touch below --> +<?php +include("fend.inc"); +echo $snort_custom_rnd_box; +?> + + +</body> +</html> diff --git a/config/snort-dev/snort_build.inc b/config/snort-dev/snortsam-package-code/snort_build.inc index 2c18d3d3..2c18d3d3 100644 --- a/config/snort-dev/snort_build.inc +++ b/config/snort-dev/snortsam-package-code/snort_build.inc diff --git a/config/snort-dev/snortsam-package-code/snort_define_servers.php b/config/snort-dev/snortsam-package-code/snort_define_servers.php new file mode 100644 index 00000000..05e7709e --- /dev/null +++ b/config/snort-dev/snortsam-package-code/snort_define_servers.php @@ -0,0 +1,450 @@ +<?php +/* $Id$ */ +/* + + part of pfSense + All rights reserved. + + Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + All rights reserved. + + Pfsense Old snort GUI + Copyright (C) 2006 Scott Ullrich. + + Pfsense snort GUI + Copyright (C) 2008-2012 Robert Zelaya. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the pfSense nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + + 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_new.inc"); +require_once("/usr/local/pkg/snort/snort_gui.inc"); + +//Set no caching +header("Expires: Mon, 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"); + +// set page vars + +$uuid = $_GET['uuid']; +if (isset($_POST['uuid'])) +$uuid = $_POST['uuid']; + +if ($uuid == '') { + echo 'error: no uuid'; + exit(0); +} + + +$a_list = snortSql_fetchAllSettings('snortDB', 'SnortIfaces', 'uuid', $uuid); + + + $pgtitle = "Snort: Interface Define Servers:"; + include("/usr/local/pkg/snort/snort_head.inc"); + +?> + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + +<!-- loading msg --> +<div id="loadingWaiting"> + <div class="snortModal" style="top: 200px; left: 700px;"> + <div class="snortModalTop"> + <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> + </div> + <div class="snortModalTitle"> + <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> + </div> + <div> + <p class="loadingWaitingMessage"></p> + </div> + </div> +</div> + +<?php include("fbegin.inc"); ?> +<!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"> +<a href="../index.php" id="status-link2"> +<img src="./images/transparent.gif" border="0"></img> +</a> +</div> + +<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> + +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td> + + <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> + <ul class="newtabmenu"> + <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> + <li><a href="/snort/snort_interfaces_edit.php?uuid=<?=$uuid;?>"><span>If Settings</span></a></li> + <li><a href="/snort/snort_rulesets.php?uuid=<?=$uuid;?>"><span>Categories</span></a></li> + <li><a href="/snort/snort_rules.php?uuid=<?=$uuid;?>"><span>Rules</span></a></li> + <li><a href="/snort/snort_rulesets_ips.php?uuid=<?=$uuid;?>"><span>Ruleset Ips</span></a></li> + <li class="newtabmenu_active"><a href="/snort/snort_define_servers.php?uuid=<?=$uuid;?>"><span>Servers</span></a></li> + <li><a href="/snort/snort_preprocessors.php?uuid=<?=$uuid;?>"><span>Preprocessors</span></a></li> + <li><a href="/snort/snort_barnyard.php?uuid=<?=$uuid;?>"><span>Barnyard2</span></a></li> + </ul> + </div> + + </td> + </tr> + <tr> + <td id="tdbggrey"> + <table width="100%" border="0" cellpadding="10px" cellspacing="0"> + <tr> + <td class="tabnavtbl"> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <!-- START MAIN AREA --> + + <form id="iform" > + <input type="hidden" name="snortSaveSettings" value="1" /> <!-- what to do, save --> + <input type="hidden" name="dbName" value="snortDB" /> <!-- what db--> + <input type="hidden" name="dbTable" value="SnortIfaces" /> <!-- what db table--> + <input type="hidden" name="ifaceTab" value="snort_define_servers" /> <!-- what interface tab --> + <input name="uuid" type="hidden" value="<?=$uuid; ?>"> + + <tr> + <td width="22%" valign="top"> </td> + <td width="78%"><span class="vexpl"> + <span class="red"><strong>Note:</strong></span><br> + Please save your settings before you click start.<br> + Please make sure there are <strong>no spaces</strong> in your definitions. + </td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic">Define Servers</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define DNS_SERVERS</td> + <td width="78%" class="vtable"> + <input name="def_dns_servers" type="text" class="formfld" id="def_dns_servers" size="40" value="<?=$a_list['def_dns_servers']; ?>"> + <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define DNS_PORTS</td> + <td width="78%" class="vtable"> + <input name="def_dns_ports" type="text" class="formfld" id="def_dns_ports" size="40" value="<?=$a_list['def_dns_ports']; ?>"> + <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 53.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define SMTP_SERVERS</td> + <td width="78%" class="vtable"> + <input name="def_smtp_servers" type="text" class="formfld" id="def_smtp_servers" size="40" value="<?=$a_list['def_smtp_servers']; ?>"> + <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define SMTP_PORTS</td> + <td width="78%" class="vtable"> + <input name="def_smtp_ports" type="text" class="formfld" id="def_smtp_ports" size="40" value="<?=$a_list['def_smtp_ports']; ?>"> + <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 25.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define Mail_Ports</td> + <td width="78%" class="vtable"> + <input name="def_mail_ports" type="text" class="formfld" id="def_mail_ports" size="40" value="<?=$a_list['def_mail_ports']; ?>"> + <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 25,143,465,691.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define HTTP_SERVERS</td> + <td width="78%" class="vtable"> + <input name="def_http_servers" type="text" class="formfld" id="def_http_servers" size="40" value="<?=$a_list['def_http_servers']; ?>"> + <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define WWW_SERVERS</td> + <td width="78%" class="vtable"> + <input name="def_www_servers" type="text" class="formfld" id="def_www_servers" size="40" value="<?=$a_list['def_www_servers']; ?>"> + <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define HTTP_PORTS</td> + <td width="78%" class="vtable"> + <input name="def_http_ports" type="text" class="formfld" id="def_http_ports" size="40" value="<?=$a_list['def_http_ports']; ?>"> + <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 80.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define SQL_SERVERS</td> + <td width="78%" class="vtable"> + <input name="def_sql_servers" type="text" class="formfld" id="def_sql_servers" size="40" value="<?=$a_list['def_sql_servers']; ?>"> + <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define ORACLE_PORTS</td> + <td width="78%" class="vtable"> + <input name="def_oracle_ports" type="text" class="formfld" id="def_oracle_ports" size="40" value="<?=$a_list['def_oracle_ports']; ?>"> + <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 1521.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define MSSQL_PORTS</td> + <td width="78%" class="vtable"> + <input name="def_mssql_ports" type="text" class="formfld" id="def_mssql_ports" size="40" value="<?=$a_list['def_mssql_ports']; ?>"> + <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 1433.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define TELNET_SERVERS</td> + <td width="78%" class="vtable"> + <input name="def_telnet_servers" type="text" class="formfld" id="def_telnet_servers" size="40" value="<?=$a_list['def_telnet_servers']; ?>"> + <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define TELNET_PORTS</td> + <td width="78%" class="vtable"> + <input name="def_telnet_ports" type="text" class="formfld" id="def_telnet_ports" size="40" value="<?=$a_list['def_telnet_ports']; ?>"> + <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 23.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define SNMP_SERVERS</td> + <td width="78%" class="vtable"> + <input name="def_snmp_servers" type="text" class="formfld" id="def_snmp_servers" size="40" value="<?=$a_list['def_snmp_servers']; ?>"> + <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define SNMP_PORTS</td> + <td width="78%" class="vtable"> + <input name="def_snmp_ports" type="text" class="formfld" id="def_snmp_ports" size="40" value="<?=$a_list['def_snmp_ports']; ?>"> + <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 161.</span></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define FTP_SERVERS</td> + <td width="78%" class="vtable"> + <input name="def_ftp_servers" type="text" class="formfld" id="def_ftp_servers" size="40" value="<?=$a_list['def_ftp_servers']; ?>"> + <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define FTP_PORTS</td> + <td width="78%" class="vtable"> + <input name="def_ftp_ports" type="text" class="formfld" id="def_ftp_ports" size="40" value="<?=$a_list['def_ftp_ports']; ?>"> + <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 21.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define SSH_SERVERS</td> + <td width="78%" class="vtable"> + <input name="def_ssh_servers" type="text" class="formfld" id="def_ssh_servers" size="40" value="<?=$a_list['def_ssh_servers']; ?>"> + <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define SSH_PORTS</td> + <td width="78%" class="vtable"> + <input name="def_ssh_ports" type="text" class="formfld" id="def_ssh_ports" size="40" value="<?=$a_list['def_ssh_ports']; ?>"> + <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is Pfsense SSH port.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define POP_SERVERS</td> + <td width="78%" class="vtable"> + <input name="def_pop_servers" type="text" class="formfld" id="def_pop_servers" size="40" value="<?=$a_list['def_pop_servers']; ?>"> + <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define POP2_PORTS</td> + <td width="78%" class="vtable"> + <input name="def_pop2_ports" type="text" class="formfld" id="def_pop2_ports" size="40" value="<?=$a_list['def_pop2_ports']; ?>"> + <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 109.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define POP3_PORTS</td> + <td width="78%" class="vtable"> + <input name="def_pop3_ports" type="text" class="formfld" id="def_pop3_ports" size="40" value="<?=$a_list['def_pop3_ports']; ?>"> + <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 110.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define IMAP_SERVERS</td> + <td width="78%" class="vtable"> + <input name="def_imap_servers" type="text" class="formfld" id="def_imap_servers" size="40" value="<?=$a_list['def_imap_servers']; ?>"> + <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define IMAP_PORTS</td> + <td width="78%" class="vtable"> + <input name="def_imap_ports" type="text" class="formfld" id="def_imap_ports" size="40" value="<?=$a_list['def_imap_ports']; ?>"> + <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 143.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define SIP_PROXY_IP</td> + <td width="78%" class="vtable"> + <input name="def_sip_proxy_ip" type="text" class="formfld" id="def_sip_proxy_ip" size="40" value="<?=$a_list['def_sip_proxy_ip']; ?>"> + <br> + <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave blank to scan all networks.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define SIP_PROXY_PORTS</td> + <td width="78%" class="vtable"> + <input name="def_sip_proxy_ports" type="text" class="formfld" id="def_sip_proxy_ports" size="40" value="<?=$a_list['def_sip_proxy_ports']; ?>"> + <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 5060:5090,16384:32768.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define AUTH_PORTS</td> + <td width="78%" class="vtable"> + <input name="def_auth_ports" type="text" class="formfld" id="def_auth_ports" size="40" value="<?=$a_list['def_auth_ports']; ?>"> + <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 113.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define FINGER_PORTS</td> + <td width="78%" class="vtable"> + <input name="def_finger_ports" type="text" class="formfld" id="def_finger_ports" size="40" value="<?=$a_list['def_finger_ports']; ?>"> + <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 79.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define IRC_PORTS</td> + <td width="78%" class="vtable"> + <input name="def_irc_ports" type="text" class="formfld" id="def_irc_ports" size="40" value="<?=$a_list['def_irc_ports']; ?>"> + <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 6665,6666,6667,6668,6669,7000.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define NNTP_PORTS</td> + <td width="78%" class="vtable"> + <input name="def_nntp_ports" type="text" class="formfld" id="def_nntp_ports" size="40" value="<?=$a_list['def_nntp_ports']; ?>"> + <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 119.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define RLOGIN_PORTS</td> + <td width="78%" class="vtable"> + <input name="def_rlogin_ports" type="text" class="formfld" id="def_rlogin_ports" size="40" value="<?=$a_list['def_rlogin_ports']; ?>"> + <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 513.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define RSH_PORTS</td> + <td width="78%" class="vtable"> + <input name="def_rsh_ports" type="text" class="formfld" id="def_rsh_ports" size="40" value="<?=$a_list['def_rsh_ports']; ?>"> + <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 514.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define SSL_PORTS</td> + <td width="78%" class="vtable"> + <input name="def_ssl_ports" type="text" class="formfld" id="def_ssl_ports" size="40" value="<?=$a_list['def_ssl_ports']; ?>"> + <br> + <span class="vexpl">Example: Specific ports "25,443" or All ports betwen "5060:5090 . Default is 25,443,465,636,993,995.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top"> </td> + <td width="78%"> + <input name="Submit" type="submit" class="formbtn" value="Save"> + <input id="cancel" type="button" class="formbtn" value="Cancel"> + </td> + </tr> + <tr> + <td width="22%" valign="top"> </td> + <td width="78%"> + <span class="vexpl"><span class="red"><strong>Note:</strong></span> + <br> + Please save your settings before you click start.</span> + </td> + </tr> + + + + + </form> + <!-- STOP MAIN AREA --> + </table> + </td> + </tr> + </table> + </td> + </tr> +</table> +</div> + + +<!-- footer do not touch below --> +<?php +include("fend.inc"); +echo $snort_custom_rnd_box; +?> + + +</body> +</html> diff --git a/config/snort-dev/snort_download_rules.inc b/config/snort-dev/snortsam-package-code/snort_download_rules.inc index 8953a65c..8953a65c 100644 --- a/config/snort-dev/snort_download_rules.inc +++ b/config/snort-dev/snortsam-package-code/snort_download_rules.inc diff --git a/config/snort-dev/snortsam-package-code/snort_download_updates.php b/config/snort-dev/snortsam-package-code/snort_download_updates.php new file mode 100644 index 00000000..445671bd --- /dev/null +++ b/config/snort-dev/snortsam-package-code/snort_download_updates.php @@ -0,0 +1,365 @@ +<?php +/* $Id$ */ +/* + + part of pfSense + All rights reserved. + + Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + All rights reserved. + + Pfsense Old snort GUI + Copyright (C) 2006 Scott Ullrich. + + Pfsense snort GUI + Copyright (C) 2008-2012 Robert Zelaya. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the pfSense nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + + 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. + + */ + +// disable csrf for downloads, progressbar did not work because of this +$nocsrf = true; + +require_once("guiconfig.inc"); +require_once("/usr/local/pkg/snort/snort_gui.inc"); +require_once("/usr/local/pkg/snort/snort_download_rules.inc"); + +//Set no caching +header("Expires: Mon, 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"); + +// set page vars +if (isset($_GET['updatenow'])) { + $updatenow = $_GET['updatenow']; +} + +header("Cache-Control: no-cache, must-revalidate"); +header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); + +// get dates of md5s + +$tmpSettingsSnort = 'N/A'; +$tmpSettingsSnortChk = snortSql_fetchAllSettings2('snortDBtemp', 'SnortDownloads', 'filename', 'snortrules-snapshot-2905.tar.gz'); +if (!empty($tmpSettingsSnortChk)) { + $tmpSettingsSnort = date('l jS \of F Y h:i:s A', $tmpSettingsSnortChk[date]); +} + +$tmpSettingsEmerging = 'N/A'; +$tmpSettingsEmergingChk = snortSql_fetchAllSettings2('snortDBtemp', 'SnortDownloads', 'filename', 'emerging.rules.tar.gz'); +if (!empty($tmpSettingsEmergingChk)) { + $tmpSettingsEmerging = date('l jS \of F Y h:i:s A', $tmpSettingsEmergingChk[date]); +} + +$tmpSettingsPfsense = 'N/A'; +$tmpSettingsPfsenseChk = snortSql_fetchAllSettings2('snortDBtemp', 'SnortDownloads', 'filename', 'pfsense_rules.tar.gz'); +if (!empty($tmpSettingsPfsenseChk)) { + $tmpSettingsPfsense = date('l jS \of F Y h:i:s A', $tmpSettingsPfsenseChk[date]); +} + +// get rule on stats +$generalSettings = snortSql_fetchAllSettings2('snortDB', 'SnortSettings', 'id', '1'); + +$snortMd5CurrentChk = @file_get_contents('/usr/local/etc/snort/snortDBrules/snort_rules/snortrules-snapshot-2905.tar.gz.md5'); + +$snortDownlodChkMark = ''; +if ($generalSettings[snortdownload] === 'on') { + $snortDownlodChkMark = 'checked="checked"'; +} + +$snortMd5Current = 'N/A'; +if (!empty($snortMd5CurrentChk)) { + preg_match('/^\".*\"/', $snortMd5CurrentChk, $snortMd5Current); + if (!empty($snortMd5Current[0])) { + $snortMd5Current = preg_replace('/\"/', '', $snortMd5Current[0]); + } +} + +$emergingMd5CurrentChk = @file_get_contents('/usr/local/etc/snort/snortDBrules/emerging_rules/emerging.rules.tar.gz.md5'); + +$emerginDownlodChkMark = ''; +if ($generalSettings[emergingthreatsdownload] !== 'off') { + $emerginDownlodChkMark = 'checked="checked"'; +} + +$emergingMd5Current = 'N/A'; +if (!empty($emergingMd5CurrentChk)) { + $emergingMd5Current = $emergingMd5CurrentChk; +} + +$pfsenseMd5CurrentChk = @file_get_contents('/usr/local/etc/snort/snortDBrules/pfsense_rules/pfsense_rules.tar.gz.md5'); + +$pfsenseMd5Current = 'N/A'; +if (!empty($pfsenseMd5CurrentChk)) { + preg_match('/^\".*\"/', $pfsenseMd5CurrentChk, $pfsenseMd5Current); + if (!empty($pfsenseMd5Current[0])) { + $pfsenseMd5Current = preg_replace('/\"/', '', $pfsenseMd5Current[0]); + } +} + + $pgtitle = 'Services: Snort: Updates'; + include("/usr/local/pkg/snort/snort_head.inc"); + +?> + + + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + +<!-- loading update msg --> +<div id="loadingRuleUpadteGUI"> + + <div class="snortModalUpdate"> + <div class="snortModalTopUpdate"> + <div class="snortModalTopClose"> + <!-- <a href="javascript:hideLoading('#loadingRuleUpadteGUI');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a> --> + </div> + </div> + <p id="UpdateMsg1" class="snortModalTitleUpdate snortModalTitleUpdateMsg1"> + </p> + <div class="snortModalTitleUpdate snortModalTitleUpdateBar"> + <table width="600px" height="43px" border="0" cellpadding="0" cellspacing="0"> + <tr><td><span class="progressBar" id="pb4"></span></td></tr> + </table> + </div> + <p id="UpdateMsg2" class="snortModalTitleUpdate snortModalTitleUpdateMsg2"> + </p> + </div> + +</div> + + +<?php include("fbegin.inc"); ?> + +<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> + +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td> + + <div class="newtabmenu" style="margin: 1px 0px; width: 790px;"><!-- Tabbed bar code--> + <ul class="newtabmenu"> + <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> + <li><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> + <li class="newtabmenu_active"><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> + <li><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> + <li><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> + <li><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> + <li><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> + <li><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> + <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> + </ul> + </div> + + </td> + </tr> + <tr> + <td> + + <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> + <ul class="newtabmenu"> + <li class="newtabmenu_active"><a href="/snort/snort_download_rules.php"><span>Rule Update</span></a></li> + <!-- <li><a href="#"><span>Upload Custom Rules</span></a></li> --> + <!-- <li><a href="#"><span>Gui Update</span></a></li> --> + </ul> + </div> + + </td> + </tr> + <tr> + <td id="tdbggrey"> + <div style="width:780px; margin-left: auto ; margin-right: auto ; padding-top: 10px; padding-bottom: 10px;"> + <!-- START MAIN AREA --> + + + <!-- start Interface Satus --> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr id="maintable77" > + <td colspan="2" valign="top" class="listtopic2"> + Rule databases that are ready to be updated. + </td> + <td width="6%" colspan="2" valign="middle" class="listtopic3" > + </td> + </tr> + </table> +<br> + + <!-- start User Interface --> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr id="maintable77" > + <td colspan="2" valign="top" class="listtopic">SIGNATURE RULESET DATABASES:</td> + </tr> + </table> + + + <table class="vncell2" width="100%" border="0" cellpadding="0" cellspacing="0"> + + <td class="list" ></td> + <td class="list" valign="middle" > + + <tr id="frheader" > + <td width="1%" class="listhdrr2">On</td> + <td width="25%" class="listhdrr2">Signature DB Name</td> + <td width="35%" class="listhdrr2">MD5 Version</td> + <td width="38%" class="listhdrr2">Last Rule DB Date</td> + <td width="1%" class="listhdrr2"> </td> + </tr> + + <!-- START javascript sid loop here --> + <tbody class="rulesetloopblock"> + +<tr id="fr0" valign="top"> +<td class="odd_ruleset2"> +<input class="domecheck" name="filenamcheckbox2[]" value="1292" <?=$snortDownlodChkMark;?> type="checkbox" disabled="disabled" > +</td> +<td class="odd_ruleset2" id="frd0">SNORT.ORG</td> +<td class="odd_ruleset2" id="frd0"><?=$snortMd5Current;?></td> +<td class="listbg" id="frd0"><font color="white"><?=$tmpSettingsSnort;?></font></td> +<td class="odd_ruleset2"> +<img src="/themes/pfsense_ng/images/icons/icon_alias_url_reload.gif" title="edit rule" width="17" border="0" height="17"> +</td> +</tr> + +<tr id="fr0" valign="top"> +<td class="odd_ruleset2"> +<input class="domecheck" name="filenamcheckbox2[]" value="1292" <?=$emerginDownlodChkMark;?> type="checkbox" disabled="disabled" > +</td> +<td class="odd_ruleset2" id="frd0">EMERGINGTHREATS.NET</td> +<td class="odd_ruleset2" id="frd0"><?=$emergingMd5Current;?></td> +<td class="listbg" id="frd0"><font color="white"><?=$tmpSettingsEmerging; ?></font></td> +<td class="odd_ruleset2"> +<img src="/themes/pfsense_ng/images/icons/icon_alias_url_reload.gif" title="edit rule" width="17" border="0" height="17"> +</td> +</tr> + +<tr id="fr0" valign="top"> +<td class="odd_ruleset2"> +<input class="domecheck" name="filenamcheckbox2[]" value="1292" checked="checked" type="checkbox" disabled="disabled" > +</td> +<td class="odd_ruleset2" id="frd0">PFSENSE.ORG</td> +<td class="odd_ruleset2" id="frd0"><?=$pfsenseMd5Current;?></td> +<td class="listbg" id="frd0"><font color="white"><?=$tmpSettingsPfsense;?></font></td> +<td class="odd_ruleset2"> +<img src="/themes/pfsense_ng/images/icons/icon_alias_url_reload.gif" title="edit rule" width="17" border="0" height="17"> +</td> +</tr> + + </tbody> + <!-- STOP javascript sid loop here --> + + </td> + <td class="list" colspan="8"></td> + + </table> + <br> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td> + <input id="openupdatebox" type="submit" class="formbtn" value="Update"> + </td> + </tr> + </table> + <br> + + <!-- stop snortsam --> + + <!-- STOP MAIN AREA --> + </div> + </td> + </tr> +</table> +</div> + +<!-- start info box --> + +<br> + +<div style="width:790px; background-color: #dddddd;" id="mainarea4"> +<div style="width:780px; margin-left: auto ; margin-right: auto ; padding-top: 10px; padding-bottom: 10px;"> +<table class="vncell2" width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr > + <td width="10%" valign="middle" > + <img style="vertical-align: middle;" src="/snort/images/icon_excli.png" width="40" height="32"> + </td> + <td width="90%" valign="middle" > + <span class="red"><strong>Note:</strong></span> + <strong> Snort.org and Emergingthreats.net will go down from time to time. Please be patient.</strong> + </td> + </tr> +</table> +</div> +</div> + + +<script type="text/javascript"> + + +//prepare the form when the DOM is ready +jQuery(document).ready(function() { + + jQuery('.closeupdatebox').live('click', function(){ + var url = '/snort/snort_download_updates.php'; + window.location = url; + }); + + jQuery('#openupdatebox').live('click', function(){ + var url = '/snort/snort_download_updates.php?updatenow=1'; + window.location = url; + }); + +}); // end of document ready + +</script> + +<?php + +if ($updatenow == 1) { + sendUpdateSnortLogDownload(''); // start main function + echo ' + <script type="text/javascript"> + jQuery(\'.snortModalTopClose\').append(\'<img class="icon_click closeupdatebox" src="/snort/images/close_9x9.gif" border="0" height="9" width="9">\'); + </script> + '; +} + +?> + + +<!-- stop info box --> + +<!-- footer do not touch below --> +<?php +include("fend.inc"); +echo $snort_custom_rnd_box; +?> + + +</body> +</html> diff --git a/config/snort-dev/snortsam-package-code/snort_gui.inc b/config/snort-dev/snortsam-package-code/snort_gui.inc new file mode 100644 index 00000000..d0a778ae --- /dev/null +++ b/config/snort-dev/snortsam-package-code/snort_gui.inc @@ -0,0 +1,83 @@ +<?php +/* $Id$ */ +/* + + part of pfSense + All rights reserved. + + Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + All rights reserved. + + Pfsense Old snort GUI + Copyright (C) 2006 Scott Ullrich. + + Pfsense snort GUI + Copyright (C) 2008-2012 Robert Zelaya. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the pfSense nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + + 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. + +*/ + +//include_once("/usr/local/pkg/snort/snort.inc"); + +function print_info_box_np2($msg) { + global $config, $g; + + echo "<table height=\"32\" width=\"100%\">\n"; + echo " <tr>\n"; + echo " <td>\n"; + echo " <div style='background-color:#990000' id='redbox'>\n"; + echo " <table width='100%'><tr><td width='8%'>\n"; + echo " <img style='vertical-align:middle' src=\"/snort/images/alert.jpg\" width=\"32\" height=\"28\">\n"; + echo " </td>\n"; + echo " <td width='70%'><font color='white'><b>{$msg}</b></font>\n"; + echo " </td>"; + if(stristr($msg, "apply") == true) { + echo " <td>"; + echo " <input name=\"apply\" type=\"submit\" class=\"formbtn\" id=\"apply\" value=\"Apply changes\">\n"; + echo " </td>"; + } + echo " </tr></table>\n"; + echo " </div>\n"; + echo " </td>\n"; + echo "</table>\n"; + echo "<script type=\"text/javascript\">\n"; + echo "NiftyCheck();\n"; + echo "Rounded(\"div#redbox\",\"all\",\"#FFF\",\"#990000\",\"smooth\");\n"; + echo "Rounded(\"td#blackbox\",\"all\",\"#FFF\",\"#000000\",\"smooth\");\n"; + echo "</script>\n"; + echo "\n<br>\n"; + + +} + +if ($config['version'] >= 6) { + $helplink = '<li><a href="/snort/help_and_info.php"><span>Help</span></a>'; +}else{ + $helplink = ' <li><a class="example8" href="/snort/help_and_info.php"><span>Help</span></a></li>'; +} + +?> diff --git a/config/snort-dev/snort_head.inc b/config/snort-dev/snortsam-package-code/snort_head.inc index 2d5aadaa..2d5aadaa 100644 --- a/config/snort-dev/snort_head.inc +++ b/config/snort-dev/snortsam-package-code/snort_head.inc diff --git a/config/snort-dev/snort_headbase.inc b/config/snort-dev/snortsam-package-code/snort_headbase.inc index 33bbd0ee..33bbd0ee 100644 --- a/config/snort-dev/snort_headbase.inc +++ b/config/snort-dev/snortsam-package-code/snort_headbase.inc diff --git a/config/snort-dev/snort_help_info.php b/config/snort-dev/snortsam-package-code/snort_help_info.php index 616133ae..616133ae 100644 --- a/config/snort-dev/snort_help_info.php +++ b/config/snort-dev/snortsam-package-code/snort_help_info.php diff --git a/config/snort-dev/snort_install.inc b/config/snort-dev/snortsam-package-code/snort_install.inc index b227b347..b227b347 100644 --- a/config/snort-dev/snort_install.inc +++ b/config/snort-dev/snortsam-package-code/snort_install.inc diff --git a/config/snort-dev/snortsam-package-code/snort_interfaces.php b/config/snort-dev/snortsam-package-code/snort_interfaces.php new file mode 100644 index 00000000..beb50f83 --- /dev/null +++ b/config/snort-dev/snortsam-package-code/snort_interfaces.php @@ -0,0 +1,415 @@ +<?php +/* $Id$ */ +/* + + part of pfSense + All rights reserved. + + Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + All rights reserved. + + Pfsense Old snort GUI + Copyright (C) 2006 Scott Ullrich. + + Pfsense snort GUI + Copyright (C) 2008-2012 Robert Zelaya. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the pfSense nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + + 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_new.inc"); +require_once("/usr/local/pkg/snort/snort_gui.inc"); + +//Set no caching +header("Expires: Mon, 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"); + +$new_ruleUUID = genAlphaNumMixFast(7, 8); + +$a_interfaces = snortSql_fetchAllInterfaceRules('SnortIfaces', 'snortDB'); + + + $pgtitle = "Services: Snort 2.9.0.5 pkg v. 2.0"; + include("/usr/local/pkg/snort/snort_head.inc"); + +?> + + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + + +<!-- loading msg --> +<div id="loadingWaiting"> + <div class="snortModal" style="top: 200px; left: 700px;"> + <div class="snortModalTop"> + <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> + </div> + <div class="snortModalTitle"> + <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> + </div> + <div> + <p class="loadingWaitingMessage"></p> + </div> + </div> +</div> + +<?php include("fbegin.inc"); ?> +<!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"> +<a href="../index.php" id="status-link2"> +<img src="./images/transparent.gif" border="0"></img> +</a> +</div> + +<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> + +<form id="iform" > + +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td> + + <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> + <ul class="newtabmenu"> + <li class="newtabmenu_active"><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> + <li><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> + <li><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> + <li><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> + <li><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> + <li><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> + <li><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> + <li><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> + <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> + </li> + </ul> + </div> + + </td> + </tr> + <tr> + <td id="tdbggrey"> + <div style="width:750px; margin-left: auto ; margin-right: auto ; padding-top: 10px; padding-bottom: 10px;"> + <!-- START MAIN AREA --> + + <!-- start snortsam --> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr id="maintable77" > + <td colspan="2" valign="top" class="listtopic">SnortSam Status</td> + </tr> + </table> + + <table class="vncell2" width="100%" border="0" cellpadding="0" cellspacing="0"> + + <td class="list" colspan="8"></td> + <td class="list" valign="middle" nowrap> + + <tr id="frheader" > + <td width="3%" class="list"> </td> + <td width="10%" class="listhdrr2">SnortSam</td> + <td width="10%" class="listhdrr">Role</td> + <td width="10%" class="listhdrr">Port</td> + <td width="10%" class="listhdrr">Pass</td> + <td width="10%" class="listhdrr">Log</td> + <td width="50%" class="listhdr">Description</td> + <td width="5%" class="list"> </td> + <td width="5%" class="list"> </td> + + + <tr valign="top" id="fr0"> + <td class="listt"> + <a href="?act=toggle&id=0"><img src="/themes/<?= $g['theme']; ?>/images/icons/icon_pass.gif" width="13" height="13" border="0" title="click to toggle start/stop snortsam"></a> + </td> + <td class="listbg" id="frd0" ondblclick="document.location='snort_interfaces_edit.php?id=0';">DISABLED</td> + <td class="listr" id="frd0" ondblclick="document.location='snort_interfaces_edit.php?id=0';">MASTER</td> + <td class="listr" id="frd0" ondblclick="document.location='snort_interfaces_edit.php?id=0';">3526</td> + <td class="listr" id="frd0" ondblclick="document.location='snort_interfaces_edit.php?id=0';">ENABLED</td> + <td class="listr" id="frd0" ondblclick="document.location='snort_interfaces_edit.php?id=0';">DISABLED</td> + <td class="listbg3" ondblclick="document.location='snort_interfaces_edit.php?id=0';"><font color="#ffffff">Mster IPs </td> + <td></td> + <td> + <a href="snort_interfaces_edit.php?id=0"><img src="/themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" width="17" height="17" border="0" title="edit rule"></a> + </td> + + </tr> + </tr> + </td> + <td class="list" colspan="8"></td> + </table> + <!-- stop snortsam --> +<br> + <!-- start Interface Satus --> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr id="maintable77" > + <td colspan="2" valign="top" class="listtopic2">Interface Status</td> + <td width="6%" colspan="2" valign="middle" class="listtopic3" > + <a href="snort_interfaces_edit.php?uuid=<?=$new_ruleUUID;?>"> + <img style="padding-left:3px;" src="/themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" width="17" height="17" border="0" title="add rule"> + </a> + </td> + </tr> + </table> +<br> + <!-- start User Interface --> + <?php + foreach ($a_interfaces as $list) + { + // make caps + $list['interface'] = strtoupper($list['interface']); + $list['performance'] = strtoupper($list['performance']); + + // rename for GUI iface + $ifaceStat = ($list['enable'] == 'on' ? 'ENABLED' : 'DISABLED'); + $blockStat = ($list['blockoffenders7'] == 'on' ? 'ENABLED' : 'DISABLED'); + $logStat = ($list['snortunifiedlog'] == 'on' ? 'ENABLED' : 'DISABLED'); + $barnyard2Stat = ($list['barnyard_enable'] == 'on' ? 'ENABLED' : 'DISABLED'); + + + echo " + <div id=\"maintable_{$list['uuid']}\" data-options='{\"pagetable\":\"SnortIfaces\", \"pagedb\":\"snortDB\", \"DoPOST\":\"true\"}'> + "; + echo ' + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr id="maintable77" > + '; + echo " + <td width=\"100%\" colspan=\"2\" valign=\"top\" class=\"listtopic\" >{$list['interface']} Interface Status ({$list['uuid']})</td> + "; + echo ' + </tr> + </table> + + <table class="vncell2" width="100%" border="0" cellpadding="0" cellspacing="0"> + + <td class="list" colspan="8"></td> + <td class="list" valign="middle" nowrap> + + <tr id="frheader" > + <td width="3%" class="list"> </td> + <td width="11%" class="listhdrr2">Snort</td> + <td width="10%" class="listhdrr">If</td> + <td width="10%" class="listhdrr">Performance</td> + <td width="10%" class="listhdrr">Block</td> + <td width="10%" class="listhdrr">Log</td> + <td width="50%" class="listhdr">Description</td> + <td width="5%" class="list"> </td> + <td width="5%" class="list"> </td> + + <tr valign="top" id="fr0"> + <td class="listt"> + '; + echo " + <a href=\"?act=toggle&id=0\"><img src=\"/themes/{$g['theme']}/images/icons/icon_pass.gif\" width=\"13\" height=\"13\" border=\"0\" title=\"click to toggle start/stop snort\"></a> + + </td> + <td class=\"listbg\" id=\"frd0\" ondblclick=\"document.location='snort_interfaces_edit.php?uuid={$list['uuid']}';\">{$ifaceStat}</td> + <td class=\"listr\" id=\"frd0\" ondblclick=\"document.location='snort_interfaces_edit.php?uuid={$list['uuid']}';\">{$list['interface']}</td> + <td class=\"listr\" id=\"frd0\" ondblclick=\"document.location='snort_interfaces_edit.php?uuid={$list['uuid']}';\">{$list['performance']}</td> + <td class=\"listr\" id=\"frd0\" ondblclick=\"document.location='snort_interfaces_edit.php?uuid={$list['uuid']}';\">{$blockStat}</td> + <td class=\"listr\" id=\"frd0\" ondblclick=\"document.location='snort_interfaces_edit.php?uuid={$list['uuid']}';\">{$logStat}</td> + <td class=\"listbg3\" ondblclick=\"document.location='snort_interfaces_edit.php?uuid={$list['uuid']}';\"><font color=\"#ffffff\">{$list['descr']}</td> + <td></td> + <td> + <a href=\"snort_interfaces_edit.php?uuid={$list['uuid']}\"><img src=\"/themes/{$g['theme']}/images/icons/icon_e.gif\" width=\"17\" height=\"17\" border=\"0\" title=\"edit rule\"></a> + "; + echo ' + </td> + + </tr> + </tr> + </td> + <td class="list" colspan="8"></td> + </table> + <table class="vncell2" width="100%" border="0" cellpadding="0" cellspacing="0"> + + <td class="list" colspan="8"></td> + <td class="list" valign="middle" nowrap> + + <tr id="frheader" > + <td width="3%" class="list"> </td> + <td width="10%" class="listhdrr2">Barnyard2</td> + <td width="10%" class="listhdrr">If</td> + <td width="10%" class="listhdrr">Sensor</td> + <td width="10%" class="listhdrr">Type</td> + <td width="10%" class="listhdrr">Log</td> + <td width="50%" class="listhdr">Description</td> + <td width="5%" class="list"> </td> + <td width="5%" class="list"> </td> + + + <tr valign="top" id="fr0"> + <td class="listt"> + '; + echo " + <a href=\"?act=toggle&id=0\"><img src=\"/themes/{$g['theme']}/images/icons/icon_pass.gif\" width=\"13\" height=\"13\" border=\"0\" title=\"click to toggle start/stop barnyard2\"></a> + </td> + <td class=\"listbg\" id=\"frd0\" ondblclick=\"document.location='snort_interfaces_edit.php?id=0';\">{$barnyard2Stat}</td> + <td class=\"listr\" id=\"frd0\" ondblclick=\"document.location='snort_interfaces_edit.php?id=0';\">{$list['interface']}</td> + <td class=\"listr\" id=\"frd0\" ondblclick=\"document.location='snort_interfaces_edit.php?id=0';\">{$list['uuid']}_{$list['interface']}</td> + <td class=\"listr\" id=\"frd0\" ondblclick=\"document.location='snort_interfaces_edit.php?id=0';\">unified2</td> + <td class=\"listr\" id=\"frd0\" ondblclick=\"document.location='snort_interfaces_edit.php?id=0';\">{$barnyard2Stat}</td> + <td class=\"listbg3\" ondblclick=\"document.location='snort_interfaces_edit.php?id=0';\"><font color=\"#ffffff\">Mster IPs </td> + <td></td> + <td> + <img id=\"icon_x_{$list['uuid']}\" class=\"icon_click icon_x\" src=\"/themes/{$g['theme']}/images/icons/icon_x.gif\" width=\"17\" height=\"17\" border=\"0\" title=\"delete rule\"> + "; + echo ' + </td> + + </tr> + </tr> + </td> + <td class="list" colspan="8"></td> + </table> + <br> + </div>'; + } // end of foreach main + ?> + <!-- stop User Interface --> + + <!-- stop Interface Sat --> + + <!-- STOP MAIN AREA --> + </div> + </td> + </tr> +</table> +</form> +</div> + +<!-- start info box --> + +<br> + +<div style="background-color: #dddddd;" id="mainarea4"> +<div style="width:750px; margin-left: auto ; margin-right: auto ; padding-top: 10px; padding-bottom: 10px;"> +<table class="vncell2" width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td> </td> + </tr> + <tr > + <td width="100%"> + <span class="red"><strong>Note:</strong></span> <br> + This is the <strong>Snort Menu</strong> where you can see an over view of all your interface settings. + Please edit the <strong>Global Settings</strong> tab before adding an interface. + <br> + <br> + <span class="red"><strong>Warning:</strong></span> + <br> + <strong>New settings will not take effect until interface restart.</strong> + <br> + <br> + <table> + <tr> + <td> + <strong>Click</strong> on the + <img src="/themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" width="17" height="17" border="0" title="Add Icon"> + icon to add a interface. + </td> + <td> + <strong>Click</strong> on the + <img src="/themes/<?= $g['theme']; ?>/images/icons/icon_pass.gif" width="13" height="13" border="0" title="Start Icon"> + icon to <strong>start</strong> snort or barnyard2. + </td> + </tr> + <tr> + <td> + <strong>Click</strong> on the + <img src="/themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" width="17" height="17" border="0" title="Edit Icon"> icon to edit a + interface and settings. + </td> + <td> + <strong>Click</strong> on the + <img src="/themes/<?= $g['theme']; ?>/images/icons/icon_block.gif" width="13" height="13" border="0" title="Stop Icon"> + icon to <strong>stop</strong> snort or barnyard2. + </td> + </tr> + <tr> + <td> + <strong> Click</strong> on the + <img src="/themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" width="17" height="17" border="0" title="Delete Icon"> + icon to delete a interface and settings. + </td> + </tr> + <tr> + <td> </td> + </tr> + </table> + </td> + </tr> +</table> +</div> +</div> + +<!-- stop info box --> + +<!-- start snort footer --> + +<br> + +<div style="background-color: #dddddd;" id="mainarea6"> +<div style="width:750px; margin-left: auto ; margin-right: auto ; padding-top: 10px; padding-bottom: 10px;"> +<table class="vncell2" width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td> </td> + </tr> + <tr > + <td width="100%"> + <div id="footer2"> + <table> + <tr> + <td style="padding-top: 40px;"> + SNORT registered ® by Sourcefire, Inc, Barnyard2 registered ® by securixlive.com, Orion registered ® by Robert Zelaya, + Emergingthreats registered ® by emergingthreats.net, Mysql registered ® by Mysql.com + </td> + </tr> + </table> + </div> + </td> + </tr> + <tr> + <td> </td> + </tr> +</table> +</div> +</div> + +<!-- stop snort footer --> + +<!-- footer do not touch below --> +<?php +include("fend.inc"); +echo $snort_custom_rnd_box; +?> + + +</body> +</html> diff --git a/config/snort-dev/snortsam-package-code/snort_interfaces_edit.php b/config/snort-dev/snortsam-package-code/snort_interfaces_edit.php new file mode 100644 index 00000000..ade5ade8 --- /dev/null +++ b/config/snort-dev/snortsam-package-code/snort_interfaces_edit.php @@ -0,0 +1,536 @@ +<?php +/* $Id$ */ +/* + + part of pfSense + All rights reserved. + + Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + All rights reserved. + + Pfsense Old snort GUI + Copyright (C) 2006 Scott Ullrich. + + Pfsense snort GUI + Copyright (C) 2008-2012 Robert Zelaya. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the pfSense nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + + 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_new.inc"); +require_once("/usr/local/pkg/snort/snort_gui.inc"); + +//Set no caching +header("Expires: Mon, 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"); + +// set page vars + +$uuid = $_GET['uuid']; +if (isset($_POST['uuid'])) +$uuid = $_POST['uuid']; + +if ($uuid == '') { + echo 'error: no uuid'; + exit(0); +} + + + +$a_list = snortSql_fetchAllSettings('snortDB', 'SnortIfaces', 'uuid', $uuid); + +$a_rules = snortSql_fetchAllSettings('snortDBrules', 'Snortrules', 'All', ''); + +if (!is_array($a_list)) { + $a_list = array(); +} + +$a_whitelist = snortSql_fetchAllWhitelistTypes('SnortWhitelist', 'SnortWhitelistips'); + +if (!is_array($a_whitelist)) { + $a_whitelist = array(); +} + +$a_suppresslist = snortSql_fetchAllWhitelistTypes('SnortSuppress', ''); + +if (!is_array($a_suppresslist)) { + $a_suppresslist = array(); +} + + + $pgtitle = "Services: Snort: Interface Edit:"; + include("/usr/local/pkg/snort/snort_head.inc"); + +?> + +<!-- START page custom script --> +<script language="JavaScript"> + +// start a jQuery sand box +jQuery(document).ready(function() { + + // misc call after a good save + jQuery.fn.miscTabCall = function () { + jQuery('.hide_newtabmenu').show(); + jQuery('#interface').attr("disabled", true); + }; + + // START disable option for snort_interfaces_edit.php + endis = !(jQuery('input[name=enable]:checked').val()); + + disableInputs=new Array( + "descr", + "performance", + "blockoffenders7", + "alertsystemlog", + "externallistname", + "homelistname", + "suppresslistname", + "tcpdumplog", + "snortunifiedlog", + "configpassthru" + ); + <?php + + if ($a_list['interface'] != '') { + echo ' + jQuery(\'[name=interface]\').attr(\'disabled\', \'true\'); + '; + } + + // disable tabs if nothing in database + if ($a_list['uuid'] == '') { + echo ' + jQuery(\'.hide_newtabmenu\').hide(); + '; + } + + ?> + + if (endis) { + for (var i = 0; i < disableInputs.length; i++) + { + jQuery('[name=' + disableInputs[i] + ']').attr('disabled', 'true'); + } + } + + jQuery("input[name=enable]").live('click', function() { + + endis = !(jQuery('input[name=enable]:checked').val()); + + if (endis) { + for (var i = 0; i < disableInputs.length; i++) + { + jQuery('[name=' + disableInputs[i] + ']').attr('disabled', 'true'); + } + }else{ + for (var i = 0; i < disableInputs.length; i++) + { + jQuery('[name=' + disableInputs[i] + ']').removeAttr('disabled'); + } + } + + + }); + // STOP disable option for snort_interfaces_edit.php + + +}); // end of on ready + +</script> + + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + +<!-- loading msg --> +<div id="loadingWaiting"> + <div class="snortModal" style="top: 200px; left: 700px;"> + <div class="snortModalTop"> + <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> + </div> + <div class="snortModalTitle"> + <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> + </div> + <div> + <p class="loadingWaitingMessage"></p> + </div> + </div> +</div> + +<?php include("fbegin.inc"); ?> +<!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"> +<a href="../index.php" id="status-link2"> +<img src="./images/transparent.gif" border="0"></img> +</a> +</div> + +<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> + +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td> + <div class="newtabmenu" style="margin: 1px 0px; width: 790px;"><!-- Tabbed bar code--> + <ul class="newtabmenu"> + <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> + <li class="newtabmenu_active"><a href="/snort/snort_interfaces_edit.php?uuid=<?=$uuid;?>"><span>If Settings</span></a></li> + <li class="hide_newtabmenu"><a href="/snort/snort_rulesets.php?uuid=<?=$uuid;?>"><span>Categories</span></a></li> + <li class="hide_newtabmenu"><a href="/snort/snort_rules.php?uuid=<?=$uuid;?>"><span>Rules</span></a></li> + <li class="hide_newtabmenu"><a href="/snort/snort_rulesets_ips.php?uuid=<?=$uuid;?>"><span>Ruleset Ips</span></a></li> + <li class="hide_newtabmenu"><a href="/snort/snort_define_servers.php?uuid=<?=$uuid;?>"><span>Servers</span></a></li> + <li class="hide_newtabmenu"><a href="/snort/snort_preprocessors.php?uuid=<?=$uuid;?>"><span>Preprocessors</span></a></li> + <li class="hide_newtabmenu"><a href="/snort/snort_barnyard.php?uuid=<?=$uuid;?>"><span>Barnyard2</span></a></li> + </ul> + </div> + </td> + </tr> + <tr> + <td id="tdbggrey"> + <table width="100%" border="0" cellpadding="10px" cellspacing="0"> + <tr> + <td class="tabnavtbl"> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <!-- START MAIN AREA --> + + <form id="iform" name="iform" > + <input type="hidden" name="snortSaveSettings" value="1" /> <!-- what to do, save --> + <input type="hidden" name="dbName" value="snortDB" /> <!-- what db--> + <input type="hidden" name="dbTable" value="SnortIfaces" /> <!-- what db table--> + <input type="hidden" name="ifaceTab" value="snort_interfaces_edit" /> <!-- what interface tab --> + <input name="uuid" type="hidden" value="<?=$uuid; ?>" > + + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <tr> + <td colspan="2" valign="top" class="listtopic">General Settings</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncellreq2">Interface</td> + <td width="22%" valign="top" class="vtable"> + + <input name="enable" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['enable'] == 'on' || $a_list['enable'] == '' ? 'checked' : '';?> "> + <span class="vexpl">Enable or Disable</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncellreq2">Interface</td> + <td width="78%" class="vtable"> + <select id="interface" name="interface" class="formfld"> + + <?php + /* add group interfaces */ + /* needs to be watched, dont know if new interfces will work */ + if (is_array($config['ifgroups']['ifgroupentry'])) + foreach($config['ifgroups']['ifgroupentry'] as $ifgen) + if (have_ruleint_access($ifgen['ifname'])) + $interfaces[$ifgen['ifname']] = $ifgen['ifname']; + $ifdescs = get_configured_interface_with_descr(); + foreach ($ifdescs as $ifent => $ifdesc) + if(have_ruleint_access($ifent)) + $interfaces[$ifent] = $ifdesc; + if ($config['l2tp']['mode'] == "server") + if(have_ruleint_access("l2tp")) + $interfaces['l2tp'] = "L2TP VPN"; + if ($config['pptpd']['mode'] == "server") + if(have_ruleint_access("pptp")) + $interfaces['pptp'] = "PPTP VPN"; + + if (is_pppoe_server_enabled() && have_ruleint_access("pppoe")) + $interfaces['pppoe'] = "PPPoE VPN"; + /* add ipsec interfaces */ + if (isset($config['ipsec']['enable']) || isset($config['ipsec']['client']['enable'])) + if(have_ruleint_access("enc0")) + $interfaces["enc0"] = "IPsec"; + /* add openvpn/tun interfaces */ + if ($config['openvpn']["openvpn-server"] || $config['openvpn']["openvpn-client"]) + $interfaces["openvpn"] = "OpenVPN"; + $selected_interfaces = explode(",", $pconfig['interface']); + foreach ($interfaces as $iface => $ifacename) + { + echo "\n" . "<option value=\"$iface\""; + if ($a_list['interface'] == strtolower($ifacename)){echo " selected ";} + echo '>' . $ifacename . '</option>' . "\r"; + } + ?> + </select> + <br> + <span class="vexpl">Choose which interface this rule applies to.<br> + Hint: in most cases, you'll want to use WAN here.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncellreq2">Description</td> + <td width="78%" class="vtable"> + <input name="descr" type="text" class="formfld" id="descr" size="40" value="<?=$a_list['descr']?>"> + <br> + <span class="vexpl">You may enter a description here for your reference (not parsed).</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Memory Performance</td> + <td width="78%" class="vtable"> + <select name="performance" class="formfld" id="performance"> + + <?php + $memoryPerfList = array('ac-bnfa' => 'AC-BNFA', 'lowmem' => 'LOWMEM', 'aclowmem-std' => 'AC-STD', 'ac' => 'AC', 'ac-banded' => 'AC-BANDED', 'ac-sparsebands' => 'AC-SPARSEBANDS', 'acs' => 'ACS'); + snortDropDownList($memoryPerfList, $a_list['performance']); + ?> + + </select> + <br> + <span class="vexpl">Lowmem and ac-bnfa are recommended for low end systems, Ac: high memory, best performance, ac-std: moderate + memory,high performance, acs: small memory, moderateperformance, ac-banded: small memory,moderate performance, ac-sparsebands: small memory, high performance.</span> + <br> + </td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic">Choose the rule DB snort should use.</td> + </tr> + + <tr> + <td width="22%" valign="top" class="vncell2">Rule DB</td> + <td width="78%" class="vtable"> + <select name="ruledbname" class="formfld" id="ruledbname"> + + <?php + // find ruleDB names and value by uuid + $selected = ''; + if ($a_list['ruledbname'] == 'default') { + $selected = 'selected'; + } + echo "\n" . '<option value="default" ' . $selected . ' >DEFAULT</option>' . "\r"; + foreach ($a_rules as $value) + { + $selected = ''; + if ($value['uuid'] == $a_list['ruledbname']) { + $selected = 'selected'; + } + + echo "\n" . '<option value="' . $value['uuid'] . '" ' . $selected . ' >' . strtoupper($value['ruledbname']) . '</option>' . "\r"; + } + ?> + + </select> + <br> + <span class="vexpl">Choose the rule database to use. <span class="red">Note:</span> Cahnges to this database are global. + <br> + <span class="red">WARNING:</span> Never change this when snort is running.</span> + </td> + </tr> + + <tr> + <td colspan="2" valign="top" class="listtopic">Choose the networks snort should inspect and whitelist.</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Home net</td> + <td width="78%" class="vtable"> + <select name="homelistname" class="formfld" id="homelistname"> + + <?php + /* find homelist names and filter by type */ + $selected = ''; + if ($a_list['homelistname'] == 'default'){$selected = 'selected';} + echo "\n" . '<option value="default" ' . $selected . ' >DEFAULT</option>' . "\r"; + foreach ($a_whitelist as $value) + { + $selected = ''; + if ($value['filename'] == $a_list['homelistname']){$selected = 'selected';}; + if ($value['snortlisttype'] == 'netlist') // filter + { + + echo "\n" . '<option value="' . $value['filename'] . '" ' . $selected . ' >' . strtoupper($value['filename']) . '</option>' . "\r"; + + } + } + ?> + + </select> + <br> + <span class="vexpl">Choose the home net you will like this rule to use. <span class="red">Note:</span> Default homenet adds only local networks. + <br> + <span class="red">Hint:</span> Most users add a list offriendly ips that the firewall cant see.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">External net</td> + <td width="78%" class="vtable"> + <select name="externallistname" class="formfld" id="externallistname"> + + <?php + /* find externallist names and filter by type */ + $selected = ''; + if ($a_list['externallistname'] == 'default'){$selected = 'selected';} + echo "\n" . '<option value="default" ' . $selected . ' >DEFAULT</option>' . "\r"; + foreach ($a_whitelist as $value) + { + $selected = ''; + if ($value['filename'] == $a_list['externallistname']){$selected = 'selected';} + if ($value['snortlisttype'] == 'netlist') // filter + { + + echo "\n" . '<option value="' . $value['filename'] . '" ' . $selected . ' >' . strtoupper($value['filename']) . '</option>' . "\r"; + + } + } + ?> + + </select> + <br> + <span class="vexpl">Choose the external net you will like this rule to use. <span class="red">Note:</span> Default external net, networks that are not home net. + <br> + <span class="red">Hint:</span> Most users should leave this setting at default.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Block offenders</td> + <td width="78%" class="vtable"> + <input name="blockoffenders7" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['blockoffenders7'] == 'on' ? 'checked' : '';?> > + <br> + <span class="vexpl">Checking this option will automatically block hosts that generate a Snort alerts with SnortSam.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Suppression and filtering</td> + <td width="78%" class="vtable"> + <select name="suppresslistname" class="formfld" id="suppresslistname"> + + <?php + /* find suppresslist names and filter by type */ + $selected = ''; + if ($a_list['suppresslistname'] == 'default'){$selected = 'selected';} + + echo "\n" . '<option value="default" ' . $selected . ' >DEFAULT</option>' . "\r"; + + foreach ($a_suppresslist as $value) + { + $selected = ''; + if ($value['filename'] == $a_list['suppresslistname']){$selected = 'selected';} + + echo "\n" . '<option value="' . $value['filename'] . '" ' . $selected . ' >' . strtoupper($value['filename']) . '</option>' . "\r"; + } + ?> + + </select> + <br> + <span class="vexpl">Choose the suppression or filtering file you will like this rule to use. <span class="red"> + Note:</span> Default option disables suppression and filtering.</span> + </td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic">Choose the types of logs snort should create.</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Type of Unified Logging</td> + <td width="78%" class="vtable"> + <select name="snortalertlogtype" class="formfld" id="snortalertlogtype"> + + <?php + $snortalertlogtypePerfList = array('full' => 'FULL', 'fast' => 'FAST', 'disable' => 'DISABLE'); + snortDropDownList($snortalertlogtypePerfList, $a_list['snortalertlogtype']); + ?> + + </select> + <br> + <span class="vexpl">Snort will log Alerts to a file in the UNIFIED format. Full is a requirement for the snort wigdet.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Send alerts to mainSystem logs</td> + <td width="78%" class="vtable"> + <input name="alertsystemlog" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['alertsystemlog'] == 'on' ? 'checked' : '';?> > + <br> + <span class="vexpl">Snort will send Alerts to the Pfsense system logs.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Log to a Tcpdump file</td> + <td width="78%" class="vtable"> + <input name="tcpdumplog" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['tcpdumplog'] == 'on' ? 'checked' : '';?> > + <br> + <span class="vexpl">Snort will log packets to a tcpdump-formatted file. The file then can be analyzed by an application such as Wireshark which understands pcap file formats. + <span class="red"><strong>WARNING:</strong></span> File may become large.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Log Alerts to a snort unified2 file</td> + <td width="78%" class="vtable"> + <input name="snortunifiedlog" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['snortunifiedlog'] == 'on' ? 'checked' : '';?> > + <br> + <span class="vexpl">Snort will log Alerts to a file in the UNIFIED2 format. This is a requirement for barnyard2.</span> + </td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic">Arguments here will be automatically inserted into the snort configuration.</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Advanced configuration pass through</td> + <td width="78%" class="vtable"> + <textarea wrap="off" name="configpassthru" cols="75" rows="12" id="configpassthru" class="formpre2"><?=base64_decode($a_list['configpassthru']); ?></textarea> + </td> + </tr> + <tr> + <td width="22%" valign="top"></td> + <td width="78%"> + <input name="Submit" type="submit" class="formbtn" value="Save"> + <input name="Submit2" type="submit" class="formbtn" value="Start"> + <input id="cancel" type="button" class="formbtn" value="Cancel"> + </td> + </tr> + <tr> + <td width="22%" valign="top"> </td> + <td width="78%"> + <span class="vexpl"><span class="red"><strong>Note:</strong></span> + Please save your settings before you click start.</span> + </td> + </tr> + </table> + </form> + + <!-- STOP MAIN AREA --> + </table> + </td> + </tr> + </table> + </td> + </tr> +</table> +</div> + + +<!-- footer do not touch below --> +<?php +include("fend.inc"); +echo $snort_custom_rnd_box; +?> + + +</body> +</html> diff --git a/config/snort-dev/snortsam-package-code/snort_interfaces_global.php b/config/snort-dev/snortsam-package-code/snort_interfaces_global.php new file mode 100644 index 00000000..fd9d27d4 --- /dev/null +++ b/config/snort-dev/snortsam-package-code/snort_interfaces_global.php @@ -0,0 +1,367 @@ +<?php +/* $Id$ */ +/* + + part of pfSense + All rights reserved. + + Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + All rights reserved. + + Pfsense Old snort GUI + Copyright (C) 2006 Scott Ullrich. + + Pfsense snort GUI + Copyright (C) 2008-2012 Robert Zelaya. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the pfSense nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + + 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_new.inc"); +require_once("/usr/local/pkg/snort/snort_gui.inc"); + +//Set no caching +header("Expires: Mon, 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"); + +// set page vars + +$generalSettings = snortSql_fetchAllSettings('snortDB', 'SnortSettings', 'id', '1'); + +$snortdownload_off = ($generalSettings['snortdownload'] == 'off' ? 'checked' : ''); +$snortdownload_on = ($generalSettings['snortdownload'] == 'on' ? 'checked' : ''); +$oinkmastercode = $generalSettings['oinkmastercode']; + +$emergingthreatsdownload_off = ($generalSettings['emergingthreatsdownload'] == 'off' ? 'checked' : ''); +$emergingthreatsdownload_basic = ($generalSettings['emergingthreatsdownload'] == 'basic' ? 'checked' : ''); +$emergingthreatsdownload_pro = ($generalSettings['emergingthreatsdownload'] == 'pro' ? 'checked' : ''); +$emergingthreatscode = $generalSettings['emergingthreatscode']; + +$updaterules = $generalSettings['updaterules']; + +$rm_blocked = $generalSettings['rm_blocked']; + +$snortloglimit_off = ($generalSettings['snortloglimit'] == 'off' ? 'checked' : ''); +$snortloglimit_on = ($generalSettings['snortloglimit'] == 'on' ? 'checked' : ''); + +$snortloglimitsize = $generalSettings['snortloglimitsize']; + +$snortalertlogtype = $generalSettings['snortalertlogtype']; + +$forcekeepsettings_on = ($generalSettings['forcekeepsettings'] == 'on' ? 'checked' : ''); + +$snortlogCurrentDSKsize = round(exec('df -k /var | grep -v "Filesystem" | awk \'{print $4}\'') / 1024); + + + $pgtitle = "Services: Snort: Global Settings"; + include("/usr/local/pkg/snort/snort_head.inc"); + +?> + + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + +<!-- loading msg --> +<div id="loadingWaiting"> + <div class="snortModal"> + <div class="snortModalTop"> + <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> + </div> + <div class="snortModalTitle"> + <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> + </div> + <div> + <p class="loadingWaitingMessage"></p> + </div> + </div> +</div> + + +<?php include("fbegin.inc"); ?> +<!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"> +<a href="../index.php" id="status-link2"> +<img src="./images/transparent.gif" border="0"></img> +</a> +</div> + +<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> + +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td> + + <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> + <ul class="newtabmenu"> + <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> + <li class="newtabmenu_active"><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> + <li><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> + <li><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> + <li><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> + <li><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> + <li><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> + <li><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> + <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> + </ul> + </div> + + </td> + </tr> + <tr> + <td id="tdbggrey"> + <table width="100%" border="0" cellpadding="10px" cellspacing="0"> + <tr> + <td class="tabnavtbl"> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <!-- START MAIN AREA --> + + <form id="iform" > + <input type="hidden" name="snortSaveSettings" value="1" /> <!-- what to do, save --> + <input type="hidden" name="dbName" value="snortDB" /> <!-- what db --> + <input type="hidden" name="dbTable" value="SnortSettings" /> <!-- what db table --> + <input type="hidden" name="ifaceTab" value="snort_interfaces_global" /> <!-- what interface tab --> + + <tr id="maintable" data-options='{"pagetable":"SnortSettings"}'> <!-- db to lookup --> + <td colspan="2" valign="top" class="listtopic">Please Choose The Type Of Rules You Wish To Download</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Install Snort.org rules</td> + <td width="78%" class="vtable"> + <table cellpadding="0" cellspacing="0"> + <tr> + <td colspan="2"> + <input name="snortdownload" type="radio" id="snortdownloadoff" value="off" <?=$snortdownload_off;?> > + <span class="vexpl">Do <strong>NOT</strong> Install</span> + </td> + </tr> + <tr> + <td colspan="2"> + <input name="snortdownload" type="radio" id="snortdownloadon" value="on" <?=$snortdownload_on;?> > + <span class="vexpl">Install Basic Rules or Premium rules</span> <br> + </td> + </tr> + </table> + <table STYLE="padding-top: 5px"> + <tr> + <td colspan="2"> + <a class="vncell2" href="https://www.snort.org/signup" target="_blank" alt="Basic rules are free but 30 days old."> + Sign Up for a Basic Rule Account + </a><br><br> + <a class="vncell2" href="http://www.snort.org/vrt/buy-a-subscription" target="_blank" alt="Premium users receive rules 30 days faster than basic users."> + Sign Up for Sourcefire VRT Certified Premium Rules. This Is Highly Recommended + </a> + </td> + </tr> + </table> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <tr> + <td colspan="2" valign="top"><span class="vexpl">Oinkmaster code</span></td> + </tr> + <tr> + <td class="vncell2" valign="top"><span class="vexpl">Code</span></td> + <td class="vtable"> + <input name="oinkmastercode" type="text"class="formfld2" id="oinkmastercode" size="52" value="<?=$oinkmastercode;?>" > <br> + <span class="vexpl">Obtain a snort.org Oinkmaster code and paste here.</span> + </td> + </table> + </tr> + + <tr> + <td width="22%" valign="top" class="vncell2">Install Emergingthreats rules</td> + <td width="78%" class="vtable"> + <table cellpadding="0" cellspacing="0"> + <tr> + <td colspan="2"> + <input name="emergingthreatsdownload" type="radio" id="emergingthreatsdownloadoff" value="off" <?=$emergingthreatsdownload_off;?> > + <span class="vexpl">Do <strong>NOT</strong> Install</span> + </td> + </tr> + <tr> + <td colspan="2"> + <input name="emergingthreatsdownload" type="radio" id="emergingthreatsdownloadon" value="basic" <?=$emergingthreatsdownload_basic;?> > + <span class="vexpl">Install <b>Basic</b> Rules: No need to register</span> <br> + </td> + </tr> + <tr> + <td colspan="2"> + <input name="emergingthreatsdownload" type="radio" id="emergingthreatsprodownloadon" value="pro" <?=$emergingthreatsdownload_pro;?> > + <span class="vexpl">Install <b>Pro</b> rules: You need to register</span> <br> + </td> + </tr> + </table> + <table STYLE="padding-top: 5px"> + <tr> + <td colspan="2"> + <a class="vncell2" href="http://www.emergingthreatspro.com" target="_blank" alt="Premium users receive rules 30 days faster than basic users."> + Sign Up for Emerging Threats Pro Certified Premium Rules. This Is Highly Recommended + </a> + </td> + </tr> + </table> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <tr> + <td colspan="2" valign="top"><span class="vexpl">Pro rules code</span></td> + </tr> + <tr> + <td class="vncell2" valign="top"><span class="vexpl">Code</span></td> + <td class="vtable"> + <input name="emergingthreatscode" type="text"class="formfld2" id="emergingthreatscode" size="52" value="<?=$emergingthreatscode;?>" > <br> + <span class="vexpl">Obtain a emergingthreatspro.com Pro rules code and paste here.</span> + </td> + </table> + </tr> + + <tr> + <td width="22%" valign="top" class="vncell2"><span>Update rules automatically</span></td> + <td width="78%" class="vtable"> + <select name="updaterules" class="formfld2" id="updaterules"> + <?php + $updateDaysList = array('never' => 'NEVER', '6h_up' => '6 HOURS', '12h_up' => '12 HOURS', '1d_up' => '1 DAY', '4d_up' => '4 DAYS', '7d_up' => '7 DAYS', '28d_up' => '28 DAYS'); + snortDropDownList($updateDaysList, $updaterules); + ?> + </select><br> + <span class="vexpl"> + Please select the update times for rules.<br> Hint: in most cases, every 12 hours is a good choice. + </span> + </td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic"><span>General Settings</span></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2"><span>Log Directory SizeLimit</span><br> + <br><br><br><br><br> + <span class="red"><strong>Note:</strong><br>Available space is <strong><?=$snortlogCurrentDSKsize; ?>MB</strong></span> + </td> + <td width="78%" class="vtable"> + <table cellpadding="0" cellspacing="0"> + <tr> + <td colspan="2"> + <input name="snortloglimit" type="radio" id="snortloglimiton" value="on" <?=$snortloglimit_on;?> > + <span class="vexpl"><strong>Enable</strong> directory size limit (Default)</span> + </td> + </tr> + <tr> + <td colspan="2"> + <input name="snortloglimit" type="radio" id="snortloglimitoff" value="off" <?=$snortloglimit_off ?> > + <span class="vexpl"><strong>Disable </strong>directory size limit</span><br><br> + <span class="vexpl red"><strong>Warning:</strong> Pfsense Nanobsd should use no more than 10MB of space.</span> + </td> + </tr> + <tr> + <td> </td> + </tr> + </table> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <tr> + <td class="vncell3"><span>Size in <strong>MB</strong></span></td> + <td class="vtable"> + <input name="snortloglimitsize" type="text" class="formfld2" id="snortloglimitsize" size="7" value="<?=$snortloglimitsize;?>"> + <span class="vexpl">Default is <strong>20%</strong> of available space.</span> + </td> + </table> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2"><span>Remove blocked hosts every</span></td> + <td width="78%" class="vtable"> + <select name="rm_blocked" class="formfld2" id="rm_blocked"> + <?php + $BlockTimeReset = array('never' => 'NEVER', '1h_b' => '1 HOUR', '3h_b' => '3 HOURS', '6h_b' => '6 HOURS', '12h_b' => '12 HOURS', '1d_b' => '1 DAY', '4d_b' => '4 DAYS', '7d_b' => '7 DAYS', '28d_b' => '28 DAYS'); + snortDropDownList($BlockTimeReset, $rm_blocked); + ?> + </select><br> + <span class="vexpl">Please select the amount of time you would likehosts to be blocked for.<br>Hint: in most cases, 1 hour is a good choice.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2"><span>Alerts file descriptiontype</span></td> + <td width="78%" class="vtable"> + <select name="snortalertlogtype" class="formfld2" id="snortalertlogtype"> + <?php + // TODO: make this option a check box with all log types + $alertLogTypeList = array('full' => 'FULL', 'fast' => 'SHORT'); + snortDropDownList($alertLogTypeList, $snortalertlogtype) + ?> + </select><br> + <span class="vexpl">Please choose the type of Alert logging you will like see in your alert file.<br> Hint: Best pratice is to chose full logging.</span> + <span class="red"><strong>WARNING:</strong></span> <strong>On change, alert file will be cleared.</strong> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2"><span>Keep snort settings after deinstall</span></td> + <td width="22%" class="vtable"> + <input name="forcekeepsettings" id="forcekeepsettings" type="checkbox" value="on" <?=$forcekeepsettings_on;?> > + <span class="vexpl">Settings will not be removed during deinstall.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2"><span>Save Settings</span></td> + <td width="30%" class="vtable"> + <input name="Submit" type="submit" class="formbtn" value="Save"> + <input id="cancel" type="button" class="formbtn" value="Cancel"> + </td> + </tr> + </form> + <form id="iform2" > + <tr> + <td width="22%" valign="top" class="vncell2"> + <input name="Reset" type="submit" class="formbtn" value="Reset" onclick="return confirm('Do you really want to remove all your settings ? All Snort Settings will be reset !')" > + <input type="hidden" name="reset_snortgeneralsettings" value="1" /> + <span class="vexpl red"><strong> WARNING:</strong><br> This will reset all global and interface settings.</span> + </td> + <td class="vtable"> + <span class="vexpl red"><strong>Note:</strong></span><br> + <span class="vexpl">Changing any settings on this page will affect all interfaces. Please, double check if your oink code is correct and the type of snort.org account you hold.</span> + </td> + </tr> + </form> + + <!-- STOP MAIN AREA --> + </table> + </td> + </tr> + </table> + </td> + </tr> +</table> +</div> + + +<!-- footer do not touch below --> +<?php +include("fend.inc"); +echo $snort_custom_rnd_box; +?> + + +</body> +</html> diff --git a/config/snort-dev/snort_interfaces_rules.php b/config/snort-dev/snortsam-package-code/snort_interfaces_rules.php index 12f9cec0..12f9cec0 100644 --- a/config/snort-dev/snort_interfaces_rules.php +++ b/config/snort-dev/snortsam-package-code/snort_interfaces_rules.php diff --git a/config/snort-dev/snort_interfaces_rules_edit.php b/config/snort-dev/snortsam-package-code/snort_interfaces_rules_edit.php index be6467bc..be6467bc 100644 --- a/config/snort-dev/snort_interfaces_rules_edit.php +++ b/config/snort-dev/snortsam-package-code/snort_interfaces_rules_edit.php diff --git a/config/snort-dev/snortsam-package-code/snort_interfaces_suppress.php b/config/snort-dev/snortsam-package-code/snort_interfaces_suppress.php new file mode 100644 index 00000000..977dcf2d --- /dev/null +++ b/config/snort-dev/snortsam-package-code/snort_interfaces_suppress.php @@ -0,0 +1,211 @@ +<?php +/* $Id$ */ +/* + + part of pfSense + All rights reserved. + + Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + All rights reserved. + + Pfsense Old snort GUI + Copyright (C) 2006 Scott Ullrich. + + Pfsense snort GUI + Copyright (C) 2008-2012 Robert Zelaya. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the pfSense nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + + 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_new.inc"); +require_once("/usr/local/pkg/snort/snort_gui.inc"); + +//Set no caching +header("Expires: Mon, 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"); + + +$a_suppress = snortSql_fetchAllWhitelistTypes('SnortSuppress', ''); + + if (!is_array($a_suppress)) + { + $a_suppress = array(); + } + + + if ($a_suppress == 'Error') + { + echo 'Error'; + exit(0); + } + + $pgtitle = "Services: Snort: Suppression"; + include("/usr/local/pkg/snort/snort_head.inc"); + +?> + + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + +<!-- loading msg --> +<div id="loadingWaiting"> + <div class="snortModal" style="top: 200px; left: 700px;"> + <div class="snortModalTop"> + <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> + </div> + <div class="snortModalTitle"> + <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> + </div> + <div> + <p class="loadingWaitingMessage"></p> + </div> + </div> +</div> + +<?php include("fbegin.inc"); ?> +<!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"> +<a href="../index.php" id="status-link2"> +<img src="./images/transparent.gif" border="0"></img> +</a> +</div> + +<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> + +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td> + + <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> + <ul class="newtabmenu"> + <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> + <li><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> + <li><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> + <li><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> + <li><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> + <li><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> + <li><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> + <li class="newtabmenu_active"><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> + <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> + </li> + </ul> + </div> + + </td> + </tr> + <tr> + <td id="tdbggrey"> + <table width="100%" border="0" cellpadding="10px" cellspacing="0"> + <tr> + <td class="tabnavtbl"> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <!-- START MAIN AREA --> + + <tr> <!-- db to lookup --> + <td width="30%" class="listhdrr">File Name</td> + <td width="70%" class="listhdr">Description</td> + <td width="10%" class="list"></td> + </tr> + <?php foreach ($a_suppress as $list): ?> + <tr id="maintable_<?=$list['uuid']?>" data-options='{"pagetable":"SnortSuppress", "pagedb":"snortDB", "DoPOST":"true"}' > + <td class="listlr" ondblclick="document.location='snort_interfaces_suppress_edit.php?uuid=<?=$list['uuid'];?>'"><?=$list['filename'];?></td> + <td class="listbg" ondblclick="document.location='snort_interfaces_suppress_edit.php?uuid=<?=$list['uuid'];?>'"> + <font color="#FFFFFF"> <?=htmlspecialchars($list['description']);?> + </td> + <td></td> + <td valign="middle" nowrap class="list"> + <table border="0" cellspacing="0" cellpadding="1"> + <tr> + <td valign="middle"> + <a href="snort_interfaces_suppress_edit.php?uuid=<?=$list['uuid'];?>"><img src="/themes/<?= $g['theme']; ?>/images/icons/icon_e.gif"width="17" height="17" border="0" title="edit suppress list"></a> + </td> + <td> + <img id="icon_x_<?=$list['uuid'];?>" class="icon_click icon_x" src="/themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" width="17" height="17" border="0" title="delete list" > + </a> + </td> + </tr> + </table> + </td> + </tr> + <?php $i++; endforeach; ?> + <tr> + <td class="list" colspan="3"></td> + <td class="list"> + <table border="0" cellspacing="0" cellpadding="1"> + <tr> + <td valign="middle" width="17"> </td> + <td valign="middle"><a href="snort_interfaces_suppress_edit.php?uuid=<?=genAlphaNumMixFast(28, 28);?> "><img src="/themes/nervecenter/images/icons/icon_plus.gif" width="17" height="17" border="0" title="add a new list"></a></td> + </tr> + </table> + </td> + </tr> + </table> + </td> + </tr> + + <!-- STOP MAIN AREA --> + </table> + </td> + </tr> + + </table> + </td> + </tr> +</table> + +<!-- 2nd box note --> +<br> +<div id=mainarea4> +<table class="tabcont" width="100%" border="0" cellpadding="0" cellspacing="0"> + <td width="100%"> + <span class="vexpl"> + <span class="red"><strong>Note:</strong></span> + <p><span class="vexpl"> + Here you can create event filtering and suppression for your snort package rules.<br> + Please note that you must restart a running rule so that changes can take effect.<br> + </span></p> + </td> +</table> +</div> + +</div> + + +<!-- footer do not touch below --> +<?php +include("fend.inc"); +echo $snort_custom_rnd_box; +?> + + +</body> +</html> diff --git a/config/snort-dev/snortsam-package-code/snort_interfaces_suppress_edit.php b/config/snort-dev/snortsam-package-code/snort_interfaces_suppress_edit.php new file mode 100644 index 00000000..e9f23254 --- /dev/null +++ b/config/snort-dev/snortsam-package-code/snort_interfaces_suppress_edit.php @@ -0,0 +1,231 @@ +<?php +/* $Id$ */ +/* + + part of pfSense + All rights reserved. + + Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + All rights reserved. + + Pfsense Old snort GUI + Copyright (C) 2006 Scott Ullrich. + + Pfsense snort GUI + Copyright (C) 2008-2012 Robert Zelaya. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the pfSense nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + + 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_new.inc"); +require_once("/usr/local/pkg/snort/snort_gui.inc"); + +//Set no caching +header("Expires: Mon, 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"); + +// set page vars + +$uuid = $_GET['uuid']; +if (isset($_POST['uuid'])) +$uuid = $_POST['uuid']; + +if ($uuid == '') { + echo 'error: no uuid'; + exit(0); +} + +$a_list = snortSql_fetchAllSettings('snortDB', 'SnortSuppress', 'uuid', $uuid); + + +// $a_list returns empty use defaults +if ($a_list == '') +{ + + $a_list = array( + 'id' => '', + 'date' => date(U), + 'uuid' => $uuid, + 'filename' => '', + 'description' => '', + 'suppresspassthru' => '' + + ); + +} + + + + + $pgtitle = 'Services: Snort: Suppression: Edit'; + include('/usr/local/pkg/snort/snort_head.inc'); + +?> + + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + +<!-- loading msg --> +<div id="loadingWaiting"> + <div class="snortModal" style="top: 200px; left: 700px;"> + <div class="snortModalTop"> + <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> + </div> + <div class="snortModalTitle"> + <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> + </div> + <div> + <p class="loadingWaitingMessage"></p> + </div> + </div> +</div> + +<?php include("fbegin.inc"); ?> +<!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"> +<a href="../index.php" id="status-link2"> +<img src="./images/transparent.gif" border="0"></img> +</a> +</div> + +<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> + +<form id="iform"> + +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td> + + <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> + <ul class="newtabmenu"> + <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> + <li><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> + <li><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> + <li><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> + <li><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> + <li><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> + <li><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> + <li class="newtabmenu_active"><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> + <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> + </li> + </ul> + </div> + + </td> + </tr> + <tr> + <td id="tdbggrey"> + <table width="100%" border="0" cellpadding="10px" cellspacing="0"> + <tr> + <td class="tabnavtbl"> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <!-- START MAIN AREA --> + + <!-- table point --> + <input name="snortSaveSuppresslist" type="hidden" value="1" /> + <input name="ifaceTab" type="hidden" value="snort_interfaces_suppress_edit" /> + <input type="hidden" name="dbName" value="snortDB" /> <!-- what db --> + <input type="hidden" name="dbTable" value="SnortSuppress" /> <!-- what db table --> + <input name="date" type="hidden" value="<?=$a_list['date'];?>" /> + <input name="uuid" type="hidden" value="<?=$a_list['uuid'];?>" /> + + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <tr> + <td colspan="2" valign="top" class="listtopic">Add the name anddescription of the file.</td> + </tr> + <tr> + <td valign="top" class="vncellreq2">Name</td> + <td class="vtable"> + <input class="formfld2" name="filename" type="text" id="filename" size="40" value="<?=$a_list['filename'] ?>" /> <br /> + <span class="vexpl"> The list name may only consist of the characters a-z, A-Z and 0-9. <span class="red">Note: </span> No Spaces. </span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Description</td> + <td width="78%" class="vtable"> + <input class="formfld2" name="description" type="text" id="description" size="40" value="<?=$a_list['description'] ?>" /> <br /> + <span class="vexpl"> You may enter a description here for your reference (not parsed). </span> + </td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic"> + Examples: + </td> + </tr> + <tr> + <td colspan="2" valign="top" class="vncell2"> + <b>Example 1;</b> suppress gen_id 1, sig_id 1852, track by_src, ip 10.1.1.54<br> + <b>Example 2;</b> event_filter gen_id 1, sig_id 1851, type limit,track by_src, count 1, seconds 60<br> + <b>Example 3;</b> rate_filter gen_id 135, sig_id 1, track by_src, count 100, seconds 1, new_action log, timeout 10 + </td> + </tr> + </table> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td colspan="2" valign="top" class="listtopic"> + Apply suppression or filters to rules. Valid keywords are 'suppress', 'event_filter' and 'rate_filter'. + </td> + </tr> + <tr> + <td colspan="2" valign="top" class="vncelltextbox"> + <textarea wrap="off" name="suppresspassthru" cols="101" rows="28" id="suppresspassthru" class="formfld2"><?=base64_decode($a_list['suppresspassthru']); ?></textarea> + </td> + </tr> + </table> + <tr> + <td style="padding-left: 160px;"> + <input name="Submit" type="submit" class="formbtn" value="Save"> + <input id="cancel" type="button" class="formbtn" value="Cancel"> + </td> + </tr> + </form> + + <!-- STOP MAIN AREA --> + </table> + </td> + </tr> + </table> + </td> + </tr> +</table> +</div> + + +<!-- footer do not touch below --> +<?php +include("fend.inc"); +echo $snort_custom_rnd_box; +?> + + +</body> +</html> diff --git a/config/snort-dev/snortsam-package-code/snort_interfaces_whitelist.php b/config/snort-dev/snortsam-package-code/snort_interfaces_whitelist.php new file mode 100644 index 00000000..3167b65f --- /dev/null +++ b/config/snort-dev/snortsam-package-code/snort_interfaces_whitelist.php @@ -0,0 +1,241 @@ +<?php +/* $Id$ */ +/* + + part of pfSense + All rights reserved. + + Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + All rights reserved. + + Pfsense Old snort GUI + Copyright (C) 2006 Scott Ullrich. + + Pfsense snort GUI + Copyright (C) 2008-2012 Robert Zelaya. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the pfSense nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + + 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_new.inc"); +require_once("/usr/local/pkg/snort/snort_gui.inc"); + +//Set no caching +header("Expires: Mon, 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"); + + +$a_whitelist = snortSql_fetchAllWhitelistTypes('SnortWhitelist', 'SnortWhitelistips'); + + if (!is_array($a_whitelist)) + { + $a_whitelist = array(); + } + + if ($a_whitelist == 'Error') + { + echo 'Error'; + exit(0); + } + + $pgtitle = "Services: Snort: Whitelist"; + include("/usr/local/pkg/snort/snort_head.inc"); + +?> + + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + +<!-- loading msg --> +<div id="loadingWaiting"> + <div class="snortModal" style="top: 200px; left: 700px;"> + <div class="snortModalTop"> + <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> + </div> + <div class="snortModalTitle"> + <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> + </div> + <div> + <p class="loadingWaitingMessage"></p> + </div> + </div> +</div> + +<?php include("fbegin.inc"); ?> +<!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"> +<a href="../index.php" id="status-link2"> +<img src="./images/transparent.gif" border="0"></img> +</a> +</div> + +<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> + +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td> + + <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> + <ul class="newtabmenu"> + <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> + <li><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> + <li><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> + <li><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> + <li><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> + <li><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> + <li class="newtabmenu_active"><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> + <li><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> + <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> + </li> + </ul> + </div> + + </td> + </tr> + <tr> + <td id="tdbggrey"> + <table width="100%" border="0" cellpadding="10px" cellspacing="0"> + <tr> + <td class="tabnavtbl"> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <!-- START MAIN AREA --> + + <tr> <!-- db to lookup --> + <td width="20%" class="listhdrr">File Name</td> + <td width="45%" class="listhdrr">Values</td> + <td width="35%" class="listhdr">Description</td> + <td width="10%" class="list"></td> + </tr> + <?php foreach ($a_whitelist as $list): ?> + <tr id="maintable_<?=$list['uuid']?>" data-options='{"pagetable":"SnortWhitelist", "pagedb":"snortDB", "DoPOST":"true"}' > + <td class="listlr" ondblclick="document.location='snort_interfaces_whitelist_edit.php?uuid=<?=$list['uuid'];?>'"><?=$list['filename'];?></td> + <td class="listr" ondblclick="document.location='snort_interfaces_whitelist_edit.php?uuid=<?=$list['uuid'];?>'"> + <?php + $a = 0; + $countList = count($list['list']); + foreach ($list['list'] as $value) + { + + $a++; + + if ($a != $countList || $countList == 1) + { + echo $value['ip']; + } + + if ($a > 0 && $a != $countList) + { + echo ',' . ' '; + }else{ + echo ' '; + } + + } // end foreach + + if ($a > 3) + { + echo '...'; + } + ?> + </td> + <td class="listbg" ondblclick="document.location='snort_interfaces_whitelist_edit.php?uuid=<?=$list['uuid'];?>'"> + <font color="#FFFFFF"> <?=htmlspecialchars($list['description']);?> + </td> + <td valign="middle" nowrap class="list"> + <table border="0" cellspacing="0" cellpadding="1"> + <tr> + <td valign="middle"> + <a href="snort_interfaces_whitelist_edit.php?uuid=<?=$list['uuid'];?>"><img src="/themes/<?= $g['theme']; ?>/images/icons/icon_e.gif"width="17" height="17" border="0" title="edit whitelist"></a> + </td> + <td> + <img id="icon_x_<?=$list['uuid'];?>" class="icon_click icon_x" src="/themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" width="17" height="17" border="0" title="delete list" > + </a> + </td> + </tr> + </table> + </td> + </tr> + <?php $i++; endforeach; ?> + <tr> + <td class="list" colspan="3"></td> + <td class="list"> + <table border="0" cellspacing="0" cellpadding="1"> + <tr> + <td valign="middle" width="17"> </td> + <td valign="middle"><a href="snort_interfaces_whitelist_edit.php?uuid=<?=genAlphaNumMixFast(28, 28);?> "><img src="/themes/nervecenter/images/icons/icon_plus.gif" width="17" height="17" border="0" title="add a new list"></a></td> + </tr> + </table> + </td> + </tr> + </table> + </td> + </tr> + + <!-- STOP MAIN AREA --> + </table> + </td> + </tr> + + </table> + </td> + </tr> +</table> + +<!-- 2nd box note --> +<br> +<div id=mainarea4> +<table class="tabcont" width="100%" border="0" cellpadding="0" cellspacing="0"> + <td width="100%"> + <span class="vexpl"> + <span class="red"><strong>Note:</strong></span> + <p><span class="vexpl"> + Here you can create whitelist files for your snort package rules.<br> + Please add all the ips or networks you want to protect against snort block decisions.<br> + Remember that the default whitelist only includes local networks.<br> + Be careful, it is very easy to get locked out of you system. + </span></p> + </td> +</table> +</div> + +</div> + + +<!-- footer do not touch below --> +<?php +include("fend.inc"); +echo $snort_custom_rnd_box; +?> + + +</body> +</html> diff --git a/config/snort-dev/snortsam-package-code/snort_interfaces_whitelist_edit.php b/config/snort-dev/snortsam-package-code/snort_interfaces_whitelist_edit.php new file mode 100644 index 00000000..dbdbb649 --- /dev/null +++ b/config/snort-dev/snortsam-package-code/snort_interfaces_whitelist_edit.php @@ -0,0 +1,341 @@ +<?php +/* $Id$ */ +/* + + part of pfSense + All rights reserved. + + Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + All rights reserved. + + Pfsense Old snort GUI + Copyright (C) 2006 Scott Ullrich. + + Pfsense snort GUI + Copyright (C) 2008-2012 Robert Zelaya. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the pfSense nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + + 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_new.inc'); +require_once('/usr/local/pkg/snort/snort_gui.inc'); + +//Set no caching +header("Expires: Mon, 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"); + +//$GLOBALS['csrf']['rewrite-js'] = false; + +$uuid = $_GET['uuid']; +if (isset($_POST['uuid'])) +$uuid = $_POST['uuid']; + +if ($uuid == '') { + echo 'error: no uuid'; + exit(0); +} + +$a_list = snortSql_fetchAllSettings('snortDB', 'SnortWhitelist', 'uuid', $uuid); + +// $a_list returns empty use defaults +if ($a_list == '') +{ + + $a_list = array( + 'id' => '', + 'date' => date(U), + 'uuid' => $uuid, + 'filename' => '', + 'snortlisttype' => 'whitelist', + 'description' => '', + 'wanips' => 'on', + 'wangateips' => 'on', + 'wandnsips' => 'on', + 'vips' => 'on', + 'vpnips' => 'on' + ); + +} + +$listFilename = $a_list['filename']; + +$a_list['list'] = snortSql_fetchAllSettingsList('SnortWhitelistips', $listFilename); + +$wanips_chk = $a_list['wanips']; +$wanips_on = ($wanips_chk == 'on' ? 'checked' : ''); + +$wangateips_chk = $a_list['wangateips']; +$wangateips_on = ($wangateips_chk == 'on' ? 'checked' : ''); + +$wandnsips_chk = $a_list['wandnsips']; +$wandnsips_on = ($wandnsips_chk == 'on' ? 'checked' : ''); + +$vips_chk = $a_list['vips']; +$vips_on = ($vips_chk == 'on' ? 'checked' : ''); + +$vpnips_chk = $a_list['vpnips']; +$vpnips_on = ($vpnips_chk == 'on' ? 'checked' : ''); + + + + $pgtitle = "Services: Snort: Whitelist Edit"; + include("/usr/local/pkg/snort/snort_head.inc"); + +?> + + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + +<!-- loading msg --> +<div id="loadingWaiting"> + <div class="snortModal" style="top: 200px; left: 700px;"> + <div class="snortModalTop"> + <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> + </div> + <div class="snortModalTitle"> + <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> + </div> + <div> + <p class="loadingWaitingMessage"></p> + </div> + </div> +</div> + +<?php include("fbegin.inc"); ?> +<!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"> +<a href="../index.php" id="status-link2"> +<img src="./images/transparent.gif" border="0"></img> +</a> +</div> + +<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> + +<form id="iform"> + +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td> + + <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> + <ul class="newtabmenu"> + <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> + <li><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> + <li><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> + <li><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> + <li><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> + <li><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> + <li class="newtabmenu_active"><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> + <li><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> + <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> + </ul> + </div> + + </td> + </tr> + <tr> + <td id="tdbggrey"> + <table width="100%" border="0" cellpadding="10px" cellspacing="0"> + <tr> + <td class="tabnavtbl"> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <!-- START MAIN AREA --> + + <!-- table point --> + <input name="snortSaveWhitelist" type="hidden" value="1" /> + <input name="ifaceTab" type="hidden" value="snort_interfaces_whitelist_edit" /> + <input type="hidden" name="dbName" value="snortDB" /> <!-- what db --> + <input type="hidden" name="dbTable" value="SnortWhitelist" /> <!-- what db table --> + <input name="date" type="hidden" value="<?=$a_list['date'];?>" /> + <input name="uuid" type="hidden" value="<?=$a_list['uuid'];?>" /> + + <tr> + <td colspan="2" valign="top" class="listtopic">Add the name and description of the file.</td> + + </tr> + <tr id="filename" data-options='{"filename":"<?=$listFilename; ?>"}' > + <td valign="top" class="vncellreq2">Name</td> + <td class="vtable"> + <input class="formfld2" name="filename" type="text" id="name" size="40" value="<?=$listFilename; ?>" /> <br /> + <span class="vexpl"> The list name may only consist of the characters a-z, A-Z and 0-9. <span class="red">Note: </span> No Spaces. </span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Description</td> + <td width="78%" class="vtable"> + <input class="formfld2" name="description" type="text" id="descr" size="40" value="<?=$a_list['description']; ?>" /> <br /> + <span class="vexpl"> You may enter a description here for your reference (not parsed). </span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">List Type</td> + <td width="78%" class="vtable"> + <div style="padding: 5px; margin-top: 16px; margin-bottom: 16px; border: 1px dashed #ff3333; background-color: #eee; color: #000; font-size: 8pt;"id="itemhelp"> + <strong>WHITELIST:</strong> This list specifies addresses that Snort Package should not block.<br><br> + <strong>NETLIST:</strong> This list is for defining addresses as $HOME_NET or $EXTERNAL_NET in the snort.conf file. + </div> + <select name="snortlisttype" class="formfld2" id="snortlisttype"> + <?php + $updateDaysList = array('whitelist' => 'WHITELIST', 'netlist' => 'NETLIST'); + snortDropDownList($updateDaysList, $a_list['snortlisttype']); + ?> + </select> + <span class="vexpl"> Choose the type of list you will like see in your <span class="red">Interface Edit Tab</span>.</span> + </td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic">Add auto generated ips.</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">WAN IPs</td> + <td width="78%" class="vtable"> + <input name="wanips" type="checkbox" id="wanips" size="40" value="on" <?=$wanips_on; ?> /> + <span class="vexpl"> Add WAN IPs to the list. </span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Wan Gateways</td> + <td width="78%" class="vtable"> + <input name="wangateips" type="checkbox" id="wangateips" size="40" value="on" <?=$wangateips_on; ?> /> + <span class="vexpl"> Add WAN Gateways to the list. </span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Wan DNS servers</td> + <td width="78%" class="vtable"> + <input name="wandnsips" type="checkbox" id="wandnsips" size="40" value="on" <?=$wandnsips_on; ?> /> + <span class="vexpl"> Add WAN DNS servers to the list. </span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Virtual IP Addresses</td> + <td width="78%" class="vtable"> + <input name="vips" type="checkbox" id="vips" size="40" value="on" <?=$vips_on; ?> /> + <span class="vexpl"> Add Virtual IP Addresses to the list. </span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">VPNs</td> + <td width="78%" class="vtable"> + <input name="vpnips" type="checkbox" id="vpnips" size="40" value="on" <?=$vpnips_on; ?> /> + <span class="vexpl"> Add VPN Addresses to the list. </span> + </td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic">Add your own custom ips.</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncellreq2"> + <div id="addressnetworkport">IP or CIDR items</div> + </td> + <td width="78%" class="vtable"> + <table > + <tbody class="insertrow"> + <tr> + <td colspan="4"> + <div style="width:550px; padding: 5px; margin-top: 16px; margin-bottom: 16px; border: 1px dashed #ff3333; background-color: #eee; color: #000; font-size: 8pt;"id="itemhelp"> + For <strong>WHITELIST's</strong> enter <strong>ONLY IPs not CIDRs</strong>. Example: 192.168.4.1<br><br> + For <strong>NETLIST's</strong> you may enter <strong>IPs and CIDRs</strong>. Example: 192.168.4.1 or 192.168.4.0/24 + </div> + </td> + </tr> + <tr> + <td> + <div id="onecolumn" style="width:175px;"><span class="vexpl">IP or CIDR</span></div> + </td> + <td> + <div id="threecolumn"><span class="vexpl">Add a Description or leave blank and a date will be added.</span></div> + </td> + </tr> + </tbody> + <!-- Start of js loop --> + <tbody id="listloopblock" class="insertrow"> + <?php echo "\r"; $i = 0; foreach ($a_list['list'] as $list): ?> + <tr id="maintable_<?=$list['uuid']?>" data-options='{"pagetable":"SnortWhitelist", "pagedb":"snortDB", "DoPOST":"false"}' > + <td> + <input class="formfld2" name="list[<?=$i; ?>][ip]" type="text" id="address" size="30" value="<?=$list['ip']; ?>" /> + </td> + <td> + <input class="formfld2" name="list[<?=$i; ?>][description]" type="text" id="detail" size="50" value="<?=$list['description'] ?>" /> + </td> + <td> + <img id="icon_x_<?=$list['uuid'];?>" class="icon_click icon_x" src="/themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" width="17" height="17" border="0" title="delete list" > + </td> + <input name="list[<?=$i; ?>][uuid]" type="hidden" value="<?=$list['uuid'];?>" /> + </tr> + <?php echo "\r"; $i++; endforeach; ?> + </tbody> + <!-- End of js loop --> + <tbody> + <tr> + <td> + </td> + <td> + </td> + <td> + <img id="iconplus_<?=$i;?>" class="icon_click icon_plus" src="/themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" width="17" height="17" border="0" title="add list" > + </td> + </tr> + </tbody> + </table> + </td> + </tr> + <tr> + <td width="22%" valign="top"> </td> + <td width="78%"> + <input id="submit" name="submit" type="submit" class="formbtn" value="Save" /> + <input id="cancel" name="cancel" type="button" class="formbtn" value="Cancel"> + </td> + </tr> + </form> + + + <!-- STOP MAIN AREA --> + </table> + </td> + </tr> + </table> + </td> + </tr> +</table> +</div> + + +<!-- footer do not touch below --> +<?php +include("fend.inc"); +echo $snort_custom_rnd_box; +?> + + +</body> +</html> diff --git a/config/snort-dev/snort_json_get.php b/config/snort-dev/snortsam-package-code/snort_json_get.php index 92058a75..92058a75 100644 --- a/config/snort-dev/snort_json_get.php +++ b/config/snort-dev/snortsam-package-code/snort_json_get.php diff --git a/config/snort-dev/snort_json_post.php b/config/snort-dev/snortsam-package-code/snort_json_post.php index 418a90be..418a90be 100644 --- a/config/snort-dev/snort_json_post.php +++ b/config/snort-dev/snortsam-package-code/snort_json_post.php diff --git a/config/snort-dev/snort_new.inc b/config/snort-dev/snortsam-package-code/snort_new.inc index b9fc2322..b9fc2322 100644 --- a/config/snort-dev/snort_new.inc +++ b/config/snort-dev/snortsam-package-code/snort_new.inc diff --git a/config/snort-dev/snortsam-package-code/snort_preprocessors.php b/config/snort-dev/snortsam-package-code/snort_preprocessors.php new file mode 100644 index 00000000..d99f7f75 --- /dev/null +++ b/config/snort-dev/snortsam-package-code/snort_preprocessors.php @@ -0,0 +1,337 @@ +<?php +/* $Id$ */ +/* + + part of pfSense + All rights reserved. + + Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + All rights reserved. + + Pfsense Old snort GUI + Copyright (C) 2006 Scott Ullrich. + + Pfsense snort GUI + Copyright (C) 2008-2012 Robert Zelaya. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the pfSense nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + + 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_new.inc"); +require_once("/usr/local/pkg/snort/snort_gui.inc"); + +//Set no caching +header("Expires: Mon, 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"); + +// set page vars + +$uuid = $_GET['uuid']; +if (isset($_POST['uuid'])) +$uuid = $_POST['uuid']; + +if ($uuid == '') { + echo 'error: no uuid'; + exit(0); +} + + +$a_list = snortSql_fetchAllSettings('snortDB', 'SnortIfaces', 'uuid', $uuid); + + $pgtitle = "Snort: Interface Preprocessors and Flow"; + include("/usr/local/pkg/snort/snort_head.inc"); + +?> + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + +<!-- loading msg --> +<div id="loadingWaiting"> + <div class="snortModal" style="top: 200px; left: 700px;"> + <div class="snortModalTop"> + <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> + </div> + <div class="snortModalTitle"> + <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> + </div> + <div> + <p class="loadingWaitingMessage"></p> + </div> + </div> +</div> + +<?php include("fbegin.inc"); ?> +<!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"> +<a href="../index.php" id="status-link2"> +<img src="./images/transparent.gif" border="0"></img> +</a> +</div> + +<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> + +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td> + + <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> + <ul class="newtabmenu"> + <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> + <li><a href="/snort/snort_interfaces_edit.php?uuid=<?=$uuid;?>"><span>If Settings</span></a></li> + <li><a href="/snort/snort_rulesets.php?uuid=<?=$uuid;?>"><span>Categories</span></a></li> + <li><a href="/snort/snort_rules.php?uuid=<?=$uuid;?>"><span>Rules</span></a></li> + <li><a href="/snort/snort_rulesets_ips.php?uuid=<?=$uuid;?>"><span>Ruleset Ips</span></a></li> + <li><a href="/snort/snort_define_servers.php?uuid=<?=$uuid;?>"><span>Servers</span></a></li> + <li class="newtabmenu_active"><a href="/snort/snort_preprocessors.php?uuid=<?=$uuid;?>"><span>Preprocessors</span></a></li> + <li><a href="/snort/snort_barnyard.php?uuid=<?=$uuid;?>"><span>Barnyard2</span></a></li> + </ul> + </div> + + </td> + </tr> + <tr> + <td id="tdbggrey"> + <table width="100%" border="0" cellpadding="10px" cellspacing="0"> + <tr> + <td class="tabnavtbl"> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <!-- START MAIN AREA --> + + <form id="iform" > + <input type="hidden" name="snortSaveSettings" value="1" /> <!-- what to do, save --> + <input type="hidden" name="dbName" value="snortDB" /> <!-- what db--> + <input type="hidden" name="dbTable" value="SnortIfaces" /> <!-- what db table--> + <input type="hidden" name="ifaceTab" value="snort_preprocessors" /> <!-- what interface tab --> + <input name="uuid" type="hidden" value="<?=$a_list['uuid']; ?>"> + + + + <tr> + <td width="22%" valign="top"> </td> + <td width="78%"><span class="vexpl"> + <span class="red"><strong>Note:</strong></span> + <br> + <span class="vexpl">Rules may be dependent on preprocessors!<br> + Defaults will be used when there is no user input.</span><br> + </td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic">Performance Statistics</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Enable</td> + <td width="78%" class="vtable"> + <input name="perform_stat" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['perform_stat'] == 'on' || $a_list['perform_stat'] == '' ? 'checked' : '';?> > + <span class="vexpl">Performance Statistics for this interface.</span> + </td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic">HTTP Inspect Settings</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Enable</td> + <td width="78%" class="vtable"> + <input name="http_inspect" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['http_inspect'] == 'on' || $a_list['http_inspect'] == '' ? 'checked' : '';?> > + <span class="vexpl">Use HTTP Inspect to Normalize/Decode and detect HTTP traffic and protocol anomalies.</span> + </td> + </tr> + <tr> + <td valign="top" class="vncell2">HTTP server flow depth</td> + <td class="vtable"> + <table cellpadding="0" cellspacing="0"> + <tr> + <td> + <input name="flow_depth" type="text" class="formfld" id="flow_depth" size="5" value="<?=$a_list['flow_depth']; ?>"> + <span class="vexpl"><strong>-1</strong> to <strong>1460</strong> (<strong>-1</strong> disables HTTP inspect, <strong>0</strong> enables all HTTP inspect)</span> + </td> + </tr> + </table> + <span class="vexpl">Amount of HTTP server response payload to inspect. Snort's performance may increase by adjusting this value. + <br> + Setting this value too low may cause false negatives. Values above 0 are specified in bytes. Default value is <strong>0</strong></span> + <br> + </td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic">Stream5 Settings</td> + </tr> + <tr> + <td valign="top" class="vncell2">Max Queued Bytes</td> + <td class="vtable"> + <table cellpadding="0" cellspacing="0"> + <tr> + <td> + <input name="max_queued_bytes" type="text" class="formfld" id="max_queued_bytes" size="5" value="<?=$a_list['max_queued_bytes']; ?>"> + <span class="vexpl">Minimum is <strong>1024</strong>, Maximum is <strong>1073741824</strong> ( default value is <strong>1048576</strong>, <strong>0</strong>means Maximum )</span> + </td> + </tr> + </table> + <span class="vexpl">The number of bytes to be queued for reassembly for TCP sessions in memory. Default value is <strong>1048576</strong></span> + <br> + </td> + </tr> + <tr> + <td valign="top" class="vncell2">Max Queued Segs</td> + <td class="vtable"> + <table cellpadding="0" cellspacing="0"> + <tr> + <td> + <input name="max_queued_segs" type="text" class="formfld" id="max_queued_segs" size="5" value="<?=$a_list['max_queued_segs']; ?>" > + <span class="vexpl">Minimum is <strong>2</strong>, Maximum is <strong>1073741824</strong> ( default value is <strong>2621</strong>, <strong>0</strong> means Maximum )</span> + </td> + </tr> + </table> + <span class="vexpl">The number of segments to be queued for reassembly for TCP sessions in memory. Default value is <strong>2621</strong></span> + <br> + </td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic">General Preprocessor Settings</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2"> + Enable <br> + RPC Decode and Back Orifice detector + </td> + <td width="78%" class="vtable"> + <input name="other_preprocs" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['other_preprocs'] == 'on' || $a_list['other_preprocs'] == '' ? 'checked' : '';?> > + <br> + <span class="vexpl">Normalize/Decode RPC traffic and detects Back Orifice traffic on the network.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2"> + Enable + <br> + FTP and Telnet Normalizer + </td> + <td width="78%" class="vtable"> + <input name="ftp_preprocessor" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['ftp_preprocessor'] == 'on' || $a_list['ftp_preprocessor'] == '' ? 'checked' : '';?> > + <br> + <span class="vexpl">Normalize/Decode FTP and Telnet traffic and protocol anomalies.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2"> + Enable + <br> + SMTP Normalizer + </td> + <td width="78%" class="vtable"> + <input name="smtp_preprocessor" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['smtp_preprocessor'] == 'on' || $a_list['smtp_preprocessor'] == '' ? 'checked' : '';?> > + <br> + <span class="vexpl">Normalize/Decode SMTP protocol for enforcement and buffer overflows.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2"> + Enable + <br> + Portscan Detection + </td> + <td width="78%" class="vtable"> + <input name="sf_portscan" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['sf_portscan'] == 'on' || $a_list['sf_portscan'] == '' ? 'checked' : '';?> > + <br> + <span class="vexpl">Detects various types of portscans and portsweeps.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2"> + Enable + <br> + DCE/RPC2 Detection + </td> + <td width="78%" class="vtable"> + <input name="dce_rpc_2" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['dce_rpc_2'] == 'on' || $a_list['dce_rpc_2'] == '' ? 'checked' : '';?> > + <br> + <span class="vexpl">The DCE/RPC preprocessor detects and decodes SMB and DCE/RPC traffic.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2"> + Enable + <br> + DNS Detection + </td> + <td width="78%" class="vtable"> + <input name="dns_preprocessor" type="checkbox" value="on" <?=$ifaceEnabled = $a_list['dns_preprocessor'] == 'on' || $a_list['dns_preprocessor'] == '' ? 'checked' : '';?> > + <br> + <span class="vexpl">The DNS preprocessor decodes DNS Response traffic and detects some vulnerabilities.</span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell2">Define SSL_IGNORE</td> + <td width="78%" class="vtable"> + <input name="def_ssl_ports_ignore" type="text" class="formfld" id="def_ssl_ports_ignore" size="40" value="<?=$a_list['def_ssl_ports_ignore']; ?>" > + <br> + <span class="vexpl">Encrypted traffic should be ignored by Snort for both performance reasons and to reduce false positives. + <br> + Default: "443 465 563 636 989 990 992 993 994 995". <strong>Please use spaces and not commas.</strong></span> + </td> + </tr> + <tr> + <td width="22%" valign="top"> </td> + <td width="78%"> + <input name="Submit" type="submit" class="formbtn" value="Save"> + <input id="cancel" type="button" class="formbtn" value="Cancel" > + </td> + </tr> + + <tr> + <td width="22%" valign="top"> </td> + <td width="78%"><span class="vexpl"> + <span class="vexpl"><span class="red"><strong>Note:</strong></span> Please save your settings before you click Start.</span> + </td> + </tr> + + + </form> + <!-- STOP MAIN AREA --> + </table> + </td> + </tr> + </table> + </td> + </tr> +</table> +</div> + + +<!-- footer do not touch below --> +<?php +include("fend.inc"); +echo $snort_custom_rnd_box; +?> + + +</body> +</html> diff --git a/config/snort-dev/snortsam-package-code/snort_rules.php b/config/snort-dev/snortsam-package-code/snort_rules.php new file mode 100644 index 00000000..fd102538 --- /dev/null +++ b/config/snort-dev/snortsam-package-code/snort_rules.php @@ -0,0 +1,600 @@ +<?php +/* $Id$ */ +/* + + part of pfSense + All rights reserved. + + Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + All rights reserved. + + Pfsense Old snort GUI + Copyright (C) 2006 Scott Ullrich. + + Pfsense snort GUI + Copyright (C) 2008-2012 Robert Zelaya. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the pfSense nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + + 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_new.inc"); +require_once("/usr/local/pkg/snort/snort_gui.inc"); + +//Set no caching +header("Expires: Mon, 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"); + +// set page vars + +if (isset($_GET['uuid']) && isset($_GET['rdbuuid'])) { + echo 'Error: more than one uuid'; + exit(0); +} + +if (isset($_GET['uuid'])) { + $uuid = $_GET['uuid']; +} + +if (isset($_GET['rdbuuid'])) { + $rdbuuid = $_GET['rdbuuid']; +}else{ + $ruledbname_pre1 = snortSql_fetchAllSettings('snortDB', 'SnortIfaces', 'uuid', $uuid); + $rdbuuid = $ruledbname_pre1['ruledbname']; +} + +// unset Session tmp on page load +unset($_SESSION['snort']['tmp']); + +// list rules in the default dir +$a_list = snortSql_fetchAllSettings('snortDBrules', 'Snortrules', 'uuid', $rdbuuid); + +$snortRuleDir = '/usr/local/etc/snort/snortDBrules/DB/' . $rdbuuid; + + // list rules in the default dir + $filterDirList = array(); + $filterDirList = snortScanDirFilter($snortRuleDir . '/rules', '\.rules'); + + // START read rule file + if ($_GET['openruleset']) { + $rulefile = $_GET['openruleset']; + }else{ + $rulefile = $filterDirList[0]; + } + + // path of rule file + $workingFile = $snortRuleDir . '/rules/' . $rulefile; + +function load_rule_file($incoming_file, $splitcontents) +{ + $pattern = '/(^alert |^# alert )/'; + foreach ( $splitcontents as $val ) + { + // remove whitespaces + $rmWhitespaces = preg_replace('/\s\s+/', ' ', $val); + + // filter none alerts + if (preg_match($pattern, $rmWhitespaces)) + { + $splitcontents2[] = $val; + } + + } + unset($splitcontents); + + return $splitcontents2; + +} + + // Load the rule file + // split the contents of the string file into an array using the delimiter + // used by rule gui edit and table build code + if (filesize($workingFile) > 0) { + $splitcontents = split_rule_file($workingFile); + + $splitcontents2 = load_rule_file($workingFile, $splitcontents); + + $countSig = count($splitcontents2); + + if ($countSig > 0) { + $newFilterRuleSigArray = newFilterRuleSig($splitcontents2); + } + } + + /* + * SET GLOBAL ARRAY $_SESSION['snort'] + * Use SESSION instead POST for security because were writing to files. + */ + + $_SESSION['snort']['tmp']['snort_rules']['dbName'] = 'snortDBrules'; + $_SESSION['snort']['tmp']['snort_rules']['dbTable'] = 'SnortruleSigs'; + $_SESSION['snort']['tmp']['snort_rules']['rdbuuid'] = $rdbuuid; + $_SESSION['snort']['tmp']['snort_rules']['rulefile'] = $rulefile; + + +// find ./ -name test.txt | xargs grep "^disablesid 127 " + + $pgtitle = "Snort: Category: rule: $rulefile"; + include("/usr/local/pkg/snort/snort_head.inc"); + +?> + + + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + +<!-- loading msg --> +<div id="loadingWaiting"> + <div class="snortModal" style="top: 200px; left: 700px;"> + <div class="snortModalTop"> + <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> + </div> + <div class="snortModalTitle"> + <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> + </div> + <div> + <p class="loadingWaitingMessage"></p> + </div> + </div> +</div> + +<!-- hidden div --> +<div id="loadingRuleEditGUI"> + + <div class="loadingRuleEditGUIDiv"> + <form id="iform2" action=""> + <input type="hidden" name="snortSidRuleEdit" value="1" /> + <input type="hidden" name="snortSidRuleDBuuid" value="<?=$rdbuuid;?>" /> <!-- what to do, save --> + <input type="hidden" name="snortSidRuleFile" value="<?=$rulefile; ?>" /> <!-- what to do, save --> + <input type="hidden" name="snortSidNum" value="" /> <!-- what to do, save --> + <table width="100%" cellpadding="9" cellspacing="9" bgcolor="#eeeeee"> + <tr> + <td> + <input name="save" type="submit" class="formbtn" id="save" value="Save" /> + <input type="button" class="formbtn closeRuleEditGUI" value="Close" > + </td> + </tr> + <tr> + <td> + <textarea id="sidstring" name="sidstring" wrap="off" style="width: 98%; margin: 7px;" rows="1" cols="" ></textarea> <!-- SID to EDIT --> + </td> + </tr> + <tr> + <td> + <textarea wrap="off" style="width: 98%; margin: 7px;" rows="<?php if(count($splitcontents) > 24){echo 24;}else{echo count($splitcontents);} ?>" cols="" disabled > + + <?php + + echo "\n"; + + foreach ($splitcontents as $sidLineGui) + + echo $sidLineGui . "\n"; + + + + ?> + </textarea> <!-- Display rule file --> + </td> + </tr> + </table> + <table width="100%" cellpadding="9" cellspacing="9" bgcolor="#eeeeee"> + <tr> + <td> + <input name="save" type="submit" class="formbtn" id="save" value="Save" /> + <input type="button" class="formbtn closeRuleEditGUI" value="Close" > + </td> + </tr> + </table> + </form> + </div> + + +</div> + +<?php include("fbegin.inc"); ?> + +<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0"></img></a></div> + +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <?php + if (!empty($uuid)) { + echo ' + <tr> + <td> + <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> + <ul class="newtabmenu"> + <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> + <li><a href="/snort/snort_interfaces_edit.php?uuid=' . $uuid . '"><span>If Settings</span></a></li> + <li><a href="/snort/snort_rulesets.php?uuid=' . $uuid . '"><span>Categories</span></a></li> + <li class="newtabmenu_active"><a href="/snort/snort_rules.php?uuid=' . $uuid . '"><span>Rules</span></a></li> + <li><a href="/snort/snort_rulesets_ips.php?uuid=' . $uuid . '"><span>Ruleset Ips</span></a></li> + <li><a href="/snort/snort_define_servers.php?uuid=' . $uuid . '"><span>Servers</span></a></li> + <li><a href="/snort/snort_preprocessors.php?uuid=' . $uuid . '"><span>Preprocessors</span></a></li> + <li><a href="/snort/snort_barnyard.php?uuid=' . $uuid . '"><span>Barnyard2</span></a></li> + </ul> + </div> + </td> + </tr> + '; + }else{ + echo ' + <tr> + <td> + <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> + <ul class="newtabmenu"> + <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> + <li><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> + <li><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> + <li class="newtabmenu_active"><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> + <li><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> + <li><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> + <li><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> + <li><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> + <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> + </ul> + </div> + </td> + </tr> + <tr> + <td> + <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> + <ul class="newtabmenu"> + <li class="hide_newtabmenu"><a href="/snort/snort_interfaces_rules_edit.php?rdbuuid=' . $rdbuuid . '"><span>Rules DB Edit</span></a></li> + <li class="hide_newtabmenu"><a href="/snort/snort_rulesets.php?rdbuuid=' . $rdbuuid . '"><span>Categories</span></a></li> + <li class="hide_newtabmenu newtabmenu_active"><a href="/snort/snort_rules.php?rdbuuid=' . $rdbuuid . '"><span>Rules</span></a></li> + <li><a href="/snort/snort_rulesets_ips.php?rdbuuid=' . $rdbuuid . '"><span>Ruleset Ips</span></a></li> + </ul> + </div> + </td> + </tr> + '; + } + ?> + <tr> + <td id="tdbggrey"> + <div style="width:780px; margin-left: auto ; margin-right: auto ; padding-top: 10px; padding-bottom: 10px;"> + <!-- START MAIN AREA --> + + + <!-- start Interface Satus --> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr id="maintable77" > + <td colspan="2" valign="top" class="listtopic2"> + Category: + <select name="selectbox" class="formfld" > + <?php + if(isset($_GET['uuid'])) { + $urlUuid = "&uuid=$uuid"; + } + + if(isset($_GET['rdbuuid'])) { + $urlUuid = "&rdbuuid=$rdbuuid"; + } + + $i=0; + foreach ($filterDirList as $value) + { + $selectedruleset = ''; + if ($value === $rulefile) { + $selectedruleset = 'selected'; + } + + echo "\n" . '<option value="?&openruleset=' . $ruledir . $value . $urlUuid . '" ' . $selectedruleset . ' >' . $value . '</option>' . "\r"; + + $i++; + + } + ?> + </select> + There are <?=$countSig; ?> rules in this category. + </td> + <td width="6%" colspan="2" valign="middle" class="listtopic3" > + <a href="snort_interfaces_edit.php?uuid=<?=$new_ruleUUID;?>"> + <img style="padding-left:3px;" src="/themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" width="17" height="17" border="0" title="add rule"> + </a> + </td> + </tr> + </table> +<br> + + <!-- Save all inputs --> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td> + <input id="select_all" type="button" class="formbtn" value="Select All" > + <input id="deselect_all" type="button" class="formbtn" value="Deselect All" > + </td> + </tr> + </table> + +<br> + + <!-- start User Interface --> + + + <form id="iform" action=""> + <input type="hidden" name="snortSaveRuleSets" value="1" /> <!-- what to do, save --> + <input type="hidden" name="ifaceTab" value="snort_rules" /> <!-- what interface tab --> + + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr id="maintable77" > + <td colspan="2" valign="top" class="listtopic">Snort Signatures:</td> + </tr> + </table> + + <table id="mainCreateTable" width="100%" border="0" cellpadding="0" cellspacing="0"> + + <tr id="frheader" > + <td class="listhdrr2">On</td> + <td class="listhdrr2">Sid</td> + <td class="listhdrr2">Proto</td> + <td class="listhdrr2">Src</td> + <td class="listhdrr2">Port</td> + <td class="listhdrr2">Dst</td> + <td class="listhdrr2">Port</td> + <td class="listhdrr2">Message</td> + <td class="listhdrr2"> </td> + </tr> + <tr> + <!-- START javascript sid loop here --> + <tbody class="rulesetloopblock"> + + + + </tbody> + <!-- STOP javascript sid loop here --> + </tr> + + </table> + <br> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td> + <input name="Submit" type="submit" class="formbtn" value="Save"> + <input id="cancel" type="button" class="formbtn" value="Cancel"> + </td> + </tr> + </table> + </form> + <br> + + <!-- stop snortsam --> + + <!-- STOP MAIN AREA --> + </div> + </td> + </tr> +</table> +</form> +</div> + +<!-- start info box --> + +<br> + +<div style="width:790px; background-color: #dddddd;" id="mainarea4"> +<div style="width:780px; margin-left: auto ; margin-right: auto ; padding-top: 10px; padding-bottom: 10px;"> +<table class="vncell2" width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td> </td> + </tr> + <tr > + <td width="100%"> + <span class="red"><strong>Note:</strong></span> <br> + This is the <strong>Snort Rule Signature Viewer</strong>. + Please make sure not to add a <strong>whitespace</strong> before <strong>alert</strong> or <strong>#alert</strong>. + <br> + <br> + <span class="red"><strong>Warning:</strong></span> + <br> + <strong>New settings will not take effect until interface restart.</strong> + <br><br> + </td> + </tr> +</table> +</div> +</div> + + +<script type="text/javascript"> + + +//prepare the form when the DOM is ready +jQuery(document).ready(function() { + + // NOTE: needs to be watched + // change url on selected dropdown rule + jQuery('select[name=selectbox]').change(function() { + window.location.replace(jQuery(this).val()); + }); + +<?php + + /* + * NOTE: + * I could have used a php loop to build the table but I wanted to see if off loading to client is faster. + * Seems to be faster on embeded systems with low specs. On higher end systems there is no difference that I can see. + * WARNING: + * If Json string is to long browsers start asking to terminate javascript. + * FIX: + * Use julienlecomte()net/blog/2007/10/28/, the more reading I do about this subject it seems that off loading to a client is not recomended. + */ + if (!empty($newFilterRuleSigArray)) + { + $countSigList = count($newFilterRuleSigArray); + + echo "\n"; + + echo 'var snortObjlist = ['; + $i = 0; + foreach ($newFilterRuleSigArray as $val3) + { + + $i++; + + // NOTE: escapeJsonString; foward slash has added spaces on each side, ie and chrome were giving issues with tablw widths + if( $i !== $countSigList ) { + echo '{"sid":"' . $val3['sid'] . '","enable":"' . $val3['enable'] . '","proto":"' . $val3['proto'] . '","src":"' . $val3['src'] . '","srcport":"' . $val3['srcport'] . '","dst":"' . $val3['dst'] . '", "dstport":"' . $val3['dstport'] . '","msg":"' . escapeJsonString($val3['msg']) . '"},'; + }else{ + echo '{"sid":"' . $val3['sid'] . '","enable":"' . $val3['enable'] . '","proto":"' . $val3['proto'] . '","src":"' . $val3['src'] . '","srcport":"' . $val3['srcport'] . '","dst":"' . $val3['dst'] . '", "dstport":"' . $val3['dstport'] . '","msg":"' . escapeJsonString($val3['msg']) . '"}'; + } + } + + echo '];' . "\n"; + } + + + + if (!empty($countSig)) { + echo 'var countRowAppend = ' . $countSig . ';' . "\n"; + }else{ + echo 'var countRowAppend = 0;' . "\n"; + } + +?> + +if(typeof escapeHtmlEntities == 'undefined') { + escapeHtmlEntities = function (text) { + return text.replace(/[\u00A0-\u2666<>\&]/g, function(c) { return '&' + + escapeHtmlEntities.entityTable[c.charCodeAt(0)] || '#'+c.charCodeAt(0) + ';'; }); + }; + + // all HTML4 entities as defined here: http://www.w3.org/TR/html4/sgml/entities.html + // added: amp, lt, gt, quot and apos + escapeHtmlEntities.entityTable = { 34 : 'quot', 38 : 'amp', 39 : 'apos', 47 : 'slash', 60 : 'lt', 62 : 'gt', 160 : 'nbsp', 161 : 'iexcl', 162 : 'cent', 163 : 'pound', 164 : 'curren', 165 : 'yen', 166 : 'brvbar', 167 : 'sect', 168 : 'uml', 169 : 'copy', 170 : 'ordf', 171 : 'laquo', 172 : 'not', 173 : 'shy', 174 : 'reg', 175 : 'macr', 176 : 'deg', 177 : 'plusmn', 178 : 'sup2', 179 : 'sup3', 180 : 'acute', 181 : 'micro', 182 : 'para', 183 : 'middot', 184 : 'cedil', 185 : 'sup1', 186 : 'ordm', 187 : 'raquo', 188 : 'frac14', 189 : 'frac12', 190 : 'frac34', 191 : 'iquest', 192 : 'Agrave', 193 : 'Aacute', 194 : 'Acirc', 195 : 'Atilde', 196 : 'Auml', 197 : 'Aring', 198 : 'AElig', 199 : 'Ccedil', 200 : 'Egrave', 201 : 'Eacute', 202 : 'Ecirc', 203 : 'Euml', 204 : 'Igrave', 205 : 'Iacute', 206 : 'Icirc', 207 : 'Iuml', 208 : 'ETH', 209 : 'Ntilde', 210 : 'Ograve', 211 : 'Oacute', 212 : 'Ocirc', 213 : 'Otilde', 214 : 'Ouml', 215 : 'times', 216 : 'Oslash', 217 : 'Ugrave', 218 : 'Uacute', 219 : 'Ucirc', 220 : 'Uuml', 221 : 'Yacute', 222 : 'THORN', 223 : 'szlig', 224 : 'agrave', 225 : 'aacute', 226 : 'acirc', 227 : 'atilde', 228 : 'auml', 229 : 'aring', 230 : 'aelig', 231 : 'ccedil', 232 : 'egrave', 233 : 'eacute', 234 : 'ecirc', 235 : 'euml', 236 : 'igrave', 237 : 'iacute', 238 : 'icirc', 239 : 'iuml', 240 : 'eth', 241 : 'ntilde', 242 : 'ograve', 243 : 'oacute', 244 : 'ocirc', 245 : 'otilde', 246 : 'ouml', 247 : 'divide', 248 : 'oslash', 249 : 'ugrave', 250 : 'uacute', 251 : 'ucirc', 252 : 'uuml', 253 : 'yacute', 254 : 'thorn', 255 : 'yuml', 402 : 'fnof', 913 : 'Alpha', 914 : 'Beta', 915 : 'Gamma', 916 : 'Delta', 917 : 'Epsilon', 918 : 'Zeta', 919 : 'Eta', 920 : 'Theta', 921 : 'Iota', 922 : 'Kappa', 923 : 'Lambda', 924 : 'Mu', 925 : 'Nu', 926 : 'Xi', 927 : 'Omicron', 928 : 'Pi', 929 : 'Rho', 931 : 'Sigma', 932 : 'Tau', 933 : 'Upsilon', 934 : 'Phi', 935 : 'Chi', 936 : 'Psi', 937 : 'Omega', 945 : 'alpha', 946 : 'beta', 947 : 'gamma', 948 : 'delta', 949 : 'epsilon', 950 : 'zeta', 951 : 'eta', 952 : 'theta', 953 : 'iota', 954 : 'kappa', 955 : 'lambda', 956 : 'mu', 957 : 'nu', 958 : 'xi', 959 : 'omicron', 960 : 'pi', 961 : 'rho', 962 : 'sigmaf', 963 : 'sigma', 964 : 'tau', 965 : 'upsilon', 966 : 'phi', 967 : 'chi', 968 : 'psi', 969 : 'omega', 977 : 'thetasym', 978 : 'upsih', 982 : 'piv', 8226 : 'bull', 8230 : 'hellip', 8242 : 'prime', 8243 : 'Prime', 8254 : 'oline', 8260 : 'frasl', 8472 : 'weierp', 8465 : 'image', 8476 : 'real', 8482 : 'trade', 8501 : 'alefsym', 8592 : 'larr', 8593 : 'uarr', 8594 : 'rarr', 8595 : 'darr', 8596 : 'harr', 8629 : 'crarr', 8656 : 'lArr', 8657 : 'uArr', 8658 : 'rArr', 8659 : 'dArr', 8660 : 'hArr', 8704 : 'forall', 8706 : 'part', 8707 : 'exist', 8709 : 'empty', 8711 : 'nabla', 8712 : 'isin', 8713 : 'notin', 8715 : 'ni', 8719 : 'prod', 8721 : 'sum', 8722 : 'minus', 8727 : 'lowast', 8730 : 'radic', 8733 : 'prop', 8734 : 'infin', 8736 : 'ang', 8743 : 'and', 8744 : 'or', 8745 : 'cap', 8746 : 'cup', 8747 : 'int', 8756 : 'there4', 8764 : 'sim', 8773 : 'cong', 8776 : 'asymp', 8800 : 'ne', 8801 : 'equiv', 8804 : 'le', 8805 : 'ge', 8834 : 'sub', 8835 : 'sup', 8836 : 'nsub', 8838 : 'sube', 8839 : 'supe', 8853 : 'oplus', 8855 : 'otimes', 8869 : 'perp', 8901 : 'sdot', 8968 : 'lceil', 8969 : 'rceil', 8970 : 'lfloor', 8971 : 'rfloor', 9001 : 'lang', 9002 : 'rang', 9674 : 'loz', 9824 : 'spades', 9827 : 'clubs', 9829 : 'hearts', 9830 : 'diams', 34 : 'quot', 38 : 'amp', 60 : 'lt', 62 : 'gt', 338 : 'OElig', 339 : 'oelig', 352 : 'Scaron', 353 : 'scaron', 376 : 'Yuml', 710 : 'circ', 732 : 'tilde', 8194 : 'ensp', 8195 : 'emsp', 8201 : 'thinsp', 8204 : 'zwnj', 8205 : 'zwj', 8206 : 'lrm', 8207 : 'rlm', 8211 : 'ndash', 8212 : 'mdash', 8216 : 'lsquo', 8217 : 'rsquo', 8218 : 'sbquo', 8220 : 'ldquo', 8221 : 'rdquo', 8222 : 'bdquo', 8224 : 'dagger', 8225 : 'Dagger', 8240 : 'permil', 8249 : 'lsaquo', 8250 : 'rsaquo', 8364 : 'euro' }; +} + + // if rowcount is not empty do this + if (countRowAppend > 0){ + + // if rowcount is more than 300 + if (countRowAppend > 200){ + // call to please wait + showLoading('#loadingWaiting'); + } + + + // Break up append row adds by chunks of 300 + // NOTE: ie9 is still giving me issues on deleted.rules 6000 sigs. I should break up the json code above into smaller parts. + incrementallyProcess(function (i){ + // loop code goes in here + //console.log('loop: ', i); + + if (isEven(i) === true){ + var rowIsEvenOdd = 'odd_ruleset2'; + }else{ + var rowIsEvenOdd = 'even_ruleset2'; + } + + if (snortObjlist[i].enable === 'on'){ + var rulesetChecked = 'checked'; + }else{ + var rulesetChecked = ''; + } + + jQuery('.rulesetloopblock').append( + + "\n" + '<tr valign="top" id="fr0">' + "\n" + + '<td class="' + rowIsEvenOdd + '">' + "\n" + + '<input class="domecheck" type="checkbox" name="filenamcheckbox2[]" value="' + snortObjlist[i].sid + '" ' + rulesetChecked + ' >' + "\n" + + '</td>' + "\n" + + '<td class="' + rowIsEvenOdd + '" id="frd0" >' + snortObjlist[i].sid + '</td>' + "\n" + + '<td class="' + rowIsEvenOdd + '" id="frd0" >' + snortObjlist[i].proto + '</td>' + "\n" + + '<td class="' + rowIsEvenOdd + '" id="frd0" >' + snortObjlist[i].src + '</td>' + "\n" + + '<td class="' + rowIsEvenOdd + '" id="frd0" >' + snortObjlist[i].srcport + '</td>' + "\n" + + '<td class="' + rowIsEvenOdd + '" id="frd0" >' + snortObjlist[i].dst + '</td>' + "\n" + + '<td class="' + rowIsEvenOdd + '" id="frd0" >' + snortObjlist[i].dstport + '</td>' + "\n" + + '<td class="listbg" id="frd0" ><font color="white">' + escapeHtmlEntities(snortObjlist[i].msg) + '</font></td>' + "\n" + + '<td class="' + rowIsEvenOdd+ '">' + "\n" + + '<img id="' + snortObjlist[i].sid + '" class="icon_click showeditrulegui" src="/themes/<?=$g['theme']; ?>/images/icons/icon_e.gif" width="17" height="17" border="0" title="edit rule">' + "\n" + + '</td>' + "\n" + + '</tr>' + "\n" + + ); + + }, + snortObjlist, // Object to work with the case Json object + 500, // chunk size + 200, // how many secs to wait + function (){ + // things that happen after the processing is done go here + // console.log('done!'); + + // if rowcount is more than 300 + if (countRowAppend > 200){ + // call to please wait + hideLoading('#loadingWaiting'); + } + + }); + } // end of if stopRowAppend + + + // On click show rule edit GUI + jQuery('.showeditrulegui').live('click', function(){ + + // Get sid + jQuery.getJSON('/snort/snort_json_get.php', + { + "snortGetSidString": "1", + "snortIface": "<?=$uuid . '_' . $a_list['interface']; ?>", + "snortRuleFile": "<?=$rulefile; ?>", + "sid": jQuery(this).attr('id') + }, + function(data){ + jQuery("textarea#sidstring").val(data.sidstring); // add string to textarea + jQuery("input[name=snortSidNum]").val(data.sid); // add sid to input + showLoading('#loadingRuleEditGUI'); + }); + }); + + jQuery('.closeRuleEditGUI').live('click', function(){ + hideLoading('#loadingRuleEditGUI'); + }); + + +}); // end of document ready + +</script> + + +<!-- stop info box --> + +<!-- footer do not touch below --> +<?php +include("fend.inc"); +echo $snort_custom_rnd_box; +?> + + +</body> +</html> diff --git a/config/snort-dev/snort_rules_ips.php b/config/snort-dev/snortsam-package-code/snort_rules_ips.php index d026b566..d026b566 100644 --- a/config/snort-dev/snort_rules_ips.php +++ b/config/snort-dev/snortsam-package-code/snort_rules_ips.php diff --git a/config/snort-dev/snortsam-package-code/snort_rulesets.php b/config/snort-dev/snortsam-package-code/snort_rulesets.php new file mode 100644 index 00000000..a2e4f7f3 --- /dev/null +++ b/config/snort-dev/snortsam-package-code/snort_rulesets.php @@ -0,0 +1,347 @@ +<?php +/* $Id$ */ +/* + + part of pfSense + All rights reserved. + + Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + All rights reserved. + + Pfsense Old snort GUI + Copyright (C) 2006 Scott Ullrich. + + Pfsense snort GUI + Copyright (C) 2008-2012 Robert Zelaya. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the pfSense nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + + 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_new.inc"); +require_once("/usr/local/pkg/snort/snort_gui.inc"); + +//Set no caching +header("Expires: Mon, 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"); + +if (isset($_GET['uuid']) && isset($_GET['rdbuuid'])) { + echo 'Error: more than one uuid'; + exit(0); +} + +// set page vars +if (isset($_GET['uuid'])) { + $uuid = $_GET['uuid']; +} + +if (isset($_GET['rdbuuid'])) { + $rdbuuid = $_GET['rdbuuid']; +}else{ + $ruledbname_pre1 = snortSql_fetchAllSettings('snortDB', 'SnortIfaces', 'uuid', $uuid); + $rdbuuid = $ruledbname_pre1['ruledbname']; +} + +//$a_list = snortSql_fetchAllSettings('snortDBrules', 'SnortIfaces', 'uuid', $uuid); + + // list rules in the default dir + $filterDirList = array(); + $filterDirList = snortScanDirFilter('/usr/local/etc/snort/snortDBrules/DB/' . $rdbuuid . '/rules', '\.rules'); + + // list rules in db that are on in a array + $listOnRules = array(); + $listOnRules = snortSql_fetchAllSettings('snortDBrules', 'SnortRuleSets', 'rdbuuid', $rdbuuid); + + if (!empty($listOnRules)) { + foreach ( $listOnRules as $val2 ) + { + if ($val2['enable'] == 'on') { + $rulesetOn[] = $val2['rulesetname']; + } + } + unset($listOnRules); + } + + $pgtitle = "Snort: Interface Rule Categories"; + include("/usr/local/pkg/snort/snort_head.inc"); + +?> + + + + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + +<script type="text/javascript"> + +//prepare the form when the DOM is ready +jQuery(document).ready(function() { + + <?php + /* + * NOTE: I could have used a php loop to build the table but off loading to client is faster + * use jQuery jason parse, make sure its in one line + */ + if (!empty($filterDirList)) { + + $countDirList = count($filterDirList); + + echo "\n"; + + echo 'var snortObjlist = jQuery.parseJSON(\' { "ruleSets": [ '; + $i = 0; + foreach ($filterDirList as $val3) + { + + $i++; + + // if list ruleset is in the db ON mark it checked + $rulesetOnChecked = 'off'; + if(!empty($rulesetOn)) + { + if (in_array($val3, $rulesetOn)) + { + $rulesetOnChecked = 'on'; + } + } + + if ( $i !== $countDirList ) + { + echo '{"rule": ' . '"' . $val3 . '", ' . '"enable": ' . '"' . $rulesetOnChecked . '"' . '}, '; + }else{ + echo '{"rule": "' . $val3 . '", ' . '"enable": ' . '"' . $rulesetOnChecked . '"' . '} '; + } + } + + echo ' ]}\');' . "\n"; + + }else{ + + echo 'var snortObjlist = jQuery.parseJSON(\' { "ruleSets": [] } \');' . "\n"; + + } + + + ?> + + // loop through object, dont use .each in jQuery as its slow + if(snortObjlist.ruleSets.length > 0) { + for (var i = 0; i < snortObjlist.ruleSets.length; i++) { + + if (isEven(i) === true) { + var rowIsEvenOdd = 'even_ruleset'; + }else{ + var rowIsEvenOdd = 'odd_ruleset'; + } + + if (snortObjlist.ruleSets[i].enable === 'on') { + var rulesetChecked = 'checked'; + }else{ + var rulesetChecked = ''; + } + + jQuery('.rulesetloopblock').append( + "\n" + '<tr>' + "\n" + + '<td class="' + rowIsEvenOdd + '" align="center" valign="top" width="9%">' + "\n" + + ' <input class="domecheck" name="filenamcheckbox[]" value="' + snortObjlist.ruleSets[i].rule + '" type="checkbox" ' + rulesetChecked + ' >' + "\n" + + '</td>' + "\n" + + '<td class="' + rowIsEvenOdd + '">' + "\n" + + ' <a href="/snort/snort_rules.php?openruleset=' + snortObjlist.ruleSets[i].rule + '<?php if(isset($uuid)){echo "&uuid=$uuid";}else{echo "&rdbuuid=$rdbuuid";}?>' + '">' + snortObjlist.ruleSets[i].rule + '</a>' + "\n" + + '</td>' + "\n" + + '</tr>' + "\n\n" + ); + }; + } + + +}); // end of document ready + +</script> + +<!-- loading msg --> +<div id="loadingWaiting"> + <div class="snortModal" style="top: 200px; left: 700px;"> + <div class="snortModalTop"> + <!-- <div class="snortModalTopClose"><a href="javascript:hideLoading('#loadingWaiting');"><img src="/snort/images/close_9x9.gif" border="0" height="9" width="9"></a></div> --> + </div> + <div class="snortModalTitle"> + <p><img src="./images/loading.gif" /><br><br>Please Wait...</p> + </div> + <div> + <p class="loadingWaitingMessage"></p> + </div> + </div> +</div> + +<?php include("fbegin.inc"); ?> + +<div class="body2"><!-- hack to fix the hardcoed fbegin link in header --> +<div id="header-left2"><a href="../index.php" id="status-link2"><img src="./images/transparent.gif" border="0" alt="transgif" ></img></a></div> + +<table width="100%" border="0" cellpadding="0" cellspacing="0"> + <?php + if (!empty($uuid)) { + echo ' + <tr> + <td> + <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> + <ul class="newtabmenu"> + <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> + <li><a href="/snort/snort_interfaces_edit.php?uuid=' . $uuid . '"><span>If Settings</span></a></li> + <li class="newtabmenu_active"><a href="/snort/snort_rulesets.php?uuid=' . $uuid . '"><span>Categories</span></a></li> + <li><a href="/snort/snort_rules.php?uuid=' . $uuid . '"><span>Rules</span></a></li> + <li><a href="/snort/snort_rulesets_ips.php?uuid=' . $uuid . '"><span>Ruleset Ips</span></a></li> + <li><a href="/snort/snort_define_servers.php?uuid=' . $uuid . '"><span>Servers</span></a></li> + <li><a href="/snort/snort_preprocessors.php?uuid=' . $uuid . '"><span>Preprocessors</span></a></li> + <li><a href="/snort/snort_barnyard.php?uuid=' . $uuid . '"><span>Barnyard2</span></a></li> + </ul> + </div> + </td> + </tr> + '; + }else{ + echo ' + <tr> + <td> + <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> + <ul class="newtabmenu"> + <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> + <li><a href="/snort/snort_interfaces_global.php"><span>Global Settings</span></a></li> + <li><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> + <li class="newtabmenu_active"><a href="/snort/snort_interfaces_rules.php"><span>RulesDB</span></a></li> + <li><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> + <li><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> + <li><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> + <li><a href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> + <li><a href="/snort/snort_help_info.php"><span>Help</span></a></li> + </ul> + </div> + </td> + </tr> + <tr> + <td> + <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> + <ul class="newtabmenu"> + <li class="hide_newtabmenu"><a href="/snort/snort_interfaces_rules_edit.php?rdbuuid=' . $rdbuuid . '"><span>Rules DB Edit</span></a></li> + <li class="hide_newtabmenu newtabmenu_active"><a href="/snort/snort_rulesets.php?rdbuuid=' . $rdbuuid . '"><span>Categories</span></a></li> + <li class="hide_newtabmenu"><a href="/snort/snort_rules.php?rdbuuid=' . $rdbuuid . '"><span>Rules</span></a></li> + <li><a href="/snort/snort_rulesets_ips.php?rdbuuid=' . $rdbuuid . '"><span>Ruleset Ips</span></a></li> + </ul> + </div> + </td> + </tr> + '; + } + ?> + <tr> + <td id="tdbggrey"> + <table width="100%" border="0" cellpadding="10px" cellspacing="0"> + <tr> + <td class="tabnavtbl"> + <table width="100%" border="0" cellpadding="6" cellspacing="0" > + <!-- START MAIN AREA --> + + + + <table width="100%" border="0" cellpadding="0" cellspacing="0" > + <tr> + <td> + </td> + <td> + <input id="select_all" type="button" class="formbtn" value="Select All" > + <input id="deselect_all" type="button" class="formbtn" value="Deselect All" > + </td> + </tr> + </table> + + <div id="checkboxdo" style="width: 100%; margin-left: auto ; margin-right: auto ; padding-top: 10px; padding-bottom: 0px;"> + <form id="iform" action="" > + <input type="hidden" name="snortSaveRuleSets" value="1" /> <!-- what to do, save --> + <input type="hidden" name="dbName" value="snortDBrules" /> <!-- what db--> + <input type="hidden" name="dbTable" value="SnortruleSets" /> <!-- what db table--> + <input type="hidden" name="ifaceTab" value="snort_rulesets" /> <!-- what interface tab --> + <input type="hidden" name="rdbuuid" value="<?=$rdbuuid;?>" /> <!-- what interface to save for --> + <input type="hidden" name="uuid" value="<?=$uuid;?>" /> <!-- create snort.conf --> + + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + + <tr > + <td width="5%" class="listtopic">Enabled</td> + <td class="listtopic">Ruleset: Rules that end with "so.rules" are shared object rules.</td> + </tr> + <table class="rulesetbkg" width="100%"> + + <tbody class="rulesetloopblock" > + <!-- javscript loop table build here --> + </tbody> + + </table> + <table class="vncell1" width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td class="listtopic" >Check the rulesets that you would like Snort to load at startup.</td> + </tr> + </table> + <tr> + <td> + <input name="Submit" type="submit" class="formbtn" value="Save"> + <input id="cancel" type="button" class="formbtn" value="Cancel"> + </td> + </tr> + <tr> + <td width="78%"> + <span class="vexpl"><span class="red"><strong>Note:</strong></span> + Please save your settings before you click start.</span> + </td> + </tr> + + </table> + </form> + </div> + + <!-- STOP MAIN AREA --> + </table> + </td> + </tr> + </table> + </td> + </tr> +</table> +</div> + +<!-- footer do not touch below --> +<?php +include("fend.inc"); +echo $snort_custom_rnd_box; +?> + + +</body> +</html> + diff --git a/config/snort-dev/snort_rulesets_ips.php b/config/snort-dev/snortsam-package-code/snort_rulesets_ips.php index abac2b6b..abac2b6b 100644 --- a/config/snort-dev/snort_rulesets_ips.php +++ b/config/snort-dev/snortsam-package-code/snort_rulesets_ips.php diff --git a/config/snort/snort.inc b/config/snort/snort.inc index a5d9ea90..f45134c5 100644 --- a/config/snort/snort.inc +++ b/config/snort/snort.inc @@ -1,32 +1,33 @@ <?php /* - snort.inc - Copyright (C) 2006 Scott Ullrich - Copyright (C) 2009-2010 Robert Zelaya - Copyright (C) 2011 Ermal Luci - 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. + * snort.inc + * + * Copyright (C) 2006 Scott Ullrich + * Copyright (C) 2009-2010 Robert Zelaya + * Copyright (C) 2011-2012 Ermal Luci + * 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. */ require_once("pfsense-utils.inc"); @@ -37,71 +38,105 @@ require_once("functions.inc"); require_once("filter.inc"); /* package version */ -$snort_package_version = 'Snort 2.9.1 pkg v. 2.1.1'; +$snort_version = "2.9.2.3"; +$pfSense_snort_version = "2.5.1"; +$snort_package_version = "Snort {$snort_version} pkg v. {$pfSense_snort_version}"; +$snort_rules_file = "snortrules-snapshot-2923.tar.gz"; +$emerging_threats_version = "2.9.0"; +define("SNORTDIR", "/usr/local/etc/snort"); +define("SNORTLOGDIR", "/var/log/snort"); + +if (!is_array($config['installedpackages']['snortglobal'])) + $config['installedpackages']['snortglobal'] = array(); -/* Allow additional execution time 0 = no limit. */ -ini_set('max_execution_time', '9999'); -ini_set('max_input_time', '9999'); +function snort_get_blocked_ips() { + $blocked_ips = ""; + exec('/sbin/pfctl -t snort2c -T show', $blocked_ips); + $blocked_ips_array = array(); + if (!empty($blocked_ips)) { + $blocked_ips_array = array(); + if (is_array($blocked_ips)) { + foreach ($blocked_ips as $blocked_ip) { + if (empty($blocked_ip)) + continue; + $blocked_ips_array[] = trim($blocked_ip, " \n\t"); + } + } + } -/* define oinkid */ -if ($config['installedpackages']['snortglobal']) - $oinkid = $config['installedpackages']['snortglobal']['oinkmastercode']; -else - $config['installedpackages']['snortglobal'] = array(); + return $blocked_ips_array; +} -/* find out if were in 1.2.3-RELEASE */ -if (intval($config['version']) > 6) - $snort_pfsense_basever = 'no'; -else - $snort_pfsense_basever = 'yes'; - -/* find out what arch where in x86 , x64 */ -global $snort_arch; -$snort_arch = 'x86'; -$snort_arch_ck = php_uname("m"); -if ($snort_arch_ck == 'i386') - $snort_arch = 'x86'; -else if ($snort_arch_ck == "amd64") - $snort_arch = 'x64'; -else - $snort_arch = "Unknown"; - -/* tell me my theme */ -$pfsense_theme_is = $config['theme']; +function snort_get_rule_part($source, $beginning, $ending, $start_pos) { -/* func builds custom white lists */ -function find_whitelist_key($find_wlist_number) { - global $config, $g; + $beginning_pos = strpos($source, $beginning, $start_pos); + if (!$beginning_pos) + return false; + $middle_pos = $beginning_pos + strlen($beginning); + $source = substr($source, $middle_pos); + $ending_pos = strpos($source, $ending, 0); + if (!$ending_pos) + return false; + return substr($source, 0, $ending_pos); +} - if (!is_array($config['installedpackages']['snortglobal']['whitelist'])) - $config['installedpackages']['snortglobal']['whitelist'] = array(); - if (!is_array($config['installedpackages']['snortglobal']['whitelist']['item'])) - return 0; /* XXX */ +function snort_generate_id() { + global $config; - foreach ($config['installedpackages']['snortglobal']['whitelist']['item'] as $w_key => $value) { - if ($value['name'] == $find_wlist_number) - return $w_key; + $snortglob = $config['installedpackages']['snortglobal']['rule']; + while (true) { + $snort_uuid = mt_rand(1, 65535); + foreach ($snortglob as $value) { + if ($value['uuid'] == $snort_uuid) + continue 2; + } + break; } + + return $snort_uuid; } -/* func builds custom suppress lists */ -function find_suppress_key($find_slist_number) { - global $config, $g; +/* func builds custom white lists */ +function snort_find_list($find_name, $type = 'whitelist') { + global $config; - if (!is_array($config['installedpackages']['snortglobal']['suppress'])) - $config['installedpackages']['snortglobal']['suppress'] = array(); - if (!is_array($config['installedpackages']['snortglobal']['suppress']['item'])) - return 0; /* XXX */ + $snortglob = $config['installedpackages']['snortglobal']; + if (!is_array($snortglob[$type])) + return ""; + if (!is_array($snortglob[$type]['item'])) + return ""; - foreach ($config['installedpackages']['snortglobal']['suppress']['item'] as $s_key => $value) { - if ($value['name'] == $find_slist_number) - return $s_key; + foreach ($snortglob[$type]['item'] as $value) { + if ($value['name'] == $find_name) + return $value; } + + return array(); } /* func builds custom whitelests */ -function build_base_whitelist($build_netlist, $wanip, $wangw, $wandns, $vips, $vpns, $userwips) { - global $config, $g, $snort_pfsense_basever; +function snort_build_list($snortcfg, $listname = "", $whitelist = false) { + global $config, $g; + + /* Add loopback to whitelist (ftphelper) */ + $home_net = "127.0.0.1 "; + + if ($listname == 'default' || empty($listname)) { + $wanip = 'yes'; $wangw = 'yes'; $wandns = 'yes'; $vips = 'yes'; $vpns = 'yes'; + } else { + $whitelist = snort_find_list($listname); + if (empty($whitelist)) + return $whitelist; + $wanip = $whitelist['wanips']; + $wangw = $whitelist['wangateips']; + $wandns = $whitelist['wandnsips']; + $vips = $whitelist['vips']; + $vpns = $whitelist['vpnips']; + if (!empty($whitelist['address']) && is_alias($whitelist['address'])) { + $home_net .= trim(filter_expand_alias($whitelist['address'])); + $home_net .= " "; + } + } /* build an interface array list */ if (function_exists('get_configured_interface_list')) @@ -109,13 +144,10 @@ function build_base_whitelist($build_netlist, $wanip, $wangw, $wandns, $vips, $v else { $int_array = array('lan'); for ($j = 1; isset ($config['interfaces']['opt' . $j]); $j++) - if(isset($config['interfaces']['opt' . $j]['enable'])) - if(isset($config['interfaces']['opt' . $j]['gateway'])) - $int_array[] = "opt{$j}"; + if(isset($config['interfaces']['opt' . $j]['enable'])) + $int_array[] = "opt{$j}"; } - $home_net = ""; - /* iterate through interface list and write out whitelist items * and also compile a home_net list for snort. */ @@ -124,8 +156,21 @@ function build_base_whitelist($build_netlist, $wanip, $wangw, $wandns, $vips, $v if (function_exists('get_interface_ip')) { $subnet = get_interface_ip($int); if (is_ipaddr($subnet)) { - $sn = get_interface_subnet($int); - $home_net .= "{$subnet}/{$sn} "; + if ($whitelist == false) { + $sn = get_interface_subnet($int); + $home_net .= "{$subnet}/{$sn} "; + } else + $home_net .= "{$subnet} "; + } + if (function_exists("get_interface_ipv6")) { + $subnet = get_interface_ipv6($int); + if (is_ipaddrv6($subnet)) { + if ($whitelist == false) { + $sn = get_interface_subnetv6($int); + $home_net .= "{$subnet}/{$sn} "; + } else + $home_net .= "{$subnet} "; + } } } else { $ifcfg = $config['interfaces'][$int]; @@ -148,35 +193,29 @@ function build_base_whitelist($build_netlist, $wanip, $wangw, $wandns, $vips, $v break; default: if (is_ipaddr($ifcfg['ipaddr'])) { - $subnet = gen_subnet($ifcfg['ipaddr'], $ifcfg['subnet']); - if ($ifcfg['subnet']) - $home_net .= "{$subnet}/{$ifcfg['subnet']} "; + $home_net .= "{$ifcfg['ipaddr']} "; } break; } } } - if ($snort_pfsense_basever == 'yes' && $wanip == 'yes') { - /* add all WAN ips to the whitelist */ - $wan_if = get_real_wan_interface(); - $ip = find_interface_ip($wan_if); - if (is_ipaddr($ip)) - $home_net .= "{$ip} "; - } - if ($wangw == 'yes') { - /* Add Gateway on WAN interface to whitelist (For RRD graphs) */ - $gw = get_interface_gateway('wan'); - if($gw) + $gw = get_interface_gateway($snortcfg['interface']); + if (is_ipaddr($gw)) $home_net .= "{$gw} "; + if (function_exists("get_interface_gatewayv6")) { + $gw = get_interface_gatewayv6($snortcfg['interface']); + if (is_ipaddrv6($gw)) + $home_net .= "{$gw} "; + } } - if($wandns == 'yes') { + if ($wandns == 'yes') { /* Add DNS server for WAN interface to whitelist */ $dns_servers = get_dns_servers(); foreach ($dns_servers as $dns) { - if($dns) + if ($dns) $home_net .= "{$dns} "; } } @@ -184,132 +223,122 @@ function build_base_whitelist($build_netlist, $wanip, $wangw, $wandns, $vips, $v if($vips == 'yes') { /* iterate all vips and add to whitelist */ if (is_array($config['virtualip']) && is_array($config['virtualip']['vip'])) { - foreach($config['virtualip']['vip'] as $vip) - if($vip['subnet']) - $home_net .= "{$vip['subnet']} "; + foreach($config['virtualip']['vip'] as $vip) { + if ($vip['subnet'] && $vip['mode'] != 'proxyarp') { + if ($whitelist == false) + $home_net .= "{$vip['subnet']}/{$vip['subnet_bits']} "; + else + $home_net .= "{$vip['subnet']} "; + } + } } } - /* Add loopback to whitelist (ftphelper) */ - $home_net .= "127.0.0.1 "; - /* grab a list of vpns and whitelist if user desires added by nestorfish 954 */ if ($vpns == 'yes') { - if ($snort_pfsense_basever == 'yes') // chk what pfsense version were on + if ($config['version'] <= 6) // chk what pfsense version were on $vpns_list = get_vpns_list(); - else if ($snort_pfsense_basever == 'no') // chk what pfsense version were on + else $vpns_list = filter_get_vpns_list(); if (!empty($vpns_list)) $home_net .= "{$vpns_list} "; } - /* never ever compair numbers to words */ - if ($userwips > -1) { - if (!is_array($config['installedpackages']['snortglobal']['whitelist']['item'])) - $config['installedpackages']['snortglobal']['whitelist']['item'] = array(); - - $home_net .= $config['installedpackages']['snortglobal']['whitelist']['item'][$userwips]['address']; - } - $home_net = trim($home_net); - - /* this foe whitelistfile, convert spaces to carriage returns */ - if ($build_netlist == 'whitelist') { - $whitelist_home_net = str_replace(" ", "\n", $home_net); - $whitelist_home_net = str_replace(" ", "\n", $home_net); - return $whitelist_home_net; - } - - /* this is for snort.conf */ $validator = explode(" ", $home_net); $valresult = array(); foreach ($validator as $vald) { if (empty($vald)) continue; - $valresult[] = $vald; + $vald = trim($vald); + if (empty($valresult[$vald])) + $valresult[$vald] = $vald; } - $home_net = implode(",", $valresult); - $home_net = "[{$home_net}]"; - return $home_net; + return $valresult; } +/* checks to see if service is running yes/no and stop/start */ +function snort_is_running($snort_uuid, $if_real, $type = 'snort') { + global $config, $g; -/* checks to see if snort is running yes/no and stop/start */ -function Running_Ck($snort_uuid, $if_real, $id) { - global $config; + if (file_exists("{$g['varrun_path']}/{$type}_{$if_real}{$snort_uuid}.pid") && isvalidpid("{$g['varrun_path']}/{$type}_{$if_real}{$snort_uuid}.pid")) + return 'yes'; + + return 'no'; +} - $snort_uph = 'no'; - $snort_up_prell = exec("/bin/ps -ax | /usr/bin/grep \"R {$snort_uuid}\" | /usr/bin/grep -v grep | /usr/bin/awk '{print \$1;}'"); - if ($snort_up_prell != '') - $snort_uph = 'yes'; +function snort_barnyard_stop($snortcfg, $if_real) { + global $config, $g; - return $snort_uph; + $snort_uuid = $snortcfg['uuid']; + if (file_exists("{$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid") && isvalidpid("{$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid")) { + killbypid("{$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid"); + @unlink("{$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid"); + } } -/* checks to see if barnyard2 is running yes/no */ -function Running_Ck_b($snort_uuid, $if_real, $id) { - global $config; +function snort_stop($snortcfg, $if_real) { + global $config, $g; - $snort_up_b = 'no'; - $snort_up_pre_b = exec("/bin/ps -ax | /usr/bin/grep barnyard2 | /usr/bin/grep \"f snort_{$snort_uuid}_{$if_real}.u2\" | /usr/bin/grep -v grep | /usr/bin/awk '{print \$1;}'"); - if ($snort_up_pre_b != '') - $snort_up_b = 'yes'; + $snort_uuid = $snortcfg['uuid']; + if (file_exists("{$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid") && isvalidpid("{$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid")) { + killbypid("{$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid"); + exec("/bin/rm {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid"); + } - return $snort_up_b; + snort_barnyard_stop($snortcfg, $if_real); + + log_error("Interface Rule STOP for {$snortcfg['descr']}({$if_real})..."); } -function Running_Stop($snort_uuid, $if_real, $id) { - global $config; +function snort_barnyard_start($snortcfg, $if_real) { + global $config, $g; - /* if snort.sh crashed this will remove the pid */ - @unlink('/tmp/snort.sh.pid'); - - $start_up = exec("/bin/ps -ax | /usr/bin/grep \"R {$snort_uuid}\" | /usr/bin/grep -v grep | /usr/bin/awk '{ print \$1; }'"); - $start_upb = exec("/bin/ps -ax | /usr/bin/grep \"snort_{$snort_uuid}_{$if_real}.u2\" | /usr/bin/grep -v grep | /usr/bin/awk '{ print \$1; }'"); - - if ($start_up != '') { - exec("/bin/kill {$start_up}"); - exec("/bin/rm /var/log/snort/run/snort_{$if_real}{$snort_uuid}*"); - exec("/bin/rm /var/log/snort/snort_{$snort_uuid}_{$if_real}*"); - exec("/bin/rm -r /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}"); - } + $snortdir = SNORTDIR; + $snort_uuid = $snortcfg['uuid']; - if ($start_upb != '') { - exec("/bin/kill {$start_upb}"); - exec("/bin/rm /var/run/barnyard2_{$snort_uuid}_{$if_real}*"); - exec("/bin/rm /var/log/snort/snort.u2_{$snort_uuid}_{$if_real}*"); - } + /* define snortbarnyardlog_chk */ + if ($snortcfg['barnyard_enable'] == 'on' && !empty($snortcfg['barnyard_mysql'])) + exec("/usr/local/bin/barnyard2 -r {$snort_uuid} -f \"snort_{$snort_uuid}_{$if_real}.u2\" --pid-path {$g['varrun_path']} --nolock-pidfile -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/barnyard2.conf -d /var/log/snort/snort_{$if_real}{$snort_uuid} -D -q"); - /* Log Iface stop */ - exec("/usr/bin/logger -p daemon.info -i -t SnortStartup 'Interface Rule STOP for {$snort_uuid}_{$if_real}...'"); - sleep(2); // Give time so GUI displays correctly } -function Running_Start($snort_uuid, $if_real, $id) { - global $config; +function snort_start($snortcfg, $if_real) { + global $config, $g; - /* if snort.sh crashed this will remove the pid */ - @unlink('/tmp/snort.sh.pid'); + $snortdir = SNORTDIR; + $snort_uuid = $snortcfg['uuid']; - $snort_info_chk = $config['installedpackages']['snortglobal']['rule'][$id]['enable']; - if ($snort_info_chk == 'on') - exec("/usr/local/bin/snort -R \"{$snort_uuid}\" -D -q -l /var/log/snort --pid-path /var/log/snort/run -G {$snort_uuid} -c /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/snort.conf -i {$if_real}"); + if ($snortcfg['enable'] == 'on') + exec("/usr/local/bin/snort -R {$snort_uuid} -D -q -l /var/log/snort/snort_{$if_real}{$snort_uuid} --pid-path {$g['varrun_path']} --nolock-pidfile -G {$snort_uuid} -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/snort.conf -i {$if_real}"); else return; - /* define snortbarnyardlog_chk */ - /* top will have trouble if the uuid is to far back */ - $snortbarnyardlog_info_chk = $config['installedpackages']['snortglobal']['rule'][$id]['barnyard_enable']; - $snortbarnyardlog_mysql_info_chk = $config['installedpackages']['snortglobal']['rule'][$id]['barnyard_mysql']; - if ($snortbarnyardlog_info_chk == 'on' && $snortbarnyardlog_mysql_info_chk != '') { - exec("/usr/local/bin/barnyard2 -f \"snort_{$snort_uuid}_{$if_real}.u2\" --pid-path /var/log/snort/run -c /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/barnyard2.conf -d /var/log/snort -D -q"); + snort_barnyard_start($snortcfg, $if_real); + + log_error("Interface Rule START for {$snortcfg['descr']}({$if_real})..."); +} + +function snort_get_friendly_interface($interface) { + + if (function_exists('convert_friendly_interface_to_friendly_descr')) + $iface = convert_friendly_interface_to_friendly_descr($interface); + else { + if (!$interface || ($interface == "wan")) + $iface = "WAN"; + else if(strtolower($interface) == "lan") + $iface = "LAN"; + else if(strtolower($interface) == "pppoe") + $iface = "PPPoE"; + else if(strtolower($interface) == "pptp") + $iface = "PPTP"; + else + $iface = strtoupper($interface); } - /* Log Iface stop */ - exec("/usr/bin/logger -p daemon.info -i -t SnortStartup 'Interface Rule START for {$id}_{$snort_uuid}_{$if_real}...'"); - sleep(2); // Give time so GUI displays correctly + return $iface; } /* get the real iface name of wan */ @@ -345,250 +374,68 @@ function snort_get_real_interface($interface) { snort is linked to these files while running, do not take the easy way out by touch and rm, snort will lose sync and not log. - this code needs to be watched. */ - -/* list dir files */ -function snort_file_list($snort_log_dir, $snort_log_file) -{ - $dir = opendir ("$snort_log_dir"); - while (false !== ($file = readdir($dir))) { - if (strpos($file, "$snort_log_file",1) ) - $file_list[] = basename($file); - } - return $file_list; -} - -/* snort dir files */ -function snort_file_sort($snort_file1, $snort_file2) -{ - if ($snort_file1 == $snort_file2) - return 0; - - return ($snort_file1 < $snort_file2); // ? -1 : 1; // this flips the array -} - -/* build files newest first array */ -function snort_build_order($snort_list) -{ - foreach ($snort_list as $value_list) - $list_order[] = $value_list; - - return $list_order; -} - -/* keep the newest remove the rest */ -function snort_remove_files($snort_list_rm, $snort_file_safe) -{ - foreach ($snort_list_rm as $value_list) { - if ($value_list != $snort_file_safe) - @unlink("/var/log/snort/$value_list"); - else - file_put_contents("/var/log/snort/$snort_file_safe", ""); - } -} - -function post_delete_logs() -{ +function snort_post_delete_logs($snort_uuid = 0) { global $config, $g; /* do not start config build if rules is empty */ if (!is_array($config['installedpackages']['snortglobal']['rule'])) return; - $snort_log_dir = '/var/log/snort'; - foreach ($config['installedpackages']['snortglobal']['rule'] as $value) { - $result_lan = $value['interface']; - $if_real = snort_get_real_interface($result_lan); - $snort_uuid = $value['uuid']; - - if ($if_real != '' && $snort_uuid != '') { - if ($value['snortunifiedlog'] == 'on') { - $snort_log_file_u2 = "{$snort_uuid}_{$if_real}.u2."; - $snort_list_u2 = snort_file_list($snort_log_dir, $snort_log_file_u2); - if (is_array($snort_list_u2)) { - usort($snort_list_u2, "snort_file_sort"); - $snort_u2_rm_list = snort_build_order($snort_list_u2); - snort_remove_files($snort_u2_rm_list, $snort_u2_rm_list[0]); - } - } else - exec("/bin/rm $snort_log_dir/snort_{$snort_uuid}_{$if_real}.u2*"); - - if ($value['tcpdumplog'] == 'on') { - $snort_log_file_tcpd = "{$snort_uuid}_{$if_real}.tcpdump."; - $snort_list_tcpd = snort_file_list($snort_log_dir, $snort_log_file_tcpd); - if (is_array($snort_list_tcpd)) { - usort($snort_list_tcpd, "snort_file_sort"); - $snort_tcpd_rm_list = snort_build_order($snort_list_tcpd); - snort_remove_files($snort_tcpd_rm_list, $snort_tcpd_rm_list[0]); + if ($value['uuid'] != $snort_uuid) + continue; + $if_real = snort_get_real_interface($value['interface']); + $snort_log_dir = "/var/log/snort/snort_{$if_real}{$snort_uuid}"; + + if ($if_real != '') { + $filelist = glob("{$snort_log_dir}/*{$snort_uuid}_{$if_real}.u2.*"); + unset($filelist[count($filelist) - 1]); + foreach ($filelist as $file) + @unlink($file); + + if ($value['perform_stat'] == 'on') { + $fd = fopen("{$snort_log_dir}/{$if_real}.stats", "w"); + if ($fd) { + ftruncate($fd, 0); + fclose($fd); } - } else - exec("/bin/rm $snort_log_dir/snort_{$snort_uuid}_{$if_real}.tcpdump*"); - - /* create barnyard2 configuration file */ - //if ($value['barnyard_enable'] == 'on') - //create_barnyard2_conf($id, $if_real, $snort_uuid); - - if ($value['perform_stat'] == 'on') - @file_put_contents("/var/log/snort/snort_{$snort_uuid}_{$if_real}.stats", ""); + } } } } -function snort_postinstall() -{ - global $config, $g, $snort_pfsense_basever, $snort_arch; +function snort_postinstall() { + global $config, $g; - /* snort -> advanced features */ - if (is_array($config['installedpackages']['snortglobal'])) { - $bpfbufsize = $config['installedpackages']['snortglobal']['bpfbufsize']; - $bpfmaxbufsize = $config['installedpackages']['snortglobal']['bpfmaxbufsize']; - $bpfmaxinsns = $config['installedpackages']['snortglobal']['bpfmaxinsns']; - } + $snortdir = SNORTDIR; /* cleanup default files */ - @rename('/usr/local/etc/snort/snort.conf-sample', '/usr/local/etc/snort/snort.conf'); - @rename('/usr/local/etc/snort/threshold.conf-sample', '/usr/local/etc/snort/threshold.conf'); - @rename('/usr/local/etc/snort/sid-msg.map-sample', '/usr/local/etc/snort/sid-msg.map'); - @rename('/usr/local/etc/snort/unicode.map-sample', '/usr/local/etc/snort/unicode.map'); - @rename('/usr/local/etc/snort/classification.config-sample', '/usr/local/etc/snort/classification.config'); - @rename('/usr/local/etc/snort/generators-sample', '/usr/local/etc/snort/generators'); - @rename('/usr/local/etc/snort/reference.config-sample', '/usr/local/etc/snort/reference.config'); - @rename('/usr/local/etc/snort/gen-msg.map-sample', '/usr/local/etc/snort/gen-msg.map'); - @unlink('/usr/local/etc/snort/sid'); - @unlink('/usr/local/etc/rc.d/snort'); - @unlink('/usr/local/etc/rc.d/bardyard2'); + @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}/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"); + @unlink("{$snortdir}/sid"); + @unlink("/usr/local/etc/rc.d/snort"); + @unlink("/usr/local/etc/rc.d/barnyard2"); /* remove example files */ if (file_exists('/usr/local/lib/snort/dynamicrules/lib_sfdynamic_example_rule.so.0')) - exec('/bin/rm /usr/local/lib/snort/dynamicrules/lib_sfdynamic_example*'); + exec('rm /usr/local/lib/snort/dynamicrules/lib_sfdynamic_example*'); if (file_exists('/usr/local/lib/snort/dynamicpreprocessor/lib_sfdynamic_preprocessor_example.so')) exec('/bin/rm /usr/local/lib/snort/dynamicpreprocessor/lib_sfdynamic_preprocessor_example*'); - /* XXX: In pfSense this really does not add much! - * add snort user and group note: 920 keep the numbers < 2000, above this is reserved in pfSense 2.0 - exec('/usr/sbin/pw groupadd snort -g 920'); - exec('/usr/sbin/pw useradd snort -u 920 -c "Snort User" -d /nonexistent -g snort -s /sbin/nologin'); - */ - - - /* create a few directories and ensure the sample files are in place */ - if (!is_dir('/usr/local/etc/snort')) - exec('/bin/mkdir -p /usr/local/etc/snort/custom_rules'); - - if (!is_dir('/usr/local/etc/snort/whitelist')) - exec('/bin/mkdir -p /usr/local/etc/snort/whitelist/'); - - if (!is_dir('/var/log/snort/run')) - exec('/bin/mkdir -p /var/log/snort/run'); - - if (!is_dir('/var/log/snort/barnyard2')) - exec('/bin/mkdir -p /var/log/snort/barnyard2'); - - if (!is_dir('/usr/local/lib/snort/dynamicrules/')) - exec('/bin/mkdir -p /usr/local/lib/snort/dynamicrules/'); - - if (!file_exists('/var/db/whitelist')) - touch('/var/db/whitelist'); - - /* if users have old log files delete them */ - if(!file_exists('/var/log/snort/alert')) - touch('/var/log/snort/alert'); - else { - exec('/bin/rm -rf /var/log/snort/*'); - touch('/var/log/snort/alert'); - } - - /* rm barnyard2 important */ - if (file_exists('/usr/local/bin/barnyard2')) - @unlink('/usr/local/bin/barnyard2'); - - /* XXX: These are needed if you run snort as snort user - mwexec('/usr/sbin/chown -R snort:snort /var/log/snort', true); - mwexec('/usr/sbin/chown -R snort:snort /usr/local/etc/snort', true); + /* + mwexec("/usr/sbin/chown -R snort:snort /var/log/snort", true); + mwexec("/usr/sbin/chown -R snort:snort {$snortdir}", true); mwexec('/usr/sbin/chown -R snort:snort /usr/local/lib/snort', true); mwexec('/usr/sbin/chown snort:snort /tmp/snort*', true); - mwexec('/usr/sbin/chown snort:snort /var/db/whitelist', true); */ - /* important */ - mwexec('/bin/chmod 660 /var/log/snort/alert', true); - mwexec('/bin/chmod 660 /var/db/whitelist', true); - mwexec('/bin/chmod -R 660 /usr/local/etc/snort/*', true); - mwexec('/bin/chmod -R 660 /tmp/snort*', true); - mwexec('/bin/chmod -R 660 /var/run/snort*', true); - mwexec('/bin/chmod -R 660 /var/snort/run/*', true); - mwexec('/bin/chmod 770 /usr/local/lib/snort', true); - mwexec('/bin/chmod 770 /usr/local/etc/snort', true); - mwexec('/bin/chmod 770 /usr/local/etc/whitelist', true); - mwexec('/bin/chmod 770 /var/log/snort', true); - mwexec('/bin/chmod 770 /var/log/snort/run', true); - mwexec('/bin/chmod 770 /var/log/snort/barnyard2', true); - - /* move files around, make it look clean */ - mwexec('/bin/mkdir -p /usr/local/www/snort/css'); - mwexec('/bin/mkdir -p /usr/local/www/snort/images'); - - chdir ("/usr/local/www/snort/css/"); - exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort/css/style.css'); - exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort/css/sexybuttons.css'); - chdir("/usr/local/www/snort/images/"); - exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort/images/alert.jpg'); - exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort/images/down.gif'); - exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort/images/down2.gif'); - exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort/images/icon-table-sort.png'); - exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort/images/icon-table-sort-asc.png'); - exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort/images/icon-table-sort-desc.png'); - exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort/images/up.gif'); - exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort/images/up2.gif'); - exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort/images/logo.jpg'); - exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort/images/icon_excli.png'); - exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort/images/arrow_down.png'); - exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort/images/awesome-overlay-sprite.png'); - exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort/images/logo22.png'); - exec('/usr/bin/fetch http://www.pfsense.com/packages/config/snort/images/page_white_text.png'); - - /* install barnyard2 for 2.0 x86 x64 and 1.2.3 x86 */ - update_status(gettext("Installing Barnyard2 for $snort_arch...")); - update_output_window(gettext("Please wait...")); - if ($snort_pfsense_basever == 'yes') - exec('/usr/bin/fetch -o /usr/local/bin/barnyard2 http://www.pfsense.com/packages/config/snort/bin/7.3.x86/barnyard2'); - else if ($snort_pfsense_basever == 'no') { - if ($snort_arch == 'x64') - exec("/usr/bin/fetch -o /usr/local/bin/barnyard2 http://files.pfsense.org/packages/amd64/8/All/barnyard2"); - else - exec("/usr/bin/fetch -o /usr/local/bin/barnyard2 http://files.pfsense.org/packages/8/All/barnyard2"); - exec('/bin/chmod 0755 /usr/local/bin/barnyard2'); - } - update_output_window(gettext("Finnished Installing Barnyard2...")); - - /* XXX: remove compeletely? */ - if ($snort_pfsense_basever == 'yes') { - if (!is_dir('/tmp/pkg_s')) - exec('/bin/mkdir -p /tmp/pkg_s'); - - $snort_tmp_pkg_dir = "{$g['tmp_path']}/pkg_s"; - chdir('$snort_tmp_pkg_dir'); - - /* install perl-threaded */ - update_status(gettext("Installing perl-threaded for {$snort_arch}...")); - update_output_window(gettext("Please wait downloading...")); - exec("/usr/bin/fetch http://files.pfsense.org/packages/snort/7.3x86/perl-threaded-5.12.1_1.tbz"); - - update_output_window(gettext("Please wait Installing...")); - if (file_exists("{$snort_tmp_pkg_dir}/perl-threaded-5.12.1_1.tbz")) - exec("/usr/sbin/pkg_add -f {$snort_tmp_pkg_dir}/perl-threaded-5.12.1_1.tbz"); - - update_output_window(gettext("Finnished Installing perl-threaded...")); - - update_output_window(gettext("Please wait Cleaning Up...")); - if (is_dir($snort_tmp_pkg_dir)) - exec("/bin/rm -r {$snort_tmp_pkg_dir}"); - - /* back to default */ - chdir('/root/'); - } /* remake saved settings */ if ($config['installedpackages']['snortglobal']['forcekeepsettings'] == 'on') { @@ -617,7 +464,7 @@ function snort_snortloglimit_install_cron($should_install) { $x=0; $is_installed = false; foreach($config['cron']['item'] as $item) { - if (strstr($item['command'], '/usr/local/pkg/snort/snort_check_cron_misc.inc')) { + if (strstr($item['command'], 'snort_check_cron_misc.inc')) { $is_installed = true; break; } @@ -830,18 +677,9 @@ function snort_rules_up_install_cron($should_install) { } /* Only run when all ifaces needed to sync. Expects filesystem rw */ -function sync_snort_package_config() -{ +function sync_snort_package_config() { global $config, $g; - /* RedDevil suggested code */ - /* TODO: more testing needs to be done */ - /* may cause voip to fail */ - //exec("/sbin/sysctl net.bpf.bufsize=8388608"); - //exec("/sbin/sysctl net.bpf.maxbufsize=4194304"); - //exec("/sbin/sysctl net.bpf.maxinsns=512"); - //exec("/sbin/sysctl net.inet.tcp.rfc1323=1"); - conf_mount_rw(); /* do not start config build if rules is empty */ @@ -851,246 +689,126 @@ function sync_snort_package_config() return; } - foreach ($config['installedpackages']['snortglobal']['rule'] as $id => $value) { + $snortconf = $config['installedpackages']['snortglobal']['rule']; + foreach ($snortconf as $value) { $if_real = snort_get_real_interface($value['interface']); - $snort_uuid = $value['uuid']; - - if ($if_real != '' && $snort_uuid != '') { - - /* only build whitelist when needed */ - if ($value['blockoffenders7'] == 'on') - create_snort_whitelist($id, $if_real); - /* only build threshold when needed */ - if ($value['suppresslistname'] != 'default') - create_snort_suppress($id, $if_real); + /* create snort configuration file */ + snort_generate_conf($value); - /* create snort configuration file */ - create_snort_conf($id, $if_real, $snort_uuid); - - /* if rules exist cp rules to each iface */ - create_rules_iface($id, $if_real, $snort_uuid); - - /* create barnyard2 configuration file */ - if ($value['barnyard_enable'] == 'on') - create_barnyard2_conf($id, $if_real, $snort_uuid); - } + /* create barnyard2 configuration file */ + if ($value['barnyard_enable'] == 'on') + snort_create_barnyard2_conf($value, $if_real); } /* create snort bootup file snort.sh only create once */ - create_snort_sh(); + snort_create_rc(); - /* all new files are for the user snort nologin */ - if (!is_dir('/var/log/snort')) - exec('/bin/mkdir -p /var/log/snort'); + $snortglob = $config['installedpackages']['snortglobal']; - if (!is_dir('/var/log/snort/run')) - exec('/bin/mkdir -p /var/log/snort/run'); + snort_snortloglimit_install_cron($snortglob['snortloglimit'] == 'on' ? true : false); - if (!is_dir('/var/log/snort/barnyard2')) - exec('/bin/mkdir -p /var/log/snort/barnyard2'); + /* set the snort block hosts time IMPORTANT */ + snort_rm_blocked_install_cron($snortglob['rm_blocked'] != "never_b" ? true : false); - /* all new files are for the user snort nologin */ - if (!file_exists('/var/log/snort/alert')) - exec('/usr/bin/touch /var/log/snort/alert'); - - /* XXX: These are needed if snort is run as snort user - mwexec('/usr/sbin/chown -R snort:snort /var/log/snort', true); - mwexec('/usr/sbin/chown -R snort:snort /usr/local/etc/snort', true); - mwexec('/usr/sbin/chown -R snort:snort /usr/local/lib/snort', true); - mwexec('/usr/sbin/chown snort:snort /tmp/snort*', true); - mwexec('/usr/sbin/chown snort:snort /var/db/whitelist', true); - */ + /* set the snort rules update time */ + snort_rules_up_install_cron($snortglob['autorulesupdate7'] != "never_up" ? true : false); - /* important */ - mwexec('/bin/chmod 770 /var/db/whitelist', true); - mwexec('/bin/chmod 770 /var/run/snort*', true); - mwexec('/bin/chmod 770 /tmp/snort*', true); - mwexec('/bin/chmod -R 770 /var/log/snort', true); - mwexec('/bin/chmod -R 770 /usr/local/lib/snort', true); - mwexec('/bin/chmod -R 770 /usr/local/etc/snort/', true); + configure_cron(); conf_mount_ro(); } /* Start of main config files */ - -/* create threshold file */ -function create_snort_suppress($id, $if_real) { +/* open snort.sh for writing" */ +function snort_create_rc() { global $config, $g; - /* make sure dir is there */ - if (!is_dir('/usr/local/etc/snort/suppress')) - exec('/bin/mkdir -p /usr/local/etc/snort/suppress'); + $snortdir = SNORTDIR; if (!is_array($config['installedpackages']['snortglobal']['rule'])) return; - if ($config['installedpackages']['snortglobal']['rule'][$id]['suppresslistname'] != 'default') { - $whitelist_key_s = find_suppress_key($config['installedpackages']['snortglobal']['rule'][$id]['suppresslistname']); - - /* file name */ - $suppress_file_name = $config['installedpackages']['snortglobal']['suppress']['item'][$whitelist_key_s]['name']; - - /* Message */ - $s_data = '# This file is auto generated by the snort package. Please do not edit this file by hand.' . "\n\n"; - - /* user added arguments */ - $s_data .= str_replace("\r", "", base64_decode($config['installedpackages']['snortglobal']['suppress']['item'][$whitelist_key_s]['suppresspassthru'])); - - /* open snort's whitelist for writing */ - @file_put_contents("/usr/local/etc/snort/suppress/$suppress_file_name", $s_data); - } -} - -function create_snort_whitelist($id, $if_real) { - global $config, $g; - - /* make sure dir is there */ - if (!is_dir('/usr/local/etc/snort/whitelist')) - exec('/bin/mkdir -p /usr/local/etc/snort/whitelist'); - - if ($config['installedpackages']['snortglobal']['rule'][$id]['whitelistname'] == 'default') { - - $w_data = build_base_whitelist('whitelist', 'yes', 'yes', 'yes', 'yes', 'yes', 'no'); - - /* open snort's whitelist for writing */ - @file_put_contents("/usr/local/etc/snort/whitelist/defaultwlist", $w_data); - - } else if (!empty($config['installedpackages']['snortglobal']['rule'][$id]['whitelistname'])) { - $whitelist_key_w = find_whitelist_key($config['installedpackages']['snortglobal']['rule'][$id]['whitelistname']); - - if (!is_array($config['installedpackages']['snortglobal']['whitelist']['item'])) - return; - - $whitelist = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_w]; - $w_data = build_base_whitelist($whitelist['snortlisttype'], $whitelist['wanips'], $whitelist['wangateips'], - $whitelist['wandnsips'], $whitelist['vips'], $whitelist['vpnips'], $whitelist_key_w); - - /* open snort's whitelist for writing */ - @file_put_contents("/usr/local/etc/snort/whitelist/" . $config['installedpackages']['snortglobal']['rule'][$id]['whitelistname'], $w_data); - } -} - -function create_snort_homenet($id, $if_real) { - global $config, $g; - - if ($config['installedpackages']['snortglobal']['rule'][$id]['homelistname'] == 'default' || $config['installedpackages']['snortglobal']['rule'][$id]['homelistname'] == '') - return build_base_whitelist('netlist', 'yes', 'yes', 'yes', 'yes', 'yes', 'no'); - else if (!empty($config['installedpackages']['snortglobal']['rule'][$id]['homelistname'])) { - $whitelist_key_h = find_whitelist_key($config['installedpackages']['snortglobal']['rule'][$id]['homelistname']); - - if (!is_array($config['installedpackages']['snortglobal']['whitelist']['item'])) - return; - - $build_netlist_h = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_h]['snortlisttype']; - $wanip_h = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_h]['wanips']; - $wangw_h = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_h]['wangateips']; - $wandns_h = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_h]['wandnsips']; - $vips_h = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_h]['vips']; - $vpns_h = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_h]['vpnips']; - - return build_base_whitelist($build_netlist_h, $wanip_h, $wangw_h, $wandns_h, $vips_h, $vpns_h, $whitelist_key_h); - } -} - -function create_snort_externalnet($id, $if_real) { - global $config, $g; - - if (!empty($config['installedpackages']['snortglobal']['rule'][$id]['externallistname'])) { - $whitelist_key_ex = find_whitelist_key($config['installedpackages']['snortglobal']['rule'][$id]['externallistname']); - - if (!is_array($config['installedpackages']['snortglobal']['whitelist']['item'])) - return; - - $build_netlist_ex = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_ex]['snortlisttype']; - $wanip_ex = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_ex]['wanips']; - $wangw_ex = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_ex]['wangateips']; - $wandns_ex = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_ex]['wandnsips']; - $vips_ex = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_ex]['vips']; - $vpns_ex = $config['installedpackages']['snortglobal']['whitelist']['item'][$whitelist_key_ex]['vpnips']; - - return build_base_whitelist($build_netlist_ex, $wanip_ex, $wangw_ex, $wandns_ex, $vips_ex, $vpns_ex, $whitelist_key_ex); - } -} - -/* open snort.sh for writing" */ -function create_snort_sh() -{ - global $config, $g; - - if (!is_array($config['installedpackages']['snortglobal']['rule'])) + $snortconf =& $config['installedpackages']['snortglobal']['rule']; + /* do not start config build if rules is empty */ + if (empty($snortconf)) return; - $snortconf =& $config['installedpackages']['snortglobal']['rule']; + $start_snort_iface_start = array(); + $start_snort_iface_stop = array(); + foreach ($snortconf as $value) { + $snort_uuid = $value['uuid']; + $if_real = snort_get_real_interface($value['interface']); - $snort_sh_text3 = array(); - $snort_sh_text4 = array(); + $start_barnyard = <<<EOE - /* do not start config build if rules is empty */ - if (!empty($snortconf)) { - foreach ($snortconf as $value) { - $snort_uuid = $value['uuid']; - $result_lan = $value['interface']; - $if_real = snort_get_real_interface($result_lan); + if [ ! -f {$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid ]; then + /bin/pgrep -xf '/usr/local/bin/barnyard2 -r {$snort_uuid} -f snort_{$snort_uuid}_{$if_real}.u2 --pid-path {$g['varrun_path']} --nolock-pidfile -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/barnyard2.conf -d /var/log/snort/snort_{$if_real}{$snort_uuid} -D -q' > {$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid + fi + /bin/pgrep -F {$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid + if [ $? = 0 ]; then + /bin/pkill -HUP -F {$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid -a + else + /usr/local/bin/barnyard2 -r {$snort_uuid} -f snort_{$snort_uuid}_{$if_real}.u2 --pid-path {$g['varrun_path']} --nolock-pidfile -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/barnyard2.conf -d /var/log/snort/snort_{$if_real}{$snort_uuid} -D -q + fi - /* define snortbarnyardlog_chk */ - $snortbarnyardlog_info_chk = $value['barnyard_enable']; - $snortbarnyardlog_mysql_info_chk = $value['barnyard_mysql']; +EOE; + $stop_barnyard2 = <<<EOE - if ($snortbarnyardlog_info_chk == 'on' && $snortbarnyardlog_mysql_info_chk != '') - $start_barnyard2 = "sleep 4;/usr/local/bin/barnyard2 -f snort_{$snort_uuid}_{$if_real}.u2 --pid-path /var/log/snort/run -c /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/barnyard2.conf -d /var/log/snort -D -q"; + if [ -f {$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid ]; then + /bin/pkill -F {$g['varrun_path']}/barnyard2_{$if_real}{$snort_uuid}.pid -a + /bin/rm /var/run/barnyard2_{$if_real}{$snort_uuid}.pid + else + /bin/pkill -xf '/usr/local/bin/barnyard2 -r {$snort_uuid} -f snort_{$snort_uuid}_{$if_real}.u2 --pid-path {$g['varrun_path']} --nolock-pidfile -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/barnyard2.conf -d /var/log/snort/snort_{$if_real}{$snort_uuid} -D -q' + fi - $snort_sh_text3[] = <<<EOE +EOE; + if ($value['barnyard_enable'] == 'on' && !empty($value['barnyard_mysql'])) + $start_barnyard2 = $start_barnyard; + else + $start_barnyard2 = $stop_barnyard2; -###### For Each Iface + $start_snort_iface_start[] = <<<EOE -#### Fake start only used on bootup and Pfsense IP changes +###### For Each Iface #### Only try to restart if snort is running on Iface -if [ "`/bin/ps -ax | /usr/bin/grep "R {$snort_uuid}" | /usr/bin/grep -v grep | /usr/bin/awk '{print $1;}'`" != "" ]; then - snort_pid=`/bin/ps -ax | /usr/bin/grep "R {$snort_uuid}" | /usr/bin/grep -v grep | /usr/bin/awk '{print $1;}'` - /usr/bin/logger -p daemon.info -i -t SnortStartup "Snort already running, soft restart" - - #### Restart Iface - /bin/kill -HUP \${snort_pid} - /usr/bin/logger -p daemon.info -i -t SnortStartup "Snort Soft Reload For {$snort_uuid}_{$if_real}..." -else - # Start snort and barnyard2 - /bin/echo "snort.sh run" > /tmp/snort.sh.pid - /bin/rm /var/run/snort_{$snort_uuid}_{$if_real}.pid - - /usr/local/bin/snort -R {$snort_uuid} -D -q -l /var/log/snort --pid-path /var/log/snort/run -G {$snort_uuid} -c /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/snort.conf -i {$if_real} - $start_barnyard2 + if [ ! -f {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid ]; then + /bin/pgrep -xf '/usr/local/bin/snort -R {$snort_uuid} -D -q -l /var/log/snort/snort_{$if_real}{$snort_uuid} --pid-path {$g['varrun_path']} --nolock-pidfile -G {$snort_uuid} -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/snort.conf -i {$if_real}' > {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid + fi + /bin/pgrep -nF {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid + if [ $? = 0 ]; then + /bin/pkill -HUP -F {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid -a + /usr/bin/logger -p daemon.info -i -t SnortStartup "Snort SOFT START For {$value['descr']}({$snort_uuid}_{$if_real})..." + else + # Start snort and barnyard2 + /bin/rm {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid + /usr/local/bin/snort -R {$snort_uuid} -D -q -l /var/log/snort/snort_{$if_real}{$snort_uuid} --pid-path {$g['varrun_path']} --nolock-pidfile -G {$snort_uuid} -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/snort.conf -i {$if_real} + /usr/bin/logger -p daemon.info -i -t SnortStartup "Snort START For {$value['descr']}({$snort_uuid}_{$if_real})..." + fi - /usr/bin/logger -p daemon.info -i -t SnortStartup "Snort HARD START For {$snort_uuid}_{$if_real}..." -fi + sleep 2 + {$start_barnyard2} EOE; - $snort_sh_text4[] = <<<EOF - -pid_s=`/bin/ps -ax | /usr/bin/grep "R {$snort_uuid}" | /usr/bin/grep -v grep | /usr/bin/awk '{print \$1;}'` -sleep 3 -pid_b=`/bin/ps -ax | /usr/bin/grep "snort_{$snort_uuid}_{$if_real}.u2" | /usr/bin/grep -v grep | /usr/bin/awk '{print \$1;}'` -if [ \${pid_s} ] ; then - - /bin/echo "snort.sh run" > /tmp/snort.sh.pid - /usr/bin/logger -p daemon.info -i -t SnortStartup "Snort HARD STOP For {$snort_uuid}_{$if_real}..." + $start_snort_iface_stop[] = <<<EOE - /bin/kill \${pid_s} - sleep 3 - /bin/kill \${pid_b} + /usr/bin/logger -p daemon.info -i -t SnortStartup "Snort STOP For {$value['descr']}({$snort_uuid}_{$if_real})..." + if [ -f {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid ]; then + /bin/pkill -F {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid -a + /bin/rm /var/run/snort_{$if_real}{$snort_uuid}.pid + else + /bin/pkill -xf '/usr/local/bin/snort -R {$snort_uuid} -D -q -l /var/log/snort/snort_{$if_real}{$snort_uuid} --pid-path {$g['varrun_path']} --nolock-pidfile -G {$snort_uuid} -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/snort.conf -i {$if_real}' + fi - /bin/rm /var/run/snort_{$snort_uuid}_{$if_real}.pid -fi + sleep 2 + {$stop_barnyard2} -EOF; - } +EOE; } - - $start_snort_iface_start = implode("\n\n", $snort_sh_text3); - $start_snort_iface_stop = implode("\n\n", $snort_sh_text4); + $rc_start = implode("\n", $start_snort_iface_start); + $rc_stop = implode("\n", $start_snort_iface_stop); $snort_sh_text = <<<EOD #!/bin/sh @@ -1101,18 +819,11 @@ EOF; ######## Begining of Main snort.sh rc_start() { - - /bin/echo "snort.sh run" > /tmp/snort.sh.pid - $start_snort_iface_start - /bin/rm /tmp/snort.sh.pid + {$rc_start} } rc_stop() { - - $start_snort_iface_stop - /bin/rm /tmp/snort.sh.pid - /bin/rm /var/run/snort* - + {$rc_stop} } case $1 in @@ -1130,70 +841,46 @@ esac EOD; /* write out snort.sh */ - $bconf = fopen("/usr/local/etc/rc.d/snort.sh", "w"); - if(!$bconf) { + if (!@file_put_contents("/usr/local/etc/rc.d/snort.sh", $snort_sh_text)) { log_error("Could not open /usr/local/etc/rc.d/snort.sh for writing."); return; } - fwrite($bconf, $snort_sh_text); - fclose($bconf); @chmod("/usr/local/etc/rc.d/snort.sh", 0755); } -/* if rules exist copy to new interfaces */ -function create_rules_iface($id, $if_real, $snort_uuid) -{ - global $config, $g; - - $if_rule_dir = "/usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}"; - $folder_chk = (count(glob("{$if_rule_dir}/rules/*")) === 0) ? 'empty' : 'full'; - - if ($folder_chk == "empty") { - if (!is_dir("/usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/rules")) - exec("/bin/mkdir -p /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/rules"); - exec("/bin/cp /usr/local/etc/snort/rules/* {$if_rule_dir}/rules"); - if (file_exists("/usr/local/etc/snort/custom_rules/local_{$snort_uuid}_{$if_real}.rules")) - exec("/bin/cp /usr/local/etc/snort/custom_rules/local_{$snort_uuid}_{$if_real}.rules {$if_rule_dir}/local_{$snort_uuid}_{$if_real}.rules"); - } -} - /* open barnyard2.conf for writing */ -function create_barnyard2_conf($id, $if_real, $snort_uuid) { +function snort_create_barnyard2_conf($snortcfg, $if_real) { global $config, $g; - if (!file_exists("/usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/barnyard2.conf")) - exec("/usr/bin/touch /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/barnyard2.conf"); + $snortdir = SNORTDIR; + $snort_uuid = $snortcfg['uuid']; - if (!file_exists("/var/log/snort/barnyard2/{$snort_uuid}_{$if_real}.waldo")) { - mwexec("/usr/bin/touch /var/log/snort/barnyard2/{$snort_uuid}_{$if_real}.waldo", true); - /* XXX: This is needed if snort is run as snort user */ - //mwexec("/usr/sbin/chown snort:snort /var/log/snort/barnyard2/{$snort_uuid}_{$if_real}.waldo", true); + if (!file_exists("{$snortdir}/snort_{$snort_uuid}_{$if_real}/barnyard2.conf")) + exec("/usr/bin/touch {$snortdir}/snort_{$snort_uuid}_{$if_real}/barnyard2.conf"); + + if (!file_exists("/var/log/snort/snort_{$if_real}{$snort_uuid}/barnyard2/{$snort_uuid}_{$if_real}.waldo")) { + @touch("/var/log/snort/snort_{$if_real}{$snort_uuid}/barnyard2/{$snort_uuid}_{$if_real}.waldo"); mwexec("/bin/chmod 770 /var/log/snort/barnyard2/{$snort_uuid}_{$if_real}.waldo", true); } - $barnyard2_conf_text = generate_barnyard2_conf($id, $if_real, $snort_uuid); + $barnyard2_conf_text = snort_generate_barnyard2_conf($snortcfg, $if_real); /* write out barnyard2_conf */ - $bconf = fopen("/usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/barnyard2.conf", "w"); - if(!$bconf) { - log_error("Could not open /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/barnyard2.conf for writing."); - return; - } - fwrite($bconf, $barnyard2_conf_text); - fclose($bconf); + @file_put_contents("{$snortdir}/snort_{$snort_uuid}_{$if_real}/barnyard2.conf", $barnyard2_conf_text); } /* open barnyard2.conf for writing" */ -function generate_barnyard2_conf($id, $if_real, $snort_uuid) { +function snort_generate_barnyard2_conf($snortcfg, $if_real) { global $config, $g; - /* define snortbarnyardlog */ - /* TODO: add support for the other 5 output plugins */ + $snortdir = SNORTDIR; + $snort_uuid = $snortcfg['uuid']; - $snortbarnyardlog_database_info_chk = $config['installedpackages']['snortglobal']['rule'][$id]['barnyard_mysql']; - $snortbarnyardlog_hostname_info_chk = exec("/bin/hostname"); + /* TODO: add support for the other 5 output plugins */ + $snortbarnyardlog_database_info_chk = $snortcfg['barnyard_mysql']; + $snortbarnyardlog_hostname_info_chk = php_uname("n"); /* user add arguments */ - $snortbarnyardlog_config_pass_thru = str_replace("\r", "", base64_decode($config['installedpackages']['snortglobal']['rule'][$id]['barnconfigpassthru'])); + $snortbarnyardlog_config_pass_thru = str_replace("\r", "", base64_decode($snortcfg['barnconfigpassthru'])); $barnyard2_conf_text = <<<EOD @@ -1202,15 +889,15 @@ function generate_barnyard2_conf($id, $if_real, $snort_uuid) { # # set the appropriate paths to the file(s) your Snort process is using -config reference_file: /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/reference.config -config classification_file: /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/classification.config -config gen_file: /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/gen-msg.map -config sid_file: /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/sid-msg.map +config reference_file: {$snortdir}/snort_{$snort_uuid}_{$if_real}/reference.config +config classification_file: {$snortdir}/snort_{$snort_uuid}_{$if_real}/classification.config +config gen_file: {$snortdir}/snort_{$snort_uuid}_{$if_real}/gen-msg.map +config sid_file: {$snortdir}/snort_{$snort_uuid}_{$if_real}/sid-msg.map config hostname: $snortbarnyardlog_hostname_info_chk -config interface: {$snort_uuid}_{$if_real} +config interface: {$if_real} config decode_data_link -config waldo_file: /var/log/snort/barnyard2/{$snort_uuid}_{$if_real}.waldo +config waldo_file: /var/log/snort/snort_{$if_real}{$snort_uuid}/barnyard2/{$snort_uuid}_{$if_real}.waldo ## START user pass through ## @@ -1221,7 +908,7 @@ config waldo_file: /var/log/snort/barnyard2/{$snort_uuid}_{$if_real}.waldo # Step 2: setup the input plugins input unified2 -config logdir: /var/log/snort +config logdir: /var/log/snort/snort_{$if_real}{$snort_uuid} # database: log to a variety of databases # output database: log, mysql, user=xxxx password=xxxxxx dbname=xxxx host=xxx.xxx.xxx.xxxx @@ -1233,39 +920,13 @@ EOD; return $barnyard2_conf_text; } -function create_snort_conf($id, $if_real, $snort_uuid) -{ - global $config, $g; - - if (!empty($if_real)&& !empty($snort_uuid)) { - if (!is_dir("/usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}")) { - exec("/bin/mkdir -p /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}"); - @touch("/usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/snort.conf"); - } - - $snort_conf_text = generate_snort_conf($id, $if_real, $snort_uuid); - if (empty($snort_conf_text)) - return; - - /* write out snort.conf */ - $conf = fopen("/usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/snort.conf", "w"); - if(!$conf) { - log_error("Could not open /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/snort.conf for writing."); - return -1; - } - fwrite($conf, $snort_conf_text); - fclose($conf); - } -} - function snort_deinstall() { global $config, $g; - /* remove custom sysctl */ - remove_text_from_file("/etc/sysctl.conf", "sysctl net.bpf.bufsize=20480"); + $snortdir = SNORTDIR; + $snortlogdir = SNORTLOGDIR; /* decrease bpf buffers back to 4096, from 20480 */ - exec('/sbin/sysctl net.bpf.bufsize=4096'); mwexec('/usr/bin/killall snort', true); sleep(2); mwexec('/usr/bin/killall -9 snort', true); @@ -1275,9 +936,19 @@ function snort_deinstall() { mwexec('/usr/bin/killall -9 barnyard2', true); sleep(2); mwexec('/usr/sbin/pw userdel snort; /usr/sbin/pw groupdel snort', true); - mwexec('/bin/rm -rf /usr/local/etc/snort*; /bin/rm -rf /usr/local/pkg/snort*', true); - mwexec('/bin/rm -r /usr/local/bin/barnyard2', true); - mwexec('/bin/rm -rf /usr/local/www/snort; /bin/rm -rf /var/log/snort', true); + + if (!function_exists("get_interface_ipv6")) { + /* create a few directories and ensure the sample files are in place */ + $snort_dirs = array( $snortdir, $snortlogdir, + "dynamicrules" => "/usr/local/lib/snort/dynamicrules", + "dynamicengine" => "/usr/local/lib/snort/dynamicengine", + "dynamicpreprocessor" => "/usr/local/lib/snort/dynamicpreprocessor" + ); + foreach ($snort_dirs as $dir) { + if (is_dir($dir)) + mwexec("/bin/rm -rf {$dir}", true); + } + } /* Remove snort cron entries Ugly code needs smoothness*/ if (!function_exists('snort_deinstall_cron')) { @@ -1303,73 +974,68 @@ function snort_deinstall() { snort_deinstall_cron("snort2c"); snort_deinstall_cron("snort_check_for_rule_updates.php"); - snort_deinstall_cron("/usr/local/pkg/snort/snort_check_cron_misc.inc"); + snort_deinstall_cron("snort_check_cron_misc.inc"); configure_cron(); - /* Unset snort registers in conf.xml IMPORTANT snort will not start with out this */ /* Keep this as a last step */ if ($config['installedpackages']['snortglobal']['forcekeepsettings'] != 'on') unset($config['installedpackages']['snortglobal']); } -function generate_snort_conf($id, $if_real, $snort_uuid) -{ - global $config, $g, $snort_pfsense_basever; +function snort_generate_conf($snortcfg) { + global $config, $g; + + $snortdir = SNORTDIR; + $snortlogdir = SNORTLOGDIR; if (!is_array($config['installedpackages']['snortglobal']['rule'])) return; - $snortcfg =& $config['installedpackages']['snortglobal']['rule'][$id]; + $if_real = snort_get_real_interface($snortcfg['interface']); + $snort_uuid = $snortcfg['uuid']; + $snortcfgdir = "{$snortdir}/snort_{$snort_uuid}_{$if_real}"; /* custom home nets */ - $home_net = create_snort_homenet($id, $if_real); + $home_net_list = snort_build_list($snortcfg, $snortcfg['homelistname']); + $home_net = implode(",", $home_net_list); - if ($snortcfg['externallistname'] == 'default') - $external_net = '!$HOME_NET'; - else - $external_net = create_snort_externalnet($id, $if_real); - - /* obtain external interface */ - /* XXX: make multi wan friendly */ - $snort_ext_int = $snortcfg['interface']; + $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'])); - /* create basic files */ - if (!is_dir("/usr/local/etc/snort/snort/snort_{$snort_uuid}_{$if_real}")) - exec("/bin/mkdir -p /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}"); - - exec("/bin/cp /usr/local/etc/snort/gen-msg.map /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/gen-msg.map"); - exec("/bin/cp /usr/local/etc/snort/classification.config /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/classification.config"); - exec("/bin/cp /usr/local/etc/snort/reference.config /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/reference.config"); - exec("/bin/cp /usr/local/etc/snort/sid-msg.map /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/sid-msg.map"); - exec("/bin/cp /usr/local/etc/snort/unicode.map /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/unicode.map"); - exec("/bin/cp /usr/local/etc/snort/threshold.conf /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/threshold.conf"); - exec("/usr/bin/touch /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/barnyard2.conf"); - - if (!is_dir("/usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/rules")) - exec("/bin/mkdir -p /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/rules"); - - /* define basic log filename */ - $snortunifiedlogbasic_type = "output unified: filename snort_{$snort_uuid}_{$if_real}.log, limit 128"; + /* 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" => "{$snortcfgdir}/dynamicrules", + "dynamicengine" => "/usr/local/lib/snort/dynamicengine", + "dynamicpreprocessor" => "{$snortcfgdir}/dynamicpreprocessor" + ); + foreach ($snort_dirs as $dir) { + if (!is_dir($dir)) + safe_mkdir($dir); + } - /* define snortalertlogtype */ - if ($config['installedpackages']['snortglobal']['snortalertlogtype'] == "fast") - $snortalertlogtype_type = "output alert_fast: alert"; - else - $snortalertlogtype_type = "output alert_full: alert"; + $snort_files = array("gen-msg.map", "classification.config", "reference.config", + "sid-msg.map", "unicode.map", "threshold.conf", "preproc_rules/preprocessor.rules", + "preproc_rules/decoder.rules", "preproc_rules/sensitive-data.rules" + ); + foreach ($snort_files as $file) { + if (file_exists("{$snortdir}/{$file}")) + @copy("{$snortdir}/{$file}", "{$snortcfgdir}/{$file}"); + } /* define alertsystemlog */ $alertsystemlog_type = ""; if ($snortcfg['alertsystemlog'] == "on") $alertsystemlog_type = "output alert_syslog: log_alert"; - /* define tcpdumplog */ - $tcpdumplog_type = ""; - if ($snortcfg['tcpdumplog'] == "on") - $tcpdumplog_type = "output log_tcpdump: snort_{$snort_uuid}_{$if_real}.tcpdump"; - /* define snortunifiedlog */ $snortunifiedlog_type = ""; if ($snortcfg['snortunifiedlog'] == "on") @@ -1378,338 +1044,83 @@ function generate_snort_conf($id, $if_real, $snort_uuid) /* define spoink */ $spoink_type = ""; if ($snortcfg['blockoffenders7'] == "on") { - if ($snortcfg['whitelistname'] == "default") - $spoink_whitelist_name = 'defaultwlist'; - else if (file_exists("/usr/local/etc/snort/whitelist/{$snortcfg['whitelistname']}")) - $spoink_whitelist_name = $snortcfg['whitelistname']; - $pfkill = ""; if ($snortcfg['blockoffenderskill'] == "on") $pfkill = "kill"; - - $spoink_type = "output alert_pf: /usr/local/etc/snort/whitelist/{$spoink_whitelist_name},snort2c,{$snortcfg['blockoffendersip']},{$pfkill}"; + /* No subnets to default addresses */ + $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 threshold file */ - $threshold_file_name = ""; - if ($snortcfg['suppresslistname'] != 'default') { - if (file_exists("/usr/local/etc/snort/suppress/{$snortcfg['suppresslistname']}")) - $threshold_file_name = "include /usr/local/etc/snort/suppress/{$snortcfg['suppresslistname']}"; + /* 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']}"; } - /* define servers and ports snortdefservers */ - /* def DNS_SERVSERS */ - $def_dns_servers_info_chk = $snortcfg['def_dns_servers']; - if ($def_dns_servers_info_chk == "") - $def_dns_servers_type = "\$HOME_NET"; - else - $def_dns_servers_type = "$def_dns_servers_info_chk"; - - /* def DNS_PORTS */ - $def_dns_ports_info_chk = $snortcfg['def_dns_ports']; - if ($def_dns_ports_info_chk == "") - $def_dns_ports_type = "53"; - else - $def_dns_ports_type = "$def_dns_ports_info_chk"; - - /* def SMTP_SERVSERS */ - $def_smtp_servers_info_chk = $snortcfg['def_smtp_servers']; - if ($def_smtp_servers_info_chk == "") - $def_smtp_servers_type = "\$HOME_NET"; - else - $def_smtp_servers_type = "$def_smtp_servers_info_chk"; - - /* def SMTP_PORTS */ - $def_smtp_ports_info_chk = $snortcfg['def_smtp_ports']; - if ($def_smtp_ports_info_chk == "") - $def_smtp_ports_type = "25"; - else - $def_smtp_ports_type = "$def_smtp_ports_info_chk"; - - /* def MAIL_PORTS */ - $def_mail_ports_info_chk = $snortcfg['def_mail_ports']; - if ($def_mail_ports_info_chk == "") - $def_mail_ports_type = "25,143,465,691"; - else - $def_mail_ports_type = "$def_mail_ports_info_chk"; - - /* def HTTP_SERVSERS */ - $def_http_servers_info_chk = $snortcfg['def_http_servers']; - if ($def_http_servers_info_chk == "") - $def_http_servers_type = "\$HOME_NET"; - else - $def_http_servers_type = "$def_http_servers_info_chk"; - - /* def WWW_SERVSERS */ - $def_www_servers_info_chk = $snortcfg['def_www_servers']; - if ($def_www_servers_info_chk == "") - $def_www_servers_type = "\$HOME_NET"; - else - $def_www_servers_type = "$def_www_servers_info_chk"; - - /* def HTTP_PORTS */ - $def_http_ports_info_chk = $snortcfg['def_http_ports']; - if ($def_http_ports_info_chk == "") - $def_http_ports_type = "80"; - else - $def_http_ports_type = "$def_http_ports_info_chk"; - - /* def SQL_SERVSERS */ - $def_sql_servers_info_chk = $snortcfg['def_sql_servers']; - if ($def_sql_servers_info_chk == "") - $def_sql_servers_type = "\$HOME_NET"; - else - $def_sql_servers_type = "$def_sql_servers_info_chk"; - - /* def ORACLE_PORTS */ - $def_oracle_ports_info_chk = $snortcfg['def_oracle_ports']; - if ($def_oracle_ports_info_chk == "") - $def_oracle_ports_type = "1521"; - else - $def_oracle_ports_type = "$def_oracle_ports_info_chk"; - - /* def MSSQL_PORTS */ - $def_mssql_ports_info_chk = $snortcfg['def_mssql_ports']; - if ($def_mssql_ports_info_chk == "") - $def_mssql_ports_type = "1433"; - else - $def_mssql_ports_type = "$def_mssql_ports_info_chk"; - - /* def TELNET_SERVSERS */ - $def_telnet_servers_info_chk = $snortcfg['def_telnet_servers']; - if ($def_telnet_servers_info_chk == "") - $def_telnet_servers_type = "\$HOME_NET"; - else - $def_telnet_servers_type = "$def_telnet_servers_info_chk"; - - /* def TELNET_PORTS */ - $def_telnet_ports_info_chk = $snortcfg['def_telnet_ports']; - if ($def_telnet_ports_info_chk == "") - $def_telnet_ports_type = "23"; - else - $def_telnet_ports_type = "$def_telnet_ports_info_chk"; - - /* def SNMP_SERVSERS */ - $def_snmp_servers_info_chk = $snortcfg['def_snmp_servers']; - if ($def_snmp_servers_info_chk == "") - $def_snmp_servers_type = "\$HOME_NET"; - else - $def_snmp_servers_type = "$def_snmp_servers_info_chk"; - - /* def SNMP_PORTS */ - $def_snmp_ports_info_chk = $snortcfg['def_snmp_ports']; - if ($def_snmp_ports_info_chk == "") - $def_snmp_ports_type = "161"; - else - $def_snmp_ports_type = "$def_snmp_ports_info_chk"; - - /* def FTP_SERVSERS */ - $def_ftp_servers_info_chk = $snortcfg['def_ftp_servers']; - if ($def_ftp_servers_info_chk == "") - $def_ftp_servers_type = "\$HOME_NET"; - else - $def_ftp_servers_type = "$def_ftp_servers_info_chk"; - - /* def FTP_PORTS */ - $def_ftp_ports_info_chk = $snortcfg['def_ftp_ports']; - if ($def_ftp_ports_info_chk == "") - $def_ftp_ports_type = "21"; - else - $def_ftp_ports_type = "$def_ftp_ports_info_chk"; - - /* def SSH_SERVSERS */ - $def_ssh_servers_info_chk = $snortcfg['def_ssh_servers']; - if ($def_ssh_servers_info_chk == "") - $def_ssh_servers_type = "\$HOME_NET"; - else - $def_ssh_servers_type = "$def_ssh_servers_info_chk"; + /* 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(isset($config['system']['ssh']['port'])) + if(is_array($config['system']['ssh']) && isset($config['system']['ssh']['port'])) $ssh_port = $config['system']['ssh']['port']; else $ssh_port = "22"; - - /* def SSH_PORTS */ - $def_ssh_ports_info_chk = $snortcfg['def_ssh_ports']; - if ($def_ssh_ports_info_chk == "") - $def_ssh_ports_type = "{$ssh_port}"; - else - $def_ssh_ports_type = "$def_ssh_ports_info_chk"; - - /* def POP_SERVSERS */ - $def_pop_servers_info_chk = $snortcfg['def_pop_servers']; - if ($def_pop_servers_info_chk == "") - $def_pop_servers_type = "\$HOME_NET"; - else - $def_pop_servers_type = "$def_pop_servers_info_chk"; - - /* def POP2_PORTS */ - $def_pop2_ports_info_chk = $snortcfg['def_pop2_ports']; - if ($def_pop2_ports_info_chk == "") - $def_pop2_ports_type = "109"; - else - $def_pop2_ports_type = "$def_pop2_ports_info_chk"; - - /* def POP3_PORTS */ - $def_pop3_ports_info_chk = $snortcfg['def_pop3_ports']; - if ($def_pop3_ports_info_chk == "") - $def_pop3_ports_type = "110"; - else - $def_pop3_ports_type = "$def_pop3_ports_info_chk"; - - /* def IMAP_SERVSERS */ - $def_imap_servers_info_chk = $snortcfg['def_imap_servers']; - if ($def_imap_servers_info_chk == "") - $def_imap_servers_type = "\$HOME_NET"; - else - $def_imap_servers_type = "$def_imap_servers_info_chk"; - - /* def IMAP_PORTS */ - $def_imap_ports_info_chk = $snortcfg['def_imap_ports']; - if ($def_imap_ports_info_chk == "") - $def_imap_ports_type = "143"; - else - $def_imap_ports_type = "$def_imap_ports_info_chk"; - - /* def SIP_PROXY_IP */ - $def_sip_proxy_ip_info_chk = $snortcfg['def_sip_proxy_ip']; - if ($def_sip_proxy_ip_info_chk == "") - $def_sip_proxy_ip_type = "\$HOME_NET"; - else - $def_sip_proxy_ip_type = "$def_sip_proxy_ip_info_chk"; - - /* def SIP_PROXY_PORTS */ - $def_sip_proxy_ports_info_chk = $snortcfg['def_sip_proxy_ports']; - if ($def_sip_proxy_ports_info_chk == "") - $def_sip_proxy_ports_type = "5060:5090,16384:32768"; - else - $def_sip_proxy_ports_type = "$def_sip_proxy_ports_info_chk"; - - /* def SIP_SERVERS */ - $def_sip_servers_info_chk = $snortcfg['def_sip_servers']; - if ($def_sip_servers_info_chk == "") - $def_sip_servers_type = "\$HOME_NET"; - else - $def_sip_servers_type = "$def_sip_servers_info_chk"; - - /* def SIP_PORTS */ - $def_sip_ports_info_chk = $snortcfg['def_sip_ports']; - if ($def_sip_ports_info_chk == "") - $def_sip_ports_type = "5060:5090,16384:32768"; - else - $def_sip_ports_type = "$def_sip_ports_info_chk"; - - /* def AUTH_PORTS */ - $def_auth_ports_info_chk = $snortcfg['def_auth_ports']; - if ($def_auth_ports_info_chk == "") - $def_auth_ports_type = "113"; - else - $def_auth_ports_type = "$def_auth_ports_info_chk"; - - /* def FINGER_PORTS */ - $def_finger_ports_info_chk = $snortcfg['def_finger_ports']; - if ($def_finger_ports_info_chk == "") - $def_finger_ports_type = "79"; - else - $def_finger_ports_type = "$def_finger_ports_info_chk"; - - /* def IRC_PORTS */ - $def_irc_ports_info_chk = $snortcfg['def_irc_ports']; - if ($def_irc_ports_info_chk == "") - $def_irc_ports_type = "6665,6666,6667,6668,6669,7000"; - else - $def_irc_ports_type = "$def_irc_ports_info_chk"; - - /* def NNTP_PORTS */ - $def_nntp_ports_info_chk = $snortcfg['def_nntp_ports']; - if ($def_nntp_ports_info_chk == "") - $def_nntp_ports_type = "119"; - else - $def_nntp_ports_type = "$def_nntp_ports_info_chk"; - - /* def RLOGIN_PORTS */ - $def_rlogin_ports_info_chk = $snortcfg['def_rlogin_ports']; - if ($def_rlogin_ports_info_chk == "") - $def_rlogin_ports_type = "513"; - else - $def_rlogin_ports_type = "$def_rlogin_ports_info_chk"; - - /* def RSH_PORTS */ - $def_rsh_ports_info_chk = $snortcfg['def_rsh_ports']; - if ($def_rsh_ports_info_chk == "") - $def_rsh_ports_type = "514"; - else - $def_rsh_ports_type = "$def_rsh_ports_info_chk"; - - /* def SSL_PORTS */ - $def_ssl_ports_info_chk = $snortcfg['def_ssl_ports']; - if ($def_ssl_ports_info_chk == "") - $def_ssl_ports_type = "443,465,563,636,989,990,992,993,994,995"; - else - $def_ssl_ports_type = "$def_ssl_ports_info_chk"; - - /* if user is on pppoe, we really want to use ng0 interface */ - if ($snort_pfsense_basever == 'yes' && $snort_ext_int == "wan") - $snort_ext_int = get_real_wan_interface(); - - /* set the snort performance model */ - if($snortcfg['performance']) - $snort_performance = $snortcfg['performance']; - else - $snort_performance = "ac-bnfa"; - - - /* generate rule sections to load */ - $enabled_rulesets = $snortcfg['rulesets']; - $selected_rules_sections = ""; - if (!empty($enabled_rulesets)) { - $enabled_rulesets_array = split("\|\|", $enabled_rulesets); - foreach($enabled_rulesets_array as $enabled_item) - $selected_rules_sections .= "include \$RULE_PATH/{$enabled_item}\n"; + $snort_ports = array( + "dns_ports" => "53", "smtp_ports" => "25", "mail_ports" => "25,143,465,691", + "http_ports" => "80", "oracle_ports" => "1521", "mssql_ports" => "1433", + "telnet_ports" => "23","snmp_ports" => "161", "ftp_ports" => "21", + "ssh_ports" => $ssh_port, "pop2_ports" => "109", "pop3_ports" => "110", + "imap_ports" => "143", "sip_proxy_ports" => "5060:5090,16384:32768", + "sip_ports" => "5060:5090,16384:32768", "auth_ports" => "113", "finger_ports" => "79", + "irc_ports" => "6665,6666,6667,6668,6669,7000", "smb_ports" => "139,445", + "nntp_ports" => "119", "rlogin_ports" => "513", "rsh_ports" => "514", + "ssl_ports" => "443,465,563,636,989,990,992,993,994,995", + "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" + ); + + $portvardef = ""; + foreach ($snort_ports as $alias => $avalue) { + if (!empty($snortcfg["def_{$alias}"]) && is_alias($snortcfg["def_{$alias}"])) + $snort_ports[$alias] = filter_expand_alias($snortcfg["def_{$alias}"]); + $snort_ports[$alias] = str_replace(" ", ",", trim($snort_ports[$alias])); + $portvardef .= "portvar " . strtoupper($alias) . " [" . $snort_ports[$alias] . "]\n"; } - ///////////////////////////// + ///////////////////////////// /* preprocessor code */ - /* def perform_stat */ - $snort_perform_stat = <<<EOD -########################## - # -# NEW # + $perform_stat = <<<EOD # Performance Statistics # - # -########################## - -preprocessor perfmonitor: time 300 file /var/log/snort/snort_{$snort_uuid}_{$if_real}.stats pktcnt 10000 +preprocessor perfmonitor: time 300 file {$snortlogdir}/snort_{$if_real}{$snort_uuid}/{$if_real}.stats pktcnt 10000 EOD; - $def_perform_stat_info_chk = $snortcfg['perform_stat']; - if ($def_perform_stat_info_chk == "on") - $def_perform_stat_type = "$snort_perform_stat"; - else - $def_perform_stat_type = ""; - - $def_flow_depth_info_chk = $snortcfg['flow_depth']; - if (empty($def_flow_depth_info_chk)) - $def_flow_depth_type = '0'; - else + $def_flow_depth_type = '0'; + if (!empty($snortcfg['flow_depth'])) $def_flow_depth_type = $snortcfg['flow_depth']; + $http_ports = str_replace(",", " ", $snort_ports['http_ports']); /* def http_inspect */ - $snort_http_inspect = <<<EOD -################# - # + $http_inspect = <<<EOD # HTTP Inspect # - # -################# - preprocessor http_inspect: global iis_unicode_map unicode.map 1252 compress_depth 65535 decompress_depth 65535 preprocessor http_inspect_server: server default \ - ports { 80 8080 } \ + ports { {$http_ports} } \ non_strict \ non_rfc_char { 0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 } \ flow_depth {$def_flow_depth_type} \ @@ -1720,6 +1131,7 @@ preprocessor http_inspect_server: server default \ extended_response_inspection \ inspect_gzip \ normalize_utf \ + normalize_javascript \ unlimited_decompress \ ascii no \ chunk_length 500000 \ @@ -1731,39 +1143,9 @@ preprocessor http_inspect_server: server default \ EOD; - $def_http_inspect_info_chk = $snortcfg['http_inspect']; - if ($def_http_inspect_info_chk == "on") - $def_http_inspect_type = "$snort_http_inspect"; - else - $def_http_inspect_type = ""; - - /* def other_preprocs */ - $snort_other_preprocs = <<<EOD -################## - # -# Other preprocs # - # -################## - -preprocessor rpc_decode: 111 32770 32771 32772 32773 32774 32775 32776 32777 32778 32779 -preprocessor bo - -EOD; - - $def_other_preprocs_info_chk = $snortcfg['other_preprocs']; - if ($def_other_preprocs_info_chk == "on") - $def_other_preprocs_type = "$snort_other_preprocs"; - else - $def_other_preprocs_type = ""; - /* def ftp_preprocessor */ - $snort_ftp_preprocessor = <<<EOD -##################### - # + $ftp_preprocessor = <<<EOD # ftp preprocessor # - # -##################### - preprocessor ftp_telnet: global \ inspection_type stateless @@ -1809,22 +1191,30 @@ preprocessor ftp_telnet_protocol: ftp client default \ EOD; - $def_ftp_preprocessor_info_chk = $snortcfg['ftp_preprocessor']; - if ($def_ftp_preprocessor_info_chk == "on") - $def_ftp_preprocessor_type = "$snort_ftp_preprocessor"; - else - $def_ftp_preprocessor_type = ""; + $pop_ports = str_replace(",", " ", $snort_ports['pop3_ports']); + $pop_preproc = <<<EOD +preprocessor pop: \ + ports { {$pop_ports} } \ + qp_decode_depth -1 \ + b64_decode_depth 0 \ + bitenc_decode_depth 100 +EOD; + $imap_ports = str_replace(",", " ", $snort_ports['imap_ports']); + $imap_preproc = <<<EOD +preprocessor imap: \ + ports { {$imap_ports} } \ + qp_decode_depth -1 \ + b64_decode_depth 0 \ + bitenc_decode_depth 100 +EOD; + + $smtp_ports = str_replace(",", " ", $snort_ports['mail_ports']); /* def smtp_preprocessor */ - $snort_smtp_preprocessor = <<<EOD -##################### - # + $smtp_preprocessor = <<<EOD # SMTP preprocessor # - # -##################### - preprocessor SMTP: \ - ports { 25 465 691 } \ + ports { {$smtp_ports} } \ inspection_type stateful \ normalize cmds \ 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 \ @@ -1844,20 +1234,9 @@ PIPELINING CHUNKING DATA DSN RSET QUIT ONEX QUEU STARTTLS TICK TIME TURNME VERB EOD; - $def_smtp_preprocessor_info_chk = $snortcfg['smtp_preprocessor']; - if ($def_smtp_preprocessor_info_chk == "on") - $def_smtp_preprocessor_type = "$snort_smtp_preprocessor"; - else - $def_smtp_preprocessor_type = ""; - /* def sf_portscan */ - $snort_sf_portscan = <<<EOD -################ - # + $sf_portscan = <<<EOD # sf Portscan # - # -################ - preprocessor sfportscan: scan_type { all } \ proto { all } \ memcap { 10000000 } \ @@ -1866,184 +1245,190 @@ preprocessor sfportscan: scan_type { all } \ EOD; - $def_sf_portscan_info_chk = $snortcfg['sf_portscan']; - if ($def_sf_portscan_info_chk == "on") - $def_sf_portscan_type = "$snort_sf_portscan"; - else - $def_sf_portscan_type = ""; + $sun_rpc_ports = str_replace(",", " ", $snort_ports['sun_rpc_ports']); + /* def other_preprocs */ + $other_preprocs = <<<EOD +# Other preprocs # +preprocessor rpc_decode: {$sun_rpc_ports} + +# Back Orifice +preprocessor bo + +EOD; /* def dce_rpc_2 */ - $snort_dce_rpc_2 = <<<EOD -############### - # -# NEW # + $dce_rpc_2 = <<<EOD # DCE/RPC 2 # - # -############### - preprocessor dcerpc2: memcap 102400, events [smb, co, cl] preprocessor dcerpc2_server: default, policy WinXP, \ - detect [smb [139,445], tcp 135, udp 135, rpc-over-http-server 593], \ + 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 EOD; - $def_dce_rpc_2_info_chk = $snortcfg['dce_rpc_2']; - if ($def_dce_rpc_2_info_chk == "on") - $def_dce_rpc_2_type = "$snort_dce_rpc_2"; - else - $def_dce_rpc_2_type = ""; - + $dns_ports = str_replace(",", " ", $snort_ports['dns_ports']); /* def dns_preprocessor */ - $snort_dns_preprocessor = <<<EOD -#################### - # + $dns_preprocessor = <<<EOD # DNS preprocessor # - # -#################### - preprocessor dns: \ - ports { 53 } \ + ports { {$dns_ports} } \ enable_rdata_overflow EOD; - $def_dns_preprocessor_info_chk = $snortcfg['dns_preprocessor']; - if ($def_dns_preprocessor_info_chk == "on") - $def_dns_preprocessor_type = "$snort_dns_preprocessor"; - else - $def_dns_preprocessor_type = ""; + $def_ssl_ports_ignore = str_replace(",", " ", $snort_ports['ssl_ports']); + $ssl_preproc = <<<EOD +# Ignore SSL and Encryption # +preprocessor ssl: ports { {$def_ssl_ports_ignore} }, trustservers, noinspect_encrypted - /* def SSL_PORTS IGNORE */ - $def_ssl_ports_ignore_info_chk = $snortcfg['def_ssl_ports_ignore']; - if ($def_ssl_ports_ignore_info_chk == "") - $def_ssl_ports_ignore_type = "443 465 563 636 989 990 992 993 994 995"; - else - $def_ssl_ports_ignore_type = "$def_ssl_ports_ignore_info_chk"; +EOD; + + $sensitive_data = "preprocessor sensitive_data:\n"; /* stream5 queued settings */ + $def_max_queued_bytes_type = ''; + if (!empty($snortcfg['max_queued_bytes'])) + $def_max_queued_bytes_type = ", max_queued_bytes {$snortcfg['max_queued_bytes']}"; + $def_max_queued_segs_type = ''; + if (!empty($snortcfg['max_queued_segs'])) + $def_max_queued_segs_type = ", max_queued_segs {$snortcfg['max_queued_segs']}"; - $def_max_queued_bytes_info_chk = $snortcfg['max_queued_bytes']; - if ($def_max_queued_bytes_info_chk == '') - $def_max_queued_bytes_type = ''; - else - $def_max_queued_bytes_type = ' max_queued_bytes ' . $snortcfg['max_queued_bytes'] . ','; + /* define servers and ports snortdefservers */ + $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", + "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" + ); + + $vardef = ""; + foreach ($snort_servers as $alias => $avalue) { + if (!empty($snortcfg["def_{$alias}"]) && is_alias($snortcfg["def_{$alias}"])) { + $avalue = filter_expand_alias($snortcfg["def_{$alias}"]); + $avalue = str_replace(" ", ",", trim($avalue)); + } + $vardef .= "var " . strtoupper($alias) . " [{$avalue}]\n"; + } - $def_max_queued_segs_info_chk = $snortcfg['max_queued_segs']; - if ($def_max_queued_segs_info_chk == '') - $def_max_queued_segs_type = ''; - else - $def_max_queued_segs_type = ' max_queued_segs ' . $snortcfg['max_queued_segs'] . ','; + $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", "smtp_preprocessor" => "smtp_preproc", "ssh_preproc" => "ssh_preproc", + "ssl_preproc" => "ssl_preproc" + ); + $snort_preproc = array ( + "perform_stat", "http_inspect", "other_preprocs", "ftp_preprocessor", "smtp_preprocessor", "ssl_preproc", + "sf_portscan", "dce_rpc_2", "dns_preprocessor", "sensitive_data", "pop_preproc", "imap_preproc" + ); + $snort_preprocessors = ""; + foreach ($snort_preproc as $preproc) { + if ($snortcfg[$preproc] == 'on') { + /* NOTE: The $$ is not a bug. Its a advanced feature of php */ + if (!empty($snort_preproc_libs[$preproc])) { + $preproclib = "libsf_" . $snort_preproc_libs[$preproc]; + if (!file_exists($snort_dirs['dynamicpreprocessor'] . "{$preproclib}.so")) { + if (file_exists("/usr/local/lib/snort/dynamicpreprocessor/{$preproclib}.so")) { + @copy("/usr/local/lib/snort/dynamicpreprocessor/{$preproclib}.so", "{$snort_dirs['dynamicpreprocessor']}/{$preproclib}.so"); + $snort_preprocessors .= $$preproc; + $snort_preprocessors .= "\n"; + } + } else { + $snort_preprocessors .= $$preproc; + $snort_preprocessors .= "\n"; + } + } else { + $snort_preprocessors .= $$preproc; + $snort_preprocessors .= "\n"; + } + } + } - $snort_preprocessor_decoder_rules = ""; - if (file_exists("/usr/local/etc/snort/preproc_rules/preprocessor.rules")) - $snort_preprocessor_decoder_rules .= "include \$PREPROC_RULE_PATH/preprocessor.rules\n"; - if (file_exists("/usr/local/etc/snort/preproc_rules/decoder.rules")) - $snort_preprocessor_decoder_rules .= "include \$PREPROC_RULE_PATH/decoder.rules\n"; + $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 (is_dir("{$snortcfgdir}/preproc_rules")) { + if ($snortcfg['sensitive_data'] == 'on') { + $sedcmd = '/^#alert.*classtype:sdf/s/^#//'; + if (file_exists("{$snortcfgdir}/preproc_rules/sensitive-data.rules")) + $snort_misc_include_rules .= "include \$PREPROC_RULE_PATH/sensitive-data.rules\n"; + } else + $sedcmd = '/^alert.*classtype:sdf/s/^/#/'; + if (file_exists("{$snortcfgdir}/preproc_rules/decoder.rules") && + file_exists("{$snortcfgdir}/preproc_rules/preprocessor.rules")) { + @file_put_contents("{$g['tmp_path']}/sedcmd", $sedcmd); + mwexec("/usr/bin/sed -I '' -f {$g['tmp_path']}/sedcmd {$snortcfgdir}/preproc_rules/preprocessor.rules"); + mwexec("/usr/bin/sed -I '' -f {$g['tmp_path']}/sedcmd {$snortcfgdir}/preproc_rules/decoder.rules"); + @unlink("{$g['tmp_path']}/sedcmd"); + + $snort_misc_include_rules .= "include \$PREPROC_RULE_PATH/decoder.rules\n"; + $snort_misc_include_rules .= "include \$PREPROC_RULE_PATH/preprocessor.rules\n"; + } else { + $snort_misc_include_rules .= "config autogenerate_preprocessor_decoder_rules\n"; + log_error("Seems preprocessor/decoder rules are missing, enabling autogeneration of them"); + } + } else { + $snort_misc_include_rules .= "config autogenerate_preprocessor_decoder_rules\n"; + log_error("Seems preprocessor/decoder rules are missing, enabling autogeneration of them"); + } + + /* generate rule sections to load */ + $selected_rules_sections = ""; + $dynamic_rules_sections = ""; + if (!empty($snortcfg['rulesets'])) { + $enabled_rulesets_array = explode("||", $snortcfg['rulesets']); + foreach($enabled_rulesets_array as $enabled_item) { + if (file_exists("{$snortdir}/rules/{$enabled_item}") && !file_exists("{$snortcfgdir}/rules/{$enabled_item}")) + @copy("{$snortdir}/rules/{$enabled_item}", "{$snortcfgdir}/rules/{$enabled_item}"); + if (substr($enabled_item, 0, 5) == "snort" && substr($enabled_item, -9) == ".so.rules") { + $slib = substr($enabled_item, 6, -6); + if (!file_exists("{$snort_dirs['dynamicrules']}/{$slib}")) + @copy("/usr/local/lib/snort/dynamicrules/{$slib}", "{$snort_dirs['dynamicrules']}/{$slib}"); + if (file_exists("{$snort_dirs['dynamicrules']}/{$slib}") && + file_exists("{$snortcfgdir}/rules/{$enabled_item}")) + $selected_rules_sections .= "include \$RULE_PATH/{$enabled_item}\n"; + } else if (file_exists("{$snortcfgdir}/rules/{$enabled_item}")) + $selected_rules_sections .= "include \$RULE_PATH/{$enabled_item}\n"; + } + } + + if (!empty($snortcfg['customrules'])) { + @file_put_contents("{$snortcfgdir}/rules/custom.rules", base64_decode($snortcfg['customrules'])); + $selected_rules_sections .= "include \$RULE_PATH/custom.rules\n"; + } else + @unlink("{$snortcfgdir}/rules/custom.rules"); + + $cksumcheck = "all"; + if ($snortcfg['cksumcheck'] == 'on') + $cksumcheck = "none"; /* build snort configuration file */ $snort_conf_text = <<<EOD # snort configuration file -# generated by the pfSense -# package manager system -# see /usr/local/pkg/snort.inc -# for more information -# snort.conf -# Snort can be found at http://www.snort.org/ - -######################### - # +# generated automatically by the pfSense subsystems do not modify manually + # Define Local Network # - # -######################### +var HOME_NET [{$home_net}] +var EXTERNAL_NET [{$external_net}] -var HOME_NET {$home_net} -var EXTERNAL_NET {$external_net} +# Define Rule Paths # +var RULE_PATH {$snortcfgdir}/rules +var PREPROC_RULE_PATH {$snortcfgdir}/preproc_rules -################### - # # Define Servers # - # -################### - -var DNS_SERVERS [{$def_dns_servers_type}] -var SMTP_SERVERS [{$def_smtp_servers_type}] -var HTTP_SERVERS [{$def_http_servers_type}] -var SQL_SERVERS [{$def_sql_servers_type}] -var TELNET_SERVERS [{$def_telnet_servers_type}] -var SNMP_SERVERS [{$def_snmp_servers_type}] -var FTP_SERVERS [{$def_ftp_servers_type}] -var SSH_SERVERS [{$def_ssh_servers_type}] -var POP_SERVERS [{$def_pop_servers_type}] -var IMAP_SERVERS [{$def_imap_servers_type}] -var RPC_SERVERS \$HOME_NET -var WWW_SERVERS [{$def_www_servers_type}] -var SIP_PROXY_IP [{$def_sip_proxy_ip_type}] -var SIP_SERVERS [{$def_sip_servers_type}] -var 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] - -######################## - # -# Define Server Ports # - # -######################## - -portvar HTTP_PORTS [{$def_http_ports_type}] -portvar FILE_DATA_PORTS [$HTTP_PORTS,110,143] -portvar SHELLCODE_PORTS !80 -portvar ORACLE_PORTS [{$def_oracle_ports_type}] -portvar AUTH_PORTS [{$def_auth_ports_type}] -portvar DNS_PORTS [{$def_dns_ports_type}] -portvar FINGER_PORTS [{$def_finger_ports_type}] -portvar FTP_PORTS [{$def_ftp_ports_type}] -portvar IMAP_PORTS [{$def_imap_ports_type}] -portvar IRC_PORTS [{$def_irc_ports_type}] -portvar MSSQL_PORTS [{$def_mssql_ports_type}] -portvar NNTP_PORTS [{$def_nntp_ports_type}] -portvar POP2_PORTS [{$def_pop2_ports_type}] -portvar POP3_PORTS [{$def_pop3_ports_type}] -portvar SUNRPC_PORTS [111,32770,32771,32772,32773,32774,32775,32776,32777,32778,32779] -portvar RLOGIN_PORTS [{$def_rlogin_ports_type}] -portvar RSH_PORTS [{$def_rsh_ports_type}] -portvar SMB_PORTS [139,445] -portvar SMTP_PORTS [{$def_smtp_ports_type}] -portvar SNMP_PORTS [{$def_snmp_ports_type}] -portvar SSH_PORTS [{$def_ssh_ports_type}] -portvar TELNET_PORTS [{$def_telnet_ports_type}] -portvar MAIL_PORTS [{$def_mail_ports_type}] -portvar SSL_PORTS [{$def_ssl_ports_type}] -portvar SIP_PROXY_PORTS [{$def_sip_proxy_ports_type}] -portvar SIP_PORTS [{$def_sip_ports_type}] - -# DCERPC NCACN-IP-TCP -portvar DCERPC_NCACN_IP_TCP [139,445] -portvar DCERPC_NCADG_IP_UDP [138,1024:] -portvar DCERPC_NCACN_IP_LONG [135,139,445,593,1024:] -portvar DCERPC_NCACN_UDP_LONG [135,1024:] -portvar DCERPC_NCACN_UDP_SHORT [135,593,1024:] -portvar DCERPC_NCACN_TCP [2103,2105,2107] -portvar DCERPC_BRIGHTSTORE [6503,6504] - -##################### - # -# Define Rule Paths # - # -##################### +{$vardef} -var RULE_PATH /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/rules -var PREPROC_RULE_PATH /usr/local/etc/snort/preproc_rules +# Define Server Ports # +{$portvardef} -################################ - # # Configure the snort decoder # - # -################################ - -config checksum_mode: all +config checksum_mode: {$cksumcheck} config disable_decode_alerts config disable_tcpopt_experimental_alerts config disable_tcpopt_obsolete_alerts @@ -2052,130 +1437,53 @@ config disable_tcpopt_alerts config disable_ipopt_alerts config disable_decode_drops -################################### - # # Configure the detection engine # -# Use lower memory models # - # -################################### - config detection: search-method {$snort_performance} max_queue_events 5 config event_queue: max_queue 8 log 3 order_events content_length #Configure dynamic loaded libraries -dynamicpreprocessor directory /usr/local/lib/snort/dynamicpreprocessor -dynamicengine /usr/local/lib/snort/dynamicengine/libsf_engine.so -dynamicdetection directory /usr/local/lib/snort/dynamicrules +dynamicpreprocessor directory {$snort_dirs['dynamicpreprocessor']} +dynamicengine directory {$snort_dirs['dynamicengine']} +dynamicdetection directory {$snort_dirs['dynamicrules']} -################### - # # Flow and stream # - # -################### - preprocessor frag3_global: max_frags 8192 preprocessor frag3_engine: policy bsd detect_anomalies preprocessor stream5_global: track_tcp yes, track_udp yes, track_icmp yes - -preprocessor stream5_tcp: policy BSD, ports both all, {$def_max_queued_bytes_type}{$def_max_queued_segs_type} +preprocessor stream5_tcp: policy BSD, ports both all{$def_max_queued_bytes_type}{$def_max_queued_segs_type} preprocessor stream5_udp: preprocessor stream5_icmp: - {$def_perform_stat_type} - - {$def_http_inspect_type} - - {$def_other_preprocs_type} - - {$def_ftp_preprocessor_type} - - {$def_smtp_preprocessor_type} - - {$def_sf_portscan_type} - - {$def_dce_rpc_2_type} - - {$def_dns_preprocessor_type} - -############################## - # -# NEW # -# Ignore SSL and Encryption # - # -############################## +{$snort_preprocessors} -preprocessor ssl: ports { {$def_ssl_ports_ignore_type} }, trustservers, noinspect_encrypted - -##################### - # # Snort Output Logs # - # -##################### - - $snortunifiedlogbasic_type - $snortalertlogtype_type - $alertsystemlog_type - $tcpdumplog_type - $snortmysqllog_info_chk - $snortunifiedlog_type - $spoink_type +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 # - # -################# - -include /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/reference.config -include /usr/local/etc/snort/snort_{$snort_uuid}_{$if_real}/classification.config -{$snort_preprocessor_decoder_rules} +{$snort_misc_include_rules} -$threshold_file_name +{$suppress_file_name} # Snort user pass through configuration {$snort_config_pass_thru} -################### - # # Rules Selection # - # -################### - - {$selected_rules_sections} +{$selected_rules_sections} EOD; - return $snort_conf_text; -} - -/* hide progress bar */ -function hide_progress_bar_status() { - global $snort_filename, $snort_filename_md5, $console_mode; - - ob_flush(); - if(!$console_mode) - echo "\n<script type=\"text/javascript\">document.progressbar.style.visibility='hidden';\n</script>"; -} - -/* unhide progress bar */ -function unhide_progress_bar_status() { - global $snort_filename, $snort_filename_md5, $console_mode; - - ob_flush(); - if(!$console_mode) - echo "\n<script type=\"text/javascript\">document.progressbar.style.visibility='visible';\n</script>"; -} - -/* update both top and bottom text box during an operation */ -function update_all_status($status) { - global $snort_filename, $snort_filename_md5, $console_mode; - - ob_flush(); - if(!$console_mode) { - update_status($status); - update_output_window($status); + /* write out snort.conf */ + $conf = fopen("{$snortcfgdir}/snort.conf", "w"); + if(!$conf) { + log_error("Could not open {$snortcfgdir}/snort.conf for writing."); + return -1; } + fwrite($conf, $snort_conf_text); + fclose($conf); } ?> diff --git a/config/snort/snort.xml b/config/snort/snort.xml index 2365bbea..07603176 100644 --- a/config/snort/snort.xml +++ b/config/snort/snort.xml @@ -46,8 +46,8 @@ <requirements>Describe your package requirements here</requirements> <faq>Currently there are no FAQ items provided.</faq> <name>Snort</name> - <version>2.9.0.5</version> - <title>Services:2.9.0.5 pkg v. 2.0</title> + <version>2.9.2.3</version> + <title>Services:2.9.2.3 pkg v. 2.5.1</title> <include_file>/usr/local/pkg/snort/snort.inc</include_file> <menu> <name>Snort</name> @@ -59,8 +59,7 @@ <name>snort</name> <rcfile>snort.sh</rcfile> <executable>snort</executable> - <description>Snort is the most widely deployed IDS/IPS technology - worldwide.</description> + <description>Snort is the most widely deployed IDS/IPS technology worldwide.</description> </service> <tabs> </tabs> @@ -72,29 +71,9 @@ <additional_files_needed> <prefix>/usr/local/pkg/snort/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort/snort_gui.inc</item> - </additional_files_needed> - <additional_files_needed> - <prefix>/usr/local/pkg/snort/</prefix> - <chmod>077</chmod> <item>http://www.pfsense.com/packages/config/snort/snort_check_cron_misc.inc</item> </additional_files_needed> <additional_files_needed> - <prefix>/usr/local/bin/</prefix> - <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort/bin/oinkmaster_contrib/create-sidmap.pl</item> - </additional_files_needed> - <additional_files_needed> - <prefix>/usr/local/bin/</prefix> - <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort/bin/oinkmaster_contrib/oinkmaster.pl</item> - </additional_files_needed> - <additional_files_needed> - <prefix>/usr/local/bin/</prefix> - <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort/bin/oinkmaster_contrib/snort_rename.pl</item> - </additional_files_needed> - <additional_files_needed> <prefix>/usr/local/www/snort/</prefix> <chmod>077</chmod> <item>http://www.pfsense.com/packages/config/snort/snort_alerts.php</item> @@ -132,11 +111,6 @@ <additional_files_needed> <prefix>/usr/local/www/snort/</prefix> <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/snort/help_and_info.php</item> - </additional_files_needed> - <additional_files_needed> - <prefix>/usr/local/www/snort/</prefix> - <chmod>077</chmod> <item>http://www.pfsense.com/packages/config/snort/snort_interfaces.php</item> </additional_files_needed> <additional_files_needed> diff --git a/config/snort/snort_alerts.php b/config/snort/snort_alerts.php index 53b9e3a2..e6ebefeb 100644 --- a/config/snort/snort_alerts.php +++ b/config/snort/snort_alerts.php @@ -1,49 +1,56 @@ <?php -/* $Id$ */ /* - snort_alerts.php - part of pfSense - - Copyright (C) 2005 Bill Marquette <bill.marquette@gmail.com>. - Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. - Copyright (C) 2006 Scott Ullrich - All rights reserved. - - Modified for the Pfsense snort package v. 1.8+ - Copyright (C) 2009 Robert Zelaya Sr. Developer - - 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. + * snort_alerts.php + * part of pfSense + * + * 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) 2012 Ermal Luci + * All rights reserved. + * + * Modified for the Pfsense snort package v. 1.8+ + * Copyright (C) 2009 Robert Zelaya Sr. Developer + * + * 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_gui.inc"); require_once("/usr/local/pkg/snort/snort.inc"); -/* load only javascript that is needed */ -$snort_load_sortabletable = 'yes'; -$snort_load_mootools = 'yes'; - $snortalertlogt = $config['installedpackages']['snortglobal']['snortalertlogtype']; -$snort_logfile = '/var/log/snort/alert'; + +if ($_GET['instance']) + $instanceid = $_GET['instance']; +if ($_POST['instance']) + $instanceid = $_POST['instance']; +if (empty($instanceid)) + $instanceid = 0; + +if (!is_array($config['installedpackages']['snortglobal']['rule'])) + $config['installedpackages']['snortglobal']['rule'] = array(); +$a_instance = &$config['installedpackages']['snortglobal']['rule']; +$snort_uuid = $a_instance[$instanceid]['uuid']; +$if_real = snort_get_real_interface($a_instance[$instanceid]['interface']); if (is_array($config['installedpackages']['snortglobal']['alertsblocks'])) { $pconfig['arefresh'] = $config['installedpackages']['snortglobal']['alertsblocks']['arefresh']; @@ -55,59 +62,83 @@ if (is_array($config['installedpackages']['snortglobal']['alertsblocks'])) { $pconfig['arefresh'] = 'off'; } -if ($_POST['save']) -{ - //unset($input_errors); - //$pconfig = $_POST; +if ($_POST['save']) { + if (!is_array($config['installedpackages']['snortglobal']['alertsblocks'])) + $config['installedpackages']['snortglobal']['alertsblocks'] = array(); + $config['installedpackages']['snortglobal']['alertsblocks']['arefresh'] = $_POST['arefresh'] ? 'on' : 'off'; + $config['installedpackages']['snortglobal']['alertsblocks']['alertnumber'] = $_POST['alertnumber']; - /* input validation */ - if ($_POST['save']) - { + write_config(); - // if (($_POST['radiusacctport'] && !is_port($_POST['radiusacctport']))) { - // $input_errors[] = "A valid port number must be specified. [".$_POST['radiusacctport']."]"; - // } - - } - - /* no errors */ - if (!$input_errors) { - if (!is_array($config['installedpackages']['snortglobal']['alertsblocks'])) - $config['installedpackages']['snortglobal']['alertsblocks'] = array(); - $config['installedpackages']['snortglobal']['alertsblocks']['arefresh'] = $_POST['arefresh'] ? 'on' : 'off'; - $config['installedpackages']['snortglobal']['alertsblocks']['alertnumber'] = $_POST['alertnumber']; + header("Location: /snort/snort_alerts.php?instance={$instanceid}"); + exit; +} - write_config(); +if ($_POST['todelete'] || $_GET['todelete']) { + $ip = ""; + if($_POST['todelete']) + $ip = $_POST['todelete']; + else if($_GET['todelete']) + $ip = $_GET['todelete']; + if (is_ipaddr($ip)) + exec("/sbin/pfctl -t snort2c -T delete {$ip}"); +} - header("Location: /snort/snort_alerts.php"); - exit; +if ($_GET['act'] == "addsuppress" && is_numeric($_GET['sidid']) && is_numeric($_GET['gen_id'])) { + if (empty($_GET['descr'])) + $suppress = "suppress gen_id {$_GET['gen_id']}, sig_id {$_GET['sidid']}\n"; + else + $suppress = "#{$_GET['descr']}\nsuppress gen_id {$_GET['gen_id']}, sig_id {$_GET['sidid']}"; + if (!is_array($config['installedpackages']['snortglobal']['suppress'])) + $config['installedpackages']['snortglobal']['suppress'] = array(); + if (!is_array($config['installedpackages']['snortglobal']['suppress']['item'])) + $config['installedpackages']['snortglobal']['suppress']['item'] = array(); + $a_suppress = &$config['installedpackages']['snortglobal']['suppress']['item']; + + if (empty($a_instance[$instanceid]['suppresslistname']) || $a_instance[$instanceid]['suppresslistname'] == 'default') { + $s_list = array(); + $s_list['name'] = $a_instance[$instanceid]['interface'] . "suppress"; + $s_list['uuid'] = uniqid(); + $s_list['descr'] = "Auto generted list for suppress"; + $s_list['suppresspassthru'] = base64_encode($suppress); + $a_suppress[] = $s_list; + $a_instance[$instanceid]['suppresslistname'] = $s_list['name']; + } else { + foreach ($a_suppress as $a_id => $alist) { + if ($alist['name'] == $a_instance[$instanceid]['suppresslistname']) { + if (!empty($alist['suppresspassthru'])) { + $tmplist = base64_decode($alist['suppresspassthru']); + $tmplist .= "\n{$suppress}"; + $alist['suppresspassthru'] = base64_encode($tmplist); + $a_suppress[$a_id] = $alist; + } + } + } } - + write_config(); + sync_snort_package_config(); } -if ($_GET['action'] == "clear" || $_POST['clear']) -{ - if(file_exists('/var/log/snort/alert')) - { - conf_mount_rw(); - @file_put_contents("/var/log/snort/alert", ""); - post_delete_logs(); - /* XXX: This is needed is snort is run as snort user */ - //mwexec('/usr/sbin/chown snort:snort /var/log/snort/*', true); - mwexec('/bin/chmod 660 /var/log/snort/*', true); - mwexec('/usr/bin/killall -HUP snort', true); - conf_mount_ro(); - } - header("Location: /snort/snort_alerts.php"); +if ($_GET['action'] == "clear" || $_POST['delete']) { + conf_mount_rw(); + snort_post_delete_logs($snort_uuid); + $fd = @fopen("/var/log/snort/snort_{$if_real}{$snort_uuid}/alert", "w+"); + if ($fd) + fclose($fd); + conf_mount_ro(); + /* XXX: This is needed is snort is run as snort user */ + //mwexec('/usr/sbin/chown snort:snort /var/log/snort/*', true); + mwexec('/bin/chmod 660 /var/log/snort/*', true); + if (file_exists("{$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid")) + mwexec("/bin/pkill -HUP -F {$g['varrun_path']}/snort_{$if_real}{$snort_uuid}.pid -a"); + header("Location: /snort/snort_alerts.php?instance={$instanceid}"); exit; } -if ($_POST['download']) -{ - +if ($_POST['download']) { $save_date = exec('/bin/date "+%Y-%m-%d-%H-%M-%S"'); - $file_name = "snort_logs_{$save_date}.tar.gz"; - exec("/usr/bin/tar cfz /tmp/{$file_name} /var/log/snort"); + $file_name = "snort_logs_{$save_date}_{$if_real}.tar.gz"; + exec("/usr/bin/tar cfz /tmp/{$file_name} /var/log/snort/snort_{$if_real}{$snort_uuid}"); if (file_exists("/tmp/{$file_name}")) { $file = "/tmp/snort_logs_{$save_date}.tar.gz"; @@ -119,141 +150,13 @@ if ($_POST['download']) header("Content-length: ".filesize($file)); header("Content-disposition: attachment; filename = {$file_name}"); readfile("$file"); - exec("/bin/rm /tmp/{$file_name}"); + @unlink("/tmp/{$file_name}"); } - header("Location: /snort/snort_alerts.php"); + header("Location: /snort/snort_alerts.php?instance={$instanceid}"); exit; } - -/* WARNING: took me forever to figure reg expression, dont lose */ -// $fileline = '12/09-18:12:02.086733 [**] [122:6:0] (portscan) TCP Filtered Decoy Portscan [**] [Priority: 3] {PROTO:255} 125.135.214.166 -> 70.61.243.50'; -function get_snort_alert_date($fileline) -{ - /* date full date \d+\/\d+-\d+:\d+:\d+\.\d+\s */ - if (preg_match("/\d+\/\d+-\d+:\d+:\d\d/", $fileline, $matches1)) - $alert_date = "$matches1[0]"; - - return $alert_date; -} - -function get_snort_alert_disc($fileline) -{ - /* disc */ - if (preg_match("/\[\*\*\] (\[.*\]) (.*) (\[\*\*\])/", $fileline, $matches)) - $alert_disc = "$matches[2]"; - - return $alert_disc; -} - -function get_snort_alert_class($fileline) -{ - /* class */ - if (preg_match('/\[Classification:\s.+[^\d]\]/', $fileline, $matches2)) - $alert_class = "$matches2[0]"; - - return $alert_class; -} - -function get_snort_alert_priority($fileline) -{ - /* Priority */ - if (preg_match('/Priority:\s\d/', $fileline, $matches3)) - $alert_priority = "$matches3[0]"; - - return $alert_priority; -} - -function get_snort_alert_proto($fileline) -{ - /* Priority */ - if (preg_match('/\{.+\}/', $fileline, $matches3)) - $alert_proto = "$matches3[0]"; - - return $alert_proto; -} - -function get_snort_alert_proto_full($fileline) -{ - /* Protocal full */ - if (preg_match('/.+\sTTL/', $fileline, $matches2)) - $alert_proto_full = "$matches2[0]"; - - return $alert_proto_full; -} - -function get_snort_alert_ip_src($fileline) -{ - /* SRC IP */ - $re1='.*?'; # Non-greedy match on filler - $re2='((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?![\\d])'; # IPv4 IP Address 1 - - if ($c=preg_match_all ("/".$re1.$re2."/is", $fileline, $matches4)) - $alert_ip_src = $matches4[1][0]; - - return $alert_ip_src; -} - -function get_snort_alert_src_p($fileline) -{ - /* source port */ - if (preg_match('/:\d+\s-/', $fileline, $matches5)) - $alert_src_p = "$matches5[0]"; - - return $alert_src_p; -} - -function get_snort_alert_flow($fileline) -{ - /* source port */ - if (preg_match('/(->|<-)/', $fileline, $matches5)) - $alert_flow = "$matches5[0]"; - - return $alert_flow; -} - -function get_snort_alert_ip_dst($fileline) -{ - /* DST IP */ - $re1dp='.*?'; # Non-greedy match on filler - $re2dp='(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?![\\d])'; # Uninteresting: ipaddress - $re3dp='.*?'; # Non-greedy match on filler - $re4dp='((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?![\\d])'; # IPv4 IP Address 1 - - if ($c=preg_match_all ("/".$re1dp.$re2dp.$re3dp.$re4dp."/is", $fileline, $matches6)) - $alert_ip_dst = $matches6[1][0]; - - return $alert_ip_dst; -} - -function get_snort_alert_dst_p($fileline) -{ - /* dst port */ - if (preg_match('/:\d+$/', $fileline, $matches7)) - $alert_dst_p = "$matches7[0]"; - - return $alert_dst_p; -} - -function get_snort_alert_dst_p_full($fileline) -{ - /* dst port full */ - if (preg_match('/:\d+\n[A-Z]+\sTTL/', $fileline, $matches7)) - $alert_dst_p = "$matches7[0]"; - - return $alert_dst_p; -} - -function get_snort_alert_sid($fileline) -{ - /* SID */ - if (preg_match('/\[\d+:\d+:\d+\]/', $fileline, $matches8)) - $alert_sid = "$matches8[0]"; - - return $alert_sid; -} - $pgtitle = "Services: Snort: Snort Alerts"; include_once("head.inc"); @@ -262,310 +165,175 @@ include_once("head.inc"); <body link="#0000CC" vlink="#0000CC" alink="#0000CC"> <?php - include_once("fbegin.inc"); -echo $snort_general_css; /* refresh every 60 secs */ if ($pconfig['arefresh'] == 'on') echo "<meta http-equiv=\"refresh\" content=\"60;url=/snort/snort_alerts.php\" />\n"; ?> -<div class="body2"><?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> - +<?php if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';} + /* Display Alert message */ + if ($input_errors) { + print_input_errors($input_errors); // TODO: add checks + } +?> +<form action="/snort/snort_alerts.php" method="post" id="formalert"> <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"), true, "/snort/snort_alerts.php"); - $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); - $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); - $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); - $tab_array[7] = array(gettext("Help"), false, "/snort/help_and_info.php"); - display_top_tabs($tab_array); + $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"), true, "/snort/snort_alerts.php?instance={$instanceid}"); + $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); + $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); + $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + display_top_tabs($tab_array); ?> </td></tr> <tr> <td> - <div id="mainarea2"> - <table class="tabcont" width="100%" border="1" cellspacing="0" - cellpadding="0"> + <table class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> - <td width="22%" colspan="0" class="listtopic">Last <?=$anentries;?> - Alert Entries.</td> - <td width="78%" class="listtopic">Latest Alert Entries Are Listed - First.</td> + <td width="22%" class="listtopic"><?php printf(gettext('Last %s Alert Entries.'),$anentries); ?></td> + <td width="78%" class="listtopic"><?php echo gettext('Latest Alert Entries Are Listed First.'); ?></td> </tr> <tr> - <td width="22%" class="vncell">Save or Remove Logs</td> + <td width="22%" class="vncell"><?php echo gettext('Instance to inspect'); ?></td> + <td width="78%" class="vtable"> + <br/> <select name="instance" id="instance" class="formselect" onChange="document.getElementById('formalert').submit()"> + <?php + foreach ($a_instance as $id => $instance) { + $selected = ""; + if ($id == $instanceid) + $selected = "selected"; + echo "<option value='{$id}' {$selected}> (" . snort_get_friendly_interface($instance['interface']) . "){$instance['descr']}</option>\n"; + } + ?> + </select><br/> <?php echo gettext('Choose which instance alerts you want to inspect.'); ?> + </td> + <tr> + <td width="22%" class="vncell"><?php echo gettext('Save or Remove Logs'); ?></td> <td width="78%" class="vtable"> - <form action="/snort/snort_alerts.php" method="post"><input - name="download" type="submit" class="formbtn" value="Download"> All - log files will be saved. <a href="/snort/snort_alerts.php?action=clear"><input name="delete" type="button" - class="formbtn" value="Clear" - onclick="return confirm('Do you really want to remove all your logs ? All snort rule interfces may have to be restarted.')"></a> - <span class="red"><strong>Warning:</strong></span> all log files - will be deleted.</form> + <input name="download" type="submit" class="formbtn" value="Download"> <?php echo gettext('All ' . + 'log files will be saved.'); ?> <a href="/snort/snort_alerts.php?action=clear&instance=<?=$instanceid;?>"> + <input name="delete" type="button" class="formbtn" value="Clear" + onclick="return confirm('Do you really want to remove all instance logs?')"></a> + <span class="red"><strong><?php echo gettext('Warning:'); ?></strong></span> <?php echo ' ' . gettext('all log files will be deleted.'); ?> </td> </tr> <tr> - <td width="22%" class="vncell">Auto Refresh and Log View</td> + <td width="22%" class="vncell"><?php echo gettext('Auto Refresh and Log View'); ?></td> <td width="78%" class="vtable"> - <form action="/snort/snort_alerts.php" method="post"><input - name="save" type="submit" class="formbtn" value="Save"> Refresh <input - name="arefresh" type="checkbox" value="on" + <input name="save" type="submit" class="formbtn" value="Save"> + <?php echo gettext('Refresh'); ?> <input name="arefresh" type="checkbox" value="on" <?php if ($config['installedpackages']['snortglobal']['alertsblocks']['arefresh']=="on") echo "checked"; ?>> - <strong>Default</strong> is <strong>ON</strong>. <input - name="alertnumber" type="text" class="formfld" id="alertnumber" - size="5" value="<?=htmlspecialchars($anentries);?>"> Enter the - number of log entries to view. <strong>Default</strong> is <strong>250</strong>. - </form> + <?php printf(gettext('%sDefault%s is %sON%s.'), '<strong>', '</strong>', '<strong>', '</strong>'); ?> + <input name="alertnumber" type="text" class="formfld" id="alertnumber" size="5" value="<?=htmlspecialchars($anentries);?>"> + <?php printf(gettext('Enter the number of log entries to view. %sDefault%s is %s250%s.'), '<strong>', '</strong>', '<strong>', '</strong>'); ?> </td> </tr> - </table> - </div> - </td> - </tr> -</table> -<table width="100%" border="0" cellpadding="0" cellspacing="0"> - <td width="100%"><br> - <div class="tableFilter"> - <form id="tableFilter" - onsubmit="myTable.filter(this.id); return false;">Filter: <select - id="column"> - <option value="1">PRIORITY</option> - <option value="2">PROTO</option> - <option value="3">DESCRIPTION</option> - <option value="4">CLASS</option> - <option value="5">SRC</option> - <option value="6">SRC PORT</option> - <option value="7">FLOW</option> - <option value="8">DST</option> - <option value="9">DST PORT</option> - <option value="10">SID</option> - <option value="11">Date</option> - </select> <input type="text" id="keyword" /> <input type="submit" - value="Submit" /> <input type="reset" value="Clear" /></form> - </div> - <table class="allRow" id="myTable" width="100%" border="2" - cellpadding="1" cellspacing="1"> - <thead> - <th axis="number">#</th> - <th axis="string">PRI</th> - <th axis="string">PROTO</th> - <th axis="string">DESCRIPTION</th> - <th axis="string">CLASS</th> - <th axis="string">SRC</th> - <th axis="string">SPORT</th> - <th axis="string">FLOW</th> - <th axis="string">DST</th> - <th axis="string">DPORT</th> - <th axis="string">SID</th> - <th axis="date">Date</th> - </thead> - <tbody> - <?php - - /* make sure alert file exists */ - if(!file_exists('/var/log/snort/alert')) - exec('/usr/bin/touch /var/log/snort/alert'); - - $logent = $anentries; - - /* detect the alert file type */ - if ($snortalertlogt == 'full') - $alerts_array = array_reverse(array_filter(explode("\n\n", file_get_contents('/var/log/snort/alert')))); - else - $alerts_array = array_reverse(array_filter(split("\n", file_get_contents('/var/log/snort/alert')))); - - - - if (is_array($alerts_array)) { - - $counter = 0; - foreach($alerts_array as $fileline) - { - - if($logent <= $counter) + <tr> + <td colspan="2" ><br/><br/></td> + </tr> + <tr> + <td width="100%" colspan="2" class='vtable'> + <table id="myTable" width="100%" class="sortable" border="1" cellpadding="0" cellspacing="0"> + <thead> + <th class='listhdr' width='10%' axis="date"><?php echo gettext("Date"); ?></th> + <th class='listhdrr' width='5%' axis="number"><?php echo gettext("PRI"); ?></th> + <th class='listhdrr' width='3%' axis="string"><?php echo gettext("PROTO"); ?></th> + <th class='listhdrr' width='7%' axis="string"><?php echo gettext("CLASS"); ?></th> + <th class='listhdrr' width='15%' axis="string"><?php echo gettext("SRC"); ?></th> + <th class='listhdrr' width='5%' axis="string"><?php echo gettext("SRCPORT"); ?></th> + <th class='listhdrr' width='15%' axis="string"><?php echo gettext("DST"); ?></th> + <th class='listhdrr' width='5%' axis="string"><?php echo gettext("DSTPORT"); ?></th> + <th class='listhdrr' width='5%' axis="string"><?php echo gettext("SID"); ?></th> + <th class='listhdrr' width='20%' axis="string"><?php echo gettext("DESCRIPTION"); ?></th> + </thead> + <tbody> + <?php + +/* make sure alert file exists */ +if (file_exists("/var/log/snort/snort_{$if_real}{$snort_uuid}/alert")) { + exec("tail -{$anentries} /var/log/snort/snort_{$if_real}{$snort_uuid}/alert | sort -r > /tmp/alert_{$snort_uuid}"); + if (file_exists("/tmp/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"); + while (($fields = fgetcsv($fd, 1000, ',', '"')) !== FALSE) { + if(count($fields) < 11) continue; - $counter++; - - /* Date */ - $alert_date_str = get_snort_alert_date($fileline); - - if($alert_date_str != '') - { - $alert_date = $alert_date_str; - }else{ - $alert_date = 'empty'; - } - - /* Discription */ - $alert_disc_str = get_snort_alert_disc($fileline); - - if($alert_disc_str != '') - { - $alert_disc = $alert_disc_str; - }else{ - $alert_disc = 'empty'; - } - - /* Classification */ - $alert_class_str = get_snort_alert_class($fileline); - - if($alert_class_str != '') - { - - $alert_class_match = array('[Classification:',']'); - $alert_class = str_replace($alert_class_match, '', "$alert_class_str"); - }else{ - $alert_class = 'Prep'; - } - - /* Priority */ - $alert_priority_str = get_snort_alert_priority($fileline); - - if($alert_priority_str != '') - { - $alert_priority_match = array('Priority: ',']'); - $alert_priority = str_replace($alert_priority_match, '', "$alert_priority_str"); - }else{ - $alert_priority = 'empty'; - } - - /* Protocol */ - /* Detect alert file type */ - if ($snortalertlogt == 'full') - { - $alert_proto_str = get_snort_alert_proto_full($fileline); - }else{ - $alert_proto_str = get_snort_alert_proto($fileline); - } - - if($alert_proto_str != '') - { - $alert_proto_match = array(" TTL",'{','}'); - $alert_proto = str_replace($alert_proto_match, '', "$alert_proto_str"); - }else{ - $alert_proto = 'empty'; - } - - /* IP SRC */ - $alert_ip_src_str = get_snort_alert_ip_src($fileline); - - if($alert_ip_src_str != '') - { - $alert_ip_src = $alert_ip_src_str; - }else{ - $alert_ip_src = 'empty'; - } - - /* IP SRC Port */ - $alert_src_p_str = get_snort_alert_src_p($fileline); - - if($alert_src_p_str != '') - { - $alert_src_p_match = array(' -',':'); - $alert_src_p = str_replace($alert_src_p_match, '', "$alert_src_p_str"); - }else{ - $alert_src_p = 'empty'; - } - - /* Flow */ - $alert_flow_str = get_snort_alert_flow($fileline); - - if($alert_flow_str != '') - { - $alert_flow = $alert_flow_str; - }else{ - $alert_flow = 'empty'; - } - - /* IP Destination */ - $alert_ip_dst_str = get_snort_alert_ip_dst($fileline); - - if($alert_ip_dst_str != '') - { - $alert_ip_dst = $alert_ip_dst_str; - }else{ - $alert_ip_dst = 'empty'; - } - - /* IP DST Port */ - if ($snortalertlogt == 'full') - { - $alert_dst_p_str = get_snort_alert_dst_p_full($fileline); - }else{ - $alert_dst_p_str = get_snort_alert_dst_p($fileline); - } - - if($alert_dst_p_str != '') - { - $alert_dst_p_match = array(':',"\n"," TTL"); - $alert_dst_p_str2 = str_replace($alert_dst_p_match, '', "$alert_dst_p_str"); - $alert_dst_p_match2 = array('/[A-Z]/'); - $alert_dst_p = preg_replace($alert_dst_p_match2, '', "$alert_dst_p_str2"); - }else{ - $alert_dst_p = 'empty'; - } - - /* SID */ - $alert_sid_str = get_snort_alert_sid($fileline); - - if($alert_sid_str != '') - { - $alert_sid_match = array('[',']'); - $alert_sid = str_replace($alert_sid_match, '', "$alert_sid_str"); - }else{ - $alert_sid_str = 'empty'; - } - - /* NOTE: using one echo improves performance by 2x */ - if ($alert_disc != 'empty') - { - echo "<tr id=\"{$counter}\"> - <td class=\"centerAlign\">{$counter}</td> - <td class=\"centerAlign\">{$alert_priority}</td> - <td class=\"centerAlign\">{$alert_proto}</td> - <td>{$alert_disc}</td> - <td class=\"centerAlign\">{$alert_class}</td> - <td>{$alert_ip_src}</td> - <td class=\"centerAlign\">{$alert_src_p}</td> - <td class=\"centerAlign\">{$alert_flow}</td> - <td>{$alert_ip_dst}</td> - <td class=\"centerAlign\">{$alert_dst_p}</td> - <td class=\"centerAlign\">{$alert_sid}</td> - <td>{$alert_date}</td> + /* Date */ + $alert_date = substr($fields[0], 0, -8); + /* Description */ + $alert_descr = $fields[4]; + $alert_descr_url = urlencode($fields[4]); + /* Priority */ + $alert_priority = $fields[12]; + /* Protocol */ + $alert_proto = $fields[5]; + /* IP SRC */ + $alert_ip_src = $fields[6]; + if (isset($tmpblocked[$fields[6]])) { + $alert_ip_src .= "<a href='?instance={$id}&todelete=" . trim(urlencode($fields[6])) . "'> + <img title=\"" . gettext("Remove from blocked ips") . "\" border=\"0\" width='10' height='10' name='todelete' id='todelete' alt=\"Delete\" src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\"></a>"; + } + /* IP SRC Port */ + $alert_src_p = $fields[7]; + /* IP Destination */ + $alert_ip_dst = $fields[8]; + if (isset($tmpblocked[$fields[8]])) { + $alert_ip_dst .= "<a href='?instance={$id}&todelete=" . trim(urlencode($fields[8])) . "'> + <img title=\"" . gettext("Remove from blocked ips") . "\" border=\"0\" width='10' height='10' name='todelete' id='todelete' alt=\"Delete\" src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\"></a>"; + } + /* IP DST Port */ + $alert_dst_p = $fields[9]; + /* SID */ + $alert_sid_str = "{$fields[1]}:{$fields[2]}:{$fields[3]}"; + $alert_class = $fields[11]; + + echo "<tr> + <td class='listr' width='10%'>{$alert_date}</td> + <td class='listr' width='5%' >{$alert_priority}</td> + <td class='listr' width='3%'>{$alert_proto}</td> + <td class='listr' width='7%' >{$alert_class}</td> + <td class='listr' width='15%'>{$alert_ip_src}</td> + <td class='listr' width='5%'>{$alert_src_p}</td> + <td class='listr' width='15%'>{$alert_ip_dst}</td> + <td class='listr' width='5%'>{$alert_dst_p}</td> + <td class='listr' width='5%' > + {$alert_sid_str} + <a href='?instance={$instanceid}&act=addsuppress&sidid={$fields[2]}&gen_id={$fields[1]}&descr={$alert_descr_url}'> + <img src='../themes/{$g['theme']}/images/icons/icon_plus.gif' + width='10' height='10' border='0' + title='" . gettext("click to add to suppress list") . "'></a> + </td> + <td class='listr' width='20%'>{$alert_descr}</td> </tr>\n"; - } - // <script type="text/javascript"> - // var myTable = {}; - // window.addEvent('domready', function(){ - // myTable = new sortableTable('myTable', {overCls: 'over', onClick: function(){alert(this.id)}}); - // }); - // </script> - - } + $counter++; } - - ?> + fclose($fd); + @unlink("/tmp/alert_{$snort_uuid}"); + } +} +?> </tbody> </table> </td> +</tr> </table> - -</div> - +</td></tr> +</table> +</form> <?php include("fend.inc"); - -echo $snort_custom_rnd_box; - ?> </body> </html> diff --git a/config/snort/snort_barnyard.php b/config/snort/snort_barnyard.php index b647c007..ccbe3c26 100644 --- a/config/snort/snort_barnyard.php +++ b/config/snort/snort_barnyard.php @@ -1,45 +1,35 @@ <?php -/* $Id$ */ /* - snort_interfaces.php - part of m0n0wall (http://m0n0.ch/wall) - - Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. - Copyright (C) 2008-2009 Robert Zelaya. - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. + * snort_barnyard.php + * part of pfSense + * + * Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + * Copyright (C) 2008-2009 Robert Zelaya. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. */ -/* - -TODO: Nov 12 09 -Clean this code up its ugly -Important add error checking - -*/ - require_once("guiconfig.inc"); -require_once("/usr/local/pkg/snort/snort_gui.inc"); require_once("/usr/local/pkg/snort/snort.inc"); global $g; @@ -56,40 +46,25 @@ if (!is_array($config['installedpackages']['snortglobal']['rule'])) $config['installedpackages']['snortglobal']['rule'] = array(); $a_nat = &$config['installedpackages']['snortglobal']['rule']; -if (isset($_GET['dup'])) { - $id = $_GET['dup']; - $after = $_GET['dup']; -} - $pconfig = array(); if (isset($id) && $a_nat[$id]) { /* old options */ $pconfig = $a_nat[$id]; - $pconfig['barnyard_enable'] = $a_nat[$id]['barnyard_enable']; - $pconfig['barnyard_mysql'] = $a_nat[$id]['barnyard_mysql']; - $pconfig['barnconfigpassthru'] = base64_decode($a_nat[$id]['barnconfigpassthru']); + if (!empty($a_nat[$id]['barnconfigpassthru'])) + $pconfig['barnconfigpassthru'] = base64_decode($a_nat[$id]['barnconfigpassthru']); } if (isset($_GET['dup'])) unset($id); -$if_real = snort_get_real_interface($pconfig['interface']); -$snort_uuid = $pconfig['uuid']; - -/* alert file */ -$d_snortconfdirty_path = "/var/run/snort_conf_{$snort_uuid}_{$if_real}.dirty"; - if ($_POST) { - /* XXX: Mising error reporting?! - * check for overlaps foreach ($a_nat as $natent) { if (isset($id) && ($a_nat[$id]) && ($a_nat[$id] === $natent)) continue; if ($natent['interface'] != $_POST['interface']) - continue; + $input_error[] = "This interface has already an instance defined"; } - */ /* if no errors write to conf */ if (!$input_errors) { @@ -98,8 +73,8 @@ if ($_POST) { $natent = $pconfig; $natent['barnyard_enable'] = $_POST['barnyard_enable'] ? 'on' : 'off'; - $natent['barnyard_mysql'] = $_POST['barnyard_mysql'] ? $_POST['barnyard_mysql'] : $pconfig['barnyard_mysql']; - $natent['barnconfigpassthru'] = $_POST['barnconfigpassthru'] ? base64_encode($_POST['barnconfigpassthru']) : $pconfig['barnconfigpassthru']; + if ($_POST['barnyard_mysql']) $natent['barnyard_mysql'] = $_POST['barnyard_mysql']; else unset($natent['barnyard_mysql']); + if ($_POST['barnconfigpassthru']) $natent['barnconfigpassthru'] = base64_encode($_POST['barnconfigpassthru']); else unset($natent['barnconfigpassthru']); if ($_POST['barnyard_enable'] == "on") $natent['snortunifiedlog'] = 'on'; else @@ -108,10 +83,7 @@ if ($_POST) { if (isset($id) && $a_nat[$id]) $a_nat[$id] = $natent; else { - if (is_numeric($after)) - array_splice($a_nat, $after+1, 0, array($natent)); - else - $a_nat[] = $natent; + $a_nat[] = $natent; } write_config(); @@ -128,7 +100,8 @@ if ($_POST) { } } -$pgtitle = "Snort: Interface: $id$if_real Barnyard2 Edit"; +$if_friendly = snort_get_friendly_interface($pconfig['interface']); +$pgtitle = "Snort: Interface: {$if_friendly} Barnyard2 Edit"; include_once("head.inc"); ?> @@ -139,19 +112,9 @@ include_once("head.inc"); <?php include("fbegin.inc"); ?> <?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> -<?php -echo "{$snort_general_css}\n"; +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> +<?php include_once("fbegin.inc"); ?> - -<div class="body2"> - -<noscript> -<div class="alert" ALIGN=CENTER><img - src="../themes/<?php echo $g['theme']; ?>/images/icons/icon_alert.gif" /><strong>Please -enable JavaScript to view this content -</CENTER></div> -</noscript> - <script language="JavaScript"> <!-- @@ -165,39 +128,33 @@ function enable_change(enable_change) { } //--> </script> -<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> -<form action="snort_barnyard.php" method="post" - enctype="multipart/form-data" name="iform" id="iform"><?php + +<?php /* Display Alert message */ if ($input_errors) { print_input_errors($input_errors); // TODO: add checks } if ($savemsg) { - print_info_box2($savemsg); + print_info_box($savemsg); } ?> +<form action="snort_barnyard.php" method="post" + enctype="multipart/form-data" name="iform" id="iform"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr><td> <?php $tab_array = array(); - $tabid = 0; - $tab_array[$tabid] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); - $tabid++; - $tab_array[$tabid] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Servers"), false, "/snort/snort_define_servers.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Barnyard2"), true, "/snort/snort_barnyard.php?id={$id}"); + $tab_array[] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); + $tab_array[] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); + $tab_array[] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); + $tab_array[] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); + $tab_array[] = array(gettext("Variables"), false, "/snort/snort_define_servers.php?id={$id}"); + $tab_array[] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); + $tab_array[] = array(gettext("Barnyard2"), true, "/snort/snort_barnyard.php?id={$id}"); display_top_tabs($tab_array); ?> </td></tr> @@ -205,40 +162,40 @@ function enable_change(enable_change) { <td class="tabcont"> <table width="100%" border="0" cellpadding="6" cellspacing="0"> <tr> - <td colspan="2" valign="top" class="listtopic">General Barnyard2 - Settings</td> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("General Barnyard2 " . + "Settings"); ?></td> </tr> <tr> - <td width="22%" valign="top" class="vncellreq2">Enable</td> + <td width="22%" valign="top" class="vncellreq"><?php echo gettext("Enable"); ?></td> <td width="78%" class="vtable"> <input name="barnyard_enable" type="checkbox" value="on" <?php if ($pconfig['barnyard_enable'] == "on") echo "checked"; ?> onClick="enable_change(false)"> - <strong>Enable Barnyard2 </strong><br> - This will enable barnyard2 for this interface. You will also have to set the database credentials.</td> + <strong><?php echo gettext("Enable Barnyard2"); ?></strong><br> + <?php echo gettext("This will enable barnyard2 for this interface. You will also have to set the database credentials."); ?></td> </tr> <tr> - <td colspan="2" valign="top" class="listtopic">Mysql Settings</td> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Mysql Settings"); ?></td> </tr> <tr> - <td width="22%" valign="top" class="vncell2">Log to a Mysql Database</td> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Log to a Mysql Database"); ?></td> <td width="78%" class="vtable"><input name="barnyard_mysql" type="text" class="formfld" id="barnyard_mysql" size="100" value="<?=htmlspecialchars($pconfig['barnyard_mysql']);?>"> <br> - <span class="vexpl">Example: output database: alert, mysql, - dbname=snort user=snort host=localhost password=xyz<br> - Example: output database: log, mysql, dbname=snort user=snort - host=localhost password=xyz</span></td> + <span class="vexpl"><?php echo gettext("Example: output database: alert, mysql, " . + "dbname=snort user=snort host=localhost password=xyz"); ?><br> + <?php echo gettext("Example: output database: log, mysql, dbname=snort user=snort " . + "host=localhost password=xyz"); ?></span></td> </tr> <tr> - <td colspan="2" valign="top" class="listtopic">Advanced Settings</td> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Advanced Settings"); ?></td> </tr> <tr> - <td width="22%" valign="top" class="vncell2">Advanced configuration - pass through</td> + <td width="22%" valign="top" class="vncell"<?php echo gettext("Advanced configuration " . + "pass through"); ?></td> <td width="78%" class="vtable"><textarea name="barnconfigpassthru" - cols="100" rows="7" id="barnconfigpassthru" class="formpre"><?=htmlspecialchars($pconfig['barnconfigpassthru']);?></textarea> + cols="60" rows="7" id="barnconfigpassthru" ><?=htmlspecialchars($pconfig['barnconfigpassthru']);?></textarea> <br> - Arguments here will be automatically inserted into the running - barnyard2 configuration.</td> + <?php echo gettext("Arguments here will be automatically inserted into the running " . + "barnyard2 configuration."); ?></td> </tr> <tr> <td width="22%" valign="top"> </td> @@ -248,17 +205,14 @@ function enable_change(enable_change) { </tr> <tr> <td width="22%" valign="top"> </td> - <td width="78%"><span class="vexpl"><span class="red"><strong>Note:</strong></span> + <td width="78%"><span class="vexpl"><span class="red"><strong><?php echo gettext("Note:"); ?></strong></span> <br> - Please save your settings befor you click start. </td> + <?php echo gettext("Please save your settings befor you click start."); ?> </td> </tr> </table> </table> </form> - -</div> - <script language="JavaScript"> <!-- enable_change(false); diff --git a/config/snort/snort_blocked.php b/config/snort/snort_blocked.php index 11e7cae6..def5dd22 100644 --- a/config/snort/snort_blocked.php +++ b/config/snort/snort_blocked.php @@ -1,37 +1,36 @@ <?php -/* $Id$ */ /* - snort_blocked.php - Copyright (C) 2006 Scott Ullrich - All rights reserved. - - Modified for the Pfsense snort package v. 1.8+ - Copyright (C) 2009 Robert Zelaya Sr. Developer - - 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. + * snort_blocked.php + * + * Copyright (C) 2006 Scott Ullrich + * All rights reserved. + * + * Modified for the Pfsense snort package v. 1.8+ + * Copyright (C) 2009 Robert Zelaya Sr. Developer + * + * 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_gui.inc"); require_once("/usr/local/pkg/snort/snort.inc"); if (!is_array($config['installedpackages']['snortglobal']['alertsblocks'])) @@ -40,168 +39,81 @@ if (!is_array($config['installedpackages']['snortglobal']['alertsblocks'])) $pconfig['brefresh'] = $config['installedpackages']['snortglobal']['alertsblocks']['brefresh']; $pconfig['blertnumber'] = $config['installedpackages']['snortglobal']['alertsblocks']['blertnumber']; -if ($pconfig['blertnumber'] == '' || $pconfig['blertnumber'] == '0') -{ +if (empty($pconfig['blertnumber'])) $bnentries = '500'; -}else{ +else $bnentries = $pconfig['blertnumber']; -} -if($_POST['todelete'] or $_GET['todelete']) { +if ($_POST['todelete'] || $_GET['todelete']) { + $ip = ""; if($_POST['todelete']) $ip = $_POST['todelete']; - if($_GET['todelete']) + else if($_GET['todelete']) $ip = $_GET['todelete']; - exec("/sbin/pfctl -t snort2c -T delete {$ip}"); + if (is_ipaddr($ip)) + exec("/sbin/pfctl -t snort2c -T delete {$ip}"); } if ($_POST['remove']) { exec("/sbin/pfctl -t snort2c -T flush"); - sleep(1); header("Location: /snort/snort_blocked.php"); exit; - } /* TODO: build a file with block ip and disc */ if ($_POST['download']) { - - ob_start(); //important or other posts will fail - $save_date = exec('/bin/date "+%Y-%m-%d-%H-%M-%S"'); - $file_name = "snort_blocked_{$save_date}.tar.gz"; - exec('/bin/mkdir /tmp/snort_blocked'); - exec('/sbin/pfctl -t snort2c -T show > /tmp/snort_block.pf'); - - $blocked_ips_array_save = str_replace(' ', '', array_filter(explode("\n", file_get_contents('/tmp/snort_block.pf')))); - - if ($blocked_ips_array_save[0] != '') { - /* build the list */ + $blocked_ips_array_save = ""; + 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) { + ob_start(); //important or other posts will fail + $save_date = exec('/bin/date "+%Y-%m-%d-%H-%M-%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", ""); - foreach($blocked_ips_array_save as $counter => $fileline3) - file_put_contents("/tmp/snort_blocked/snort_block.pf", "{$fileline3}\n", FILE_APPEND); - } - - exec("/usr/bin/tar cfz /tmp/snort_blocked_{$save_date}.tar.gz /tmp/snort_blocked"); - - if(file_exists("/tmp/snort_blocked_{$save_date}.tar.gz")) { - $file = "/tmp/snort_blocked_{$save_date}.tar.gz"; - header("Expires: Mon, 26 Jul 1997 05:00:00 GMT\n"); - header("Pragma: private"); // needed for IE - header("Cache-Control: private, must-revalidate"); // needed for IE - header('Content-type: application/force-download'); - header('Content-Transfer-Encoding: Binary'); - header("Content-length: ".filesize($file)); - header("Content-disposition: attachment; filename = {$file_name}"); - readfile("$file"); - exec("/bin/rm /tmp/snort_blocked_{$save_date}.tar.gz"); - exec("/bin/rm /tmp/snort_block.pf"); - exec("/bin/rm /tmp/snort_blocked/snort_block.pf"); - od_end_clean(); //importanr or other post will fail + 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); + } + + exec("/usr/bin/tar cf /tmp/{$file_name} /tmp/snort_blocked"); + + if(file_exists("/tmp/{$file_name}")) { + header("Expires: Mon, 26 Jul 1997 05:00:00 GMT\n"); + header("Pragma: private"); // needed for IE + header("Cache-Control: private, must-revalidate"); // needed for IE + header('Content-type: application/force-download'); + header('Content-Transfer-Encoding: Binary'); + header("Content-length: " . filesize("/tmp/{$file_name}")); + header("Content-disposition: attachment; filename = {$file_name}"); + readfile("/tmp/{$file_name}"); + ob_end_clean(); //importanr or other post will fail + @unlink("/tmp/{$file_name}"); + exec("/bin/rm -fr /tmp/snort_blocked"); + } else + $savemsg = "An error occurred while createing archive"; } else - echo 'Error no saved file.'; - + $savemsg = "No content on snort block list"; } if ($_POST['save']) { - - /* input validation */ - if ($_POST['save']) - { - - - } - /* no errors */ - if (!$input_errors) - { + if (!$input_errors) { $config['installedpackages']['snortglobal']['alertsblocks']['brefresh'] = $_POST['brefresh'] ? 'on' : 'off'; $config['installedpackages']['snortglobal']['alertsblocks']['blertnumber'] = $_POST['blertnumber']; write_config(); header("Location: /snort/snort_blocked.php"); - + exit; } } -/* build filter funcs */ -function get_snort_alert_ip_src($fileline) -{ - /* SRC IP */ - $re1='.*?'; # Non-greedy match on filler - $re2='((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?![\\d])'; # IPv4 IP Address 1 - - if ($c=preg_match_all ("/".$re1.$re2."/is", $fileline, $matches4)) - $alert_ip_src = $matches4[1][0]; - - return $alert_ip_src; -} - -function get_snort_alert_disc($fileline) -{ - /* disc */ - if (preg_match("/\[\*\*\] (\[.*\]) (.*) (\[\*\*\])/", $fileline, $matches)) - $alert_disc = "$matches[2]"; - - return $alert_disc; -} - -/* build sec filters */ -function get_snort_block_ip($fileline) -{ - /* ip */ - if (preg_match("/\[\d+\.\d+\.\d+\.\d+\]/", $fileline, $matches)) - $alert_block_ip = "$matches[0]"; - - return $alert_block_ip; -} - -function get_snort_block_disc($fileline) -{ - /* disc */ - if (preg_match("/\]\s\[.+\]$/", $fileline, $matches)) - $alert_block_disc = "$matches[0]"; - - return $alert_block_disc; -} - -/* tell the user what settings they have */ -$blockedtab_msg_chk = $config['installedpackages']['snortglobal']['rm_blocked']; -if ($blockedtab_msg_chk == "1h_b") { - $blocked_msg = "hour"; -} -if ($blockedtab_msg_chk == "3h_b") { - $blocked_msg = "3 hours"; -} -if ($blockedtab_msg_chk == "6h_b") { - $blocked_msg = "6 hours"; -} -if ($blockedtab_msg_chk == "12h_b") { - $blocked_msg = "12 hours"; -} -if ($blockedtab_msg_chk == "1d_b") { - $blocked_msg = "day"; -} -if ($blockedtab_msg_chk == "4d_b") { - $blocked_msg = "4 days"; -} -if ($blockedtab_msg_chk == "7d_b") { - $blocked_msg = "7 days"; -} -if ($blockedtab_msg_chk == "28d_b") { - $blocked_msg = "28 days"; -} - -if ($blockedtab_msg_chk != "never_b") -{ - $blocked_msg_txt = "Hosts are removed every <strong>$blocked_msg</strong>."; -}else{ - $blocked_msg_txt = "Settings are set to never <strong>remove</strong> hosts."; -} - $pgtitle = "Services: Snort Blocked Hosts"; include_once("head.inc"); @@ -212,213 +124,149 @@ include_once("head.inc"); <?php include_once("fbegin.inc"); -echo $snort_general_css; /* refresh every 60 secs */ if ($pconfig['brefresh'] == 'on') echo "<meta http-equiv=\"refresh\" content=\"60;url=/snort/snort_blocked.php\" />\n"; ?> -<div class="body2"><?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> +<?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> <?php if ($savemsg) print_info_box($savemsg); ?> +<form action="/snort/snort_blocked.php" method="post"> <table width="99%" border="0" cellpadding="0" cellspacing="0"> <tr><td> <?php - $tab_array = array(); - $tab_array[0] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); - $tab_array[1] = array(gettext("Global Settings"), false, "/snort/snort_interfaces_global.php"); - $tab_array[2] = array(gettext("Updates"), false, "/snort/snort_download_updates.php"); - $tab_array[3] = array(gettext("Alerts"), false, "/snort/snort_alerts.php"); - $tab_array[4] = array(gettext("Blocked"), true, "/snort/snort_blocked.php"); - $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); - $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); - $tab_array[7] = array(gettext("Help"), false, "/snort/help_and_info.php"); - display_top_tabs($tab_array); + $tab_array = array(); + $tab_array[0] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); + $tab_array[1] = array(gettext("Global Settings"), false, "/snort/snort_interfaces_global.php"); + $tab_array[2] = array(gettext("Updates"), false, "/snort/snort_download_updates.php"); + $tab_array[3] = array(gettext("Alerts"), false, "/snort/snort_alerts.php"); + $tab_array[4] = array(gettext("Blocked"), true, "/snort/snort_blocked.php"); + $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); + $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); + display_top_tabs($tab_array); ?> </td></tr> <tr> <td> - <div id="mainarea2"> - <table id="maintable" class="tabcont" width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> - <td width="22%" colspan="0" class="listtopic">Last <?=$bnentries;?> - Blocked.</td> - <td width="78%" class="listtopic">This page lists hosts that have - been blocked by Snort. <?=$blocked_msg_txt;?></td> + <td width="22%" colspan="0" class="listtopic"><?php printf(gettext("Last %s " . + "Blocked."), $bnentries); ?></td> + <td width="78%" class="listtopic"><?php echo gettext("This page lists hosts that have " . + "been blocked by Snort."); ?> <?=$blocked_msg_txt;?></td> </tr> <tr> - <td width="22%" class="vncell">Save or Remove Hosts</td> + <td width="22%" class="vncell"><?php echo gettext("Save or Remove Hosts"); ?></td> <td width="78%" class="vtable"> - <form action="/snort/snort_blocked.php" method="post"><input - name="download" type="submit" class="formbtn" value="Download"> All - blocked hosts will be saved. <input name="remove" type="submit" - class="formbtn" value="Clear"> <span class="red"><strong>Warning:</strong></span> - all hosts will be removed.</form> + <input name="download" type="submit" class="formbtn" value="Download"> <?php echo gettext("All " . + "blocked hosts will be saved."); ?> <input name="remove" type="submit" + class="formbtn" value="Clear"> <span class="red"><strong><?php echo gettext("Warning:"); ?></strong></span> + <?php echo gettext("all hosts will be removed."); ?></form> </td> </tr> <tr> - <td width="22%" class="vncell">Auto Refresh and Log View</td> + <td width="22%" class="vncell"><?php echo gettext("Auto Refresh and Log View"); ?></td> <td width="78%" class="vtable"> - <form action="/snort/snort_blocked.php" method="post"><input - name="save" type="submit" class="formbtn" value="Save"> Refresh <input + <input name="save" type="submit" class="formbtn" value="Save"> <?php echo gettext("Refresh"); ?> <input name="brefresh" type="checkbox" value="on" <?php if ($config['installedpackages']['snortglobal']['alertsblocks']['brefresh']=="on" || $config['installedpackages']['snortglobal']['alertsblocks']['brefresh']=='') echo "checked"; ?>> - <strong>Default</strong> is <strong>ON</strong>. <input + <?php printf(gettext("%sDefault%s is %sON%s."), '<strong>', '</strong>', '<strong>', '</strong>'); ?> <input name="blertnumber" type="text" class="formfld" id="blertnumber" - size="5" value="<?=htmlspecialchars($bnentries);?>"> Enter the - number of blocked entries to view. <strong>Default</strong> is <strong>500</strong>. - </form> + size="5" value="<?=htmlspecialchars($bnentries);?>"> <?php printf(gettext("Enter the " . + "number of blocked entries to view. %sDefault%s is %s500%s."), '<strong>', '</strong>', '<strong>', '</strong>'); ?> </td> </tr> - </table> - </div> - <br> - </td> - </tr> - - <table class="tabcont" width="100%" border="0" cellspacing="0" - cellpadding="0"> - <tr> - <td> + <tr> + <td colspan="2"> <table id="sortabletable1" class="sortable" width="100%" border="0" cellpadding="0" cellspacing="0"> <tr id="frheader"> - <td width="5%" class="listhdrr">Remove</td> - <td class="listhdrr">#</td> - <td class="listhdrr">IP</td> - <td class="listhdrr">Alert Description</td> + <td width="5%" class="listhdrr">#</td> + <td width="15%" class="listhdrr"><?php echo gettext("IP"); ?></td> + <td width="70%" class="listhdrr"><?php echo gettext("Alert Description"); ?></td> + <td width="5%" class="listhdrr"><?php echo gettext("Remove"); ?></td> </tr> - <?php - - /* set the arrays */ - exec('/sbin/pfctl -t snort2c -T show > /tmp/snort_block.cache'); - $alerts_array = array_reverse(array_filter(explode("\n\n", file_get_contents('/var/log/snort/alert')))); - $blocked_ips_array = str_replace(' ', '', array_filter(explode("\n", file_get_contents('/tmp/snort_block.cache')))); - - $logent = $bnentries; - - if ($blocked_ips_array[0] != '' && $alerts_array[0] != '') - { - - /* build the list and compare blocks to alerts */ - $counter = 0; - foreach($alerts_array as $fileline) - { - - $counter++; - - $alert_ip_src = get_snort_alert_ip_src($fileline); - $alert_ip_disc = get_snort_alert_disc($fileline); - $alert_ip_src_array[] = get_snort_alert_ip_src($fileline); - - if (in_array("$alert_ip_src", $blocked_ips_array)) - $input[] = "[$alert_ip_src] " . "[$alert_ip_disc]\n"; - } - - foreach($blocked_ips_array as $alert_block_ip) - { - - if (!in_array($alert_block_ip, $alert_ip_src_array)) - { - $input[] = "[$alert_block_ip] " . "[N\A]\n"; - } - } - - /* reduce double occurrences */ - $result = array_unique($input); - - /* buil final list, preg_match, buld html */ - $counter2 = 0; - - foreach($result as $fileline2) - { - if($logent <= $counter2) + <?php + /* set the arrays */ + $blocked_ips_array = array(); + if (is_array($blocked_ips)) { + foreach ($blocked_ips as $blocked_ip) { + if (empty($blocked_ip)) continue; - - $counter2++; - - $alert_block_ip_str = get_snort_block_ip($fileline2); - - if($alert_block_ip_str != '') - { - $alert_block_ip_match = array('[',']'); - $alert_block_ip = str_replace($alert_block_ip_match, '', "$alert_block_ip_str"); - }else{ - $alert_block_ip = 'empty'; + $blocked_ips_array[] = trim($blocked_ip, " \n\t"); + } + } + $blocked_ips_array = snort_get_blocked_ips(); + if (!empty($blocked_ips_array)) { + $tmpblocked = array_flip($blocked_ips_array); + $src_ip_list = array(); + foreach (glob("/var/log/snort/*/alert") as $alertfile) { + $fd = fopen($alertfile, "r"); + if ($fd) { + /* 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 */ + while (($fields = fgetcsv($fd, 1000, ',', '"')) !== FALSE) { + if(count($fields) < 11) + continue; + + if (isset($tmpblocked[$fields[6]])) { + if (!is_array($src_ip_list[$fields[6]])) + $src_ip_list[$fields[6]] = array(); + $src_ip_list[$fields[6]][$fields[4]] = "{$fields[4]} - " . substr($fields[0], 0, -8); } - - $alert_block_disc_str = get_snort_block_disc($fileline2); - - if($alert_block_disc_str != '') - { - $alert_block_disc_match = array('] [',']'); - $alert_block_disc = str_replace($alert_block_disc_match, '', "$alert_block_disc_str"); - }else{ - $alert_block_disc = 'empty'; + if (isset($tmpblocked[$fields[8]])) { + if (!is_array($src_ip_list[$fields[8]])) + $src_ip_list[$fields[8]] = array(); + $src_ip_list[$fields[8]][$fields[4]] = "{$fields[4]} - " . substr($fields[0], 0, -8); } - - /* use one echo to do the magic*/ - echo "<tr> - <td align=\"center\" valign=\"top\"'><a href='snort_blocked.php?todelete=" . trim(urlencode($alert_block_ip)) . "'> - <img title=\"Delete\" border=\"0\" name='todelete' id='todelete' alt=\"Delete\" src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\"></a></td> - <td> {$counter2}</td> - <td> {$alert_block_ip}</td> - <td> {$alert_block_disc}</td> - </tr>\n"; - - } - - }else{ - - /* if alerts file is empty and blocked table is not empty */ - $counter2 = 0; - - foreach($blocked_ips_array as $alert_block_ip) - { - if($logent <= $counter2) - continue; - - $counter2++; - - $alert_block_disc = 'N/A'; - - /* use one echo to do the magic*/ - echo "<tr> - <td align=\"center\" valign=\"top\"'><a href='snort_blocked.php?todelete=" . trim(urlencode($alert_block_ip)) . "'> - <img title=\"Delete\" border=\"0\" name='todelete' id='todelete' alt=\"Delete\" src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\"></a></td> - <td> {$counter2}</td> - <td> {$alert_block_ip}</td> - <td> {$alert_block_disc}</td> - </tr>\n"; } + fclose($fd); } - - echo '</table>' . "\n"; - - if (empty($blocked_ips_array[0])) - echo "\n<tr><td colspan='3' align=\"center\" valign=\"top\"><br><strong>There are currently no items being blocked by snort.</strong></td></tr>"; + } + + foreach($blocked_ips_array as $blocked_ip) { + if (is_ipaddr($blocked_ip) && !isset($src_ip_list[$blocked_ip])) + $src_ip_list[$blocked_ip] = array("N\A\n"); + } + + /* buil final list, preg_match, buld html */ + $counter = 0; + foreach($src_ip_list as $blocked_ip => $blocked_msg) { + $blocked_desc = "<br/>" . implode("<br/>", $blocked_msg); + if($counter > $bnentries) + break; else - echo "\n<tr><td colspan='3' align=\"center\" valign=\"top\">{$counter2} items listed.</td></tr>"; - - ?> - </td> - </tr> - </table> - </td> - </tr> - </table> - </div> - - <?php + $counter++; + + /* use one echo to do the magic*/ + echo "<tr> + <td width='5%' > {$counter}</td> + <td width='15%' > {$blocked_ip}</td> + <td width='70%' > {$blocked_desc}</td> + <td width='5%' align=\"center\" valign=\"top\"'><a href='snort_blocked.php?todelete=" . trim(urlencode($blocked_ip)) . "'> + <img title=\"" . gettext("Delete") . "\" border=\"0\" name='todelete' id='todelete' alt=\"Delete\" src=\"../themes/{$g['theme']}/images/icons/icon_x.gif\"></a></td> + </tr>\n"; - include("fend.inc"); + } -echo $snort_custom_rnd_box; + echo "\n<tr><td colspan='3' align=\"center\" valign=\"top\">{$counter} items listed.</td></tr>"; + } else + echo "\n<tr><td colspan='3' align=\"center\" valign=\"top\"><br><strong>There are currently no items being blocked by snort.</strong></td></tr>"; + ?> + </table> + </td> + </tr> +</table> + </td> + </tr> +</table> +</form> +<?php +include("fend.inc"); ?> - </body> </html> diff --git a/config/snort/snort_check_cron_misc.inc b/config/snort/snort_check_cron_misc.inc index 28d454b0..e988b949 100644 --- a/config/snort/snort_check_cron_misc.inc +++ b/config/snort/snort_check_cron_misc.inc @@ -1,33 +1,32 @@ <?php -/* $Id$ */ /* - snort_chk_log_dir_size.php - part of pfSense - - Modified for the Pfsense snort package v. 1.8+ - Copyright (C) 2009-2010 Robert Zelaya Developer - 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. + * snort_chk_log_dir_size.php + * part of pfSense + * + * Modified for the Pfsense snort package v. 1.8+ + * Copyright (C) 2009-2010 Robert Zelaya Developer + * 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("/usr/local/pkg/snort/snort.inc"); @@ -50,27 +49,31 @@ if ($g['booting']==true) if ($snortloglimit == 'off') return; -$snortloglimitDSKsize = exec('/bin/df -k /var | grep -v "Filesystem" | awk \'{print $4}\''); - -$snortlogAlertsizeKB = snort_Getdirsize('/var/log/snort/alert'); -$snortloglimitAlertsizeKB = round($snortlogAlertsizeKB * .70); -$snortloglimitsizeKB = round($snortloglimitsize * 1024); +if (!is_array($config['installedpackages']['snortglobal']['rule'])) + return; -/* do I need HUP kill ? */ -if (snort_Getdirsize('/var/log/snort/') >= $snortloglimitsizeKB ) { +$snortloglimitDSKsize = exec('/bin/df -k /var | grep -v "Filesystem" | awk \'{print $4}\''); - conf_mount_rw(); - if(file_exists('/var/log/snort/alert')) { - if ($snortlogAlertsizeKB >= $snortloglimitAlertsizeKB) { - exec('/bin/echo "" > /var/log/snort/alert'); +foreach ($config['installedpackages']['snortglobal']['rule'] as $value) { + $if_real = snort_get_real_interface($value['interface']); + $snort_uuid = $value['uuid']; + $snort_log_dir = "/var/log/snort/snort_{$if_real}{$snort_uuid}"; + + if (file_exists("{$snort_log_dir}/alert")) { + $snortlogAlertsizeKB = snort_Getdirsize("{$snort_log_dir}/alert"); + $snortloglimitAlertsizeKB = round($snortlogAlertsizeKB * .70); + $snortloglimitsizeKB = round($snortloglimitsize * 1024); + + /* do I need HUP kill ? */ + if (snort_Getdirsize($snort_log_dir) >= $snortloglimitsizeKB ) { + conf_mount_rw(); + if ($snortlogAlertsizeKB >= $snortloglimitAlertsizeKB) + @file_put_contents("{$snort_log_dir}/alert", ""); + snort_post_delete_logs($snort_uuid); + conf_mount_ro(); } - post_delete_logs(); - /* XXX: This is needed if snort is run as snort user */ - //mwexec('/usr/sbin/chown snort:snort /var/log/snort/*', true); - mwexec('/bin/chmod 660 /var/log/snort/*', true); - } - conf_mount_ro(); + } } ?> diff --git a/config/snort/snort_check_for_rule_updates.php b/config/snort/snort_check_for_rule_updates.php index 5043a624..689b3174 100644 --- a/config/snort/snort_check_for_rule_updates.php +++ b/config/snort/snort_check_for_rule_updates.php @@ -1,311 +1,147 @@ <?php /* - snort_check_for_rule_updates.php - Copyright (C) 2006 Scott Ullrich - Copyright (C) 2009 Robert Zelaya - Copyright (C) 2011 Ermal Luci - 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. + * snort_check_for_rule_updates.php + * + * Copyright (C) 2006 Scott Ullrich + * Copyright (C) 2009 Robert Zelaya + * Copyright (C) 2011-2012 Ermal Luci + * 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. */ -/* Setup enviroment */ - -/* TODO: review if include files are needed */ require_once("functions.inc"); require_once("service-utils.inc"); require_once("/usr/local/pkg/snort/snort.inc"); -$pkg_interface = "console"; +global $snort_gui_include; -$tmpfname = "/usr/local/etc/snort/tmp/snort_rules_up"; -$snortdir = "/usr/local/etc/snort"; -$snortdir_wan = "/usr/local/etc/snort"; -$snort_filename_md5 = "snortrules-snapshot-2905.tar.gz.md5"; -$snort_filename = "snortrules-snapshot-2905.tar.gz"; -$emergingthreats_filename_md5 = "emerging.rules.tar.gz.md5"; -$emergingthreats_filename = "emerging.rules.tar.gz"; -$pfsense_rules_filename_md5 = "pfsense_rules.tar.gz.md5"; -$pfsense_rules_filename = "pfsense_rules.tar.gz"; +$snortdir = SNORTDIR; -/* Time stamps define */ -$last_md5_download = $config['installedpackages']['snortglobal']['last_md5_download']; -$last_rules_install = $config['installedpackages']['snortglobal']['last_rules_install']; +if (!isset($snort_gui_include)) + $pkg_interface = "console"; -$up_date_time = date('l jS \of F Y h:i:s A'); -echo "\n"; -echo "#########################\n"; -echo "$up_date_time\n"; -echo "#########################\n"; -echo "\n\n"; +$tmpfname = "{$snortdir}/tmp/snort_rules_up"; +$snort_filename_md5 = "{$snort_rules_file}.md5"; +$snort_filename = "{$snort_rules_file}"; +$emergingthreats_filename_md5 = "emerging.rules.tar.gz.md5"; +$emergingthreats_filename = "emerging.rules.tar.gz"; /* define checks */ $oinkid = $config['installedpackages']['snortglobal']['oinkmastercode']; $snortdownload = $config['installedpackages']['snortglobal']['snortdownload']; $emergingthreats = $config['installedpackages']['snortglobal']['emergingthreats']; -if ($snortdownload == 'off' && $emergingthreats != 'on') -{ - $snort_emrging_info = 'stop'; -} - -if ($oinkid == "" && $snortdownload != 'off') -{ - $snort_oinkid_info = 'stop'; -} - - -/* check if main rule directory is empty */ -$if_mrule_dir = "/usr/local/etc/snort/rules"; -$mfolder_chk = (count(glob("$if_mrule_dir/*")) === 0) ? 'empty' : 'full'; - - -if (file_exists('/var/run/snort.conf.dirty')) { - $snort_dirty_d = 'stop'; -} - /* Start of code */ conf_mount_rw(); -if (!is_dir('/usr/local/etc/snort/tmp')) { - exec('/bin/mkdir -p /usr/local/etc/snort/tmp'); -} - -$snort_md5_check_ok = 'off'; -$emerg_md5_check_ok = 'off'; -$pfsense_md5_check_ok = 'off'; +if (!is_dir($tmpfname)) + exec("/bin/mkdir -p {$tmpfname}"); /* Set user agent to Mozilla */ ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)'); ini_set("memory_limit","150M"); -/* mark the time update started */ -$config['installedpackages']['snortglobal']['last_md5_download'] = date("Y-M-jS-h:i-A"); - -/* send current buffer */ -ob_flush(); - -/* send current buffer */ -ob_flush(); - /* remove old $tmpfname files */ -if (is_dir("{$tmpfname}")) { - update_status(gettext("Removing old tmp files...")); +if (is_dir("{$tmpfname}")) exec("/bin/rm -r {$tmpfname}"); - apc_clear_cache(); -} /* Make shure snortdir exits */ -exec("/bin/mkdir -p {$snortdir}"); exec("/bin/mkdir -p {$snortdir}/rules"); exec("/bin/mkdir -p {$snortdir}/signatures"); exec("/bin/mkdir -p {$tmpfname}"); -exec("/bin/mkdir -p /usr/local/lib/snort/dynamicrules/"); - -/* send current buffer */ -ob_flush(); - -$pfsensedownload = 'on'; +exec("/bin/mkdir -p /usr/local/lib/snort/dynamicrules"); /* download md5 sig from snort.org */ -if ($snortdownload == 'on') -{ - if (file_exists("{$tmpfname}/{$snort_filename_md5}") && - filesize("{$tmpfname}/{$snort_filename_md5}") > 0) { - update_status(gettext("snort.org md5 temp file exists...")); - } else { - update_status(gettext("Downloading snort.org md5 file...")); - ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)'); - - //$image = @file_get_contents("http://www.mtest.local/pub-bin/oinkmaster.cgi/{$oinkid}/{$snort_filename_md5}"); - $image = @file_get_contents("http://www.snort.org/pub-bin/oinkmaster.cgi/{$oinkid}/{$snort_filename_md5}"); - @file_put_contents("{$tmpfname}/{$snort_filename_md5}", $image); - update_status(gettext("Done downloading snort.org md5")); - } -} - -/* download md5 sig from emergingthreats.net */ -if ($emergingthreats == 'on') -{ - update_status(gettext("Downloading emergingthreats md5 file...")); - ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)'); - // $image = @file_get_contents("http://www.mtest.local/pub-bin/oinkmaster.cgi/{$oinkid}/version.txt"); - $image = @file_get_contents('http://rules.emergingthreats.net/open/snort-2.9.0/emerging.rules.tar.gz.md5'); - @file_put_contents("{$tmpfname}/{$emergingthreats_filename_md5}", $image); - update_status(gettext("Done downloading emergingthreats md5")); -} - -/* download md5 sig from pfsense.org */ -if (file_exists("{$tmpfname}/{$pfsense_rules_filename_md5}")) { - update_status(gettext("pfsense md5 temp file exists...")); -} else { - update_status(gettext("Downloading pfsense md5 file...")); - ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)'); - //$image = @file_get_contents("http://www.mtest.local/pub-bin/oinkmaster.cgi/{$oinkid}/pfsense_rules.tar.gz.md5"); - $image = @file_get_contents("http://www.pfsense.com/packages/config/snort/pfsense_rules/pfsense_rules.tar.gz.md5"); - @file_put_contents("{$tmpfname}/pfsense_rules.tar.gz.md5", $image); - update_status(gettext("Done downloading pfsense md5.")); -} - -/* If md5 file is empty wait 15min exit */ -if ($snortdownload == 'on') -{ - if (0 == filesize("{$tmpfname}/{$snort_filename_md5}")) - { +if ($snortdownload == 'on') { + update_status(gettext("Downloading snort.org md5 file...")); + $image = @file_get_contents("http://www.snort.org/pub-bin/oinkmaster.cgi/{$oinkid}/{$snort_filename_md5}"); + @file_put_contents("{$tmpfname}/{$snort_filename_md5}", $image); + if (0 == filesize("{$tmpfname}/{$snort_filename_md5}")) { update_status(gettext("Please wait... You may only check for New Rules every 15 minutes...")); + log_error("Please wait... You may only check for New Rules every 15 minutes..."); update_output_window(gettext("Rules are released every month from snort.org. You may download the Rules at any time.")); $snortdownload = 'off'; - } -} - -/* If pfsense md5 file is empty wait 15min exit */ -if (0 == filesize("{$tmpfname}/$pfsense_rules_filename_md5")){ - update_status(gettext("Please wait... You may only check for New Pfsense Rules every 15 minutes...")); - update_output_window(gettext("Rules are released to support Pfsense packages.")); - $pfsensedownload = 'off'; + } else + update_status(gettext("Done downloading snort.org md5")); } /* Check if were up to date snort.org */ -if ($snortdownload == 'on') -{ - if (file_exists("{$snortdir}/{$snort_filename_md5}")) - { - $md5_check_new_parse = file_get_contents("{$tmpfname}/{$snort_filename_md5}"); - $md5_check_new = `/bin/echo "{$md5_check_new_parse}" | /usr/bin/awk '{ print $1 }'`; - $md5_check_old_parse = file_get_contents("{$snortdir}/{$snort_filename_md5}"); - $md5_check_old = `/bin/echo "{$md5_check_old_parse}" | /usr/bin/awk '{ print $1 }'`; - if ($md5_check_new == $md5_check_old) - { - update_status(gettext("Your rules are up to date...")); - update_output_window(gettext("You may start Snort now, check update.")); - $snort_md5_check_ok = 'on'; - } else { - update_status(gettext("Your rules are not up to date...")); - $snort_md5_check_ok = 'off'; +if ($snortdownload == 'on') { + if (file_exists("{$snortdir}/{$snort_filename_md5}")) { + $md5_check_new = file_get_contents("{$tmpfname}/{$snort_filename_md5}"); + $md5_check_old = file_get_contents("{$snortdir}/{$snort_filename_md5}"); + if ($md5_check_new == $md5_check_old) { + update_status(gettext("Snort rules are up to date...")); + log_error("Snort rules are up to date..."); + $snortdownload = 'off'; } } } -/* Check if were up to date emergingthreats.net */ -if ($emergingthreats == 'on') -{ - if (file_exists("{$snortdir}/{$emergingthreats_filename_md5}")) - { - $emerg_md5_check_new_parse = file_get_contents("{$tmpfname}/{$emergingthreats_filename_md5}"); - $emerg_md5_check_new = `/bin/echo "{$emerg_md5_check_new_parse}" | /usr/bin/awk '{ print $1 }'`; - $emerg_md5_check_old_parse = file_get_contents("{$snortdir}/{$emergingthreats_filename_md5}"); - $emerg_md5_check_old = `/bin/echo "{$emerg_md5_check_old_parse}" | /usr/bin/awk '{ print $1 }'`; - if ($emerg_md5_check_new == $emerg_md5_check_old) - { - $emerg_md5_check_ok = 'on'; - } else - $emerg_md5_check_ok = 'off'; - } -} - -/* Check if were up to date pfsense.org */ -if ($pfsensedownload == 'on' && file_exists("{$snortdir}/pfsense_rules.tar.gz.md5")) -{ - $pfsense_check_new_parse = file_get_contents("{$tmpfname}/pfsense_rules.tar.gz.md5"); - $pfsense_md5_check_new = `/bin/echo "{$pfsense_md5_check_new_parse}" | /usr/bin/awk '{ print $1 }'`; - $pfsense_md5_check_old_parse = file_get_contents("{$snortdir}/pfsense_rules.tar.gz.md5"); - $pfsense_md5_check_old = `/bin/echo "{$pfsense_md5_check_old_parse}" | /usr/bin/awk '{ print $1 }'`; - if ($pfsense_md5_check_new == $pfsense_md5_check_old) - { - $pfsense_md5_check_ok = 'on'; - } else - $pfsense_md5_check_ok = 'off'; -} - +/* download snortrules file */ if ($snortdownload == 'on') { - if ($snort_md5_check_ok == 'on') - { - update_status(gettext("Your snort.org rules are up to date...")); - update_output_window(gettext("You may start Snort now...")); + update_status(gettext("There is a new set of Snort.org rules posted. Downloading...")); + log_error("There is a new set of Snort.org rules posted. Downloading..."); + download_file_with_progress_bar("http://www.snort.org/pub-bin/oinkmaster.cgi/{$oinkid}/{$snort_filename}", "{$tmpfname}/{$snort_filename}"); + update_status(gettext("Done downloading rules file.")); + if (300000 > filesize("{$tmpfname}/$snort_filename")){ + update_output_window(gettext("Snort rules file downloaded failed...")); + log_error("Snort rules file downloaded failed..."); $snortdownload = 'off'; } } + +/* download md5 sig from emergingthreats.net */ if ($emergingthreats == 'on') { - if ($emerg_md5_check_ok == 'on') - { - update_status(gettext("Your Emergingthreats rules are up to date...")); - update_output_window(gettext("You may start Snort now...")); - $emergingthreats = 'off'; - } -} + update_status(gettext("Downloading emergingthreats md5 file...")); + $image = @file_get_contents("http://rules.emergingthreats.net/open/snort-{$emerging_threats_version}/emerging.rules.tar.gz.md5"); + /* XXX: error checking */ + @file_put_contents("{$tmpfname}/{$emergingthreats_filename_md5}", $image); + update_status(gettext("Done downloading emergingthreats md5")); -/* download snortrules file */ -if ($snortdownload == 'on') -{ - if ($snort_md5_check_ok != 'on') { - if (file_exists("{$tmpfname}/{$snort_filename}")) { - update_status(gettext("Snortrule tar file exists...")); - } else { - update_status(gettext("There is a new set of Snort.org rules posted. Downloading...")); - update_output_window(gettext("May take 4 to 10 min...")); - download_file_with_progress_bar("http://www.snort.org/pub-bin/oinkmaster.cgi/{$oinkid}/{$snort_filename}", "{$tmpfname}/{$snort_filename}"); - update_all_status($static_output); - update_status(gettext("Done downloading rules file.")); - if (300000 > filesize("{$tmpfname}/$snort_filename")){ - update_status(gettext("Error with the snort rules download...")); - update_output_window(gettext("Snort rules file downloaded failed...")); - $snortdownload = 'off'; - } + if (file_exists("{$snortdir}/{$emergingthreats_filename_md5}")) { + /* Check if were up to date emergingthreats.net */ + $emerg_md5_check_new = file_get_contents("{$tmpfname}/{$emergingthreats_filename_md5}"); + $emerg_md5_check_old = file_get_contents("{$snortdir}/{$emergingthreats_filename_md5}"); + if ($emerg_md5_check_new == $emerg_md5_check_old) { + update_status(gettext("Emerging threat rules are up to date...")); + log_error("Emerging threat rules are up to date..."); + $emergingthreats = 'off'; } } } /* download emergingthreats rules file */ -if ($emergingthreats == "on") -{ - if ($emerg_md5_check_ok != 'on') - { - if (file_exists("{$tmpfname}/{$emergingthreats_filename}")) - { - update_status(gettext('Emergingthreats tar file exists...')); - }else{ - update_status(gettext("There is a new set of Emergingthreats rules posted. Downloading...")); - update_output_window(gettext("May take 4 to 10 min...")); - download_file_with_progress_bar('http://rules.emergingthreats.net/open/snort-2.9.0/emerging.rules.tar.gz', "{$tmpfname}/{$emergingthreats_filename}"); - update_status(gettext('Done downloading Emergingthreats rules file.')); - } - } -} - -/* download pfsense rules file */ -if ($pfsensedownload == 'on' && $pfsense_md5_check_ok != 'on') { - if (file_exists("{$tmpfname}/{$pfsense_rules_filename}")) { - update_status(gettext("Snortrule tar file exists...")); - } else { - update_status(gettext("There is a new set of Pfsense rules posted. Downloading...")); - update_output_window(gettext("May take 4 to 10 min...")); - download_file_with_progress_bar("http://www.pfsense.com/packages/config/snort/pfsense_rules/pfsense_rules.tar.gz", $tmpfname . "/{$pfsense_rules_filename}"); - update_all_status($static_output); - update_status(gettext("Done downloading rules file.")); - } +if ($emergingthreats == "on") { + update_status(gettext("There is a new set of Emergingthreats rules posted. Downloading...")); + log_error("There is a new set of Emergingthreats rules posted. Downloading..."); + download_file_with_progress_bar("http://rules.emergingthreats.net/open/snort-{$emerging_threats_version}/emerging.rules.tar.gz", "{$tmpfname}/{$emergingthreats_filename}"); + update_status(gettext('Done downloading Emergingthreats rules file.')); + log_error("Emergingthreats rules file update downloaded succsesfully"); } +/* XXX: need to be verified */ /* Compair md5 sig to file sig */ - //$premium_url_chk = $config['installedpackages']['snort']['config'][0]['subscriber']; //if ($premium_url_chk == on) { //$md5 = file_get_contents("{$tmpfname}/{$snort_filename_md5}"); @@ -319,377 +155,252 @@ if ($pfsensedownload == 'on' && $pfsense_md5_check_ok != 'on') { // } //} -//$premium_url_chk = $config['installedpackages']['snort']['config'][0]['subscriber']; -//if ($premium_url_chk != on) { -//$md55 = `/bin/cat {$tmpfname}/{$snort_filename_md5} | /usr/bin/awk '{ print $4 }'`; -//$file_md5_ondisk2 = `/sbin/md5 {$tmpfname}/{$snort_filename} | /usr/bin/awk '{ print $4 }'`; -// if ($md55 == $file_md5_ondisk2) { -// update_status(gettext("Valid md5 checksum pass...")); -//} else { -// update_status(gettext("The downloaded file does not match the md5 file...Not P")); -// update_output_window(gettext("Error md5 Mismatch...")); -// return; -// } -//} - -/* Untar snort rules file individually to help people with low system specs */ -if ($snortdownload == 'on') -{ - if ($snort_md5_check_ok != 'on') { - if (file_exists("{$tmpfname}/{$snort_filename}")) { - - if ($pfsense_stable == 'yes') - $freebsd_version_so = 'FreeBSD-7-2'; - else - $freebsd_version_so = 'FreeBSD-8-1'; - - update_status(gettext("Extracting Snort.org rules...")); - update_output_window(gettext("May take a while...")); - /* extract snort.org rules and add prefix to all snort.org files*/ - exec("/bin/rm -r {$snortdir}/rules"); - sleep(2); - exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} rules/"); - chdir ("/usr/local/etc/snort/rules"); - sleep(2); - exec('/usr/local/bin/perl /usr/local/bin/snort_rename.pl s/^/snort_/ *.rules'); - - /* extract so rules */ - exec('/bin/mkdir -p /usr/local/lib/snort/dynamicrules/'); - if($snort_arch == 'x86'){ - exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} so_rules/precompiled/$freebsd_version_so/i386/2.9.0.5/"); - exec("/bin/mv -f {$snortdir}/so_rules/precompiled/$freebsd_version_so/i386/2.9.0.5/* /usr/local/lib/snort/dynamicrules/"); - } else if ($snort_arch == 'x64') { - exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} so_rules/precompiled/$freebsd_version_so/x86-64/2.9.0.5/"); - exec("/bin/mv -f {$snortdir}/so_rules/precompiled/$freebsd_version_so/x86-64/2.9.0.5/* /usr/local/lib/snort/dynamicrules/"); - } - /* extract so rules none bin and rename */ - exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} so_rules/bad-traffic.rules/" . - " so_rules/chat.rules/" . - " so_rules/dos.rules/" . - " so_rules/exploit.rules/" . - " so_rules/icmp.rules/" . - " so_rules/imap.rules/" . - " so_rules/misc.rules/" . - " so_rules/multimedia.rules/" . - " so_rules/netbios.rules/" . - " so_rules/nntp.rules/" . - " so_rules/p2p.rules/" . - " so_rules/smtp.rules/" . - " so_rules/sql.rules/" . - " so_rules/web-activex.rules/" . - " so_rules/web-client.rules/" . - " so_rules/web-iis.rules/" . - " so_rules/web-misc.rules/"); - - exec("/bin/mv -f {$snortdir}/so_rules/bad-traffic.rules {$snortdir}/rules/snort_bad-traffic.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/chat.rules {$snortdir}/rules/snort_chat.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/dos.rules {$snortdir}/rules/snort_dos.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/exploit.rules {$snortdir}/rules/snort_exploit.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/icmp.rules {$snortdir}/rules/snort_icmp.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/imap.rules {$snortdir}/rules/snort_imap.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/misc.rules {$snortdir}/rules/snort_misc.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/multimedia.rules {$snortdir}/rules/snort_multimedia.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/netbios.rules {$snortdir}/rules/snort_netbios.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/nntp.rules {$snortdir}/rules/snort_nntp.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/p2p.rules {$snortdir}/rules/snort_p2p.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/smtp.rules {$snortdir}/rules/snort_smtp.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/sql.rules {$snortdir}/rules/snort_sql.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/web-activex.rules {$snortdir}/rules/snort_web-activex.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/web-client.rules {$snortdir}/rules/snort_web-client.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/web-iis.rules {$snortdir}/rules/snort_web-iis.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/web-misc.rules {$snortdir}/rules/snort_web-misc.so.rules"); - exec("/bin/rm -r {$snortdir}/so_rules"); - } - - /* extract base etc files */ - exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} etc/"); - exec("/bin/mv -f {$snortdir}/etc/* {$snortdir}"); - exec("/bin/rm -r {$snortdir}/etc"); - - update_status(gettext("Done extracting Snort.org Rules.")); - }else{ - update_status(gettext("Error extracting Snort.org Rules...")); - update_output_window(gettext("Error Line 755")); - $snortdownload = 'off'; - } -} +/* Normalize rulesets */ +$sedcmd = "s/^#alert/# alert/g\n"; +$sedcmd .= "s/^##alert/# alert/g\n"; +$sedcmd .= "s/^#[ \\t#]*alert/# alert/g\n"; +$sedcmd .= "s/^##\\talert/# alert/g\n"; +$sedcmd .= "s/^\\talert/alert/g\n"; +$sedcmd .= "s/^[ \\t]*alert/alert/g\n"; +@file_put_contents("{$snortdir}/tmp/sedcmd", $sedcmd); /* Untar emergingthreats rules to tmp */ -if ($emergingthreats == 'on') -{ - if ($emerg_md5_check_ok != 'on') - { - if (file_exists("{$tmpfname}/{$emergingthreats_filename}")) - { - update_status(gettext("Extracting rules...")); - update_output_window(gettext("May take a while...")); - exec("/usr/bin/tar xzf {$tmpfname}/{$emergingthreats_filename} -C {$snortdir} rules/"); - } - } -} - -/* Untar Pfsense rules to tmp */ -if ($pfsensedownload == 'on' && $pfsense_md5_check_ok != 'on') { - if (file_exists("{$tmpfname}/{$pfsense_rules_filename}")) { - update_status(gettext("Extracting Pfsense rules...")); - update_output_window(gettext("May take a while...")); - exec("/usr/bin/tar xzf {$tmpfname}/{$pfsense_rules_filename} -C {$snortdir} rules/"); - } -} - -/* Untar snort signatures */ -if ($snortdownload == 'on' && $snort_md5_check_ok != 'on') { - if (file_exists("{$tmpfname}/{$snort_filename}")) { - $signature_info_chk = $config['installedpackages']['snortglobal']['signatureinfo']; - if ($premium_url_chk == 'on') { - update_status(gettext("Extracting Signatures...")); - update_output_window(gettext("May take a while...")); - exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} doc/signatures/"); - update_status(gettext("Done extracting Signatures.")); +if ($emergingthreats == 'on') { + safe_mkdir("{$snortdir}/tmp/emerging"); + if (file_exists("{$tmpfname}/{$emergingthreats_filename}")) { + update_status(gettext("Extracting rules...")); + exec("/usr/bin/tar xzf {$tmpfname}/{$emergingthreats_filename} -C {$snortdir}/tmp/emerging rules/"); + + $files = glob("{$snortdir}/tmp/emerging/rules/*.rules"); + foreach ($files as $file) { + $newfile = basename($file); + @copy($file, "{$snortdir}/rules/{$newfile}"); } - } -} - -/* Copy md5 sig to snort dir */ -if ($snortdownload == 'on') -{ - if ($snort_md5_check_ok != 'on') { - if (file_exists("{$tmpfname}/$snort_filename_md5")) { - update_status(gettext("Copying md5 sig to snort directory...")); - exec("/bin/cp {$tmpfname}/$snort_filename_md5 {$snortdir}/$snort_filename_md5"); - }else{ - update_status(gettext("The md5 file does not exist...")); - update_output_window(gettext("Error copying config...")); - $snortdownload = 'off'; + /* IP lists */ + $files = glob("{$snortdir}/tmp/emerging/rules/*.txt"); + foreach ($files as $file) { + $newfile = basename($file); + @copy($file, "{$snortdir}/rules/{$newfile}"); } - } -} - -/* Copy emergingthreats md5 sig to snort dir */ -if ($emergingthreats == "on") -{ - if ($emerg_md5_check_ok != 'on') - { - if (file_exists("{$tmpfname}/$emergingthreats_filename_md5")) - { - update_status(gettext("Copying md5 sig to snort directory...")); - exec("/bin/cp {$tmpfname}/$emergingthreats_filename_md5 {$snortdir}/$emergingthreats_filename_md5"); - }else{ - update_status(gettext("The emergingthreats md5 file does not exist...")); - update_output_window(gettext("Error copying config...")); - $emergingthreats = 'off'; + if ($snortdownload == 'off') { + foreach (array("classification.config", "reference.config", "sid-msg.map", "unicode.map") as $file) { + if (file_exists("{$snortdir}/tmp/emerging/rules/{$file}")) + @copy("{$snortdir}/tmp/emerging/rules/{$file}", "{$snortdir}/{$file}"); + } } - } -} -/* Copy Pfsense md5 sig to snort dir */ -if ($pfsensedownload == 'on' && $pfsense_md5_check_ok != 'on') { - if (file_exists("{$tmpfname}/$pfsense_rules_filename_md5")) { - update_status(gettext("Copying Pfsense md5 sig to snort directory...")); - exec("/bin/cp {$tmpfname}/$pfsense_rules_filename_md5 {$snortdir}/$pfsense_rules_filename_md5"); - } else { - update_status(gettext("The Pfsense md5 file does not exist...")); - update_output_window(gettext("Error copying config...")); - $pfsensedownload = 'off'; - } -} + /* make shure default rules are in the right format */ + exec("/usr/bin/sed -I '' -f {$snortdir}/tmp/sedcmd {$snortdir}/rules/emerging*.rules"); -/* Copy signatures dir to snort dir */ -if ($snortdownload == 'on') -{ - if ($snort_md5_check_ok != 'on') - { - $signature_info_chk = $config['installedpackages']['snortglobal']['signatureinfo']; - if ($premium_url_chk == 'on') - { - if (file_exists("{$snortdir}/doc/signatures")) { - update_status(gettext("Copying signatures...")); - update_output_window(gettext("May take a while...")); - exec("/bin/mv -f {$snortdir}/doc/signatures {$snortdir}/signatures"); - exec("/bin/rm -r {$snortdir}/doc/signatures"); - update_status(gettext("Done copying signatures.")); - }else{ - update_status(gettext("Directory signatures exist...")); - update_output_window(gettext("Error copying signature...")); - $snortdownload = 'off'; - } + /* Copy emergingthreats md5 sig to snort dir */ + if (file_exists("{$tmpfname}/$emergingthreats_filename_md5")) { + update_status(gettext("Copying md5 sig to snort directory...")); + @copy("{$tmpfname}/$emergingthreats_filename_md5", "{$snortdir}/$emergingthreats_filename_md5"); } } } -/* double make shure cleanup emerg rules that dont belong */ -if (file_exists("/usr/local/etc/snort/rules/emerging-botcc-BLOCK.rules")) { - apc_clear_cache(); - @unlink("/usr/local/etc/snort/rules/emerging-botcc-BLOCK.rules"); - @unlink("/usr/local/etc/snort/rules/emerging-botcc.rules"); - @unlink("/usr/local/etc/snort/rules/emerging-compromised-BLOCK.rules"); - @unlink("/usr/local/etc/snort/rules/emerging-drop-BLOCK.rules"); - @unlink("/usr/local/etc/snort/rules/emerging-dshield-BLOCK.rules"); - @unlink("/usr/local/etc/snort/rules/emerging-rbn-BLOCK.rules"); - @unlink("/usr/local/etc/snort/rules/emerging-tor-BLOCK.rules"); -} - -if (file_exists("/usr/local/lib/snort/dynamicrules/lib_sfdynamic_example_rule.so")) { - exec("/bin/rm /usr/local/lib/snort/dynamicrules/lib_sfdynamic_example_rule.so"); - exec("/bin/rm /usr/local/lib/snort/dynamicrules/lib_sfdynamic_example\*"); -} - -/* make shure default rules are in the right format */ -exec("/usr/local/bin/perl -pi -e 's/#alert/# alert/g' /usr/local/etc/snort/rules/*.rules"); -exec("/usr/local/bin/perl -pi -e 's/##alert/# alert/g' /usr/local/etc/snort/rules/*.rules"); -exec("/usr/local/bin/perl -pi -e 's/## alert/# alert/g' /usr/local/etc/snort/rules/*.rules"); - -/* create a msg-map for snort */ -update_status(gettext("Updating Alert Messages...")); -update_output_window(gettext("Please Wait...")); -exec("/usr/local/bin/perl /usr/local/bin/create-sidmap.pl /usr/local/etc/snort/rules > /usr/local/etc/snort/sid-msg.map"); - - -////////////////// -/* open oinkmaster_conf for writing" function */ -function oinkmaster_conf($id, $if_real, $iface_uuid) -{ - global $config, $g, $snort_md5_check_ok, $emerg_md5_check_ok, $pfsense_md5_check_ok; - - @unlink("/usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/oinkmaster_{$iface_uuid}_{$if_real}.conf"); - - /* enable disable setting will carry over with updates */ - /* TODO carry signature changes with the updates */ - if ($snort_md5_check_ok != 'on' || $emerg_md5_check_ok != 'on' || $pfsense_md5_check_ok != 'on') { - - $selected_sid_on_section = ""; - $selected_sid_off_sections = ""; - - if (!empty($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_on'])) { - $enabled_sid_on = trim($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_on']); - $enabled_sid_on_array = split('\|\|', $enabled_sid_on); - foreach($enabled_sid_on_array as $enabled_item_on) - $selected_sid_on_sections .= "$enabled_item_on\n"; +/* Untar snort rules file individually to help people with low system specs */ +if ($snortdownload == 'on') { + if (file_exists("{$tmpfname}/{$snort_filename}")) { + if ($pfsense_stable == 'yes') + $freebsd_version_so = 'FreeBSD-7-2'; + else + $freebsd_version_so = 'FreeBSD-8-1'; + + update_status(gettext("Extracting Snort.org rules...")); + /* extract snort.org rules and add prefix to all snort.org files*/ + safe_mkdir("{$snortdir}/tmp/snortrules"); + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir}/tmp/snortrules rules/"); + $files = glob("{$snortdir}/tmp/snortrules/rules/*.rules"); + foreach ($files as $file) { + $newfile = basename($file); + @copy($file, "{$snortdir}/rules/snort_{$newfile}"); } - - if (!empty($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_off'])) { - $enabled_sid_off = trim($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_off']); - $enabled_sid_off_array = split('\|\|', $enabled_sid_off); - foreach($enabled_sid_off_array as $enabled_item_off) - $selected_sid_off_sections .= "$enabled_item_off\n"; + /* IP lists */ + $files = glob("{$snortdir}/tmp/snortrules/rules/*.txt"); + foreach ($files as $file) { + $newfile = basename($file); + @copy($file, "{$snortdir}/rules/{$newfile}"); } + exec("rm -r {$snortdir}/tmp/snortrules"); + + /* extract so rules */ + exec('/bin/mkdir -p /usr/local/lib/snort/dynamicrules/'); + $snort_arch = php_uname("m"); + $nosorules = false; + if ($snort_arch == 'i386'){ + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir}/tmp so_rules/precompiled/$freebsd_version_so/i386/{$snort_version}/"); + exec("/bin/cp {$snortdir}/tmp/so_rules/precompiled/$freebsd_version_so/i386/{$snort_version}/* /usr/local/lib/snort/dynamicrules/"); + } else if ($snort_arch == 'amd64') { + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir}/tmp so_rules/precompiled/$freebsd_version_so/x86-64/{$snort_version}/"); + exec("/bin/cp {$snortdir}/tmp/so_rules/precompiled/$freebsd_version_so/x86-64/{$snort_version}/* /usr/local/lib/snort/dynamicrules/"); + } else + $nosorules = true; + exec("rm -r {$snortdir}/tmp/so_rules"); - if (!empty($selected_sid_off_sections) || !empty($selected_sid_on_section)) { - $snort_sid_text = <<<EOD - -########################################### -# # -# this is auto generated on snort updates # -# # -########################################### - -path = /bin:/usr/bin:/usr/local/bin - -update_files = \.rules$|\.config$|\.conf$|\.txt$|\.map$ + if ($nosorules == false) { + /* extract so rules none bin and rename */ + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir}/tmp so_rules/"); + $files = glob("{$snortdir}/tmp/so_rules/*.rules"); + foreach ($files as $file) { + $newfile = basename($file, ".rules"); + @copy($file, "{$snortdir}/rules/snort_{$newfile}.so.rules"); + } + exec("rm -r {$snortdir}/tmp/so_rules"); -url = dir:///usr/local/etc/snort/rules + /* extract base etc files */ + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir}/tmp etc/"); + foreach (array("classification.config", "reference.config", "gen-msg.map", "sid-msg.map", "unicode.map") as $file) { + if (file_exists("{$snortdir}/tmp/etc/{$file}")) + @copy("{$snortdir}/tmp/etc/{$file}", "{$snortdir}/{$file}"); + } + exec("rm -r {$snortdir}/tmp/etc"); + + /* Untar snort signatures */ + $signature_info_chk = $config['installedpackages']['snortglobal']['signatureinfo']; + if ($premium_url_chk == 'on') { + update_status(gettext("Extracting Signatures...")); + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} doc/signatures/"); + update_status(gettext("Done extracting Signatures.")); + + if (is_dir("{$snortdir}/doc/signatures")) { + update_status(gettext("Copying signatures...")); + exec("/bin/cp -r {$snortdir}/doc/signatures {$snortdir}/signatures"); + update_status(gettext("Done copying signatures.")); + } + } -$selected_sid_on_sections + foreach (glob("/usr/local/lib/snort/dynamicrules/*example*") as $file) + @unlink($file); -$selected_sid_off_sections + exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} preproc_rules/"); -EOD; + /* make shure default rules are in the right format */ + exec("/usr/bin/sed -I '' -f {$snortdir}/tmp/sedcmd {$snortdir}/rules/snort_*.rules"); - /* open snort's oinkmaster.conf for writing */ - @file_put_contents("/usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/oinkmaster_{$iface_uuid}_{$if_real}.conf", $snort_sid_text); + if (file_exists("{$tmpfname}/{$snort_filename_md5}")) { + update_status(gettext("Copying md5 sig to snort directory...")); + @copy("{$tmpfname}/$snort_filename_md5", "{$snortdir}/$snort_filename_md5"); + } } } } -/* Run oinkmaster to snort_wan and cp configs */ -/* If oinkmaster is not needed cp rules normally */ -/* TODO add per interface settings here */ -function oinkmaster_run($id, $if_real, $iface_uuid) -{ - global $config, $g, $snortdir_wan, $snortdir, $snort_md5_check_ok, $emerg_md5_check_ok, $pfsense_md5_check_ok; - - if ($snort_md5_check_ok != 'on' || $emerg_md5_check_ok != 'on' || $pfsense_md5_check_ok != 'on') { - if (empty($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_on']) && empty($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_off'])) { - update_status(gettext("Your first set of rules are being copied...")); - update_output_window(gettext("May take a while...")); - exec("/bin/cp {$snortdir}/rules/* {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}/rules/"); - exec("/bin/cp {$snortdir}/classification.config {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/gen-msg.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/generators {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/reference.config {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/sid {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/sid-msg.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/unicode.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - } else { - update_status(gettext("Your enable and disable changes are being applied to your fresh set of rules...")); - update_output_window(gettext("May take a while...")); - exec("/bin/cp {$snortdir}/rules/* {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}/rules/"); - exec("/bin/cp {$snortdir}/classification.config {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/gen-msg.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/generators {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/reference.config {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/sid {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/sid-msg.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/unicode.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - - /* might have to add a sleep for 3sec for flash drives or old drives */ - exec("/usr/local/bin/perl /usr/local/bin/oinkmaster.pl -C /usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/oinkmaster_{$iface_uuid}_{$if_real}.conf -o /usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules > /usr/local/etc/snort/oinkmaster_{$iface_uuid}_{$if_real}.log"); - +/* remove old $tmpfname files */ +if (is_dir("{$snortdir}/tmp")) { + update_status(gettext("Cleaning up...")); + exec("/bin/rm -r {$snortdir}/tmp"); +} + +function snort_apply_customizations($snortcfg, $if_real) { + global $config, $g, $snortdir; + + if (empty($snortcfg['rulesets'])) + return; + else { + update_status(gettext("Your set of configured rules are being copied...")); + log_error("Your set of configured rules are being copied..."); + $enabled_rulesets_array = explode("||", $snortcfg['rulesets']); + foreach($enabled_rulesets_array as $enabled_item) { + @copy("{$snortdir}/rules/{$enabled_item}", "{$snortdir}/snort_{$snortcfg['uuid']}_{$if_real}/rules/{$enabled_item}"); + if (substr($enabled_item, 0, 5) == "snort" && substr($enabled_item, -9) == ".so.rules") { + $slib = substr($enabled_item, 6, -6); + if (file_exists("/usr/local/lib/snort/dynamicrules/{$slib}")) + @copy("/usr/local/lib/snort/dynamicrules/{$slib}", "{$snortdir}/snort_{$snortcfg['uuid']}_{$if_real}/dynamicrules/{$slib}"); + + } } + + @copy("{$snortdir}/classification.config", "{$snortdir}/snort_{$snortcfg['uuid']}_{$if_real}/classification.config"); + @copy("{$snortdir}/gen-msg.map", "{$snortdir}/snort_{$snortcfg['uuid']}_{$if_real}/gen-msg.map"); + if (is_dir("{$snortdir}/generators")) + exec("/bin/cp -r {$snortdir}/generators {$snortdir}/snort_{$snortcfg['uuid']}_{$if_real}"); + @copy("{$snortdir}/reference.config", "{$snortdir}/snort_{$snortcfg['uuid']}_{$if_real}/reference.config"); + @copy("{$snortdir}/sid", "{$snortdir}/snort_{$snortcfg['uuid']}_{$if_real}/sid"); + @copy("{$snortdir}/sid-msg.map", "{$snortdir}/snort_{$snortcfg['uuid']}_{$if_real}/sid-msg.map"); + @copy("{$snortdir}/unicode.map", "{$snortdir}/snort_{$snortcfg['uuid']}_{$if_real}/unicode.map"); } -} -/* Start the proccess for every interface rule */ -/* TODO: try to make the code smother */ -if (is_array($config['installedpackages']['snortglobal']['rule'])) -{ - foreach ($config['installedpackages']['snortglobal']['rule'] as $id => $value) { - $result_lan = $value['interface']; - $if_real = snort_get_real_interface($result_lan); - $iface_uuid = $value['uuid']; + if (!empty($snortcfg['rule_sid_on']) || !empty($snortcfg['rule_sid_off'])) { + if (!empty($snortcfg['rule_sid_on'])) { + $enabled_sid_on_array = explode("||", trim($snortcfg['rule_sid_on'])); + $enabled_sids = array_flip($enabled_sid_on_array); + } - /* make oinkmaster.conf for each interface rule */ - oinkmaster_conf($id, $if_real, $iface_uuid); + if (!empty($snortcfg['rule_sid_off'])) { + $enabled_sid_off_array = explode("||", trim($snortcfg['rule_sid_off'])); + $disabled_sids = array_flip($enabled_sid_off_array); + } - /* run oinkmaster for each interface rule */ - oinkmaster_run($id, $if_real, $iface_uuid); + $files = glob("{$snortdir}/snort_{$snortcfg}_{$if_real}/rules/*.rules"); + foreach ($files as $file) { + $splitcontents = file($file); + $changed = false; + foreach ( $splitcontents as $counter => $value ) { + $sid = snort_get_rule_part($value, 'sid:', ';', 0); + if (!is_numeric($sid)) + continue; + if (isset($enabled_sids["enablesid {$sid}"])) { + if (substr($value, 0, 5) == "alert") + /* Rule is already enabled */ + continue; + if (substr($value, 0, 7) == "# alert") { + /* Rule is disabled, change */ + $splitcontents[$counter] = substr($value, 2); + $changed = true; + } else if (substr($splitcontents[$counter - 1], 0, 5) == "alert") { + /* Rule is already enabled */ + continue; + } else if (substr($splitcontents[$counter - 1], 0, 7) == "# alert") { + /* Rule is disabled, change */ + $splitcontents[$counter - 1] = substr($value, 2); + $changed = true; + } + } else if (isset($disabled_sids["disablesid {$sid}"])) { + if (substr($value, 0, 7) == "# alert") + /* Rule is already disabled */ + continue; + if (substr($value, 0, 5) == "alert") { + /* Rule is enabled, change */ + $splitcontents[$counter] = "# {$value}"; + $changed = true; + } else if (substr($splitcontents[$counter - 1], 0, 7) == "# alert") { + /* Rule is already disabled */ + continue; + } else if (substr($splitcontents[$counter - 1], 0, 5) == "alert") { + /* Rule is enabled, change */ + $splitcontents[$counter - 1] = "# {$value}"; + $changed = true; + } + + } + } + if ($changed == true) + @file_put_contents($file, implode("\n", $splitcontents)); + } } } -////////////// +if ($snortdownload == 'on' || $emergingthreats == 'on') { + /* You are Not Up to date, always stop snort when updating rules for low end machines */; -/* mark the time update finnished */ -$config['installedpackages']['snortglobal']['last_rules_install'] = date("Y-M-jS-h:i-A"); + /* Start the proccess for every interface rule */ + if (is_array($config['installedpackages']['snortglobal']['rule'])) { + foreach ($config['installedpackages']['snortglobal']['rule'] as $id => $value) { + $if_real = snort_get_real_interface($value['interface']); -/* remove old $tmpfname files */ -if (is_dir('/usr/local/etc/snort/tmp')) { - update_status(gettext("Cleaning up...")); - exec("/bin/rm -r /usr/local/etc/snort/tmp/snort_rules_up"); - sleep(2); - exec("/bin/rm -r /usr/local/etc/snort/tmp/rules_bk"); -} + /* make oinkmaster.conf for each interface rule */ + snort_apply_customizations($value, $if_real); + } + } -/* XXX: These are needed if snort is run as snort user -mwexec("/usr/sbin/chown -R snort:snort /var/log/snort", true); -mwexec("/usr/sbin/chown -R snort:snort /usr/local/etc/snort", true); -mwexec("/usr/sbin/chown -R snort:snort /usr/local/lib/snort", true); -*/ -/* make all dirs snorts */ -mwexec("/bin/chmod -R 755 /var/log/snort", true); -mwexec("/bin/chmod -R 755 /usr/local/etc/snort", true); -mwexec("/bin/chmod -R 755 /usr/local/lib/snort", true); - -if ($snortdownload == 'off' && $emergingthreats == 'off' && $pfsensedownload == 'off') - update_output_window(gettext("Finished...")); -else if ($snort_md5_check_ok == 'on' && $emerg_md5_check_ok == 'on' && $pfsense_md5_check_ok == 'on') - update_output_window(gettext("Finished...")); -else { - /* You are Not Up to date, always stop snort when updating rules for low end machines */; - update_status(gettext("You are NOT up to date...")); - exec("/bin/sh /usr/local/etc/rc.d/snort.sh start"); - update_status(gettext("The Rules update finished...")); - update_output_window(gettext("Snort has restarted with your new set of rules...")); - exec("/bin/rm /tmp/snort_download_halt.pid"); + if (is_process_running("snort")) { + exec("/bin/sh /usr/local/etc/rc.d/snort.sh restart"); + update_output_window(gettext("Snort has restarted with your new set of rules...")); + log_error("Snort has restarted with your new set of rules..."); + } else + log_error("Snort Rules update finished..."); } update_status(gettext("The Rules update finished...")); diff --git a/config/snort/snort_define_servers.php b/config/snort/snort_define_servers.php index 497f0a79..20917d00 100644 --- a/config/snort/snort_define_servers.php +++ b/config/snort/snort_define_servers.php @@ -1,46 +1,36 @@ <?php -/* $Id$ */ /* - snort_define_servers.php - part of m0n0wall (http://m0n0.ch/wall) - - Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. - Copyright (C) 2008-2009 Robert Zelaya. - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. + * snort_define_servers.php + * part of pfSense + * + * Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + * Copyright (C) 2008-2009 Robert Zelaya. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. */ -/* - -TODO: Nov 12 09 -Clean this code up its ugly -Important add error checking - -*/ - //require_once("globals.inc"); require_once("guiconfig.inc"); -require_once("/usr/local/pkg/snort/snort_gui.inc"); require_once("/usr/local/pkg/snort/snort.inc"); global $g; @@ -58,47 +48,41 @@ if (!is_array($config['installedpackages']['snortglobal']['rule'])) { } $a_nat = &$config['installedpackages']['snortglobal']['rule']; -$pconfig = array(); -if (isset($id) && $a_nat[$id]) { - $pconfig = $a_nat[$id]; - - /* old options */ - $pconfig['def_dns_servers'] = $a_nat[$id]['def_dns_servers']; - $pconfig['def_dns_ports'] = $a_nat[$id]['def_dns_ports']; - $pconfig['def_smtp_servers'] = $a_nat[$id]['def_smtp_servers']; - $pconfig['def_smtp_ports'] = $a_nat[$id]['def_smtp_ports']; - $pconfig['def_mail_ports'] = $a_nat[$id]['def_mail_ports']; - $pconfig['def_http_servers'] = $a_nat[$id]['def_http_servers']; - $pconfig['def_www_servers'] = $a_nat[$id]['def_www_servers']; - $pconfig['def_http_ports'] = $a_nat[$id]['def_http_ports']; - $pconfig['def_sql_servers'] = $a_nat[$id]['def_sql_servers']; - $pconfig['def_oracle_ports'] = $a_nat[$id]['def_oracle_ports']; - $pconfig['def_mssql_ports'] = $a_nat[$id]['def_mssql_ports']; - $pconfig['def_telnet_servers'] = $a_nat[$id]['def_telnet_servers']; - $pconfig['def_telnet_ports'] = $a_nat[$id]['def_telnet_ports']; - $pconfig['def_snmp_servers'] = $a_nat[$id]['def_snmp_servers']; - $pconfig['def_snmp_ports'] = $a_nat[$id]['def_snmp_ports']; - $pconfig['def_ftp_servers'] = $a_nat[$id]['def_ftp_servers']; - $pconfig['def_ftp_ports'] = $a_nat[$id]['def_ftp_ports']; - $pconfig['def_ssh_servers'] = $a_nat[$id]['def_ssh_servers']; - $pconfig['def_ssh_ports'] = $a_nat[$id]['def_ssh_ports']; - $pconfig['def_pop_servers'] = $a_nat[$id]['def_pop_servers']; - $pconfig['def_pop2_ports'] = $a_nat[$id]['def_pop2_ports']; - $pconfig['def_pop3_ports'] = $a_nat[$id]['def_pop3_ports']; - $pconfig['def_imap_servers'] = $a_nat[$id]['def_imap_servers']; - $pconfig['def_imap_ports'] = $a_nat[$id]['def_imap_ports']; - $pconfig['def_sip_proxy_ip'] = $a_nat[$id]['def_sip_proxy_ip']; - $pconfig['def_sip_servers'] = $a_nat[$id]['def_sip_servers']; - $pconfig['def_sip_ports'] = $a_nat[$id]['def_sip_ports']; - $pconfig['def_sip_proxy_ports'] = $a_nat[$id]['def_sip_proxy_ports']; - $pconfig['def_auth_ports'] = $a_nat[$id]['def_auth_ports']; - $pconfig['def_finger_ports'] = $a_nat[$id]['def_finger_ports']; - $pconfig['def_irc_ports'] = $a_nat[$id]['def_irc_ports']; - $pconfig['def_nntp_ports'] = $a_nat[$id]['def_nntp_ports']; - $pconfig['def_rlogin_ports'] = $a_nat[$id]['def_rlogin_ports']; - $pconfig['def_rsh_ports'] = $a_nat[$id]['def_rsh_ports']; - $pconfig['def_ssl_ports'] = $a_nat[$id]['def_ssl_ports']; -} +/* NOTE: KEEP IN SYNC WITH SNORT.INC since global do not work quite well with package */ +/* define servers and ports snortdefservers */ +$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", +"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" +); + +/* 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"; +$snort_ports = array( +"dns_ports" => "53", "smtp_ports" => "25", "mail_ports" => "25,143,465,691", +"http_ports" => "80", "oracle_ports" => "1521", "mssql_ports" => "1433", +"telnet_ports" => "23","snmp_ports" => "161", "ftp_ports" => "21", +"ssh_ports" => $ssh_port, "pop2_ports" => "109", "pop3_ports" => "110", +"imap_ports" => "143", "sip_proxy_ports" => "5060:5090,16384:32768", +"sip_ports" => "5060:5090,16384:32768", "auth_ports" => "113", "finger_ports" => "79", +"irc_ports" => "6665,6666,6667,6668,6669,7000", "smb_ports" => "139,445", +"nntp_ports" => "119", "rlogin_ports" => "513", "rsh_ports" => "514", +"ssl_ports" => "443,465,563,636,989,990,992,993,994,995", +"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" +); + +$pconfig = $a_nat[$id]; /* convert fake interfaces to real */ $if_real = snort_get_real_interface($pconfig['interface']); @@ -112,55 +96,32 @@ if ($_POST) { $natent = array(); $natent = $pconfig; + foreach ($snort_servers as $key => $server) { + if ($_POST["def_{$key}"] && !is_alias($_POST["def_{$key}"])) + $input_errors[] = "Only aliases are allowed"; + } + foreach ($snort_ports as $key => $server) { + if ($_POST["def_{$key}"] && !is_alias($_POST["def_{$key}"])) + $input_errors[] = "Only aliases are allowed"; + } /* if no errors write to conf */ if (!$input_errors) { /* post new options */ - if ($_POST['def_dns_servers'] != "") { $natent['def_dns_servers'] = $_POST['def_dns_servers']; }else{ $natent['def_dns_servers'] = ""; } - if ($_POST['def_dns_ports'] != "") { $natent['def_dns_ports'] = $_POST['def_dns_ports']; }else{ $natent['def_dns_ports'] = ""; } - if ($_POST['def_smtp_servers'] != "") { $natent['def_smtp_servers'] = $_POST['def_smtp_servers']; }else{ $natent['def_smtp_servers'] = ""; } - if ($_POST['def_smtp_ports'] != "") { $natent['def_smtp_ports'] = $_POST['def_smtp_ports']; }else{ $natent['def_smtp_ports'] = ""; } - if ($_POST['def_mail_ports'] != "") { $natent['def_mail_ports'] = $_POST['def_mail_ports']; }else{ $natent['def_mail_ports'] = ""; } - if ($_POST['def_http_servers'] != "") { $natent['def_http_servers'] = $_POST['def_http_servers']; }else{ $natent['def_http_servers'] = ""; } - if ($_POST['def_www_servers'] != "") { $natent['def_www_servers'] = $_POST['def_www_servers']; }else{ $natent['def_www_servers'] = ""; } - if ($_POST['def_http_ports'] != "") { $natent['def_http_ports'] = $_POST['def_http_ports']; }else{ $natent['def_http_ports'] = ""; } - if ($_POST['def_sql_servers'] != "") { $natent['def_sql_servers'] = $_POST['def_sql_servers']; }else{ $natent['def_sql_servers'] = ""; } - if ($_POST['def_oracle_ports'] != "") { $natent['def_oracle_ports'] = $_POST['def_oracle_ports']; }else{ $natent['def_oracle_ports'] = ""; } - if ($_POST['def_mssql_ports'] != "") { $natent['def_mssql_ports'] = $_POST['def_mssql_ports']; }else{ $natent['def_mssql_ports'] = ""; } - if ($_POST['def_telnet_servers'] != "") { $natent['def_telnet_servers'] = $_POST['def_telnet_servers']; }else{ $natent['def_telnet_servers'] = ""; } - if ($_POST['def_telnet_ports'] != "") { $natent['def_telnet_ports'] = $_POST['def_telnet_ports']; }else{ $natent['def_telnet_ports'] = ""; } - if ($_POST['def_snmp_servers'] != "") { $natent['def_snmp_servers'] = $_POST['def_snmp_servers']; }else{ $natent['def_snmp_servers'] = ""; } - if ($_POST['def_snmp_ports'] != "") { $natent['def_snmp_ports'] = $_POST['def_snmp_ports']; }else{ $natent['def_snmp_ports'] = ""; } - if ($_POST['def_ftp_servers'] != "") { $natent['def_ftp_servers'] = $_POST['def_ftp_servers']; }else{ $natent['def_ftp_servers'] = ""; } - if ($_POST['def_ftp_ports'] != "") { $natent['def_ftp_ports'] = $_POST['def_ftp_ports']; }else{ $natent['def_ftp_ports'] = ""; } - if ($_POST['def_ssh_servers'] != "") { $natent['def_ssh_servers'] = $_POST['def_ssh_servers']; }else{ $natent['def_ssh_servers'] = ""; } - if ($_POST['def_ssh_ports'] != "") { $natent['def_ssh_ports'] = $_POST['def_ssh_ports']; }else{ $natent['def_ssh_ports'] = ""; } - if ($_POST['def_pop_servers'] != "") { $natent['def_pop_servers'] = $_POST['def_pop_servers']; }else{ $natent['def_pop_servers'] = ""; } - if ($_POST['def_pop2_ports'] != "") { $natent['def_pop2_ports'] = $_POST['def_pop2_ports']; }else{ $natent['def_pop2_ports'] = ""; } - if ($_POST['def_pop3_ports'] != "") { $natent['def_pop3_ports'] = $_POST['def_pop3_ports']; }else{ $natent['def_pop3_ports'] = ""; } - if ($_POST['def_imap_servers'] != "") { $natent['def_imap_servers'] = $_POST['def_imap_servers']; }else{ $natent['def_imap_servers'] = ""; } - if ($_POST['def_imap_ports'] != "") { $natent['def_imap_ports'] = $_POST['def_imap_ports']; }else{ $natent['def_imap_ports'] = ""; } - if ($_POST['def_sip_proxy_ip'] != "") { $natent['def_sip_proxy_ip'] = $_POST['def_sip_proxy_ip']; }else{ $natent['def_sip_proxy_ip'] = ""; } - if ($_POST['def_sip_proxy_ports'] != "") { $natent['def_sip_proxy_ports'] = $_POST['def_sip_proxy_ports']; }else{ $natent['def_sip_proxy_ports'] = ""; } - if ($_POST['def_sip_servers'] != "") { $natent['def_sip_servers'] = $_POST['def_sip_servers']; }else{ $natent['def_sip_servers'] = ""; } - if ($_POST['def_sip_ports'] != "") { $natent['def_sip_ports'] = $_POST['def_sip_ports']; }else{ $natent['def_sip_ports'] = ""; } - if ($_POST['def_auth_ports'] != "") { $natent['def_auth_ports'] = $_POST['def_auth_ports']; }else{ $natent['def_auth_ports'] = ""; } - if ($_POST['def_finger_ports'] != "") { $natent['def_finger_ports'] = $_POST['def_finger_ports']; }else{ $natent['def_finger_ports'] = ""; } - if ($_POST['def_irc_ports'] != "") { $natent['def_irc_ports'] = $_POST['def_irc_ports']; }else{ $natent['def_irc_ports'] = ""; } - if ($_POST['def_nntp_ports'] != "") { $natent['def_nntp_ports'] = $_POST['def_nntp_ports']; }else{ $natent['def_nntp_ports'] = ""; } - if ($_POST['def_rlogin_ports'] != "") { $natent['def_rlogin_ports'] = $_POST['def_rlogin_ports']; }else{ $natent['def_rlogin_ports'] = ""; } - if ($_POST['def_rsh_ports'] != "") { $natent['def_rsh_ports'] = $_POST['def_rsh_ports']; }else{ $natent['def_rsh_ports'] = ""; } - if ($_POST['def_ssl_ports'] != "") { $natent['def_ssl_ports'] = $_POST['def_ssl_ports']; }else{ $natent['def_ssl_ports'] = ""; } - - - if (isset($id) && $a_nat[$id]) - $a_nat[$id] = $natent; - else { - if (is_numeric($after)) - array_splice($a_nat, $after+1, 0, array($natent)); + foreach ($snort_servers as $key => $server) { + if ($_POST["def_{$key}"]) + $natent["def_{$key}"] = $_POST["def_{$key}"]; else - $a_nat[] = $natent; + unset($natent["def_{$key}"]); + } + foreach ($snort_ports as $key => $server) { + if ($_POST["def_{$key}"]) + $natent["def_{$key}"] = $_POST["def_{$key}"]; + else + unset($natent["def_{$key}"]); } + $a_nat[$id] = $natent; + write_config(); sync_snort_package_config(); @@ -176,366 +137,138 @@ if ($_POST) { } } -$pgtitle = "Snort: Interface $id$if_real Define Servers"; +$if_friendly = snort_get_friendly_interface($pconfig['interface']); +$pgtitle = "Snort: Interface {$if_friendly} Define Servers"; include_once("head.inc"); ?> -<body - link="#0000CC" vlink="#0000CC" alink="#0000CC"> +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> <?php include("fbegin.inc"); if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';} - -echo "{$snort_general_css}\n"; +/* Display Alert message */ +if ($input_errors) + print_input_errors($input_errors); // TODO: add checks +if ($savemsg) + print_info_box($savemsg); ?> -<form action="snort_define_servers.php" method="post" - enctype="multipart/form-data" name="iform" id="iform"><?php - - /* Display Alert message */ - - if ($input_errors) { - print_input_errors($input_errors); // TODO: add checks - } - - if ($savemsg) { - print_info_box2($savemsg); - } - - ?> - +<script type="text/javascript" src="/javascript/autosuggest.js"> +</script> +<script type="text/javascript" src="/javascript/suggestions.js"> +</script> +<form action="snort_define_servers.php" method="post" name="iform" id="iform"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr><td> <?php $tab_array = array(); - $tabid = 0; - $tab_array[$tabid] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); - $tabid++; - $tab_array[$tabid] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Servers"), true, "/snort/snort_define_servers.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); + $tab_array[] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); + $tab_array[] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); + $tab_array[] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); + $tab_array[] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); + $tab_array[] = array(gettext("Variables"), true, "/snort/snort_define_servers.php?id={$id}"); + $tab_array[] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); + $tab_array[] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); display_top_tabs($tab_array); ?> </td></tr> <tr> <td class="tabcont"> <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Define Servers"); ?></td> + </tr> +<?php + foreach ($snort_servers as $key => $server): + if (strlen($server) > 40) + $server = substr($server, 0, 40) . "..."; + $label = strtoupper($key); + $value = ""; + if (!empty($pconfig["def_{$key}"])) + $value = htmlspecialchars($pconfig["def_{$key}"]); +?> <tr> - <td width="22%" valign="top"> </td> - <td width="78%"><span class="vexpl"><span class="red"><strong>Note:</strong></span><br> - Please save your settings before you click start.<br> - Please make sure there are <strong>no spaces</strong> in your - definitions. </td> - </tr> - <tr> - <td colspan="2" valign="top" class="listtopic">Define Servers</td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define DNS_SERVERS</td> - <td width="78%" class="vtable"><input name="def_dns_servers" - type="text" class="formfld" id="def_dns_servers" size="40" - value="<?=htmlspecialchars($pconfig['def_dns_servers']);?>"> <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave - blank to scan all networks.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define DNS_PORTS</td> - <td width="78%" class="vtable"><input name="def_dns_ports" - type="text" class="formfld" id="def_dns_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_dns_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is 53.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define SMTP_SERVERS</td> - <td width="78%" class="vtable"><input name="def_smtp_servers" - type="text" class="formfld" id="def_smtp_servers" size="40" - value="<?=htmlspecialchars($pconfig['def_smtp_servers']);?>"> <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave - blank to scan all networks.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define SMTP_PORTS</td> - <td width="78%" class="vtable"><input name="def_smtp_ports" - type="text" class="formfld" id="def_smtp_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_smtp_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is 25.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define Mail_Ports</td> - <td width="78%" class="vtable"><input name="def_mail_ports" - type="text" class="formfld" id="def_mail_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_mail_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is 25,143,465,691.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define HTTP_SERVERS</td> - <td width="78%" class="vtable"><input name="def_http_servers" - type="text" class="formfld" id="def_http_servers" size="40" - value="<?=htmlspecialchars($pconfig['def_http_servers']);?>"> <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave - blank to scan all networks.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define WWW_SERVERS</td> - <td width="78%" class="vtable"><input name="def_www_servers" - type="text" class="formfld" id="def_www_servers" size="40" - value="<?=htmlspecialchars($pconfig['def_www_servers']);?>"> <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave - blank to scan all networks.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define HTTP_PORTS</td> - <td width="78%" class="vtable"><input name="def_http_ports" - type="text" class="formfld" id="def_http_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_http_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is 80.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define SQL_SERVERS</td> - <td width="78%" class="vtable"><input name="def_sql_servers" - type="text" class="formfld" id="def_sql_servers" size="40" - value="<?=htmlspecialchars($pconfig['def_sql_servers']);?>"> <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave - blank to scan all networks.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define ORACLE_PORTS</td> - <td width="78%" class="vtable"><input name="def_oracle_ports" - type="text" class="formfld" id="def_oracle_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_oracle_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is 1521.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define MSSQL_PORTS</td> - <td width="78%" class="vtable"><input name="def_mssql_ports" - type="text" class="formfld" id="def_mssql_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_mssql_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is 1433.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define TELNET_SERVERS</td> - <td width="78%" class="vtable"><input name="def_telnet_servers" - type="text" class="formfld" id="def_telnet_servers" size="40" - value="<?=htmlspecialchars($pconfig['def_telnet_servers']);?>"> <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave - blank to scan all networks.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define TELNET_PORTS</td> - <td width="78%" class="vtable"><input name="def_telnet_ports" - type="text" class="formfld" id="def_telnet_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_telnet_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is 23.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define SNMP_SERVERS</td> - <td width="78%" class="vtable"><input name="def_snmp_servers" - type="text" class="formfld" id="def_snmp_servers" size="40" - value="<?=htmlspecialchars($pconfig['def_snmp_servers']);?>"> <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave - blank to scan all networks.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define SNMP_PORTS</td> - <td width="78%" class="vtable"><input name="def_snmp_ports" - type="text" class="formfld" id="def_snmp_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_snmp_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is 161.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define FTP_SERVERS</td> - <td width="78%" class="vtable"><input name="def_ftp_servers" - type="text" class="formfld" id="def_ftp_servers" size="40" - value="<?=htmlspecialchars($pconfig['def_ftp_servers']);?>"> <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave - blank to scan all networks.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define FTP_PORTS</td> - <td width="78%" class="vtable"><input name="def_ftp_ports" - type="text" class="formfld" id="def_ftp_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_ftp_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is 21.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define SSH_SERVERS</td> - <td width="78%" class="vtable"><input name="def_ssh_servers" - type="text" class="formfld" id="def_ssh_servers" size="40" - value="<?=htmlspecialchars($pconfig['def_ssh_servers']);?>"> <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave - blank to scan all networks.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define SSH_PORTS</td> - <td width="78%" class="vtable"><input name="def_ssh_ports" - type="text" class="formfld" id="def_ssh_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_ssh_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is the firewall's SSH port.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define POP_SERVERS</td> - <td width="78%" class="vtable"><input name="def_pop_servers" - type="text" class="formfld" id="def_pop_servers" size="40" - value="<?=htmlspecialchars($pconfig['def_pop_servers']);?>"> <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave - blank to scan all networks.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define POP2_PORTS</td> - <td width="78%" class="vtable"><input name="def_pop2_ports" - type="text" class="formfld" id="def_pop2_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_pop2_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is 109.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define POP3_PORTS</td> - <td width="78%" class="vtable"><input name="def_pop3_ports" - type="text" class="formfld" id="def_pop3_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_pop3_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is 110.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define IMAP_SERVERS</td> - <td width="78%" class="vtable"><input name="def_imap_servers" - type="text" class="formfld" id="def_imap_servers" size="40" - value="<?=htmlspecialchars($pconfig['def_imap_servers']);?>"> <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave - blank to scan all networks.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define IMAP_PORTS</td> - <td width="78%" class="vtable"><input name="def_imap_ports" - type="text" class="formfld" id="def_imap_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_imap_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is 143.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define SIP_PROXY_IP</td> - <td width="78%" class="vtable"><input name="def_sip_proxy_ip" - type="text" class="formfld" id="def_sip_proxy_ip" size="40" - value="<?=htmlspecialchars($pconfig['def_sip_proxy_ip']);?>"> <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave - blank to scan all networks.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define SIP_PROXY_PORTS</td> - <td width="78%" class="vtable"><input name="def_sip_proxy_ports" - type="text" class="formfld" id="def_sip_proxy_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_sip_proxy_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is 5060:5090,16384:32768.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define SIP_SERVERS</td> - <td width="78%" class="vtable"><input name="def_sip_servers" - type="text" class="formfld" id="def_sip_servers" size="40" - value="<?=htmlspecialchars($pconfig['def_sip_servers']);?>"> <br> - <span class="vexpl">Example: "192.168.1.3/24,192.168.1.4/24". Leave - blank to scan all networks.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define SIP_PORTS</td> - <td width="78%" class="vtable"><input name="def_sip_ports" - type="text" class="formfld" id="def_sip_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_sip_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is 5060:5090,16384:32768.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define AUTH_PORTS</td> - <td width="78%" class="vtable"><input name="def_auth_ports" - type="text" class="formfld" id="def_auth_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_auth_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is 113.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define FINGER_PORTS</td> - <td width="78%" class="vtable"><input name="def_finger_ports" - type="text" class="formfld" id="def_finger_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_finger_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is 79.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define IRC_PORTS</td> - <td width="78%" class="vtable"><input name="def_irc_ports" - type="text" class="formfld" id="def_irc_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_irc_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is 6665,6666,6667,6668,6669,7000.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define NNTP_PORTS</td> - <td width="78%" class="vtable"><input name="def_nntp_ports" - type="text" class="formfld" id="def_nntp_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_nntp_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is 119.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define RLOGIN_PORTS</td> - <td width="78%" class="vtable"><input name="def_rlogin_ports" - type="text" class="formfld" id="def_rlogin_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_rlogin_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is 513.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define RSH_PORTS</td> - <td width="78%" class="vtable"><input name="def_rsh_ports" - type="text" class="formfld" id="def_rsh_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_rsh_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is 514.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Define SSL_PORTS</td> - <td width="78%" class="vtable"><input name="def_ssl_ports" - type="text" class="formfld" id="def_ssl_ports" size="40" - value="<?=htmlspecialchars($pconfig['def_ssl_ports']);?>"> <br> - <span class="vexpl">Example: Specific ports "25,443" or All ports - betwen "5060:5090 . Default is 25,443,465,636,993,995.</span></td> - </tr> - <tr> - <td width="22%" valign="top"> </td> - <td width="78%"> - <input name="Submit" type="submit" class="formbtn" value="Save"> - <input name="id" type="hidden" value="<?=$id;?>"> + <td width='22%' valign='top' class='vncell'><?php echo gettext("Define"); ?> <?=$label;?></td> + <td width="78%" class="vtable"> + <input name="def_<?=$key;?>" size="40" + type="text" autocomplete="off" class="formfldalias" id="def_<?=$key;?>" + value="<?=$value;?>"> <br/> + <span class="vexpl"><?php echo gettext("Default value:"); ?> "<?=$server;?>" <br/><?php echo gettext("Leave " . + "blank for default value."); ?></span> </td> </tr> +<?php endforeach; ?> + <tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Define Ports"); ?></td> + </tr> +<?php + foreach ($snort_ports as $key => $server): + $server = substr($server, 0, 20); + $label = strtoupper($key); + $value = ""; + if (!empty($pconfig["def_{$key}"])) + $value = htmlspecialchars($pconfig["def_{$key}"]); +?> <tr> - <td width="22%" valign="top"> </td> - <td width="78%"><span class="vexpl"><span class="red"><strong>Note:</strong></span> - <br> - Please save your settings before you click start. </td> + <td width='22%' valign='top' class='vncell'><?php echo gettext("Define"); ?> <?=$label;?></td> + <td width="78%" class="vtable"> + <input name="def_<?=$key;?>" type="text" size="40" autocomplete="off" class="formfldalias" id="def_<?=$key;?>" + value="<?=$value;?>"> <br/> + <span class="vexpl"><?php echo gettext("Default value:"); ?> "<?=$server;?>" <br/> <?php echo gettext("Leave " . + "blank for default value."); ?></span> + </td> </tr> - </table> - +<?php endforeach; ?> + <tr> + <td width="22%" valign="top"> </td> + <td width="78%"> + <input name="Submit" type="submit" class="formbtn" value="Save"> + <input name="id" type="hidden" value="<?=$id;?>"> + </td> + </tr> + </table> +</td></tr> </table> </form> +<script type="text/javascript"> +<?php + $isfirst = 0; + $aliases = ""; + $addrisfirst = 0; + $portisfirst = 0; + $aliasesaddr = ""; + $aliasesports = ""; + if(isset($config['aliases']['alias']) && is_array($config['aliases']['alias'])) + foreach($config['aliases']['alias'] as $alias_name) { + if ($alias_name['type'] == "host" || $alias_name['type'] == "network") { + if($addrisfirst == 1) $aliasesaddr .= ","; + $aliasesaddr .= "'" . $alias_name['name'] . "'"; + $addrisfirst = 1; + } else if ($alias_name['type'] == "port") { + if($portisfirst == 1) $aliasesports .= ","; + $aliasesports .= "'" . $alias_name['name'] . "'"; + $portisfirst = 1; + } + } +?> + + var addressarray=new Array(<?php echo $aliasesaddr; ?>); + var portsarray=new Array(<?php echo $aliasesports; ?>); + +function createAutoSuggest() { +<?php + foreach ($snort_servers as $key => $server) + echo "objAlias{$key} = new AutoSuggestControl(document.getElementById('def_{$key}'), new StateSuggestions(addressarray));\n"; + foreach ($snort_ports as $key => $server) + echo "pobjAlias{$key} = new AutoSuggestControl(document.getElementById('def_{$key}'), new StateSuggestions(portsarray));\n"; +?> +} + +setTimeout("createAutoSuggest();", 500); + +</script> + <?php include("fend.inc"); ?> </body> </html> diff --git a/config/snort/snort_download_rules.php b/config/snort/snort_download_rules.php index 1056c337..bbbf689c 100644 --- a/config/snort/snort_download_rules.php +++ b/config/snort/snort_download_rules.php @@ -1,88 +1,41 @@ <?php /* - snort_download_rules.php - Copyright (C) 2006 Scott Ullrich - Copyright (C) 2009 Robert Zelaya - Copyright (C) 2011 Ermal Luci - 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. + * snort_download_rules.php + * + * Copyright (C) 2006 Scott Ullrich + * Copyright (C) 2009 Robert Zelaya + * Copyright (C) 2011-2012 Ermal Luci + * 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. */ -/* Setup enviroment */ - -/* TODO: review if include files are needed */ require_once("guiconfig.inc"); require_once("functions.inc"); require_once("service-utils.inc"); require_once("/usr/local/pkg/snort/snort.inc"); -$tmpfname = "/usr/local/etc/snort/tmp/snort_rules_up"; -$snortdir = "/usr/local/etc/snort"; -$snortdir_wan = "/usr/local/etc/snort"; -$snort_filename_md5 = "snortrules-snapshot-2905.tar.gz.md5"; -$snort_filename = "snortrules-snapshot-2905.tar.gz"; -$emergingthreats_filename_md5 = "emerging.rules.tar.gz.md5"; -$emergingthreats_filename = "emerging.rules.tar.gz"; -$pfsense_rules_filename_md5 = "pfsense_rules.tar.gz.md5"; -$pfsense_rules_filename = "pfsense_rules.tar.gz"; - -$id = $_GET['id']; -if (isset($_POST['id'])) - $id = $_POST['id']; - -/* Time stamps define */ -$last_md5_download = $config['installedpackages']['snortglobal']['last_md5_download']; -$last_rules_install = $config['installedpackages']['snortglobal']['last_rules_install']; - -/* define checks */ -$oinkid = $config['installedpackages']['snortglobal']['oinkmastercode']; -$snortdownload = $config['installedpackages']['snortglobal']['snortdownload']; -$emergingthreats = $config['installedpackages']['snortglobal']['emergingthreats']; - -if ($snortdownload == 'off' && $emergingthreats != 'on') -{ - $snort_emrging_info = 'stop'; -} - -if ($oinkid == "" && $snortdownload != 'off') -{ - $snort_oinkid_info = 'stop'; -} - - -/* check if main rule directory is empty */ -$if_mrule_dir = "/usr/local/etc/snort/rules"; -$mfolder_chk = (count(glob("$if_mrule_dir/*")) === 0) ? 'empty' : 'full'; - - -if (file_exists('/var/run/snort.conf.dirty')) { - $snort_dirty_d = 'stop'; -} - $pgtitle = "Services: Snort: Update Rules"; - include("head.inc"); - ?> <body link="#0000CC" vlink="#0000CC" alink="#0000CC"> @@ -90,7 +43,7 @@ include("head.inc"); <?php include("fbegin.inc"); ?> <?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> -<form action="/snort/snort_testing.php" method="post"> +<form action="/snort/snort_download_updates.php" method="GET"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td> @@ -98,668 +51,38 @@ include("head.inc"); <table class="tabcont" width="100%" border="0" cellpadding="6" cellspacing="0"> <tr> <td ><!-- progress bar --> - <table id="progholder" width='320' - style='border-collapse: collapse; border: 1px solid #000000;' - cellpadding='2' cellspacing='2'> - <tr> - <td><img border='0' - src='../themes/<?= $g['theme']; ?>/images/misc/progress_bar.gif' - width='280' height='23' name='progressbar' id='progressbar' - alt='' /> - </td> - </tr> + <table id="progholder" width='320' style='border-collapse: collapse; border: 1px solid #000000;' cellpadding='2' cellspacing='2'> + <tr> + <td> + <img border='0' src='../themes/<?= $g['theme']; ?>/images/misc/progress_bar.gif' + width='280' height='23' name='progressbar' id='progressbar' alt='' /> + </td> + </tr> </table> <br /> - <!-- status box --> <textarea cols="60" rows="2" name="status" id="status" wrap="hard"> - <?=gettext("Initializing...");?> - </textarea> - <!-- command output box --> <textarea cols="60" rows="2" name="output" id="output" wrap="hard"> - </textarea> + <textarea cols="60" rows="2" name="status" id="status" wrap="hard"> + <?=gettext("Initializing...");?> + </textarea> + <textarea cols="60" rows="2" name="output" id="output" wrap="hard"> + </textarea> </td> </tr> </table> </div> </td> </tr> -<tr><td><a href="/snort/snort_download_updates.php"><input type="button" Value="Return"></a></td></tr> + <tr><td><input type="submit" name="return" id="return" Value="Return"></td></tr> </table> </form> - <?php include("fend.inc");?> </body> </html> - <?php -/* Start of code */ -conf_mount_rw(); - -if (!is_dir('/usr/local/etc/snort/tmp')) { - exec('/bin/mkdir -p /usr/local/etc/snort/tmp'); -} - -$snort_md5_check_ok = 'off'; -$emerg_md5_check_ok = 'off'; -$pfsense_md5_check_ok = 'off'; - -/* Set user agent to Mozilla */ -ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)'); -ini_set("memory_limit","150M"); - -/* mark the time update started */ -$config['installedpackages']['snortglobal']['last_md5_download'] = date("Y-M-jS-h:i-A"); - -/* send current buffer */ -ob_flush(); - -/* hide progress bar */ -hide_progress_bar_status(); - -/* send current buffer */ -ob_flush(); - -/* remove old $tmpfname files */ -if (is_dir("{$tmpfname}")) { - update_status(gettext("Removing old tmp files...")); - exec("/bin/rm -r {$tmpfname}"); - apc_clear_cache(); -} - -/* Make shure snortdir exits */ -exec("/bin/mkdir -p {$snortdir}"); -exec("/bin/mkdir -p {$snortdir}/rules"); -exec("/bin/mkdir -p {$snortdir}/signatures"); -exec("/bin/mkdir -p {$tmpfname}"); -exec("/bin/mkdir -p /usr/local/lib/snort/dynamicrules/"); - -/* send current buffer */ -ob_flush(); - -/* unhide progress bar and lets end this party */ -unhide_progress_bar_status(); - -$pfsensedownload = 'on'; - -/* download md5 sig from snort.org */ -if ($snortdownload == 'on') -{ - if (file_exists("{$tmpfname}/{$snort_filename_md5}") && - filesize("{$tmpfname}/{$snort_filename_md5}") > 0) { - update_status(gettext("snort.org md5 temp file exists...")); - } else { - update_status(gettext("Downloading snort.org md5 file...")); - ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)'); - - //$image = @file_get_contents("http://www.mtest.local/pub-bin/oinkmaster.cgi/{$oinkid}/{$snort_filename_md5}"); - $image = @file_get_contents("http://www.snort.org/pub-bin/oinkmaster.cgi/{$oinkid}/{$snort_filename_md5}"); - @file_put_contents("{$tmpfname}/{$snort_filename_md5}", $image); - update_status(gettext("Done downloading snort.org md5")); - } -} - -/* download md5 sig from emergingthreats.net */ -if ($emergingthreats == 'on') -{ - update_status(gettext("Downloading emergingthreats md5 file...")); - ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)'); - // $image = @file_get_contents("http://www.mtest.local/pub-bin/oinkmaster.cgi/{$oinkid}/version.txt"); - $image = @file_get_contents('http://rules.emergingthreats.net/open/snort-2.9.0/emerging.rules.tar.gz.md5'); - @file_put_contents("{$tmpfname}/{$emergingthreats_filename_md5}", $image); - update_status(gettext("Done downloading emergingthreats md5")); -} - -/* download md5 sig from pfsense.org */ -if (file_exists("{$tmpfname}/{$pfsense_rules_filename_md5}")) { - update_status(gettext("pfsense md5 temp file exists...")); -} else { - update_status(gettext("Downloading pfsense md5 file...")); - ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)'); - //$image = @file_get_contents("http://www.mtest.local/pub-bin/oinkmaster.cgi/{$oinkid}/pfsense_rules.tar.gz.md5"); - $image = @file_get_contents("http://www.pfsense.com/packages/config/snort/pfsense_rules/pfsense_rules.tar.gz.md5"); - @file_put_contents("{$tmpfname}/pfsense_rules.tar.gz.md5", $image); - update_status(gettext("Done downloading pfsense md5.")); -} - -/* If md5 file is empty wait 15min exit */ -if ($snortdownload == 'on') -{ - if (0 == filesize("{$tmpfname}/{$snort_filename_md5}")) - { - update_status(gettext("Please wait... You may only check for New Rules every 15 minutes...")); - update_output_window(gettext("Rules are released every month from snort.org. You may download the Rules at any time.")); - hide_progress_bar_status(); - $snortdownload = 'off'; - } -} - -/* If pfsense md5 file is empty wait 15min exit */ -if (0 == filesize("{$tmpfname}/$pfsense_rules_filename_md5")){ - update_status(gettext("Please wait... You may only check for New Pfsense Rules every 15 minutes...")); - update_output_window(gettext("Rules are released to support Pfsense packages.")); - hide_progress_bar_status(); - $pfsensedownload = 'off'; -} - -/* Check if were up to date snort.org */ -if ($snortdownload == 'on') -{ - if (file_exists("{$snortdir}/{$snort_filename_md5}")) - { - $md5_check_new_parse = file_get_contents("{$tmpfname}/{$snort_filename_md5}"); - $md5_check_new = `/bin/echo "{$md5_check_new_parse}" | /usr/bin/awk '{ print $1 }'`; - $md5_check_old_parse = file_get_contents("{$snortdir}/{$snort_filename_md5}"); - $md5_check_old = `/bin/echo "{$md5_check_old_parse}" | /usr/bin/awk '{ print $1 }'`; - if ($md5_check_new == $md5_check_old) - { - update_status(gettext("Your rules are up to date...")); - update_output_window(gettext("You may start Snort now, check update.")); - hide_progress_bar_status(); - $snort_md5_check_ok = 'on'; - } else { - update_status(gettext("Your rules are not up to date...")); - $snort_md5_check_ok = 'off'; - } - } -} - -/* Check if were up to date emergingthreats.net */ -if ($emergingthreats == 'on') -{ - if (file_exists("{$snortdir}/{$emergingthreats_filename_md5}")) - { - $emerg_md5_check_new_parse = file_get_contents("{$tmpfname}/{$emergingthreats_filename_md5}"); - $emerg_md5_check_new = `/bin/echo "{$emerg_md5_check_new_parse}" | /usr/bin/awk '{ print $1 }'`; - $emerg_md5_check_old_parse = file_get_contents("{$snortdir}/{$emergingthreats_filename_md5}"); - $emerg_md5_check_old = `/bin/echo "{$emerg_md5_check_old_parse}" | /usr/bin/awk '{ print $1 }'`; - if ($emerg_md5_check_new == $emerg_md5_check_old) - { - hide_progress_bar_status(); - $emerg_md5_check_ok = 'on'; - } else - $emerg_md5_check_ok = 'off'; - } -} - -/* Check if were up to date pfsense.org */ -if ($pfsensedownload == 'on' && file_exists("{$snortdir}/pfsense_rules.tar.gz.md5")) -{ - $pfsense_check_new_parse = file_get_contents("{$tmpfname}/pfsense_rules.tar.gz.md5"); - $pfsense_md5_check_new = `/bin/echo "{$pfsense_md5_check_new_parse}" | /usr/bin/awk '{ print $1 }'`; - $pfsense_md5_check_old_parse = file_get_contents("{$snortdir}/pfsense_rules.tar.gz.md5"); - $pfsense_md5_check_old = `/bin/echo "{$pfsense_md5_check_old_parse}" | /usr/bin/awk '{ print $1 }'`; - if ($pfsense_md5_check_new == $pfsense_md5_check_old) - { - hide_progress_bar_status(); - $pfsense_md5_check_ok = 'on'; - } else - $pfsense_md5_check_ok = 'off'; -} - -if ($snortdownload == 'on') { - if ($snort_md5_check_ok == 'on') - { - update_status(gettext("Your snort.org rules are up to date...")); - update_output_window(gettext("You may start Snort now...")); - $snortdownload = 'off'; - } -} -if ($emergingthreats == 'on') { - if ($emerg_md5_check_ok == 'on') - { - update_status(gettext("Your Emergingthreats rules are up to date...")); - update_output_window(gettext("You may start Snort now...")); - $emergingthreats = 'off'; - } -} - -/* download snortrules file */ -if ($snortdownload == 'on') -{ - if ($snort_md5_check_ok != 'on') { - if (file_exists("{$tmpfname}/{$snort_filename}")) { - update_status(gettext("Snortrule tar file exists...")); - } else { - unhide_progress_bar_status(); - update_status(gettext("There is a new set of Snort.org rules posted. Downloading...")); - update_output_window(gettext("May take 4 to 10 min...")); - download_file_with_progress_bar("http://www.snort.org/pub-bin/oinkmaster.cgi/{$oinkid}/{$snort_filename}", "{$tmpfname}/{$snort_filename}"); - update_all_status($static_output); - update_status(gettext("Done downloading rules file.")); - if (150000 > filesize("{$tmpfname}/$snort_filename")){ - update_status(gettext("Error with the snort rules download...")); - - update_output_window(gettext("Snort rules file downloaded failed...")); - $snortdownload = 'off'; - } - } - } -} - -/* download emergingthreats rules file */ -if ($emergingthreats == "on") -{ - if ($emerg_md5_check_ok != 'on') - { - if (file_exists("{$tmpfname}/{$emergingthreats_filename}")) - { - update_status(gettext('Emergingthreats tar file exists...')); - }else{ - update_status(gettext("There is a new set of Emergingthreats rules posted. Downloading...")); - update_output_window(gettext("May take 4 to 10 min...")); - download_file_with_progress_bar('http://rules.emergingthreats.net/open/snort-2.9.0/emerging.rules.tar.gz', "{$tmpfname}/{$emergingthreats_filename}"); - update_status(gettext('Done downloading Emergingthreats rules file.')); - } - } -} - -/* download pfsense rules file */ -if ($pfsensedownload == 'on' && $pfsense_md5_check_ok != 'on') { - if (file_exists("{$tmpfname}/{$pfsense_rules_filename}")) { - update_status(gettext("Snortrule tar file exists...")); - } else { - unhide_progress_bar_status(); - update_status(gettext("There is a new set of Pfsense rules posted. Downloading...")); - update_output_window(gettext("May take 4 to 10 min...")); - download_file_with_progress_bar("http://www.pfsense.com/packages/config/snort/pfsense_rules/pfsense_rules.tar.gz", $tmpfname . "/{$pfsense_rules_filename}"); - update_all_status($static_output); - update_status(gettext("Done downloading rules file.")); - } -} - -/* Compair md5 sig to file sig */ - -//$premium_url_chk = $config['installedpackages']['snort']['config'][0]['subscriber']; -//if ($premium_url_chk == on) { -//$md5 = file_get_contents("{$tmpfname}/{$snort_filename_md5}"); -//$file_md5_ondisk = `/sbin/md5 {$tmpfname}/{$snort_filename} | /usr/bin/awk '{ print $4 }'`; -// if ($md5 == $file_md5_ondisk) { -// update_status(gettext("Valid md5 checksum pass...")); -//} else { -// update_status(gettext("The downloaded file does not match the md5 file...P is ON")); -// update_output_window(gettext("Error md5 Mismatch...")); -// return; -// } -//} -//$premium_url_chk = $config['installedpackages']['snort']['config'][0]['subscriber']; -//if ($premium_url_chk != on) { -//$md55 = `/bin/cat {$tmpfname}/{$snort_filename_md5} | /usr/bin/awk '{ print $4 }'`; -//$file_md5_ondisk2 = `/sbin/md5 {$tmpfname}/{$snort_filename} | /usr/bin/awk '{ print $4 }'`; -// if ($md55 == $file_md5_ondisk2) { -// update_status(gettext("Valid md5 checksum pass...")); -//} else { -// update_status(gettext("The downloaded file does not match the md5 file...Not P")); -// update_output_window(gettext("Error md5 Mismatch...")); -// return; -// } -//} - -/* Untar snort rules file individually to help people with low system specs */ -if ($snortdownload == 'on') -{ - if ($snort_md5_check_ok != 'on') { - if (file_exists("{$tmpfname}/{$snort_filename}")) { - - if ($pfsense_stable == 'yes') - { - $freebsd_version_so = 'FreeBSD-7-2'; - }else{ - $freebsd_version_so = 'FreeBSD-8-1'; - } - - update_status(gettext("Extracting Snort.org rules...")); - update_output_window(gettext("May take a while...")); - /* extract snort.org rules and add prefix to all snort.org files*/ - exec("/bin/rm -r {$snortdir}/rules"); - sleep(2); - exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} rules/"); - chdir ("/usr/local/etc/snort/rules"); - sleep(2); - exec('/usr/local/bin/perl /usr/local/bin/snort_rename.pl s/^/snort_/ *.rules'); - - /* extract so rules */ - exec('/bin/mkdir -p /usr/local/lib/snort/dynamicrules/'); - if($snort_arch == 'x86') { - exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} so_rules/precompiled/$freebsd_version_so/i386/2.9.0.5/"); - exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} so_rules/precompiled/$freebsd_version_so/i386/2.9.0.5/"); - exec("/bin/mv -f {$snortdir}/so_rules/precompiled/$freebsd_version_so/i386/2.9.0.5/* /usr/local/lib/snort/dynamicrules/"); - } else if ($snort_arch == 'x64') { - exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} so_rules/precompiled/$freebsd_version_so/x86-64/2.9.0.5/"); - exec("/bin/mv -f {$snortdir}/so_rules/precompiled/$freebsd_version_so/x86-64/2.9.0.5/* /usr/local/lib/snort/dynamicrules/"); - } - /* extract so rules none bin and rename */ - exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} so_rules/bad-traffic.rules/" . - " so_rules/chat.rules/" . - " so_rules/dos.rules/" . - " so_rules/exploit.rules/" . - " so_rules/icmp.rules/" . - " so_rules/imap.rules/" . - " so_rules/misc.rules/" . - " so_rules/multimedia.rules/" . - " so_rules/netbios.rules/" . - " so_rules/nntp.rules/" . - " so_rules/p2p.rules/" . - " so_rules/smtp.rules/" . - " so_rules/sql.rules/" . - " so_rules/web-activex.rules/" . - " so_rules/web-client.rules/" . - " so_rules/web-iis.rules/" . - " so_rules/web-misc.rules/"); - - exec("/bin/mv -f {$snortdir}/so_rules/bad-traffic.rules {$snortdir}/rules/snort_bad-traffic.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/chat.rules {$snortdir}/rules/snort_chat.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/dos.rules {$snortdir}/rules/snort_dos.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/exploit.rules {$snortdir}/rules/snort_exploit.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/icmp.rules {$snortdir}/rules/snort_icmp.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/imap.rules {$snortdir}/rules/snort_imap.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/misc.rules {$snortdir}/rules/snort_misc.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/multimedia.rules {$snortdir}/rules/snort_multimedia.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/netbios.rules {$snortdir}/rules/snort_netbios.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/nntp.rules {$snortdir}/rules/snort_nntp.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/p2p.rules {$snortdir}/rules/snort_p2p.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/smtp.rules {$snortdir}/rules/snort_smtp.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/sql.rules {$snortdir}/rules/snort_sql.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/web-activex.rules {$snortdir}/rules/snort_web-activex.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/web-client.rules {$snortdir}/rules/snort_web-client.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/web-iis.rules {$snortdir}/rules/snort_web-iis.so.rules"); - exec("/bin/mv -f {$snortdir}/so_rules/web-misc.rules {$snortdir}/rules/snort_web-misc.so.rules"); - exec("/bin/rm -r {$snortdir}/so_rules"); - } - - /* extract base etc files */ - exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} etc/"); - exec("/bin/mv -f {$snortdir}/etc/* {$snortdir}"); - exec("/bin/rm -r {$snortdir}/etc"); - - update_status(gettext("Done extracting Snort.org Rules.")); - }else{ - update_status(gettext("Error extracting Snort.org Rules...")); - update_output_window(gettext("Error Line 755")); - $snortdownload = 'off'; - } -} - -/* Untar emergingthreats rules to tmp */ -if ($emergingthreats == 'on') -{ - if ($emerg_md5_check_ok != 'on') - { - if (file_exists("{$tmpfname}/{$emergingthreats_filename}")) - { - update_status(gettext("Extracting rules...")); - update_output_window(gettext("May take a while...")); - exec("/usr/bin/tar xzf {$tmpfname}/{$emergingthreats_filename} -C {$snortdir} rules/"); - } - } -} - -/* Untar Pfsense rules to tmp */ -if ($pfsensedownload == 'on' && $pfsense_md5_check_ok != 'on') { - if (file_exists("{$tmpfname}/{$pfsense_rules_filename}")) { - update_status(gettext("Extracting Pfsense rules...")); - update_output_window(gettext("May take a while...")); - exec("/usr/bin/tar xzf {$tmpfname}/{$pfsense_rules_filename} -C {$snortdir} rules/"); - } -} - -/* Untar snort signatures */ -if ($snortdownload == 'on' && $snort_md5_check_ok != 'on') { - if (file_exists("{$tmpfname}/{$snort_filename}")) { - $signature_info_chk = $config['installedpackages']['snortglobal']['signatureinfo']; - if ($premium_url_chk == 'on') { - update_status(gettext("Extracting Signatures...")); - update_output_window(gettext("May take a while...")); - exec("/usr/bin/tar xzf {$tmpfname}/{$snort_filename} -C {$snortdir} doc/signatures/"); - update_status(gettext("Done extracting Signatures.")); - } - } -} - -/* Copy md5 sig to snort dir */ -if ($snortdownload == 'on') -{ - if ($snort_md5_check_ok != 'on') { - if (file_exists("{$tmpfname}/$snort_filename_md5")) { - update_status(gettext("Copying md5 sig to snort directory...")); - exec("/bin/cp {$tmpfname}/$snort_filename_md5 {$snortdir}/$snort_filename_md5"); - }else{ - update_status(gettext("The md5 file does not exist...")); - update_output_window(gettext("Error copying config...")); - $snortdownload = 'off'; - } - } -} - -/* Copy emergingthreats md5 sig to snort dir */ -if ($emergingthreats == "on") -{ - if ($emerg_md5_check_ok != 'on') - { - if (file_exists("{$tmpfname}/$emergingthreats_filename_md5")) - { - update_status(gettext("Copying md5 sig to snort directory...")); - exec("/bin/cp {$tmpfname}/$emergingthreats_filename_md5 {$snortdir}/$emergingthreats_filename_md5"); - }else{ - update_status(gettext("The emergingthreats md5 file does not exist...")); - update_output_window(gettext("Error copying config...")); - $emergingthreats = 'off'; - } - } -} - -/* Copy Pfsense md5 sig to snort dir */ -if ($pfsensedownload == 'on' && $pfsense_md5_check_ok != 'on') { - if (file_exists("{$tmpfname}/$pfsense_rules_filename_md5")) { - update_status(gettext("Copying Pfsense md5 sig to snort directory...")); - exec("/bin/cp {$tmpfname}/$pfsense_rules_filename_md5 {$snortdir}/$pfsense_rules_filename_md5"); - } else { - update_status(gettext("The Pfsense md5 file does not exist...")); - update_output_window(gettext("Error copying config...")); - $pfsensedownload = 'off'; - } -} - -/* Copy signatures dir to snort dir */ -if ($snortdownload == 'on') -{ - if ($snort_md5_check_ok != 'on') - { - $signature_info_chk = $config['installedpackages']['snortglobal']['signatureinfo']; - if ($premium_url_chk == 'on') - { - if (file_exists("{$snortdir}/doc/signatures")) { - update_status(gettext("Copying signatures...")); - update_output_window(gettext("May take a while...")); - exec("/bin/mv -f {$snortdir}/doc/signatures {$snortdir}/signatures"); - exec("/bin/rm -r {$snortdir}/doc/signatures"); - update_status(gettext("Done copying signatures.")); - }else{ - update_status(gettext("Directory signatures exist...")); - update_output_window(gettext("Error copying signature...")); - $snortdownload = 'off'; - } - } - } -} - -/* double make shure cleanup emerg rules that dont belong */ -if (file_exists("/usr/local/etc/snort/rules/emerging-botcc-BLOCK.rules")) { - apc_clear_cache(); - @unlink("/usr/local/etc/snort/rules/emerging-botcc-BLOCK.rules"); - @unlink("/usr/local/etc/snort/rules/emerging-botcc.rules"); - @unlink("/usr/local/etc/snort/rules/emerging-compromised-BLOCK.rules"); - @unlink("/usr/local/etc/snort/rules/emerging-drop-BLOCK.rules"); - @unlink("/usr/local/etc/snort/rules/emerging-dshield-BLOCK.rules"); - @unlink("/usr/local/etc/snort/rules/emerging-rbn-BLOCK.rules"); - @unlink("/usr/local/etc/snort/rules/emerging-tor-BLOCK.rules"); -} - -if (file_exists("/usr/local/lib/snort/dynamicrules/lib_sfdynamic_example_rule.so")) { - exec("/bin/rm /usr/local/lib/snort/dynamicrules/lib_sfdynamic_example_rule.so"); - exec("/bin/rm /usr/local/lib/snort/dynamicrules/lib_sfdynamic_example\*"); -} - -/* make shure default rules are in the right format */ -exec("/usr/local/bin/perl -pi -e 's/#alert/# alert/g' /usr/local/etc/snort/rules/*.rules"); -exec("/usr/local/bin/perl -pi -e 's/##alert/# alert/g' /usr/local/etc/snort/rules/*.rules"); -exec("/usr/local/bin/perl -pi -e 's/## alert/# alert/g' /usr/local/etc/snort/rules/*.rules"); - -/* create a msg-map for snort */ -update_status(gettext("Updating Alert Messages...")); -update_output_window(gettext("Please Wait...")); -exec("/usr/local/bin/perl /usr/local/bin/create-sidmap.pl /usr/local/etc/snort/rules > /usr/local/etc/snort/sid-msg.map"); - - -////////////////// - -/* open oinkmaster_conf for writing" function */ -function oinkmaster_conf($id, $if_real, $iface_uuid) -{ - global $config, $snort_md5_check_ok, $emerg_md5_check_ok, $pfsense_md5_check_ok; - - @unlink("/usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/oinkmaster_{$iface_uuid}_{$if_real}.conf"); - - /* enable disable setting will carry over with updates */ - /* TODO carry signature changes with the updates */ - if ($snort_md5_check_ok != 'on' || $emerg_md5_check_ok != 'on' || $pfsense_md5_check_ok != 'on') { - - $selected_sid_on_sections = ""; - $selected_sid_off_sections = ""; - - if (!empty($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_on'])) { - $enabled_sid_on = trim($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_on']); - $enabled_sid_on_array = split('\|\|', $enabled_sid_on); - foreach($enabled_sid_on_array as $enabled_item_on) - $selected_sid_on_sections .= "$enabled_item_on\n"; - } - - if (!empty($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_off'])) { - $enabled_sid_off = trim($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_off']); - $enabled_sid_off_array = split('\|\|', $enabled_sid_off); - foreach($enabled_sid_off_array as $enabled_item_off) - $selected_sid_off_sections .= "$enabled_item_off\n"; - } - - if (!empty($selected_sid_on_sections) || !empty($selected_sid_off_sections)) { - $snort_sid_text = <<<EOD - -########################################### -# # -# this is auto generated on snort updates # -# # -########################################### - -path = /bin:/usr/bin:/usr/local/bin - -update_files = \.rules$|\.config$|\.conf$|\.txt$|\.map$ - -url = dir:///usr/local/etc/snort/rules - -$selected_sid_on_sections - -$selected_sid_off_sections - -EOD; - - /* open snort's oinkmaster.conf for writing */ - @file_put_contents("/usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/oinkmaster_{$iface_uuid}_{$if_real}.conf", $snort_sid_text); - } - } -} - -/* Run oinkmaster to snort_wan and cp configs */ -/* If oinkmaster is not needed cp rules normally */ -/* TODO add per interface settings here */ -function oinkmaster_run($id, $if_real, $iface_uuid) -{ - global $config, $g, $snortdir_wan, $snortdir, $snort_md5_check_ok, $emerg_md5_check_ok, $pfsense_md5_check_ok; - - if ($snort_md5_check_ok != 'on' || $emerg_md5_check_ok != 'on' || $pfsense_md5_check_ok != 'on') { - if (empty($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_on']) && empty($config['installedpackages']['snortglobal']['rule'][$id]['rule_sid_off'])) { - update_status(gettext("Your first set of rules are being copied...")); - update_output_window(gettext("May take a while...")); - exec("/bin/cp {$snortdir}/rules/* {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}/rules/"); - exec("/bin/cp {$snortdir}/classification.config {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/gen-msg.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/generators {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/reference.config {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/sid {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/sid-msg.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/unicode.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - } else { - update_status(gettext("Your enable and disable changes are being applied to your fresh set of rules...")); - update_output_window(gettext("May take a while...")); - exec("/bin/cp {$snortdir}/rules/* {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}/rules/"); - exec("/bin/cp {$snortdir}/classification.config {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/gen-msg.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/generators {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/reference.config {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/sid {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/sid-msg.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - exec("/bin/cp {$snortdir}/unicode.map {$snortdir_wan}/snort_{$iface_uuid}_{$if_real}"); - - /* might have to add a sleep for 3sec for flash drives or old drives */ - exec("/usr/local/bin/perl /usr/local/bin/oinkmaster.pl -C /usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/oinkmaster_{$iface_uuid}_{$if_real}.conf -o /usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules > /usr/local/etc/snort/oinkmaster_{$iface_uuid}_{$if_real}.log"); - } - } -} - -/* Start the proccess for every interface rule */ -/* TODO: try to make the code smother */ -if (is_array($config['installedpackages']['snortglobal']['rule'])) -{ - foreach ($config['installedpackages']['snortglobal']['rule'] as $id => $value) { - $result_lan = $value['interface']; - $if_real = snort_get_real_interface($result_lan); - $iface_uuid = $value['uuid']; - - /* make oinkmaster.conf for each interface rule */ - oinkmaster_conf($id, $if_real, $iface_uuid); - - /* run oinkmaster for each interface rule */ - oinkmaster_run($id, $if_real, $iface_uuid); - } -} - -////////////// - -/* mark the time update finnished */ -$config['installedpackages']['snortglobal']['last_rules_install'] = date("Y-M-jS-h:i-A"); - -/* remove old $tmpfname files */ -if (is_dir('/usr/local/etc/snort/tmp')) { - update_status(gettext("Cleaning up...")); - exec("/bin/rm -r /usr/local/etc/snort/tmp/snort_rules_up"); - sleep(2); - exec("/bin/rm -r /usr/local/etc/snort/tmp/rules_bk"); -} - -/* XXX: These are needed if snort is run as snort user -mwexec("/usr/sbin/chown -R snort:snort /var/log/snort", true); -mwexec("/usr/sbin/chown -R snort:snort /usr/local/etc/snort", true); -mwexec("/usr/sbin/chown -R snort:snort /usr/local/lib/snort", true); -*/ -/* make all dirs snorts */ -mwexec("/bin/chmod -R 755 /var/log/snort", true); -mwexec("/bin/chmod -R 755 /usr/local/etc/snort", true); -mwexec("/bin/chmod -R 755 /usr/local/lib/snort", true); +$snort_gui_include = true; +include("/usr/local/pkg/snort/snort_check_for_rule_updates.php"); /* hide progress bar and lets end this party */ -hide_progress_bar_status(); - -if ($snortdownload == 'off' && $emergingthreats == 'off' && $pfsensedownload == 'off') - update_output_window(gettext("Finished...")); -else if ($snort_md5_check_ok == 'on' && $emerg_md5_check_ok == 'on' && $pfsense_md5_check_ok == 'on') - update_output_window(gettext("Finished...")); -else { - /* You are Not Up to date, always stop snort when updating rules for low end machines */; - update_status(gettext("You are NOT up to date...")); - exec("/bin/sh /usr/local/etc/rc.d/snort.sh start"); - update_status(gettext("The Rules update finished...")); - update_output_window(gettext("Snort has restarted with your new set of rules...")); - exec("/bin/rm /tmp/snort_download_halt.pid"); -} - -update_status(gettext("The Rules update finished...")); -conf_mount_ro(); +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 ebde5729..4c4202a8 100644 --- a/config/snort/snort_download_updates.php +++ b/config/snort/snort_download_updates.php @@ -1,132 +1,73 @@ <?php /* - snort_download_updates.php - part of pfSense - Copyright (C) 2004 Scott Ullrich - Copyright (C) 2011 Ermal Luci - All rights reserved. - - part of m0n0wall as reboot.php (http://m0n0.ch/wall) - Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. + * snort_download_updates.php + * part of pfSense + * + * Copyright (C) 2004 Scott Ullrich + * Copyright (C) 2011-2012 Ermal Luci + * All rights reserved. + * + * part of m0n0wall as reboot.php (http://m0n0.ch/wall) + * Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. */ require_once("guiconfig.inc"); -require_once("/usr/local/pkg/snort/snort_gui.inc"); require_once("/usr/local/pkg/snort/snort.inc"); global $g; +$snortdir = SNORTDIR; + /* load only javascript that is needed */ $snort_load_jquery = 'yes'; $snort_load_jquery_colorbox = 'yes'; - - -/* quick md5s chk */ -if(file_exists('/usr/local/etc/snort/snortrules-snapshot-2905.tar.gz.md5')) -{ - $snort_org_sig_chk_local = exec('/bin/cat /usr/local/etc/snort/snortrules-snapshot-2905.tar.gz.md5'); -}else{ - $snort_org_sig_chk_local = 'N/A'; -} - -if(file_exists('/usr/local/etc/snort/emerging.rules.tar.gz.md5')) -{ - $emergingt_net_sig_chk_local = exec('/bin/cat /usr/local/etc/snort/emerging.rules.tar.gz.md5'); -}else{ - $emergingt_net_sig_chk_local = 'N/A'; -} - -if(file_exists('/usr/local/etc/snort/pfsense_rules.tar.gz.md5')) -{ - $pfsense_org_sig_chk_local = exec('/bin/cat /usr/local/etc/snort/pfsense_rules.tar.gz.md5'); -}else{ - $pfsense_org_sig_chk_local = 'N/A'; -} - -/* define checks */ -$oinkid = $config['installedpackages']['snortglobal']['oinkmastercode']; $snortdownload = $config['installedpackages']['snortglobal']['snortdownload']; $emergingthreats = $config['installedpackages']['snortglobal']['emergingthreats']; -if ($snortdownload != 'on' && $emergingthreats != 'on') -{ - $snort_emrging_info = 'stop'; -} - -if ($oinkid == '' && $snortdownload != 'off') -{ - $snort_oinkid_info = 'stop'; -} - -if ($snort_emrging_info == 'stop' || $snort_oinkid_info == 'stop') { - $error_stop = 'true'; -} - +/* quick md5s chk */ +$snort_org_sig_chk_local = 'N/A'; +if (file_exists("{$snortdir}/{$snort_rules_file}.md5")) + $snort_org_sig_chk_local = file_get_contents("{$snortdir}/{$snort_rules_file}.md5"); -/* check if main rule directory is empty */ -$if_mrule_dir = "/usr/local/etc/snort/rules"; -$mfolder_chk = (count(glob("$if_mrule_dir/*")) === 0) ? 'empty' : 'full'; +$emergingt_net_sig_chk_local = 'N/A'; +if (file_exists("{$snortdir}/emerging.rules.tar.gz.md5")) + $emergingt_net_sig_chk_local = file_get_contents("{$snortdir}/emerging.rules.tar.gz.md5"); /* check for logfile */ -if(file_exists('/usr/local/etc/snort/snort_update.log')) -{ +$update_logfile_chk = 'no'; +if (file_exists("{$snortdir}/snort_update.log")) $update_logfile_chk = 'yes'; -}else{ - $update_logfile_chk = 'no'; -} - -header("snort_help_info.php"); -header( "Expires: Mon, 20 Dec 1998 01:00:00 GMT" ); -header( "Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT" ); -header( "Cache-Control: no-cache, must-revalidate" ); -header( "Pragma: no-cache" ); - $pgtitle = "Services: Snort: Updates"; include_once("head.inc"); - ?> <body link="#000000" vlink="#000000" alink="#000000"> -<?php -echo "{$snort_general_css}\n"; -echo "$snort_interfaces_css\n"; -?> - <?php include("fbegin.inc"); ?> - <?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> - -<noscript> -<div class="alert" ALIGN=CENTER><img - src="../themes/<?php echo $g['theme']; ?>/images/icons/icon_alert.gif" /><strong>Please -enable JavaScript to view this content -</CENTER></div> -</noscript> - <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr><td> <?php @@ -138,7 +79,6 @@ enable JavaScript to view this content $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); - $tab_array[7] = array(gettext("Help"), false, "/snort/help_and_info.php"); display_top_tabs($tab_array); ?> </td></tr> @@ -147,171 +87,101 @@ enable JavaScript to view this content <div id="mainarea3"> <table id="maintable4" class="tabcont" width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td><!-- grey line --> - <table height="12px" width="725px" border="0" cellpadding="5px" - cellspacing="0"> - <tr> - <td style='background-color: #eeeeee'> - <div height="12px" width="725px" style='background-color: #dddddd'> - </div> - </td> - </tr> - </table> - - <br> - + <tr align="center"> + <td> + <br/> <table id="download_rules" height="32px" width="725px" border="0" cellpadding="5px" cellspacing="0"> <tr> <td id="download_rules_td" style="background-color: #eeeeee"> <div height="32" width="725px" style="background-color: #eeeeee"> - <font color="#777777" size="1.5px"><b>INSTALLED SIGNATURE RULESET</b></font><br> - <br> - <p style="text-align: left; margin-left: 225px;"><font - color="#FF850A" size="1px"><b>SNORT.ORG >>></b></font><font - size="1px" color="#000000"> <? echo $snort_org_sig_chk_local; ?></font><br> - <font color="#FF850A" size="1px"><b>EMERGINGTHREATS.NET >>></b></font><font - size="1px" color="#000000"> <? echo $emergingt_net_sig_chk_local; ?></font><br> - <font color="#FF850A" size="1px"><b>PFSENSE.ORG >>></b></font><font - size="1px" color="#000000"> <? echo $pfsense_org_sig_chk_local; ?></font><br> + <font color="#777777" size="1.5px"> + <p style="text-align: left; margin-left: 225px;"> + <b><?php echo gettext("INSTALLED SIGNATURE RULESET"); ?></b></font><br> + <br> + <font color="#FF850A" size="1px"><b>SNORT.ORG >>></b></font> + <font size="1px" color="#000000"> <? echo $snort_org_sig_chk_local; ?></font><br> + <font color="#FF850A" size="1px"><b>EMERGINGTHREATS.NET >>></b></font> + <font size="1px" color="#000000"> <? echo $emergingt_net_sig_chk_local; ?></font><br> </p> - </div> </td> </tr> </table> - - <br> - - <!-- grey line --> - <table height="12px" width="725px" border="0" cellpadding="5px" - cellspacing="0"> - <tr> - <td style='background-color: #eeeeee'> - <div height="12px" width="725px" style='background-color: #eeeeee'> - </div> - </td> - </tr> - </table> - - <br> - + <br/> <table id="download_rules" height="32px" width="725px" border="0" cellpadding="5px" cellspacing="0"> <tr> <td id="download_rules_td" style='background-color: #eeeeee'> <div height="32" width="725px" style='background-color: #eeeeee'> - <font color='#777777' size='1.5px'><b>UPDATE YOUR RULES</b></font><br> - <br> + <p style="text-align: left; margin-left: 225px;"> + <font color='#777777' size='1.5px'><b><?php echo gettext("UPDATE YOUR RULES"); ?></b></font><br> + <br/> <?php - if ($error_stop == 'true') { + if ($snortdownload != 'on' && $emergingthreats != 'on') { echo ' - - <button class="sexybutton disabled" disabled="disabled"><span class="download">Update Rules </span></button><br/> + <button disabled="disabled"><span class="download">' . gettext("Update Rules") . ' </span></button><br/> <p style="text-align:left; margin-left:150px;"> - <font color="#fc3608" size="2px"><b>WARNING:</b></font><font size="1px" color="#000000"> No rule types have been selected for download. "Global Settings Tab"</font><br>'; - - if ($mfolder_chk == 'empty') { - - echo ' - <font color="#fc3608" size="2px"><b>WARNING:</b></font><font size="1px" color="#000000"> The main rules directory is empty. /usr/local/etc/snort/rules</font>' ."\n"; - } + <font color="#fc3608" size="2px"><b>' . gettext("WARNING:") . '</b></font><font size="1px" color="#000000"> ' . gettext('No rule types have been selected for download. "Global Settings Tab"') . '</font><br>'; echo '</p>' . "\n"; - - }else{ + } else { echo ' - - <a href="/snort/snort_download_rules.php"><button class="sexybutton disabled"><span class="download">Update Rules </span></button></a><br/>' . "\n"; - - if ($mfolder_chk == 'empty') { - - echo ' - <p style="text-align:left; margin-left:150px;"> - <font color="#fc3608" size="2px"><b>WARNING:</b></font><font size="1px" color="#000000"> The main rules directory is empty. /usr/local/etc/snort/rules</font> - </p>'; - } + <a href="/snort/snort_download_rules.php"><button ><span class="download">' . gettext("Update Rules") . ' </span></button></a><br/>' . "\n"; } - ?> <br> - + ?> <br/> + </p> </div> </td> </tr> </table> - - <br> - + <br/> <table id="download_rules" height="32px" width="725px" border="0" cellpadding="5px" cellspacing="0"> <tr> <td id="download_rules_td" style='background-color: #eeeeee'> <div height="32" width="725px" style='background-color: #eeeeee'> - <font color='#777777' size='1.5px'><b>VIEW UPDATE LOG</b></font><br> + <p style="text-align: left; margin-left: 225px;"> + <font color='#777777' size='1.5px'><b><?php echo gettext("VIEW UPDATE LOG"); ?></b></font><br> <br> - <?php + <?php if ($update_logfile_chk == 'yes') { - echo ' - <button class="sexybutton sexysimple example9" href="/snort/snort_rules_edit.php?openruleset=/usr/local/etc/snort/snort_update.log"><span class="pwhitetxt">Update Log </span></button>' . "\n"; + echo " + <button href='/snort/snort_rules_edit.php?openruleset={$snortdir}/snort_update.log'><span class='pwhitetxt'>" . gettext("Update Log") . " </span></button>\n"; }else{ - echo ' - <button class="sexybutton disabled" disabled="disabled" href="/snort/snort_rules_edit.php?openruleset=/usr/local/etc/snort/snort_update.log"><span class="pwhitetxt">Update Log </span></button>' . "\n"; + echo " + <button disabled='disabled' href='/snort/snort_rules_edit.php?openruleset={$snortdir}/snort_update.log'><span class='pwhitetxt'>" . gettext("Update Log") . " </span></button>\n"; } - ?> <br> - <br> - - </div> - </td> - </tr> - </table> - - <br> - - <table height="12px" width="725px" border="0" cellpadding="5px" - cellspacing="0"> - <tr> - <td style='background-color: #eeeeee'> - <div height="12px" width="725px" style='background-color: #eeeeee'> + ?> + <br/> + </p> </div> </td> </tr> </table> - <br> + <br/> <table id="download_rules" height="32px" width="725px" border="0" cellpadding="5px" cellspacing="0"> <tr> <td id="download_rules_td" style='background-color: #eeeeee'> <div height="32" width="725px" style='background-color: #eeeeee'> - - <img style='vertical-align: middle' - src="/snort/images/icon_excli.png" width="40" height="32"> <font - color='#FF850A' size='1px'><b>NOTE:</b></font><font size='1px' - color='#000000'> Snort.org and Emergingthreats.net - will go down from time to time. Please be patient.</font></div> - </td> - </tr> - </table> - - <br> - - <table height="12px" width="725px" border="0" cellpadding="5px" - cellspacing="0"> - <tr> - <td style='background-color: #eeeeee'> - <div height="12px" width="725px" style='background-color: #eeeeee'> + <font color='#FF850A' size='1px'><b><?php echo gettext("NOTE:"); ?></b></font><font size='1px' + color='#000000'> <?php echo gettext("Snort.org and Emergingthreats.net " . + "will go down from time to time. Please be patient."); ?> + </font> </div> </td> </tr> @@ -331,10 +201,6 @@ enable JavaScript to view this content </tr> </table> <!-- end of final table --></div> - <?php include("fend.inc"); ?> - -<?php echo "$snort_custom_rnd_box\n"; ?> - </body> </html> diff --git a/config/snort/snort_gui.inc b/config/snort/snort_gui.inc deleted file mode 100644 index d2fd4e30..00000000 --- a/config/snort/snort_gui.inc +++ /dev/null @@ -1,203 +0,0 @@ -<?php -/* $Id$ */ -/* - snort.inc - Copyright (C) 2006 Scott Ullrich - Copyright (C) 2006 Robert Zelaya - 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. - */ - -include_once("/usr/local/pkg/snort/snort.inc"); - -function print_info_box_np2($msg) { - global $config, $g; - - echo "<table height=\"32\" width=\"100%\">\n"; - echo " <tr>\n"; - echo " <td>\n"; - echo " <div style='background-color:#990000' id='redbox'>\n"; - echo " <table width='100%'><tr><td width='8%'>\n"; - echo " <img style='vertical-align:middle' src=\"/snort/images/alert.jpg\" width=\"32\" height=\"28\">\n"; - echo " </td>\n"; - echo " <td width='70%'><font color='white'><b>{$msg}</b></font>\n"; - echo " </td>"; - if(stristr($msg, "apply") == true) { - echo " <td>"; - echo " <input name=\"apply\" type=\"submit\" class=\"formbtn\" id=\"apply\" value=\"Apply changes\">\n"; - echo " </td>"; - } - echo " </tr></table>\n"; - echo " </div>\n"; - echo " </td>\n"; - echo "</table>\n"; - echo "<script type=\"text/javascript\">\n"; - echo "NiftyCheck();\n"; - echo "Rounded(\"div#redbox\",\"all\",\"#FFF\",\"#990000\",\"smooth\");\n"; - echo "Rounded(\"td#blackbox\",\"all\",\"#FFF\",\"#000000\",\"smooth\");\n"; - echo "</script>\n"; - echo "\n<br>\n"; - - -} - - -/* makes boxes round */ -/* load at bottom */ - -$snort_custom_rnd_box = ' -<script type="text/javascript"> -<!-- - - NiftyCheck(); - Rounded("div#mainarea2","bl br tr","#FFF","#dddddd","smooth"); - Rounded("div#mainarea3","bl br tr","#FFF","#dddddd","smooth"); - Rounded("div#mainarea4","all","#FFF","#dddddd","smooth"); - Rounded("div#mainarea5","all","#eeeeee","#dddddd","smooth"); - -//--> -</script>' . "\n"; - -/* general css code */ -$snort_general_css = ' - -<style type="text/css"> - -.alert { - position:absolute; - top:10px; - left:0px; - width:94%; - height:90%; - -background:#FCE9C0; -background-position: 15px; -border-top:2px solid #DBAC48; -border-bottom:2px solid #DBAC48; -padding: 15px 10px 85% 50px; -} - -.formpre { -font-family:arial; -font-size: 1.1em; -} - -#download_rules { -font-family: arial; -font-size: 13px; -font-weight: bold; -text-align: center -} - -#download_rules_td { -font-family: arial; -font-size: 13px; -font-weight: bold; -text-align: center -} - -body2 { -font-family:arial; -font-size:12px; -} - -.tabcont { -background-color: #dddddd; -padding-right: 12px; -padding-left: 12px; -padding-top: 12px; -padding-bottom: 12px; -} - -.tabcont2 { -background-color: #eeeeee; -padding-right: 12px; -padding-left: 12px; -padding-top: 12px; -padding-bottom: 12px; -} - -.vncell2 { - background-color: #eeeeee; - padding-right: 20px; - padding-left: 8px; - border-bottom: 1px solid #999999; -} - -/* global tab, white lil box */ -.vncell3 { - width: 50px; - background-color: #eeeeee; - padding-right: 2px; - padding-left: 2px; - border-bottom-width: 1px; - border-bottom-style: solid; - border-bottom-color: #999999; -} - -.vncellreq2 { -background-color: #eeeeee; -padding-right: 20px; -padding-left: 8px; -font-weight: bold; -border-bottom-width: 1px; -border-bottom-style: solid; -border-bottom-color: #999999; -} - -</style> ' . "\n"; - - -/* general css code for snort_interface.php */ -$snort_interfaces_css = ' - -<style type="text/css"> - -.listbg2 { - border-right: 1px solid #999999; - border-bottom: 1px solid #999999; - font-size: 11px; - background-color: #090; - color: #000; - padding-right: 16px; - padding-left: 6px; - padding-top: 4px; - padding-bottom: 4px; -} - -.listbg3 { - border-right: 1px solid #999999; - border-bottom: 1px solid #999999; - font-size: 11px; - background-color: #777777; - color: #000; - padding-right: 16px; - padding-left: 6px; - padding-top: 4px; - padding-bottom: 4px; -} - -</style>' . "\n"; - -?> diff --git a/config/snort/snort_interfaces.php b/config/snort/snort_interfaces.php index 9174c24f..1e155e82 100644 --- a/config/snort/snort_interfaces.php +++ b/config/snort/snort_interfaces.php @@ -1,43 +1,41 @@ <?php -/* $Id$ */ /* + * snort_interfaces.php + * + * Copyright (C) 2008-2009 Robert Zelaya. + * Copyright (C) 2011-2012 Ermal Luci + * 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. + */ -originally part of m0n0wall (http://m0n0.ch/wall) -Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. -Copyright (C) 2008-2009 Robert Zelaya. -Copyright (C) 2011 Ermal Luci -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. -*/ - -/* TODO: redo check if snort is up */ $nocsrf = true; require_once("guiconfig.inc"); -require_once("/usr/local/pkg/snort/snort_gui.inc"); require_once("/usr/local/pkg/snort/snort.inc"); global $g; +$snortdir = SNORTDIR; + $id = $_GET['id']; if (isset($_POST['id'])) $id = $_POST['id']; @@ -52,12 +50,12 @@ if (isset($_POST['del_x'])) { if (is_array($_POST['rule'])) { conf_mount_rw(); foreach ($_POST['rule'] as $rulei) { - /* convert fake interfaces to real */ $if_real = snort_get_real_interface($a_nat[$rulei]['interface']); $snort_uuid = $a_nat[$rulei]['uuid']; - - Running_Stop($snort_uuid,$if_real, $rulei); + snort_stop($a_nat[$rulei], $if_real); + exec("/bin/rm -r /var/log/snort/snort_{$if_real}{$snort_uuid}"); + exec("/bin/rm -r {$snortdir}/snort_{$snort_uuid}_{$if_real}"); unset($a_nat[$rulei]); } @@ -68,10 +66,10 @@ if (isset($_POST['del_x'])) { /* if there are no ifaces do not create snort.sh */ if (!empty($config['installedpackages']['snortglobal']['rule'])) - create_snort_sh(); + snort_create_rc(); else { conf_mount_rw(); - exec('/bin/rm /usr/local/etc/rc.d/snort.sh'); + @unlink('/usr/local/etc/rc.d/snort.sh'); conf_mount_ro(); } @@ -88,31 +86,45 @@ if (isset($_POST['del_x'])) { } - /* start/stop snort */ -if ($_GET['act'] == 'toggle' && is_numeric($id)) { +if ($_GET['act'] == 'bartoggle' && is_numeric($id)) { + $snortcfg = $config['installedpackages']['snortglobal']['rule'][$id]; + $if_real = snort_get_real_interface($snortcfg['interface']); + $if_friendly = snort_get_friendly_interface($snortcfg['interface']); - $if_real = snort_get_real_interface($config['installedpackages']['snortglobal']['rule'][$id]['interface']); - $snort_uuid = $config['installedpackages']['snortglobal']['rule'][$id]['uuid']; - - /* Log Iface stop */ - exec("/usr/bin/logger -p daemon.info -i -t SnortStartup 'Toggle for {$snort_uuid}_{$if_real}...'"); + if (snort_is_running($snortcfg['uuid'], $if_real, 'barnyard2') == 'no') { + log_error("Toggle(barnyard starting) for {$if_friendly}({$snortcfg['descr']}}..."); + sync_snort_package_config(); + snort_barnyard_start($snortcfg, $if_real); + } else { + log_error("Toggle(barnyard stopping) for {$if_friendly}({$snortcfg['descr']}}..."); + snort_barnyard_stop($snortcfg, $if_real); + } - sync_snort_package_config(); + sleep(3); // So the GUI reports correctly + header("Location: /snort/snort_interfaces.php"); + exit; +} - $tester2 = Running_Ck($snort_uuid, $if_real, $id); +/* start/stop snort */ +if ($_GET['act'] == 'toggle' && is_numeric($id)) { + $snortcfg = $config['installedpackages']['snortglobal']['rule'][$id]; + $if_real = snort_get_real_interface($snortcfg['interface']); + $if_friendly = snort_get_friendly_interface($snortcfg['interface']); - if ($tester2 == 'yes') { - Running_Stop($snort_uuid, $if_real, $id); + if (snort_is_running($snortcfg['uuid'], $if_real) == 'yes') { + log_error("Toggle(snort stopping) for {$if_friendly}({$snortcfg['descr']})..."); + snort_stop($snortcfg, $if_real); header( 'Expires: Sat, 26 Jul 1997 05:00:00 GMT' ); 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' ); - } else { - Running_Start($snort_uuid, $if_real, $id); + log_error("Toggle(snort starting) for {$if_friendly}({$snortcfg['descr']})..."); + sync_snort_package_config(); + snort_start($snortcfg, $if_real); header( 'Expires: Sat, 26 Jul 1997 05:00:00 GMT' ); header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' ); @@ -120,12 +132,11 @@ if ($_GET['act'] == 'toggle' && is_numeric($id)) { header( 'Cache-Control: post-check=0, pre-check=0', false ); header( 'Pragma: no-cache' ); } - sleep(4); // So the GUI reports correctly + sleep(3); // So the GUI reports correctly header("Location: /snort/snort_interfaces.php"); exit; } - $pgtitle = "Services: $snort_package_version"; include_once("head.inc"); @@ -133,21 +144,11 @@ include_once("head.inc"); <body link="#000000" vlink="#000000" alink="#000000"> <?php -echo "{$snort_general_css}\n"; -echo "$snort_interfaces_css\n"; - include_once("fbegin.inc"); if ($pfsense_stable == 'yes') echo '<p class="pgtitle">' . $pgtitle . '</p>'; ?> -<noscript> -<div class="alert" ALIGN=CENTER><img - src="../themes/<?php echo $g['theme']; ?>/images/icons/icon_alert.gif" /><strong>Please -enable JavaScript to view this content -</CENTER></div> -</noscript> - <form action="snort_interfaces.php" method="post" enctype="multipart/form-data" name="iform" id="iform"> <?php /* Display Alert message */ @@ -155,19 +156,19 @@ enable JavaScript to view this content print_input_errors($input_errors); // TODO: add checks if ($savemsg) - print_info_box2($savemsg); + print_info_box($savemsg); //if (file_exists($d_snortconfdirty_path)) { if ($d_snortconfdirty_path_ls != '') { echo '<p>'; if($savemsg) - print_info_box_np2("{$savemsg}"); + print_info_box_np("{$savemsg}"); else { - print_info_box_np2(' - The Snort configuration has changed for one or more interfaces.<br> - You must apply the changes in order for them to take effect.<br> - '); + print_info_box_np(gettext( + 'The Snort configuration has changed for one or more interfaces.<br>' . + 'You must apply the changes in order for them to take effect.<br>' + )); } } ?> @@ -183,154 +184,128 @@ enable JavaScript to view this content $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); - $tab_array[7] = array(gettext("Help"), false, "/snort/help_and_info.php"); display_top_tabs($tab_array); ?> </td></tr> <tr> <td> - <div id="mainarea2"> - <table class="tabcont" width="100%" border="0" cellpadding="0" - cellspacing="0"> - <tr id="frheader"> - <td width="5%" class="list"> </td> - <td width="1%" class="list"> </td> - <td width="10%" class="listhdrr">If</td> - <td width="10%" class="listhdrr">Snort</td> - <td width="10%" class="listhdrr">Performance</td> - <td width="10%" class="listhdrr">Block</td> - <td width="10%" class="listhdrr">Barnyard2</td> - <td width="50%" class="listhdr">Description</td> - <td width="3%" class="list"> - <table border="0" cellspacing="0" cellpadding="1"> - <tr> - <td width="17"></td> - <td><a href="snort_interfaces_edit.php?id=<?php echo $id_gen;?>"><img - src="../themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" - width="17" height="17" border="0"></a></td> - </tr> - </table> - </td> - </tr> - <?php $nnats = $i = 0; foreach ($a_nat as $natent): ?> - <tr valign="top" id="fr<?=$nnats;?>"> - <?php - - /* convert fake interfaces to real and check if iface is up */ - /* There has to be a smarter way to do this */ - $if_real = snort_get_real_interface($natent['interface']); - $snort_uuid = $natent['uuid']; - - $tester2 = Running_Ck($snort_uuid, $if_real, $id); + <div id="mainarea2"> + <table class="tabcont" width="100%" border="0" cellpadding="0" + cellspacing="0"> + <tr id="frheader"> + <td width="5%" class="list"> </td> + <td width="10%" class="listhdrr"><?php echo gettext("If"); ?></td> + <td width="13%" class="listhdrr"><?php echo gettext("Snort"); ?></td> + <td width="10%" class="listhdrr"><?php echo gettext("Performance"); ?></td> + <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"> + <table border="0" cellspacing="0" cellpadding="1"> + <tr> + <td width="17"></td> + <td><a href="snort_interfaces_edit.php?id=<?php echo $id_gen;?>"><img + src="../themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" + width="17" height="17" border="0"></a></td> + </tr> + </table> + </td> + </tr> +<?php $nnats = $i = 0; foreach ($a_nat as $natent): ?> +<tr valign="top" id="fr<?=$nnats;?>"> +<?php - if ($tester2 == 'no') { - $iconfn = 'pass'; - $class_color_up = 'listbg'; +/* convert fake interfaces to real and check if iface is up */ +/* There has to be a smarter way to do this */ + $if_real = snort_get_real_interface($natent['interface']); + $snort_uuid = $natent['uuid']; + if (snort_is_running($snort_uuid, $if_real) == 'no') + $iconfn = 'pass'; + else + $iconfn = 'block'; + if (snort_is_running($snort_uuid, $if_real, 'barnyard2') == 'no') + $biconfn = 'pass'; + else + $biconfn = 'block'; + + ?> + <td class="listt"> + <input type="checkbox" id="frc<?=$nnats;?>" name="rule[]" value="<?=$i;?>" onClick="fr_bgcolor('<?=$nnats;?>')" style="margin: 0; padding: 0;"></td> + <td class="listr" + id="frd<?=$nnats;?>" + ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> + <?php + echo snort_get_friendly_interface($natent['interface']); + ?> + </td> + <td class="listr" + id="frd<?=$nnats;?>" + ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> + <?php + $check_snort_info = $config['installedpackages']['snortglobal']['rule'][$nnats]['enable']; + if ($check_snort_info == "on") { + echo strtoupper("enabled"); + echo "<a href='?act=toggle&id={$i}'> + <img src='../themes/{$g['theme']}/images/icons/icon_{$iconfn}.gif' + width='13' height='13' border='0' + title='" . gettext('click to toggle start/stop snort') . "'></a>"; + } else + echo strtoupper("disabled"); + ?> + </td> + <td class="listr" + id="frd<?=$nnats;?>" + ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> + <?php + $check_performance_info = $config['installedpackages']['snortglobal']['rule'][$nnats]['performance']; + if ($check_performance_info != "") { + $check_performance = $check_performance_info; }else{ - $class_color_up = 'listbg2'; - $iconfn = 'block'; + $check_performance = "lowmem"; } - + ?> <?=strtoupper($check_performance);?></td> + <td class="listr" + id="frd<?=$nnats;?>" + ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> + <?php + $check_blockoffenders_info = $config['installedpackages']['snortglobal']['rule'][$nnats]['blockoffenders7']; + if ($check_blockoffenders_info == "on") + { + $check_blockoffenders = enabled; + } else { + $check_blockoffenders = disabled; + } + ?> <?=strtoupper($check_blockoffenders);?></td> + <td class="listr" + id="frd<?=$nnats;?>" + ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> + <?php + $check_snortbarnyardlog_info = $config['installedpackages']['snortglobal']['rule'][$nnats]['barnyard_enable']; + if ($check_snortbarnyardlog_info == "on") { + echo strtoupper("enabled"); + echo "<a href='?act=bartoggle&id={$i}'> + <img src='../themes/{$g['theme']}/images/icons/icon_{$biconfn}.gif' + width='13' height='13' border='0' + title='" . gettext('click to toggle start/stop barnyard') . "'></a>"; + } else + echo strtoupper("disabled"); ?> - <td class="listt"> - <a href="?act=toggle&id=<?=$i;?>"> - <img src="../themes/<?= $g['theme']; ?>/images/icons/icon_<?=$iconfn;?>.gif" - width="13" height="13" border="0" - title="click to toggle start/stop snort"></a> - <input type="checkbox" id="frc<?=$nnats;?>" name="rule[]" value="<?=$i;?>" onClick="fr_bgcolor('<?=$nnats;?>')" style="margin: 0; padding: 0;"></td> - <td class="listt" align="center"></td> - <td class="<?=$class_color_up;?>" onClick="fr_toggle(<?=$nnats;?>)" - id="frd<?=$nnats;?>" - ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> - <?php - if (function_exists('convert_friendly_interface_to_friendly_descr')) - echo convert_friendly_interface_to_friendly_descr($natent['interface']); - else { - if (!$natent['interface'] || ($natent['interface'] == "wan")) - echo "WAN"; - else if(strtolower($natent['interface']) == "lan") - echo "LAN"; - else if(strtolower($natent['interface']) == "pppoe") - echo "PPPoE"; - else if(strtolower($natent['interface']) == "pptp") - echo "PPTP"; - else - echo strtoupper($natent['interface']); - } - ?></td> - <td class="listr" onClick="fr_toggle(<?=$nnats;?>)" - id="frd<?=$nnats;?>" - ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> - <?php - $check_snort_info = $config['installedpackages']['snortglobal']['rule'][$nnats]['enable']; - if ($check_snort_info == "on") - { - $check_snort = enabled; - } else { - $check_snort = disabled; - } - ?> <?=strtoupper($check_snort);?></td> - <td class="listr" onClick="fr_toggle(<?=$nnats;?>)" - id="frd<?=$nnats;?>" - ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> - <?php - $check_performance_info = $config['installedpackages']['snortglobal']['rule'][$nnats]['performance']; - if ($check_performance_info != "") { - $check_performance = $check_performance_info; - }else{ - $check_performance = "lowmem"; - } - ?> <?=strtoupper($check_performance);?></td> - <td class="listr" onClick="fr_toggle(<?=$nnats;?>)" - id="frd<?=$nnats;?>" - ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> - <?php - $check_blockoffenders_info = $config['installedpackages']['snortglobal']['rule'][$nnats]['blockoffenders7']; - if ($check_blockoffenders_info == "on") - { - $check_blockoffenders = enabled; - } else { - $check_blockoffenders = disabled; - } - ?> <?=strtoupper($check_blockoffenders);?></td> - <?php - - $color2_upb = Running_Ck_b($snort_uuid, $if_real, $id); - - if ($color2_upb == 'yes') { - $class_color_upb = 'listbg2'; - }else{ - $class_color_upb = 'listbg'; - } - - ?> - <td class="<?=$class_color_upb;?>" onClick="fr_toggle(<?=$nnats;?>)" - id="frd<?=$nnats;?>" - ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> - <?php - $check_snortbarnyardlog_info = $config['installedpackages']['snortglobal']['rule'][$nnats]['barnyard_enable']; - if ($check_snortbarnyardlog_info == "on") - { - $check_snortbarnyardlog = strtoupper(enabled); - }else{ - $check_snortbarnyardlog = strtoupper(disabled); - } - ?> <?php echo "$check_snortbarnyardlog";?></td> - <td class="listbg3" onClick="fr_toggle(<?=$nnats;?>)" - ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> - <font color="#ffffff"> <?=htmlspecialchars($natent['descr']);?> - </td> - <td valign="middle" class="list" nowrap> - <table border="0" cellspacing="0" cellpadding="1"> - <tr> - <td><a href="snort_interfaces_edit.php?id=<?=$i;?>"><img - src="/themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" - width="17" height="17" border="0" title="edit rule"></a></td> - </tr> - </table> - + </td> + <td class="listbg" + ondblclick="document.location='snort_interfaces_edit.php?id=<?=$nnats;?>';"> + <font color="#ffffff"> <?=htmlspecialchars($natent['descr']);?> + </td> + <td valign="middle" class="list" nowrap> + <table border="0" cellspacing="0" cellpadding="1"> + <tr> + <td><a href="snort_interfaces_edit.php?id=<?=$i;?>"><img + src="/themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" + width="17" height="17" border="0" title="<?php echo gettext('edit rule'); ?>"></a></td> </tr> - <?php $i++; $nnats++; endforeach; ?> + </table> + + </tr> + <?php $i++; $nnats++; endforeach; ?> <tr> <td class="list" colspan="8"></td> <td class="list" valign="middle" nowrap> @@ -338,10 +313,10 @@ enable JavaScript to view this content <tr> <td><?php if ($nnats == 0): ?><img src="../themes/<?= $g['theme']; ?>/images/icons/icon_x_d.gif" - width="17" height="17" title="delete selected rules" border="0"><?php else: ?><input + width="17" height="17" title="<?php echo gettext("delete selected rules"); ?>" border="0"><?php else: ?><input name="del" type="image" src="../themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" - width="17" height="17" title="delete selected mappings" + width="17" height="17" title="<?php echo gettext("delete selected mappings"); ?>" onclick="return confirm('Do you really want to delete the selected Snort Rule?')"><?php endif; ?></td> </tr> </table> @@ -361,35 +336,35 @@ enable JavaScript to view this content <table class="tabcont" width="100%" border="0" cellpadding="0" cellspacing="0"> <tr id="frheader"> - <td width="100%"><span class="red"><strong>Note:</strong></span> <br> - This is the <strong>Snort Menu</strong> where you can see an over - view of all your interface settings. <br> - Please edit the <strong>Global Settings</strong> tab before adding - an interface. <br> + <td width="100%"><span class="red"><strong><?php echo gettext("Note:"); ?></strong></span> <br> + <?php echo gettext('This is the <strong>Snort Menu</strong> where you can see an over ' . + 'view of all your interface settings. <br> ' . + 'Please edit the <strong>Global Settings</strong> tab before adding ' . + 'an interface.'); ?> <br> <br> - <span class="red"><strong>Warning:</strong></span> <br> - <strong>New settings will not take effect until interface restart.</strong> + <span class="red"><strong><?php echo gettext("Warning:"); ?></strong></span> <br> + <strong><?php echo gettext("New settings will not take effect until interface restart."); ?></strong> <br> <br> <strong>Click</strong> on the <img src="../themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" - width="17" height="17" border="0" title="Add Icon"> icon to add a + width="17" height="17" border="0" title="<?php echo gettext("Add Icon"); ?>"> icon to add a interface.<strong> Click</strong> on the <img src="../themes/<?= $g['theme']; ?>/images/icons/icon_pass.gif" - width="13" height="13" border="0" title="Start Icon"> icon to <strong>start</strong> + width="13" height="13" border="0" title="<?php echo gettext("Start Icon"); ?>"> icon to <strong>start</strong> snort and barnyard2. <br> <strong>Click</strong> on the <img src="../themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" - width="17" height="17" border="0" title="Edit Icon"> icon to edit a + width="17" height="17" border="0" title="<?php echo gettext("Edit Icon"); ?>"> icon to edit a interface and settings.<strong> Click</strong> on the <img src="../themes/<?= $g['theme']; ?>/images/icons/icon_block.gif" - width="13" height="13" border="0" title="Stop Icon"> icon to <strong>stop</strong> + width="13" height="13" border="0" title="<?php echo gettext("Stop Icon"); ?>"> icon to <strong>stop</strong> snort and barnyard2. <br> <strong> Click</strong> on the <img src="../themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" - width="17" height="17" border="0" title="Delete Icon"> icon to + width="17" height="17" border="0" title="<?php echo gettext("Delete Icon"); ?>"> icon to delete a interface and settings.</td> </tr> </table> @@ -398,54 +373,9 @@ enable JavaScript to view this content </tr> </td> </table> - - <?php - if ($pkg['tabs'] <> "") { - echo "</td></tr></table>"; - } - ?></form> -</div> - -<br> -<br> -<br> - -<style type="text/css"> -#footer2 { - position: relative; - background-color: transparent; - background-image: url("./images/logo22.png"); - background-repeat: no-repeat; - background-attachment: scroll; - background-position: 0% 0%; - top: 10px; - left: 0px; - width: 770px; - height: 60px; - color: #000000; - text-align: center; - font-size: 0.8em; - padding-top: 40px; - margin-bottom: -35px; - clear: both; -} -</style> - -<div id="footer2">SNORT registered � by Sourcefire, Inc, Barnyard2 -registered � by securixlive.com, Orion registered � by Robert Zelaya, -Emergingthreats registered � by emergingthreats.net, Mysql registered � -by Mysql.com</div> -<!-- Footer DIV --> - - <?php - - include("fend.inc"); - - echo $snort_custom_rnd_box; - - ?> - - - +</form> +<?php +include("fend.inc"); +?> </body> </html> diff --git a/config/snort/snort_interfaces_edit.php b/config/snort/snort_interfaces_edit.php index f3d96848..f47a055e 100644 --- a/config/snort/snort_interfaces_edit.php +++ b/config/snort/snort_interfaces_edit.php @@ -1,44 +1,45 @@ <?php /* - snort_interfaces_edit.php - part of m0n0wall (http://m0n0.ch/wall) - - Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. - Copyright (C) 2008-2009 Robert Zelaya. - Copyright (C) 2011 Ermal Luci - 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. + * snort_interfaces_edit.php + * + * Copyright (C) 2008-2009 Robert Zelaya. + * Copyright (C) 2011-2012 Ermal Luci + * 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_gui.inc"); require_once("/usr/local/pkg/snort/snort.inc"); global $g; +if (!is_array($config['installedpackages']['snortglobal'])) + $config['installedpackages']['snortglobal'] = array(); +$snortglob = $config['installedpackages']['snortglobal']; + if (!is_array($config['installedpackages']['snortglobal']['rule'])) $config['installedpackages']['snortglobal']['rule'] = array(); -$a_nat = &$config['installedpackages']['snortglobal']['rule']; +$a_rule = &$config['installedpackages']['snortglobal']['rule']; $id = $_GET['id']; if (isset($_POST['id'])) @@ -48,302 +49,100 @@ if (is_null($id)) { exit; } -if (isset($_GET['dup'])) { - $id = $_GET['dup']; - $after = $_GET['dup']; -} - - -/* always have a limit of (65535) numbers only or snort will not start do to id limits */ -/* TODO: When inline gets added make the uuid the port number lisstening */ $pconfig = array(); - -/* gen uuid for each iface !inportant */ -if (empty($config['installedpackages']['snortglobal']['rule'][$id]['uuid'])) { - //$snort_uuid = gen_snort_uuid(strrev(uniqid(true))); - $snort_uuid = 0; - while ($snort_uuid > 65535 || $snort_uuid == 0) { - $snort_uuid = mt_rand(1, 65535); +if (empty($snortglob['rule'][$id]['uuid'])) + $pconfig['uuid'] = snort_generate_id(); +else + $pconfig['uuid'] = $a_rule[$id]['uuid']; +$snort_uuid = $pconfig['uuid']; + +if (isset($id) && $a_rule[$id]) { + /* old options */ + $pconfig = $a_rule[$id]; + if (!empty($pconfig['configpassthru'])) + $pconfig['configpassthru'] = base64_decode($pconfig['configpassthru']); + if (empty($pconfig['uuid'])) $pconfig['uuid'] = $snort_uuid; - } -} else { - $snort_uuid = $a_nat[$id]['uuid']; - $pconfig['uuid'] = $snort_uuid; -} - -if (isset($id) && $a_nat[$id]) { - - /* old options */ - $pconfig['def_ssl_ports_ignore'] = $a_nat[$id]['def_ssl_ports_ignore']; - $pconfig['flow_depth'] = $a_nat[$id]['flow_depth']; - $pconfig['max_queued_bytes'] = $a_nat[$id]['max_queued_bytes']; - $pconfig['max_queued_segs'] = $a_nat[$id]['max_queued_segs']; - $pconfig['perform_stat'] = $a_nat[$id]['perform_stat']; - $pconfig['http_inspect'] = $a_nat[$id]['http_inspect']; - $pconfig['other_preprocs'] = $a_nat[$id]['other_preprocs']; - $pconfig['ftp_preprocessor'] = $a_nat[$id]['ftp_preprocessor']; - $pconfig['smtp_preprocessor'] = $a_nat[$id]['smtp_preprocessor']; - $pconfig['sf_portscan'] = $a_nat[$id]['sf_portscan']; - $pconfig['dce_rpc_2'] = $a_nat[$id]['dce_rpc_2']; - $pconfig['dns_preprocessor'] = $a_nat[$id]['dns_preprocessor']; - $pconfig['def_dns_servers'] = $a_nat[$id]['def_dns_servers']; - $pconfig['def_dns_ports'] = $a_nat[$id]['def_dns_ports']; - $pconfig['def_smtp_servers'] = $a_nat[$id]['def_smtp_servers']; - $pconfig['def_smtp_ports'] = $a_nat[$id]['def_smtp_ports']; - $pconfig['def_mail_ports'] = $a_nat[$id]['def_mail_ports']; - $pconfig['def_http_servers'] = $a_nat[$id]['def_http_servers']; - $pconfig['def_www_servers'] = $a_nat[$id]['def_www_servers']; - $pconfig['def_http_ports'] = $a_nat[$id]['def_http_ports']; - $pconfig['def_sql_servers'] = $a_nat[$id]['def_sql_servers']; - $pconfig['def_oracle_ports'] = $a_nat[$id]['def_oracle_ports']; - $pconfig['def_mssql_ports'] = $a_nat[$id]['def_mssql_ports']; - $pconfig['def_telnet_servers'] = $a_nat[$id]['def_telnet_servers']; - $pconfig['def_telnet_ports'] = $a_nat[$id]['def_telnet_ports']; - $pconfig['def_snmp_servers'] = $a_nat[$id]['def_snmp_servers']; - $pconfig['def_snmp_ports'] = $a_nat[$id]['def_snmp_ports']; - $pconfig['def_ftp_servers'] = $a_nat[$id]['def_ftp_servers']; - $pconfig['def_ftp_ports'] = $a_nat[$id]['def_ftp_ports']; - $pconfig['def_ssh_servers'] = $a_nat[$id]['def_ssh_servers']; - $pconfig['def_ssh_ports'] = $a_nat[$id]['def_ssh_ports']; - $pconfig['def_pop_servers'] = $a_nat[$id]['def_pop_servers']; - $pconfig['def_pop2_ports'] = $a_nat[$id]['def_pop2_ports']; - $pconfig['def_pop3_ports'] = $a_nat[$id]['def_pop3_ports']; - $pconfig['def_imap_servers'] = $a_nat[$id]['def_imap_servers']; - $pconfig['def_imap_ports'] = $a_nat[$id]['def_imap_ports']; - $pconfig['def_sip_proxy_ip'] = $a_nat[$id]['def_sip_proxy_ip']; - $pconfig['def_sip_servers'] = $a_nat[$id]['def_sip_servers']; - $pconfig['def_sip_ports'] = $a_nat[$id]['def_sip_ports']; - $pconfig['def_sip_proxy_ports'] = $a_nat[$id]['def_sip_proxy_ports']; - $pconfig['def_auth_ports'] = $a_nat[$id]['def_auth_ports']; - $pconfig['def_finger_ports'] = $a_nat[$id]['def_finger_ports']; - $pconfig['def_irc_ports'] = $a_nat[$id]['def_irc_ports']; - $pconfig['def_nntp_ports'] = $a_nat[$id]['def_nntp_ports']; - $pconfig['def_rlogin_ports'] = $a_nat[$id]['def_rlogin_ports']; - $pconfig['def_rsh_ports'] = $a_nat[$id]['def_rsh_ports']; - $pconfig['def_ssl_ports'] = $a_nat[$id]['def_ssl_ports']; - $pconfig['barnyard_enable'] = $a_nat[$id]['barnyard_enable']; - $pconfig['barnyard_mysql'] = $a_nat[$id]['barnyard_mysql']; - $pconfig['enable'] = $a_nat[$id]['enable']; - $pconfig['interface'] = $a_nat[$id]['interface']; - $pconfig['descr'] = $a_nat[$id]['descr']; - $pconfig['performance'] = $a_nat[$id]['performance']; - $pconfig['blockoffenders7'] = $a_nat[$id]['blockoffenders7']; - $pconfig['blockoffenderskill'] = $a_nat[$id]['blockoffenderskill']; - $pconfig['blockoffendersip'] = $a_nat[$id]['blockoffendersip']; - $pconfig['whitelistname'] = $a_nat[$id]['whitelistname']; - $pconfig['homelistname'] = $a_nat[$id]['homelistname']; - $pconfig['externallistname'] = $a_nat[$id]['externallistname']; - $pconfig['suppresslistname'] = $a_nat[$id]['suppresslistname']; - $pconfig['snortalertlogtype'] = $a_nat[$id]['snortalertlogtype']; - $pconfig['alertsystemlog'] = $a_nat[$id]['alertsystemlog']; - $pconfig['tcpdumplog'] = $a_nat[$id]['tcpdumplog']; - $pconfig['snortunifiedlog'] = $a_nat[$id]['snortunifiedlog']; - $pconfig['configpassthru'] = base64_decode($a_nat[$id]['configpassthru']); - $pconfig['barnconfigpassthru'] = $a_nat[$id]['barnconfigpassthru']; - $pconfig['rulesets'] = $a_nat[$id]['rulesets']; - $pconfig['rule_sid_off'] = $a_nat[$id]['rule_sid_off']; - $pconfig['rule_sid_on'] = $a_nat[$id]['rule_sid_on']; - - - if (!$pconfig['interface']) - $pconfig['interface'] = "wan"; - } else + if (!$pconfig['interface']) $pconfig['interface'] = "wan"; - -/* convert fake interfaces to real */ -$if_real = snort_get_real_interface($pconfig['interface']); +} if (isset($_GET['dup'])) unset($id); - /* alert file */ - $d_snortconfdirty_path = "/var/run/snort_conf_{$snort_uuid}_{$if_real}.dirty"; - - if ($_POST["Submit"]) { - - if ($_POST['descr'] == '' && $pconfig['descr'] == '') { - $input_errors[] = "Please enter a description for your reference."; - } - - if ($id == "" && $config['installedpackages']['snortglobal']['rule'][0]['interface'] != "") { - - $rule_array = $config['installedpackages']['snortglobal']['rule']; - foreach ($config['installedpackages']['snortglobal']['rule'] as $value) { - - $result_lan = $value['interface']; - $if_real = snort_get_real_interface($result_lan); - - if ($_POST['interface'] == $result_lan) - $input_errors[] = "Interface $result_lan is in use. Please select another interface."; - } - } - - /* XXX: Void code - * check for overlaps - foreach ($a_nat as $natent) { - if (isset($id) && ($a_nat[$id]) && ($a_nat[$id] === $natent)) - continue; - if ($natent['interface'] != $_POST['interface']) - continue; - } - */ - - /* if no errors write to conf */ - if (!$input_errors) { - $natent = array(); - - /* write to conf for 1st time or rewrite the answer */ - if ($_POST['interface']) - $natent['interface'] = $_POST['interface']; - - /* if post write to conf or rewite the answer */ - $natent['enable'] = $_POST['enable'] ? 'on' : 'off'; - $natent['uuid'] = $pconfig['uuid']; - $natent['descr'] = $_POST['descr'] ? $_POST['descr'] : $pconfig['descr']; - $natent['performance'] = $_POST['performance'] ? $_POST['performance'] : $pconfig['performance']; - /* if post = on use on off or rewrite the conf */ - if ($_POST['blockoffenders7'] == "on") - $natent['blockoffenders7'] = 'on'; - else - $natent['blockoffenders7'] = 'off'; - if ($_POST['blockoffenderskill'] == "on") - $natent['blockoffenderskill'] = 'on'; - if ($_POST['blockoffendersip']) - $natent['blockoffendersip'] = $_POST['blockoffendersip']; - - $natent['whitelistname'] = $_POST['whitelistname'] ? $_POST['whitelistname'] : $pconfig['whitelistname']; - $natent['homelistname'] = $_POST['homelistname'] ? $_POST['homelistname'] : $pconfig['homelistname']; - $natent['externallistname'] = $_POST['externallistname'] ? $_POST['externallistname'] : $pconfig['externallistname']; - $natent['suppresslistname'] = $_POST['suppresslistname'] ? $_POST['suppresslistname'] : $pconfig['suppresslistname']; - $natent['snortalertlogtype'] = $_POST['snortalertlogtype'] ? $_POST['snortalertlogtype'] : $pconfig['snortalertlogtype']; - if ($_POST['alertsystemlog'] == "on") { $natent['alertsystemlog'] = 'on'; }else{ $natent['alertsystemlog'] = 'off'; } - if ($_POST['enable']) { $natent['enable'] = 'on'; } else unset($natent['enable']); - if ($_POST['tcpdumplog'] == "on") { $natent['tcpdumplog'] = 'on'; }else{ $natent['tcpdumplog'] = 'off'; } - if ($_POST['snortunifiedlog'] == "on") { $natent['snortunifiedlog'] = 'on'; }else{ $natent['snortunifiedlog'] = 'off'; } - $natent['configpassthru'] = $_POST['configpassthru'] ? base64_encode($_POST['configpassthru']) : $pconfig['configpassthru']; - /* if optiion = 0 then the old descr way will not work */ - - /* rewrite the options that are not in post */ - /* make shure values are set befor repost or conf.xml will be broken */ - if ($pconfig['def_ssl_ports_ignore'] != "") { $natent['def_ssl_ports_ignore'] = $pconfig['def_ssl_ports_ignore']; } - if ($pconfig['flow_depth'] != "") { $natent['flow_depth'] = $pconfig['flow_depth']; } - if ($pconfig['max_queued_bytes'] != "") { $natent['max_queued_bytes'] = $pconfig['max_queued_bytes']; } - if ($pconfig['max_queued_segs'] != "") { $natent['max_queued_segs'] = $pconfig['max_queued_segs']; } - if ($pconfig['perform_stat'] != "") { $natent['perform_stat'] = $pconfig['perform_stat']; } - if ($pconfig['http_inspect'] != "") { $natent['http_inspect'] = $pconfig['http_inspect']; } - if ($pconfig['other_preprocs'] != "") { $natent['other_preprocs'] = $pconfig['other_preprocs']; } - if ($pconfig['ftp_preprocessor'] != "") { $natent['ftp_preprocessor'] = $pconfig['ftp_preprocessor']; } - if ($pconfig['smtp_preprocessor'] != "") { $natent['smtp_preprocessor'] = $pconfig['smtp_preprocessor']; } - if ($pconfig['sf_portscan'] != "") { $natent['sf_portscan'] = $pconfig['sf_portscan']; } - if ($pconfig['dce_rpc_2'] != "") { $natent['dce_rpc_2'] = $pconfig['dce_rpc_2']; } - if ($pconfig['dns_preprocessor'] != "") { $natent['dns_preprocessor'] = $pconfig['dns_preprocessor']; } - if ($pconfig['def_dns_servers'] != "") { $natent['def_dns_servers'] = $pconfig['def_dns_servers']; } - if ($pconfig['def_dns_ports'] != "") { $natent['def_dns_ports'] = $pconfig['def_dns_ports']; } - if ($pconfig['def_smtp_servers'] != "") { $natent['def_smtp_servers'] = $pconfig['def_smtp_servers']; } - if ($pconfig['def_smtp_ports'] != "") { $natent['def_smtp_ports'] = $pconfig['def_smtp_ports']; } - if ($pconfig['def_mail_ports'] != "") { $natent['def_mail_ports'] = $pconfig['def_mail_ports']; } - if ($pconfig['def_http_servers'] != "") { $natent['def_http_servers'] = $pconfig['def_http_servers']; } - if ($pconfig['def_www_servers'] != "") { $natent['def_www_servers'] = $pconfig['def_www_servers']; } - if ($pconfig['def_http_ports'] != "") { $natent['def_http_ports'] = $pconfig['def_http_ports']; } - if ($pconfig['def_sql_servers'] != "") { $natent['def_sql_servers'] = $pconfig['def_sql_servers']; } - if ($pconfig['def_oracle_ports'] != "") { $natent['def_oracle_ports'] = $pconfig['def_oracle_ports']; } - if ($pconfig['def_mssql_ports'] != "") { $natent['def_mssql_ports'] = $pconfig['def_mssql_ports']; } - if ($pconfig['def_telnet_servers'] != "") { $natent['def_telnet_servers'] = $pconfig['def_telnet_servers']; } - if ($pconfig['def_telnet_ports'] != "") { $natent['def_telnet_ports'] = $pconfig['def_telnet_ports']; } - if ($pconfig['def_snmp_servers'] != "") { $natent['def_snmp_servers'] = $pconfig['def_snmp_servers']; } - if ($pconfig['def_snmp_ports'] != "") { $natent['def_snmp_ports'] = $pconfig['def_snmp_ports']; } - if ($pconfig['def_ftp_servers'] != "") { $natent['def_ftp_servers'] = $pconfig['def_ftp_servers']; } - if ($pconfig['def_ftp_ports'] != "") { $natent['def_ftp_ports'] = $pconfig['def_ftp_ports']; } - if ($pconfig['def_ssh_servers'] != "") { $natent['def_ssh_servers'] = $pconfig['def_ssh_servers']; } - if ($pconfig['def_ssh_ports'] != "") { $natent['def_ssh_ports'] = $pconfig['def_ssh_ports']; } - if ($pconfig['def_pop_servers'] != "") { $natent['def_pop_servers'] = $pconfig['def_pop_servers']; } - if ($pconfig['def_pop2_ports'] != "") { $natent['def_pop2_ports'] = $pconfig['def_pop2_ports']; } - if ($pconfig['def_pop3_ports'] != "") { $natent['def_pop3_ports'] = $pconfig['def_pop3_ports']; } - if ($pconfig['def_imap_servers'] != "") { $natent['def_imap_servers'] = $pconfig['def_imap_servers']; } - if ($pconfig['def_imap_ports'] != "") { $natent['def_imap_ports'] = $pconfig['def_imap_ports']; } - if ($pconfig['def_sip_proxy_ip'] != "") { $natent['def_sip_proxy_ip'] = $pconfig['def_sip_proxy_ip']; } - if ($pconfig['def_sip_servers'] != "") { $natent['def_sip_servers'] = $pconfig['def_sip_servers']; }else{ $natent['def_sip_servers'] = ""; } - if ($pconfig['def_sip_ports'] != "") { $natent['def_sip_ports'] = $pconfig['def_sip_ports']; }else{ $natent['def_sip_ports'] = ""; } - if ($pconfig['def_sip_proxy_ports'] != "") { $natent['def_sip_proxy_ports'] = $pconfig['def_sip_proxy_ports']; } - if ($pconfig['def_auth_ports'] != "") { $natent['def_auth_ports'] = $pconfig['def_auth_ports']; } - if ($pconfig['def_finger_ports'] != "") { $natent['def_finger_ports'] = $pconfig['def_finger_ports']; } - if ($pconfig['def_irc_ports'] != "") { $natent['def_irc_ports'] = $pconfig['def_irc_ports']; } - if ($pconfig['def_nntp_ports'] != "") { $natent['def_nntp_ports'] = $pconfig['def_nntp_ports']; } - if ($pconfig['def_rlogin_ports'] != "") { $natent['def_rlogin_ports'] = $pconfig['def_rlogin_ports']; } - if ($pconfig['def_rsh_ports'] != "") { $natent['def_rsh_ports'] = $pconfig['def_rsh_ports']; } - if ($pconfig['def_ssl_ports'] != "") { $natent['def_ssl_ports'] = $pconfig['def_ssl_ports']; } - if ($pconfig['barnyard_enable'] != "") { $natent['barnyard_enable'] = $pconfig['barnyard_enable']; } - if ($pconfig['barnyard_mysql'] != "") { $natent['barnyard_mysql'] = $pconfig['barnyard_mysql']; } - if ($pconfig['barnconfigpassthru'] != "") { $natent['barnconfigpassthru'] = $pconfig['barnconfigpassthru']; } - if ($pconfig['rulesets'] != "") { $natent['rulesets'] = $pconfig['rulesets']; } - if ($pconfig['rule_sid_off'] != "") { $natent['rule_sid_off'] = $pconfig['rule_sid_off']; } - if ($pconfig['rule_sid_on'] != "") { $natent['rule_sid_on'] = $pconfig['rule_sid_on']; } - - - $if_real = snort_get_real_interface($natent['interface']); - - if (isset($id) && $a_nat[$id]) { - if ($natent['interface'] != $a_nat[$id]['interface']) - Running_Stop($snort_uuid, $if_real, $id); - $a_nat[$id] = $natent; - } else { - if (is_numeric($after)) - array_splice($a_nat, $after+1, 0, array($natent)); - else - $a_nat[] = $natent; - } - - write_config(); - - sync_snort_package_config(); - sleep(1); - - /* if snort.sh crashed this will remove the pid */ - exec('/bin/rm /tmp/snort.sh.pid'); - - 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 ($_POST["Submit"]) { + if ($_POST['descr'] == '' && $pconfig['descr'] == '') { + $input_errors[] = "Please enter a description for your reference."; } - if ($_POST["Submit2"]) { + if (!$_POST['interface']) + $input_errors[] = "Interface is mandatory"; +/* + foreach ($a_rule as $natent) { + if (isset($id) && ($a_rule[$id]) && ($a_rule[$id] === $natent)) + continue; + if ($natent['interface'] == $_POST['interface']) + $input_errors[] = "This interface is already configured for another instance"; + } +*/ + + /* if no errors write to conf */ + if (!$input_errors) { + $natent = $a_rule[$id]; + $natent['interface'] = $_POST['interface']; + $natent['enable'] = $_POST['enable'] ? 'on' : 'off'; + $natent['uuid'] = $pconfig['uuid']; + if ($_POST['descr']) $natent['descr'] = $_POST['descr']; else unset($natent['descr']); + 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'; + if ($_POST['blockoffenderskill'] == "on") $natent['blockoffenderskill'] = 'on'; else unset($natent['blockoffenderskill']); + if ($_POST['blockoffendersip']) $natent['blockoffendersip'] = $_POST['blockoffendersip']; else unset($natent['blockoffendersip']); + if ($_POST['whitelistname']) $natent['whitelistname'] = $_POST['whitelistname']; else unset($natent['whitelistname']); + if ($_POST['homelistname']) $natent['homelistname'] = $_POST['homelistname']; else unset($natent['homelistname']); + 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['cksumcheck']) $natent['cksumcheck'] = 'on'; else $natent['cksumcheck'] = 'off'; + + $if_real = snort_get_real_interface($natent['interface']); + if (isset($id) && $a_rule[$id]) { + if ($natent['interface'] != $a_rule[$id]['interface']) { + $oif_real = snort_get_real_interface($a_rule[$id]['interface']); + snort_stop($a_rule[$id], $oif_real); + exec("rm -r /var/log/snort_{$oif_real}" . $a_rule[$id]['uuid']); + exec("mv -f {$snortdir}/snort_" . $a_rule[$id]['uuid'] . "_{$oif_real} {$snortdir}/snort_" . $a_rule[$id]['uuid'] . "_{$if_real}"); + } + $a_rule[$id] = $natent; + } else + $a_rule[] = $natent; + if ($natent['enable'] != 'on') + snort_stop($natent, $if_real); + write_config(); sync_snort_package_config(); - sleep(1); - - Running_Start($snort_uuid, $if_real, $id); 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_edit.php?id=$id"); + header("Location: /snort/snort_interfaces.php"); exit; - } + } else + $pconfig = $_POST; +} -$pgtitle = "Snort: Interface Edit: $id $snort_uuid $if_real"; +$if_friendly = snort_get_friendly_interface($pconfig['interface']); +$pgtitle = "Snort: Interface Edit: {$if_friendly}"; include_once("head.inc"); - ?> <body link="#0000CC" vlink="#0000CC" alink="#0000CC"> -<?php - include("fbegin.inc"); - echo "{$snort_general_css}\n"; -?> -<noscript> -<div class="alert" ALIGN=CENTER><img - src="/themes/<?php echo $g['theme']; ?>/images/icons/icon_alert.gif" /><strong>Please -enable JavaScript to view this content</strong></div> -</noscript> +<?php include("fbegin.inc"); ?> + <script language="JavaScript"> <!-- @@ -363,17 +162,12 @@ function enable_change(enable_change) { document.iform.externallistname.disabled = endis; document.iform.homelistname.disabled = endis; document.iform.suppresslistname.disabled = endis; - document.iform.tcpdumplog.disabled = endis; - document.iform.snortunifiedlog.disabled = endis; document.iform.configpassthru.disabled = endis; } //--> </script> <?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> -<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> - -<form action="snort_interfaces_edit.php<?php echo "?id=$id";?>" method="post" enctype="multipart/form-data" name="iform" id="iform"> <?php /* Display Alert message */ if ($input_errors) { @@ -381,125 +175,77 @@ function enable_change(enable_change) { } if ($savemsg) { - print_info_box2($savemsg); - } - - //if (file_exists($d_snortconfdirty_path)) { - if (file_exists($d_snortconfdirty_path) || file_exists("/var/run/snort_conf_{$snort_uuid}_.dirty")) { - echo '<p>'; - - if($savemsg) - print_info_box_np2("{$savemsg}"); - else { - print_info_box_np2(' - The Snort configuration has changed and snort needs to be restarted on this interface.<br> - You must apply the changes in order for them to take effect.<br> - '); - } + print_info_box($savemsg); } ?> +<form action="snort_interfaces_edit.php<?php echo "?id=$id";?>" method="post" name="iform" id="iform"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> -<tr><td> +<tr><td class="tabnavtbl"> <?php $tab_array = array(); - $tabid = 0; - $tab_array[$tabid] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); - $tabid++; - $tab_array[$tabid] = array(gettext("If Settings"), true, "/snort/snort_interfaces_edit.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Servers"), false, "/snort/snort_define_servers.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); + $tab_array[] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); + $tab_array[] = array(gettext("If Settings"), true, "/snort/snort_interfaces_edit.php?id={$id}"); + $tab_array[] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); + $tab_array[] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); + $tab_array[] = array(gettext("Variables"), false, "/snort/snort_define_servers.php?id={$id}"); + $tab_array[] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); + $tab_array[] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); display_top_tabs($tab_array); ?> </td></tr> +<tr><td class="tabcont"> +<table 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 class="tabnavtbl"> + <td width="22%" valign="top" class="vncellreq"><?php echo gettext("Enable"); ?></td> + <td width="78%" valign="top" class="vtable"> <?php - if ($a_nat[$id]['interface'] != '') { - /* get the interface name */ - $snortInterfaces = array(); /* -gtm */ - - $if_list = $config['installedpackages']['snortglobal']['rule'][$id]['interface']; - $if_array = split(',', $if_list); - if($if_array) { - foreach($if_array as $iface2) { - /* build a list of user specified interfaces -gtm */ - $if2 = snort_get_real_interface($iface2); - if ($if2) - array_push($snortInterfaces, $if2); - } - - if (count($snortInterfaces) < 1) - log_error("Snort will not start. You must select an interface for it to listen on."); - } - - } + if ($pconfig['enable'] == "on") + $checked = "checked"; + echo " + <input name=\"enable\" type=\"checkbox\" value=\"on\" $checked onClick=\"enable_change(false)\"> + " . gettext("Enable or Disable") . "\n"; ?> + <br/> </td> </tr> <tr> - <td class="tabcont"> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> - <tr> - <td colspan="2" valign="top" class="listtopic">General Settings</td> - </tr> - <tr> - <td width="22%" valign="top" class="vncellreq2">Enable</td> - <td width="22%" valign="top" class="vtable"> <?php - // <input name="enable" type="checkbox" value="yes" checked onClick="enable_change(false)"> - // care with spaces - if ($pconfig['enable'] == "on") - $checked = checked; - - $onclick_enable = "onClick=\"enable_change(false)\">"; - - echo " - <input name=\"enable\" type=\"checkbox\" value=\"on\" $checked $onclick_enable - Enable or Disable</td>\n\n"; - ?></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncellreq2">Interface</td> - <td width="78%" class="vtable"> - <select name="interface" class="formfld"> - <?php - if (function_exists('get_configured_interface_with_descr')) - $interfaces = get_configured_interface_with_descr(); - else { - $interfaces = array('wan' => 'WAN', 'lan' => 'LAN'); - for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++) { - $interfaces['opt' . $i] = $config['interfaces']['opt' . $i]['descr']; - } - } - foreach ($interfaces as $iface => $ifacename): ?> - <option value="<?=$iface;?>" - <?php if ($iface == $pconfig['interface']) echo "selected"; ?>><?=htmlspecialchars($ifacename);?> - </option> - <?php endforeach; ?> - </select><br> - <span class="vexpl">Choose which interface this rule applies to.<br> - Hint: in most cases, you'll want to use WAN here.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncellreq2">Description</td> + <td width="22%" valign="top" class="vncellreq"><?php echo gettext("Interface"); ?></td> + <td width="78%" class="vtable"> + <select name="interface" class="formselect"> + <?php + if (function_exists('get_configured_interface_with_descr')) + $interfaces = get_configured_interface_with_descr(); + else { + $interfaces = array('wan' => 'WAN', 'lan' => 'LAN'); + for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++) { + $interfaces['opt' . $i] = $config['interfaces']['opt' . $i]['descr']; + } + } + foreach ($interfaces as $iface => $ifacename): ?> + <option value="<?=$iface;?>" + <?php if ($iface == $pconfig['interface']) echo "selected"; ?>><?=htmlspecialchars($ifacename);?> + </option> + <?php endforeach; ?> + </select><br> + <span class="vexpl"><?php echo gettext("Choose which interface this rule applies to."); ?><br/> + <b><?php echo gettext("Hint:"); ?> </b><?php echo gettext("in most cases, you'll want to use WAN here."); ?></span><br/><br/></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncellreq"><?php echo gettext("Description"); ?></td> <td width="78%" class="vtable"><input name="descr" type="text" class="formfld" id="descr" size="40" - value="<?=htmlspecialchars($pconfig['descr']);?>"> <br> - <span class="vexpl">You may enter a description here for your - reference (not parsed).</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Memory Performance</td> - <td width="78%" class="vtable"><select name="performance" - class="formfld" id="performance"> + value="<?=htmlspecialchars($pconfig['descr']);?>"> <br/> + <span class="vexpl"><?php echo gettext("You may enter a description here for your " . + "reference (not parsed)."); ?></span><br/><br/></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Memory Performance"); ?></td> + <td width="78%" class="vtable"> + <select name="performance" class="formselect" id="performance"> <?php $interfaces2 = array('ac-bnfa' => 'AC-BNFA', 'lowmem' => 'LOWMEM', 'ac-std' => 'AC-STD', 'ac' => 'AC', 'ac-banded' => 'AC-BANDED', 'ac-sparsebands' => 'AC-SPARSEBANDS', 'acs' => 'ACS'); foreach ($interfaces2 as $iface2 => $ifacename2): ?> @@ -508,91 +254,87 @@ function enable_change(enable_change) { <?=htmlspecialchars($ifacename2);?></option> <?php endforeach; ?> </select><br> - <span class="vexpl">Lowmem and ac-bnfa are recommended for low end - systems, Ac: high memory, best performance, ac-std: moderate - memory,high performance, acs: small memory, moderateperformance, - ac-banded: small memory,moderate performance, ac-sparsebands: small - memory, high performance.<br> - </span></td> - </tr> - <tr> - <td colspan="2" valign="top" class="listtopic">Choose the networks - snort should inspect and whitelist.</td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Home net</td> - <td width="78%" class="vtable"><select name="homelistname" - class="formfld" id="homelistname"> + <span class="vexpl"><?php echo gettext("Lowmem and ac-bnfa are recommended for low end " . + "systems, Ac: high memory, best performance, ac-std: moderate " . + "memory,high performance, acs: small memory, moderateperformance, " . + "ac-banded: small memory,moderate performance, ac-sparsebands: small " . + "memory, high performance."); ?> + </span><br/></td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Choose the networks " . + "snort should inspect and whitelist."); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Home net"); ?></td> + <td width="78%" class="vtable"> + <select name="homelistname" class="formselect" id="homelistname"> <?php echo "<option value='default' >default</option>"; /* find whitelist names and filter by type */ - if (is_array($config['installedpackages']['snortglobal']['whitelist']['item'])) { - foreach ($config['installedpackages']['snortglobal']['whitelist']['item'] as $value) { - if ($value['snortlisttype'] == 'netlist') { - $ilistname = $value['name']; - if ($ilistname == $pconfig['homelistname']) - echo "<option value='$ilistname' selected>"; - else - echo "<option value='$ilistname'>"; - echo htmlspecialchars($ilistname) . '</option>'; - } + if (is_array($snortglob['whitelist']['item'])) { + foreach ($snortglob['whitelist']['item'] as $value) { + $ilistname = $value['name']; + if ($ilistname == $pconfig['homelistname']) + echo "<option value='$ilistname' selected>"; + else + echo "<option value='$ilistname'>"; + echo htmlspecialchars($ilistname) . '</option>'; } } ?> - </select><br> - <span class="vexpl">Choose the home net you will like this rule to - use. </span> <br/><span class="red">Note:</span> Default home - net adds only local networks.<br> - <span class="red">Hint:</span> Most users add a list of - friendly ips that the firewall cant see.</td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">External net</td> - <td width="78%" class="vtable"><select name="externallistname" - class="formfld" id="externallistname"> + </select><br/> + <span class="vexpl"><?php echo gettext("Choose the home net you will like this rule to " . + "use."); ?> </span><br/> <br/><span class="red"><?php echo gettext("Note:"); ?></span> <?php echo gettext("Default home " . + "net adds only local networks."); ?><br> + <span class="red"><?php echo gettext("Hint:"); ?></span> <?php echo gettext("Most users add a list of " . + "friendly ips that the firewall cant see."); ?><br/></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("External net"); ?></td> + <td width="78%" class="vtable"> + <select name="externallistname" class="formselect" id="externallistname"> <?php echo "<option value='default' >default</option>"; /* find whitelist names and filter by type */ - if (is_array($config['installedpackages']['snortglobal']['whitelist']['item'])) { - foreach ($config['installedpackages']['snortglobal']['whitelist']['item'] as $value) { - if ($value['snortlisttype'] == 'netlist') { - $ilistname = $value['name']; - if ($ilistname == $pconfig['externallistname']) - echo "<option value='$ilistname' selected>"; - else - echo "<option value='$ilistname'>"; - echo htmlspecialchars($ilistname) . '</option>'; - } + if (is_array($snortglob['whitelist']['item'])) { + foreach ($snortglob['whitelist']['item'] as $value) { + $ilistname = $value['name']; + if ($ilistname == $pconfig['externallistname']) + echo "<option value='$ilistname' selected>"; + else + echo "<option value='$ilistname'>"; + echo htmlspecialchars($ilistname) . '</option>'; } } ?> </select><br/> - <span class="vexpl">Choose the external net you will like this rule - to use. </span> <br/><span class="red">Note:</span> Default - external net, networks that are not home net.<br> - <span class="red">Hint:</span> Most users should leave this - setting at default.</td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Block offenders</td> + <span class="vexpl"><?php echo gettext("Choose the external net you will like this rule " . + "to use."); ?> </span> <br/><span class="red"><?php echo gettext("Note:"); ?></span> <?php echo gettext("Default " . + "external net, networks that are not home net."); ?><br/> + <span class="red"><?php echo gettext("Hint:"); ?></span> <?php echo gettext("Most users should leave this " . + "setting at default."); ?><br/></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Block offenders"); ?></td> <td width="78%" class="vtable"> <input name="blockoffenders7" id="blockoffenders7" type="checkbox" value="on" <?php if ($pconfig['blockoffenders7'] == "on") echo "checked"; ?> onClick="enable_blockoffenders()"><br> - Checking this option will automatically block hosts that generate a - Snort alert.</td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Kill states</td> + <?php echo gettext("Checking this option will automatically block hosts that generate a " . + "Snort alert."); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Kill states"); ?></td> <td width="78%" class="vtable"> <input name="blockoffenderskill" id="blockoffenderskill" type="checkbox" value="on" <?php if ($pconfig['blockoffenderskill'] == "on") echo "checked"; ?>> - <br/>Should firewall states be killed for the blocked ip + <br/<?php echo gettext("Should firewall states be killed for the blocked ip"); ?>> </td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Which ip to block</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Which ip to block"); ?></td> <td width="78%" class="vtable"> - <select name="blockoffendersip" class="formfld" id="blockoffendersip"> + <select name="blockoffendersip" class="formselect" id="blockoffendersip"> <?php foreach (array("src", "dst", "both") as $btype) { if ($btype == $pconfig['blockoffendersip']) @@ -603,131 +345,107 @@ function enable_change(enable_change) { } ?> </select> - <br/> Which ip extracted from the packet you want to block + <br/><?php echo gettext("Which ip extracted from the packet you want to block"); ?> </td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Whitelist</td> - <td width="78%" class="vtable"> - <select name="whitelistname" class="formfld" id="whitelistname"> - <?php - /* find whitelist names and filter by type, make sure to track by uuid */ - echo "<option value='default' >default</option>\n"; - if (is_array($config['installedpackages']['snortglobal']['whitelist']['item'])) { - foreach ($config['installedpackages']['snortglobal']['whitelist']['item'] as $value) { - if ($value['snortlisttype'] == 'whitelist') { - if ($value['name'] == $pconfig['whitelistname']) - echo "<option value='{$value['name']}' selected>"; - else - echo "<option value='{$value['name']}'>"; - echo htmlspecialchars($value['name']) . '</option>'; - } - } - } - ?> - </select><br> - <span class="vexpl">Choose the whitelist you will like this rule to - use. </span> <br/><span class="red">Note:</span> Default - whitelist adds only local networks.<br/> - <span class="red">Note:</span> This option will only be used when block offenders is on. - </td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Suppression and - filtering</td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Whitelist"); ?></td> + <td width="78%" class="vtable"> + <select name="whitelistname" class="formselect" id="whitelistname"> + <?php + /* find whitelist names and filter by type, make sure to track by uuid */ + echo "<option value='default' >default</option>\n"; + if (is_array($snortglob['whitelist']['item'])) { + foreach ($snortglob['whitelist']['item'] as $value) { + if ($value['name'] == $pconfig['whitelistname']) + echo "<option value='{$value['name']}' selected>"; + else + echo "<option value='{$value['name']}'>"; + echo htmlspecialchars($value['name']) . '</option>'; + } + } + ?> + </select><br> + <span class="vexpl"><?php echo gettext("Choose the whitelist you will like this rule to " . + "use."); ?> </span><br/> <br/><span class="red"><?php echo gettext("Note:"); ?></span><br/> <?php echo gettext("Default " . + "whitelist adds only local networks."); ?><br/> + <span class="red"><?php echo gettext("Note:"); ?></span><br/> <?php echo gettext("This option will only be used when block offenders is on."); ?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Suppression and filtering"); ?></td> + <td width="78%" class="vtable"> + <select name="suppresslistname" class="formselect" id="suppresslistname"> + <?php + echo "<option value='default' >default</option>\n"; + if (is_array($snortglob['suppress']['item'])) { + $slist_select = $snortglob['suppress']['item']; + foreach ($slist_select as $value) { + $ilistname = $value['name']; + if ($ilistname == $pconfig['suppresslistname']) + echo "<option value='$ilistname' selected>"; + else + echo "<option value='$ilistname'>"; + echo htmlspecialchars($ilistname) . '</option>'; + } + } + ?> + </select><br> + <span class="vexpl"><?php echo gettext("Choose the suppression or filtering file you " . + "will like this rule to use."); ?> </span><br/> <br/><span class="red"><?php echo gettext("Note:"); ?></span><br/> <?php echo gettext("Default " . + "option disables suppression and filtering."); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Checksum checking"); ?></td> <td width="78%" class="vtable"> - <select name="suppresslistname" class="formfld" id="suppresslistname"> - <?php - echo "<option value='default' >default</option>\n"; - if (is_array($config['installedpackages']['snortglobal']['suppress']['item'])) { - $slist_select = $config['installedpackages']['snortglobal']['suppress']['item']; - foreach ($slist_select as $value) { - $ilistname = $value['name']; - if ($ilistname == $pconfig['suppresslistname']) - echo "<option value='$ilistname' selected>"; - else - echo "<option value='$ilistname'>"; - echo htmlspecialchars($ilistname) . '</option>'; - } - } - ?> - </select><br> - <span class="vexpl">Choose the suppression or filtering file you - will like this rule to use. </span> <br/><span class="red">Note:</span> Default - option disables suppression and filtering.</td> - </tr> - - <tr> - <td colspan="2" valign="top" class="listtopic">Choose the types of - logs snort should create.</td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Send alerts to main - System logs</td> - <td width="78%" class="vtable"><input name="alertsystemlog" - type="checkbox" value="on" - <?php if ($pconfig['alertsystemlog'] == "on") echo "checked"; ?> - onClick="enable_change(false)"><br> - Snort will send Alerts to the firewall's system logs.</td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Log to a Tcpdump file</td> - <td width="78%" class="vtable"><input name="tcpdumplog" - type="checkbox" value="on" - <?php if ($pconfig['tcpdumplog'] == "on") echo "checked"; ?> - onClick="enable_change(false)"><br> - Snort will log packets to a tcpdump-formatted file. The file then - can be analyzed by an application such as Wireshark which - understands pcap file formats. <span class="red"><strong>WARNING:</strong></span> - File may become large.</td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Log Alerts to a snort - unified2 file</td> - <td width="78%" class="vtable"><input name="snortunifiedlog" - type="checkbox" value="on" - <?php if ($pconfig['snortunifiedlog'] == "on") echo "checked"; ?> - onClick="enable_change(false)"><br> - Snort will log Alerts to a file in the UNIFIED2 format. This is a - requirement for barnyard2.</td> - </tr> - <tr> - <td colspan="2" valign="top" class="listtopic">Arguments here will - be automatically inserted into the snort configuration.</td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Advanced configuration - pass through</td> - <td width="78%" class="vtable"><textarea wrap="off" - name="configpassthru" cols="75" rows="12" id="configpassthru" - class="formpre2"><?=htmlspecialchars($pconfig['configpassthru']);?></textarea> + <input name="cksumcheck" id="cksumcheck" type="checkbox" value="on" <?php if ($pconfig['cksumcheck'] == "on") echo "checked"; ?>> + <br/<?php echo gettext("If ticked checksum checking on snort will be disabled to improve performance."); ?>> + <br/<?php echo gettext("Most of this is already done on the firewall/filter level"); ?>> </td> - </tr> - <tr> - <td width="22%" valign="top"></td> - <td width="78%"><input name="Submit" type="submit" class="formbtn" value="Save"> - <?php if (isset($id) && $a_nat[$id]): ?> - <input name="id" type="hidden" value="<?=$id;?>"> - <?php endif; ?></td> - </tr> - <tr> - <td width="22%" valign="top"> </td> - <td width="78%"><span class="vexpl"><span class="red"><strong>Note:</strong></span> - <br> - Please save your settings before you click start. </td> - </tr> - </table> - + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Send alerts to main " . + "lSystem logs"); ?></td> + <td width="78%" class="vtable"><input name="alertsystemlog" + type="checkbox" value="on" + <?php if ($pconfig['alertsystemlog'] == "on") echo "checked"; ?> + onClick="enable_change(false)"><br> + <?php echo gettext("Snort will send Alerts to the firewall's system logs."); ?></td> + </tr> +<tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Arguments here will " . + "be automatically inserted into the snort configuration."); ?></td> +</tr> +<tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Advanced configuration pass through"); ?></td> + <td width="78%" class="vtable"> + <textarea wrap="off" name="configpassthru" cols="65" rows="12" id="configpassthru"><?=htmlspecialchars($pconfig['configpassthru']);?></textarea> + + </td> +</tr> +<tr> + <td width="22%" valign="top"></td> + <td width="78%"><input name="Submit" type="submit" class="formbtn" value="Save"> + <input name="id" type="hidden" value="<?=$id;?>"> + </td> +</tr> +<tr> + <td width="22%" valign="top"> </td> + <td width="78%"><span class="vexpl"><span class="red"><strong><?php echo gettext("Note:"); ?></strong></span><br/> + <br> + <?php echo gettext("Please save your settings before you click start."); ?> + </td> +</tr> +</table> +</td></tr> </table> </form> - <script language="JavaScript"> <!-- enable_change(false); enable_blockoffenders(); //--> </script> - <?php include("fend.inc"); ?> </body> </html> diff --git a/config/snort/snort_interfaces_global.php b/config/snort/snort_interfaces_global.php index a267f561..eb371119 100644 --- a/config/snort/snort_interfaces_global.php +++ b/config/snort/snort_interfaces_global.php @@ -1,46 +1,45 @@ <?php /* - snort_interfaces_global.php - part of m0n0wall (http://m0n0.ch/wall) - - Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. - Copyright (C) 2011 Ermal Luci - All rights reserved. - - Copyright (C) 2008-2009 Robert Zelaya - Modified for the Pfsense snort package. - 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. + * snort_interfaces_global.php + * part of pfSense + * + * Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + * Copyright (C) 2011-2012 Ermal Luci + * All rights reserved. + * + * Copyright (C) 2008-2009 Robert Zelaya + * Modified for the Pfsense snort package. + * 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_gui.inc"); require_once("/usr/local/pkg/snort/snort.inc"); global $g; -$d_snort_global_dirty_path = '/var/run/snort_global.dirty'; +$snortdir = SNORTDIR; /* make things short */ $pconfig['snortdownload'] = $config['installedpackages']['snortglobal']['snortdownload']; @@ -50,7 +49,6 @@ $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['snortalertlogtype'] = $config['installedpackages']['snortglobal']['snortalertlogtype']; $pconfig['forcekeepsettings'] = $config['installedpackages']['snortglobal']['forcekeepsettings']; /* if no errors move foward */ @@ -73,33 +71,10 @@ if (!$input_errors) { $config['installedpackages']['snortglobal']['snortloglimitsize'] = $snortloglimitDSKsize; } $config['installedpackages']['snortglobal']['autorulesupdate7'] = $_POST['autorulesupdate7']; - $config['installedpackages']['snortglobal']['snortalertlogtype'] = $_POST['snortalertlogtype']; $config['installedpackages']['snortglobal']['forcekeepsettings'] = $_POST['forcekeepsettings'] ? 'on' : 'off'; $retval = 0; - $snort_snortloglimit_info_ck = $config['installedpackages']['snortglobal']['snortloglimit']; - snort_snortloglimit_install_cron($snort_snortloglimit_info_ck == 'ok' ? true : false); - - /* set the snort block hosts time IMPORTANT */ - $snort_rm_blocked_info_ck = $config['installedpackages']['snortglobal']['rm_blocked']; - if ($snort_rm_blocked_info_ck == "never_b") - $snort_rm_blocked_false = false; - else - $snort_rm_blocked_false = true; - - snort_rm_blocked_install_cron($snort_rm_blocked_false); - - /* set the snort rules update time */ - $snort_rules_up_info_ck = $config['installedpackages']['snortglobal']['autorulesupdate7']; - if ($snort_rules_up_info_ck == "never_up") - $snort_rules_up_false = false; - else - $snort_rules_up_false = true; - - snort_rules_up_install_cron($snort_rules_up_false); - - configure_cron(); write_config(); /* create whitelist and homenet file then sync files */ @@ -116,71 +91,6 @@ if (!$input_errors) { } } - -if ($_POST["Reset"]) { - - function snort_deinstall_settings() { - global $config, $g, $id, $if_real; - - exec("/usr/usr/bin/killall snort"); - sleep(2); - exec("/usr/usr/bin/killall -9 snort"); - sleep(2); - exec("/usr/usr/bin/killall barnyard2"); - sleep(2); - exec("/usr/usr/bin/killall -9 barnyard2"); - sleep(2); - - /* Remove snort cron entries Ugly code needs smoothness*/ - if (!function_exists('snort_deinstall_cron')) { - function snort_deinstall_cron($cronmatch) { - global $config, $g; - - - if(!$config['cron']['item']) - return; - - $x=0; - $is_installed = false; - foreach($config['cron']['item'] as $item) { - if (strstr($item['command'], $cronmatch)) { - $is_installed = true; - break; - } - $x++; - } - if($is_installed == true) - unset($config['cron']['item'][$x]); - - configure_cron(); - } - } - - snort_deinstall_cron("snort2c"); - snort_deinstall_cron("snort_check_for_rule_updates.php"); - - - /* Unset snort registers in conf.xml IMPORTANT snort will not start with out this */ - /* Keep this as a last step */ - unset($config['installedpackages']['snortglobal']); - - /* remove all snort iface dir */ - exec('rm -r /usr/local/etc/snort/snort_*'); - exec('rm /var/log/snort/*'); - } - - snort_deinstall_settings(); - write_config(); /* XXX */ - - 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_global.php"); - exit; -} - $pgtitle = 'Services: Snort: Global Settings'; include_once("head.inc"); @@ -189,40 +99,20 @@ include_once("head.inc"); <body link="#000000" vlink="#000000" alink="#000000"> <?php -echo "{$snort_general_css}\n"; -echo "$snort_interfaces_css\n"; - include_once("fbegin.inc"); if($pfsense_stable == 'yes') echo '<p class="pgtitle">' . $pgtitle . '</p>'; -?> -<noscript> -<div class="alert" ALIGN=CENTER><img - src="../themes/<?php echo $g['theme']; ?>/images/icons/icon_alert.gif" /><strong>Please -enable JavaScript to view this content -</CENTER></div> -</noscript> +/* Display Alert message, under form tag or no refresh */ +if ($input_errors) + print_input_errors($input_errors); // TODO: add checks -<form action="snort_interfaces_global.php" method="post" enctype="multipart/form-data" name="iform" id="iform"> -<?php - /* Display Alert message, under form tag or no refresh */ - if ($input_errors) - print_input_errors($input_errors); // TODO: add checks - - if (!$input_errors) { - if (file_exists($d_snort_global_dirty_path)) { - print_info_box_np2(' - The Snort configuration has changed and snort needs to be restarted on this interface.<br> - You must apply the changes in order for them to take effect.<br> - '); - } - } ?> +<form action="snort_interfaces_global.php" method="post" enctype="multipart/form-data" name="iform" id="iform"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> -<tr><td> +<tr><td class="tabnavtbl"> <?php $tab_array = array(); $tab_array[0] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); @@ -232,206 +122,170 @@ enable JavaScript to view this content $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); - $tab_array[7] = array(gettext("Help"), false, "/snort/help_and_info.php"); display_top_tabs($tab_array); ?> </td></tr> <tr> <td class="tabcont"> - <table id="maintable2" width="100%" border="0" cellpadding="6" - cellspacing="0"> - <tr> - <tr> - <td colspan="2" valign="top" class="listtopic">Please Choose The - Type Of Rules You Wish To Download</td> - </tr> - <td width="22%" valign="top" class="vncell2">Install Snort.org rules</td> - <td width="78%" class="vtable"> - <table cellpadding="0" cellspacing="0"> - <tr> - <td colspan="2"><input name="snortdownload" type="radio" - id="snortdownload" value="off" onClick="enable_change(false)" - <?php if($pconfig['snortdownload']=='off' || $pconfig['snortdownload']=='') echo 'checked'; ?>> - Do <strong>NOT</strong> Install</td> - </tr> - <tr> - <td colspan="2"><input name="snortdownload" type="radio" - id="snortdownload" value="on" onClick="enable_change(false)" - <?php if($pconfig['snortdownload']=='on') echo 'checked'; ?>> Install - Basic Rules or Premium rules <br> - <a - href="https://www.snort.org/signup" target="_blank">Sign Up for a - Basic Rule Account</a><br> - <a - href="http://www.snort.org/vrt/buy-a-subscription" - target="_blank">Sign Up for Sourcefire VRT Certified Premium - Rules. This Is Highly Recommended</a></td> - </tr> - <tr> - <td> </td> - </tr> - </table> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> - <tr> - <td colspan="2" valign="top" class="optsect_t2">Oinkmaster code</td> - </tr> - <tr> - <td class="vncell2" valign="top">Code</td> - <td class="vtable"><input name="oinkmastercode" type="text" - class="formfld" id="oinkmastercode" size="52" - value="<?=htmlspecialchars($pconfig['oinkmastercode']);?>"><br> - Obtain a snort.org Oinkmaster code and paste here.</td> - - </table> - - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Install <strong>Emergingthreats</strong> - rules</td> - <td width="78%" class="vtable"><input name="emergingthreats" - type="checkbox" value="yes" - <?php if ($config['installedpackages']['snortglobal']['emergingthreats']=="on") echo "checked"; ?> - onClick="enable_change(false)"><br> - Emerging Threats is an open source community that produces fastest - moving and diverse Snort Rules.</td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Update rules - automatically</td> - <td width="78%" class="vtable"><select name="autorulesupdate7" - class="formfld" id="autorulesupdate7"> - <?php - $interfaces3 = array('never_up' => 'NEVER', '6h_up' => '6 HOURS', '12h_up' => '12 HOURS', '1d_up' => '1 DAY', '4d_up' => '4 DAYS', '7d_up' => '7 DAYS', '28d_up' => '28 DAYS'); - foreach ($interfaces3 as $iface3 => $ifacename3): ?> - <option value="<?=$iface3;?>" - <?php if ($iface3 == $pconfig['autorulesupdate7']) echo "selected"; ?>> - <?=htmlspecialchars($ifacename3);?></option> - <?php endforeach; ?> - </select><br> - <span class="vexpl">Please select the update times for rules.<br> - Hint: in most cases, every 12 hours is a good choice.</span></td> - </tr> - <tr> - <td colspan="2" valign="top" class="listtopic">General Settings</td> - </tr> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> +<tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Please Choose The " . + "Type Of Rules You Wish To Download"); ?></td> +</tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Install Snort.org rules"); ?></td> + <td width="78%" class="vtable"> + <table cellpadding="0" cellspacing="0"> + <tr> + <td colspan="2"><input name="snortdownload" type="radio" + id="snortdownload" value="off" +<?php if($pconfig['snortdownload']=='off' || $pconfig['snortdownload']=='') echo 'checked'; ?>> + <?php printf(gettext("Do %sNOT%s Install"), '<strong>', '</strong>'); ?></td> + </tr> + <tr> + <td colspan="2"><input name="snortdownload" type="radio" + id="snortdownload" value="on" + <?php if($pconfig['snortdownload']=='on') echo 'checked'; ?>> <?php echo gettext("Install " . + "Basic Rules or Premium rules"); ?> <br> + <a + href="https://www.snort.org/signup" target="_blank"><?php echo gettext("Sign Up for a " . + "Basic Rule Account"); ?></a><br> + <a + href="http://www.snort.org/vrt/buy-a-subscription" + target="_blank"><?php echo gettext("Sign Up for Sourcefire VRT Certified Premium " . + "Rules. This Is Highly Recommended"); ?></a></td> + </tr> + <tr> + <td> </td> + </tr> + </table> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <tr> + <td colspan="2" valign="top" class="optsect_t2"><?php echo gettext("Oinkmaster code"); ?></td> + </tr> + <tr> + <td class="vncell" valign="top"><?php echo gettext("Code"); ?></td> + <td class="vtable"><input name="oinkmastercode" type="text" + class="formfld" id="oinkmastercode" size="52" + value="<?=htmlspecialchars($pconfig['oinkmastercode']);?>"><br> + <?php echo gettext("Obtain a snort.org Oinkmaster code and paste here."); ?></td> + + </table> + +</tr> +<tr> + <td width="22%" valign="top" class="vncell"><?php printf(gettext("Install %sEmergingthreats%s " . + "rules"), '<strong>' , '</strong>'); ?></td> + <td width="78%" class="vtable"><input name="emergingthreats" + type="checkbox" value="yes" + <?php if ($config['installedpackages']['snortglobal']['emergingthreats']=="on") echo "checked"; ?> + ><br> + <?php echo gettext("Emerging Threats is an open source community that produces fastest " . + "moving and diverse Snort Rules."); ?></td> +</tr> +<tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Update rules " . + "automatically"); ?></td> + <td width="78%" class="vtable"> + <select name="autorulesupdate7" class="formselect" id="autorulesupdate7"> + <?php + $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"; ?>> + <?=htmlspecialchars($ifacename3);?></option> + <?php endforeach; ?> + </select><br> + <span class="vexpl"><?php echo gettext("Please select the update times for rules."); ?><br> + <?php echo gettext("Hint: in most cases, every 12 hours is a good choice."); ?></span></td> +</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="vncell2">Log Directory Size - Limit<br> - <br> - <br> - <br> - <br> - <br> - <span class="red"><strong>Note</span>:</strong><br> - 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" onClick="enable_change(false)" - <?php if($pconfig['snortloglimit']=='on') echo 'checked'; ?>> - <strong>Enable</strong> directory size limit (<strong>Default</strong>)</td> - </tr> - <tr> - <td colspan="2"><input name="snortloglimit" type="radio" - id="snortloglimit" value="off" onClick="enable_change(false)" - <?php if($pconfig['snortloglimit']=='off') echo 'checked'; ?>> <strong>Disable</strong> - directory size limit<br> - <br> - <span class="red"><strong>Warning</span>:</strong> Nanobsd - should use no more than 10MB of space.</td> - </tr> - <tr> - <td> </td> - </tr> - </table> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> - <tr> - <td class="vncell3">Size in <strong>MB</strong></td> - <td class="vtable"><input name="snortloglimitsize" type="text" - class="formfld" id="snortloglimitsize" size="7" - value="<?=htmlspecialchars($pconfig['snortloglimitsize']);?>"> - Default is <strong>20%</strong> of available space.</td> - - </table> - - </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/> + <span class="red"><strong><?php echo gettext("Note"); ?></span>:</strong><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'; ?>> + <strong><?php echo gettext("Enable"); ?></strong> <?php echo gettext("directory size limit"); ?> (<strong><?php echo gettext("Default"); ?></strong>)</td> + </tr> + <tr> + <td colspan="2"><input name="snortloglimit" type="radio" + id="snortloglimit" value="off" +<?php if($pconfig['snortloglimit']=='off') echo 'checked'; ?>> <strong><?php echo gettext("Disable"); ?></strong> + <?php echo gettext("directory size limit"); ?><br> + <br> + <span class="red"><strong><?php echo gettext("Warning"); ?></span>:</strong> <?php echo gettext("Nanobsd " . + "should use no more than 10MB of space."); ?></td> + </tr> + <tr> + <td> </td> + </tr> + </table> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <tr> + <td class="vncell3"><?php echo gettext("Size in"); ?> <strong>MB</strong></td> + <td class="vtable"><input name="snortloglimitsize" type="text" + class="formfld" id="snortloglimitsize" size="7" + value="<?=htmlspecialchars($pconfig['snortloglimitsize']);?>"> + <?php echo gettext("Default is"); ?> <strong>20%</strong> <?php echo gettext("of available space."); ?></td> + + </table> + +</tr> - <tr> - <td width="22%" valign="top" class="vncell2">Remove blocked hosts - every</td> - <td width="78%" class="vtable"><select name="rm_blocked" - class="formfld" id="rm_blocked"> - <?php - $interfaces3 = array('never_b' => 'NEVER', '1h_b' => '1 HOUR', '3h_b' => '3 HOURS', '6h_b' => '6 HOURS', '12h_b' => '12 HOURS', '1d_b' => '1 DAY', '4d_b' => '4 DAYS', '7d_b' => '7 DAYS', '28d_b' => '28 DAYS'); - foreach ($interfaces3 as $iface3 => $ifacename3): ?> - <option value="<?=$iface3;?>" - <?php if ($iface3 == $pconfig['rm_blocked']) echo "selected"; ?>> - <?=htmlspecialchars($ifacename3);?></option> - <?php endforeach; ?> - </select><br> - <span class="vexpl">Please select the amount of time you would like - hosts to be blocked for.<br> - Hint: in most cases, 1 hour is a good choice.</span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Alerts file description - type</td> - <td width="78%" class="vtable"><select name="snortalertlogtype" - class="formfld" id="snortalertlogtype"> - <?php - $interfaces4 = array('full' => 'FULL', 'fast' => 'SHORT'); - foreach ($interfaces4 as $iface4 => $ifacename4): ?> - <option value="<?=$iface4;?>" - <?php if ($iface4 == $pconfig['snortalertlogtype']) echo "selected"; ?>> - <?=htmlspecialchars($ifacename4);?></option> - <?php endforeach; ?> - </select><br> - <span class="vexpl">Please choose the type of Alert logging you will - like see in your alert file.<br> - Hint: Best pratice is to chose full logging.</span> <span - class="red"><strong>WARNING:</strong></span> <strong>On - change, alert file will be cleared.</strong></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">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"; ?> - onClick="enable_change(false)"><br> - Settings will not be removed during deinstall.</td> - </tr> - <tr> - <td width="22%" valign="top"><input name="Reset" type="submit" - class="formbtn" value="Reset" - onclick="return confirm('Do you really want to delete all global and interface settings?')"><span - class="red"><strong> WARNING:</strong><br> - This will reset all global and interface settings.</span></td> - <td width="78%"><input name="Submit" type="submit" class="formbtn" - value="Save" onClick="enable_change(true)"> - </td> - </tr> - <tr> - <td width="22%" valign="top"> </td> - <td width="78%"><span class="vexpl"><span class="red"><strong>Note:<br> - </strong></span> Changing any settings on this page will affect all - interfaces. Please, double check if your oink code is correct and - the type of snort.org account you hold.</span></td> - </tr> - </table> - </td> - </tr> +<tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Remove blocked hosts " . + "every"); ?></td> + <td width="78%" class="vtable"> + <select name="rm_blocked" class="formselect" id="rm_blocked"> + <?php + $interfaces3 = array('never_b' => gettext('NEVER'), '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"; ?>> + <?=htmlspecialchars($ifacename3);?></option> + <?php endforeach; ?> + </select><br> + <span class="vexpl"><?php echo gettext("Please select the amount of time you would like " . + "hosts to be blocked for."); ?><br> + <?php echo gettext("Hint: in most cases, 1 hour is a good choice."); ?></span></td> +</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"; ?> + ><br> + <?php echo gettext("Settings will not be removed during deinstall."); ?></td> +</tr> +<tr> + <td width="22%" valign="top"> + <td width="78%"> + <input name="Submit" type="submit" class="formbtn" value="Save" > + </td> +</tr> +<tr> + <td width="22%" valign="top"> </td> + <td width="78%"><span class="vexpl"><span class="red"><strong><?php echo gettext("Note:"); ?><br> + </strong></span> <?php echo gettext("Changing any settings on this page will affect all " . + "interfaces. Please, double check if your oink code is correct and " . + "the type of snort.org account you hold."); ?></span></td> +</tr> + </table> +</td></tr> </table> </form> - -</div> - - <?php include("fend.inc"); ?> - - <?php echo "$snort_custom_rnd_box\n"; ?> - +<?php include("fend.inc"); ?> </body> </html> diff --git a/config/snort/snort_interfaces_suppress.php b/config/snort/snort_interfaces_suppress.php index 4eeed42d..93d3f2dc 100644 --- a/config/snort/snort_interfaces_suppress.php +++ b/config/snort/snort_interfaces_suppress.php @@ -1,45 +1,42 @@ <?php -/* $Id$ */ /* - Copyright (C) 2004 Scott Ullrich - Copyright (C) 2011 Ermal Luci - All rights reserved. - - originially part of m0n0wall (http://m0n0.ch/wall) - Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. - All rights reserved. - - modified for the pfsense snort package - Copyright (C) 2009-2010 Robert Zelaya. - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. + * Copyright (C) 2004 Scott Ullrich + * Copyright (C) 2011-2012 Ermal Luci + * All rights reserved. + * + * originially part of m0n0wall (http://m0n0.ch/wall) + * Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + * All rights reserved. + * + * modified for the pfsense snort package + * Copyright (C) 2009-2010 Robert Zelaya. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. */ require_once("guiconfig.inc"); -require_once("/usr/local/pkg/snort/snort_gui.inc"); require_once("/usr/local/pkg/snort/snort.inc"); - if (!is_array($config['installedpackages']['snortglobal']['suppress'])) $config['installedpackages']['snortglobal']['suppress'] = array(); if (!is_array($config['installedpackages']['snortglobal']['suppress']['item'])) @@ -47,15 +44,12 @@ if (!is_array($config['installedpackages']['snortglobal']['suppress']['item'])) $a_suppress = &$config['installedpackages']['snortglobal']['suppress']['item']; $id_gen = count($config['installedpackages']['snortglobal']['suppress']['item']); -$d_suppresslistdirty_path = '/var/run/snort_suppress.dirty'; - if ($_GET['act'] == "del") { if ($a_suppress[$_GET['id']]) { /* make sure rule is not being referenced by any nat or filter rules */ unset($a_suppress[$_GET['id']]); write_config(); - filter_configure(); header("Location: /snort/snort_interfaces_suppress.php"); exit; } @@ -70,16 +64,10 @@ include_once("head.inc"); <?php include_once("fbegin.inc"); -echo $snort_general_css; +if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';} ?> -<div class="body2"><?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> - <form action="/snort/snort_interfaces_suppress.php" method="post"><?php if ($savemsg) print_info_box($savemsg); ?> -<?php if (file_exists($d_suppresslistdirty_path)): ?> -<p><?php print_info_box_np("The white list has been changed.<br>You must apply the changes in order for them to take effect.");?> -<?php endif; ?> - <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr><td> <?php @@ -91,81 +79,69 @@ echo $snort_general_css; $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); $tab_array[5] = array(gettext("Whitelists"), false, "/snort/snort_interfaces_whitelist.php"); $tab_array[6] = array(gettext("Suppress"), true, "/snort/snort_interfaces_suppress.php"); - $tab_array[7] = array(gettext("Help"), false, "/snort/help_and_info.php"); display_top_tabs($tab_array); ?> - </td> - </tr> - <tr> - <td class="tabcont"> - - <table width="100%" border="0" cellpadding="0" cellspacing="0"> - - <tr> - <td width="30%" class="listhdrr">File Name</td> - <td width="70%" class="listhdr">Description</td> - - <td width="10%" class="list"></td> - </tr> - <?php $i = 0; foreach ($a_suppress as $list): ?> - <tr> - <td class="listlr" - ondblclick="document.location='snort_interfaces_suppress_edit.php?id=<?=$i;?>';"> - <?=htmlspecialchars($list['name']);?></td> - <td class="listbg" - ondblclick="document.location='snort_interfaces_suppress_edit.php?id=<?=$i;?>';"> - <font color="#FFFFFF"> <?=htmlspecialchars($list['descr']);?> - </td> - - <td valign="middle" nowrap class="list"> - <table border="0" cellspacing="0" cellpadding="1"> - <tr> - <td valign="middle"><a - href="snort_interfaces_suppress_edit.php?id=<?=$i;?>"><img - src="/themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" - width="17" height="17" border="0" title="edit whitelist"></a></td> - <td><a - href="/snort/snort_interfaces_suppress.php?act=del&id=<?=$i;?>" - onclick="return confirm('Do you really want to delete this whitelist? All elements that still use it will become invalid (e.g. snort rules will fall back to the default whitelist)!')"><img - src="/themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" - width="17" height="17" border="0" title="delete whitelist"></a></td> - </tr> - </table> - </td> - </tr> - <?php $i++; endforeach; ?> - <tr> - <td class="list" colspan="2"></td> - <td class="list"> - <table border="0" cellspacing="0" cellpadding="1"> - <tr> - <td valign="middle" width="17"> </td> - <td valign="middle"><a - href="snort_interfaces_suppress_edit.php?id=<?php echo $id_gen;?> "><img - src="/themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" - width="17" height="17" border="0" title="add a new list"></a></td> - </tr> - </table> - </td> - </tr> - </table> - </td> - </tr> +</td> +</tr> +<tr><td class="tabcont"> +<table width="100%" border="0" cellpadding="0" cellspacing="0"> +<tr> + <td width="30%" class="listhdrr"><?php echo gettext("File Name"); ?></td> + <td width="60%" class="listhdr"><?php echo gettext("Description"); ?></td> + <td width="10%" class="list"></td> +</tr> +<?php $i = 0; foreach ($a_suppress as $list): ?> +<tr> + <td class="listlr" + ondblclick="document.location='snort_interfaces_suppress_edit.php?id=<?=$i;?>';"> + <?=htmlspecialchars($list['name']);?></td> + <td class="listbg" + ondblclick="document.location='snort_interfaces_suppress_edit.php?id=<?=$i;?>';"> + <font color="#FFFFFF"> <?=htmlspecialchars($list['descr']);?> + </td> + + <td valign="middle" nowrap class="list"> + <table border="0" cellspacing="0" cellpadding="1"> + <tr> + <td valign="middle"><a + href="snort_interfaces_suppress_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 whitelist"); ?>"></a></td> + <td><a + href="/snort/snort_interfaces_suppress.php?act=del&id=<?=$i;?>" + onclick="return confirm('<?php echo gettext("Do you really want to delete this whitelist? All elements that still use it will become invalid (e.g. snort rules will fall back to the default whitelist)!"); ?>')"><img + src="/themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" + width="17" height="17" border="0" title="<?php echo gettext("delete whitelist"); ?>"></a></td> + </tr> + </table> + </td> +</tr> +<?php $i++; endforeach; ?> +<tr> + <td class="list" colspan="2"></td> + <td class="list"> + <table border="0" cellspacing="0" cellpadding="1"> + <tr> + <td valign="middle" width="17"> </td> + <td valign="middle"><a + href="snort_interfaces_suppress_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 a new list"); ?>"></a></td> + </tr> + </table> + </td> +</tr> </table> -<br> -<table class="tabcont" width="100%" border="0" cellpadding="0" - cellspacing="0"> - <td width="100%"><span class="vexpl"><span class="red"><strong>Note:</strong></span> - <p><span class="vexpl">Here you can create event filtering and - suppression for your snort package rules.<br> - Please note that you must restart a running rule so that changes can - take effect.</span></p></td> +</td></tr> +<tr> + <td colspan="3" width="100%"><span class="vexpl"><span class="red"><strong><?php echo gettext("Note:"); ?></strong></span> + <p><span class="vexpl"><?php echo gettext("Here you can create event filtering and " . + "suppression for your snort package rules."); ?><br> + <?php echo gettext("Please note that you must restart a running rule so that changes can " . + "take effect."); ?></span></p></td> +</tr> </table> - </form> - -</div> - <?php include("fend.inc"); ?> </body> </html> diff --git a/config/snort/snort_interfaces_suppress_edit.php b/config/snort/snort_interfaces_suppress_edit.php index 7303349f..782b9784 100644 --- a/config/snort/snort_interfaces_suppress_edit.php +++ b/config/snort/snort_interfaces_suppress_edit.php @@ -1,44 +1,47 @@ <?php -/* $Id$ */ /* - firewall_aliases_edit.php - Copyright (C) 2004 Scott Ullrich - All rights reserved. - - originially part of m0n0wall (http://m0n0.ch/wall) - Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. - All rights reserved. - - modified for the pfsense snort package - Copyright (C) 2009-2010 Robert Zelaya. - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. + * snort_interfaces_suppress_edit.php + * Copyright (C) 2004 Scott Ullrich + * All rights reserved. + * + * originially part of m0n0wall (http://m0n0.ch/wall) + * Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + * All rights reserved. + * + * modified for the pfsense snort package + * Copyright (C) 2009-2010 Robert Zelaya. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. */ require_once("guiconfig.inc"); -require_once("/usr/local/pkg/snort/snort_gui.inc"); require_once("/usr/local/pkg/snort/snort.inc"); + +if (!is_array($config['installedpackages']['snortglobal'])) + $config['installedpackages']['snortglobal'] = array(); +$snortglob = $config['installedpackages']['snortglobal']; + if (!is_array($config['installedpackages']['snortglobal']['suppress'])) $config['installedpackages']['snortglobal']['suppress'] = array(); if (!is_array($config['installedpackages']['snortglobal']['suppress']['item'])) @@ -48,25 +51,7 @@ $a_suppress = &$config['installedpackages']['snortglobal']['suppress']['item']; $id = $_GET['id']; if (isset($_POST['id'])) $id = $_POST['id']; -if (!is_numeric($id)) - $id = 0; // XXX: safety belt - - -/* gen uuid for each iface */ -if (is_array($config['installedpackages']['snortglobal']['suppress']['item'][$id])) { - if ($config['installedpackages']['snortglobal']['suppress']['item'][$id]['uuid'] == '') { - //$snort_uuid = gen_snort_uuid(strrev(uniqid(true))); - $suppress_uuid = 0; - while ($suppress_uuid > 65535 || $suppress_uuid == 0) { - $suppress_uuid = mt_rand(1, 65535); - $pconfig['uuid'] = $suppress_uuid; - } - } else if ($config['installedpackages']['snortglobal']['suppress']['item'][$id]['uuid'] != '') { - $suppress_uuid = $config['installedpackages']['snortglobal']['suppress']['item'][$id]['uuid']; - } -} -$d_snort_suppress_dirty_path = '/var/run/snort_suppress.dirty'; /* returns true if $name is a valid name for a whitelist file name or ip */ function is_validwhitelistname($name) { @@ -85,27 +70,25 @@ if (isset($id) && $a_suppress[$id]) { $pconfig['name'] = $a_suppress[$id]['name']; $pconfig['uuid'] = $a_suppress[$id]['uuid']; $pconfig['descr'] = $a_suppress[$id]['descr']; - $pconfig['suppresspassthru'] = base64_decode($a_suppress[$id]['suppresspassthru']); + if (!empty($a_suppress[$id]['suppresspassthru'])); + $pconfig['suppresspassthru'] = base64_decode($a_suppress[$id]['suppresspassthru']); + if (empty($a_suppress[$id]['uuid'])) + $pconfig['uuid'] = uniqid(); } if ($_POST['submit']) { - unset($input_errors); $pconfig = $_POST; + $reqdfields = explode(" ", "name"); + $reqdfieldsn = array("Name"); do_input_validation($_POST, $reqdfields, $reqdfieldsn, &$input_errors); if(strtolower($_POST['name']) == "defaultwhitelist") $input_errors[] = "Whitelist file names may not be named defaultwhitelist."; - $x = is_validwhitelistname($_POST['name']); - if (!isset($x)) { - $input_errors[] = "Reserved word used for whitelist file name."; - } else { - if (is_validwhitelistname($_POST['name']) == false) - $input_errors[] = "Whitelist file name may only consist of the characters a-z, A-Z and 0-9 _. Note: No Spaces. Press Cancel to reset."; - } - + if (is_validwhitelistname($_POST['name']) == false) + $input_errors[] = "Whitelist file name may only consist of the characters a-z, A-Z and 0-9 _. Note: No Spaces. Press Cancel to reset."; /* check for name conflicts */ foreach ($a_suppress as $s_list) { @@ -122,9 +105,10 @@ if ($_POST['submit']) { if (!$input_errors) { $s_list = array(); $s_list['name'] = $_POST['name']; - $s_list['uuid'] = $suppress_uuid; + $s_list['uuid'] = uniqid(); $s_list['descr'] = mb_convert_encoding($_POST['descr'],"HTML-ENTITIES","auto"); - $s_list['suppresspassthru'] = base64_encode($_POST['suppresspassthru']); + if ($_POST['suppresspassthru']) + $s_list['suppresspassthru'] = base64_encode($_POST['suppresspassthru']); if (isset($id) && $a_suppress[$id]) $a_suppress[$id] = $s_list; @@ -132,16 +116,14 @@ if ($_POST['submit']) { $a_suppress[] = $s_list; write_config(); - sync_snort_package_config(); header("Location: /snort/snort_interfaces_suppress.php"); exit; } - } -$pgtitle = "Services: Snort: Suppression: Edit $suppress_uuid"; +$pgtitle = "Services: Snort: Suppression: Edit"; include_once("head.inc"); ?> @@ -150,146 +132,85 @@ include_once("head.inc"); <?php include("fbegin.inc"); -echo $snort_general_css; -?> - -<div class="body2"><?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> +if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';} -<?php if ($input_errors) print_input_errors($input_errors); ?> -<div id="inputerrors"></div> - -<form action="/snort/snort_interfaces_suppress_edit.php?id=<?=$id?>" - method="post" name="iform" id="iform"><?php - /* Display Alert message */ - if ($input_errors) { - print_input_errors($input_errors); // TODO: add checks - } - - if ($savemsg) { - print_info_box2($savemsg); - } - - //if (file_exists($d_snortconfdirty_path)) { - if (file_exists($d_snort_suppress_dirty_path)) { - echo '<p>'; - - if($savemsg) { - print_info_box_np2("{$savemsg}"); - }else{ - print_info_box_np2(' - The Snort configuration has changed and snort needs to be restarted on this interface.<br> - You must apply the changes in order for them to take effect.<br> - '); - } - } - ?> +if ($input_errors) print_input_errors($input_errors); +if ($savemsg) + print_info_box($savemsg); +?> +<form action="/snort/snort_interfaces_suppress_edit.php" name="iform" id="iform" method="post"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td class="tabnavtbl"> - - <div class="newtabmenu" style="margin: 1px 0px; width: 775px;"><!-- Tabbed bar code--> - <ul class="newtabmenu"> - <li><a href="/snort/snort_interfaces.php"><span>Snort Interfaces</span></a></li> - <li><a href="/snort/snort_interfaces_global.php"><span>Global - Settings</span></a></li> - <li><a href="/snort/snort_download_updates.php"><span>Updates</span></a></li> - <li><a href="/snort/snort_alerts.php"><span>Alerts</span></a></li> - <li><a href="/snort/snort_blocked.php"><span>Blocked</span></a></li> - <li><a href="/snort/snort_interfaces_whitelist.php"><span>Whitelists</span></a></li> - <li class="newtabmenu_active"><a - href="/snort/snort_interfaces_suppress.php"><span>Suppress</span></a></li> - <li><a class="example8" href="/snort/help_and_info.php"><span>Help</span></a></li> - </ul> - </div> - - </td> - </tr> - - <tr> - <td class="tabcont"> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> +<tr><td class="tabcont"> +<table width="100%" border="0" cellpadding="6" cellspacing="0"> +<tr> + <td colspan="2" class="listtopic">Add the name and description of the file.</td> +</tr> +<tr> + <td width="22%" valign="top" class="vncellreq"><?php echo gettext("Name"); ?></td> + <td width="78%" class="vtable"><input name="name" type="text" id="name" + class="formfld unkown" size="40" value="<?=htmlspecialchars($pconfig['name']);?>" /> <br /> + <span class="vexpl"> <?php echo gettext("The list name may only consist of the " . + "characters a-z, A-Z and 0-9."); ?> <span class="red"><?php echo gettext("Note:"); ?> </span> + <?php echo gettext("No Spaces."); ?> </span></td> +</tr> +<tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Description"); ?></td> + <td width="78%" class="vtable"><input name="descr" type="text" + class="formfld unkown" id="descr" size="40" value="<?=$pconfig['descr'];?>" /> <br /> + <span class="vexpl"> <?php echo gettext("You may enter a description here for your " . + "reference (not parsed)."); ?> </span></td> +</tr> +<tr> + <td colspan="2"> + <div style='background-color: #E0E0E0' id='redbox'> + <table width='100%'> <tr> - <td colspan="2" valign="top" class="listtopic">Add the name and - description of the file.</td> + <td width='8%'> </td> + <td width='70%'><font size="2" color='#FF850A'><b><?php echo gettext("NOTE:"); ?></b></font> + <font color='#000000'> <?php echo gettext("The threshold keyword " . + "is deprecated as of version 2.8.5. Use the event_filter keyword " . + "instead."); ?></font></td> </tr> - <tr> - <td valign="top" class="vncellreq2">Name</td> - <td class="vtable"><input name="name" type="text" id="name" - size="40" value="<?=htmlspecialchars($pconfig['name']);?>" /> <br /> - <span class="vexpl"> The list name may only consist of the - characters a-z, A-Z and 0-9. <span class="red">Note: </span> No - Spaces. </span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Description</td> - <td width="78%" class="vtable"><input name="descr" type="text" - id="descr" size="40" value="<?=$pconfig['descr'];?>" /> <br /> - <span class="vexpl"> You may enter a description here for your - reference (not parsed). </span></td> - </tr> - </table> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> - <table height="32" width="100%"> - <tr> - <td> - <div style='background-color: #E0E0E0' id='redbox'> - <table width='100%'> - <tr> - <td width='8%'> <img - style='vertical-align: middle' - src="/snort/images/icon_excli.png" width="40" height="32"></td> - <td width='70%'><font size="2" color='#FF850A'><b>NOTE:</b></font> - <font size="2" color='#000000'> The threshold keyword - is deprecated as of version 2.8.5. Use the event_filter keyword - instead.</font></td> - </tr> - </table> - </div> - </td> - </tr> - <script type="text/javascript"> - NiftyCheck(); - Rounded("div#redbox","all","#FFF","#E0E0E0","smooth"); - Rounded("td#blackbox","all","#FFF","#000000","smooth"); - </script> - <tr> - <td colspan="2" valign="top" class="listtopic">Apply suppression or - filters to rules. Valid keywords are 'suppress', 'event_filter' and - 'rate_filter'.</td> - </tr> - <tr> - <td colspan="2" valign="top" class="vncell"><b>Example 1;</b> - suppress gen_id 1, sig_id 1852, track by_src, ip 10.1.1.54<br> - <b>Example 2;</b> event_filter gen_id 1, sig_id 1851, type limit, - track by_src, count 1, seconds 60<br> - <b>Example 3;</b> rate_filter gen_id 135, sig_id 1, track by_src, - count 100, seconds 1, new_action log, timeout 10</td> - </tr> - <tr> - <td width="100%" class="vtable"><textarea wrap="off" - name="suppresspassthru" cols="142" rows="28" id="suppresspassthru" - class="formpre"><?=htmlspecialchars($pconfig['suppresspassthru']);?></textarea> - </td> - </tr> - <tr> - <td width="78%"><input id="submit" name="submit" type="submit" - class="formbtn" value="Save" /> <input id="cancelbutton" - name="cancelbutton" type="button" class="formbtn" value="Cancel" - onclick="history.back()" /> <?php if (isset($id) && $a_suppress[$id]): ?> - <input name="id" type="hidden" value="<?=$id;?>" /> <?php endif; ?> - </td> - </tr> - </table> </table> - </td> - </tr> + </div> + </td> +</tr> +<tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Apply suppression or " . + "filters to rules. Valid keywords are 'suppress', 'event_filter' and " . + "'rate_filter'."); ?></td> +</tr> +<tr> +<td colspan="2" valign="top" class="vncell"><b><?php echo gettext("Example 1;"); ?></b> + suppress gen_id 1, sig_id 1852, track by_src, ip 10.1.1.54<br> + <b><?php echo gettext("Example 2;"); ?></b> event_filter gen_id 1, sig_id 1851, type limit, + track by_src, count 1, seconds 60<br> + <b><?php echo gettext("Example 3;"); ?></b> rate_filter gen_id 135, sig_id 1, track by_src, + count 100, seconds 1, new_action log, timeout 10</td> +</tr> +<tr> + <td width="10%" class="vncell"> <?php echo gettext("Advanced pass through"); ?></td> + <td width="100%" class="vtable"><textarea wrap="off" + name="suppresspassthru" cols="90" rows="28" id="suppresspassthru" class="formpre"><?=htmlspecialchars($pconfig['suppresspassthru']);?></textarea> + </td> +</tr> +<tr> + <td width="22%"> </td> + <td width="78%"><input id="submit" name="submit" type="submit" + class="formbtn" value="Save" /> <input id="cancelbutton" + name="cancelbutton" type="button" class="formbtn" value="Cancel" + onclick="history.back()" /> <?php if (isset($id) && $a_suppress[$id]): ?> + <input name="id" type="hidden" value="<?=$id;?>" /> <?php endif; ?> + </td> +</tr> +</table> +</td></tr> </table> </form> - -</div> - - <?php include("fend.inc"); ?> - +<?php include("fend.inc"); ?> +<script type="text/javascript"> +Rounded("div#redbox","all","#FFF","#E0E0E0","smooth"); +</script> </body> </html> diff --git a/config/snort/snort_interfaces_whitelist.php b/config/snort/snort_interfaces_whitelist.php index 2dc2d491..f90cbe1f 100644 --- a/config/snort/snort_interfaces_whitelist.php +++ b/config/snort/snort_interfaces_whitelist.php @@ -1,67 +1,61 @@ <?php -/* $Id$ */ /* - firewall_aliases.php - Copyright (C) 2004 Scott Ullrich - Copyright (C) 2011 Ermal Luci - All rights reserved. - - originially part of m0n0wall (http://m0n0.ch/wall) - Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. - All rights reserved. - - modified for the pfsense snort package - Copyright (C) 2009-2010 Robert Zelaya. - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. + * snort_interfaces_whitelist.php + * + * Copyright (C) 2004 Scott Ullrich + * Copyright (C) 2011-2012 Ermal Luci + * All rights reserved. + * + * originially part of m0n0wall (http://m0n0.ch/wall) + * Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + * All rights reserved. + * + * modified for the pfsense snort package + * Copyright (C) 2009-2010 Robert Zelaya. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. */ require_once("guiconfig.inc"); -require_once("/usr/local/pkg/snort/snort_gui.inc"); require_once("/usr/local/pkg/snort/snort.inc"); - +if (!is_array($config['installedpackages']['snortglobal']['whitelist'])) + $config['installedpackages']['snortglobal']['whitelist'] = array(); if (!is_array($config['installedpackages']['snortglobal']['whitelist']['item'])) -$config['installedpackages']['snortglobal']['whitelist']['item'] = array(); - -//aliases_sort(); << what ? + $config['installedpackages']['snortglobal']['whitelist']['item'] = array(); $a_whitelist = &$config['installedpackages']['snortglobal']['whitelist']['item']; -if (isset($config['installedpackages']['snortglobal']['whitelist']['item'])) { +if (isset($config['installedpackages']['snortglobal']['whitelist']['item'])) $id_gen = count($config['installedpackages']['snortglobal']['whitelist']['item']); -}else{ +else $id_gen = '0'; -} - -$d_whitelistdirty_path = '/var/run/snort_whitelist.dirty'; if ($_GET['act'] == "del") { if ($a_whitelist[$_GET['id']]) { /* make sure rule is not being referenced by any nat or filter rules */ - unset($a_whitelist[$_GET['id']]); write_config(); - filter_configure(); + sync_snort_package_config(); header("Location: /snort/snort_interfaces_whitelist.php"); exit; } @@ -69,23 +63,17 @@ if ($_GET['act'] == "del") { $pgtitle = "Services: Snort: Whitelist"; include_once("head.inc"); - ?> <body link="#0000CC" vlink="#0000CC" alink="#0000CC"> <?php include_once("fbegin.inc"); -echo $snort_general_css; +if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';} +if ($savemsg) print_info_box($savemsg); ?> -<div class="body2"><?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> - -<form action="/snort/snort_interfaces_whitelist.php" method="post"><?php if ($savemsg) print_info_box($savemsg); ?> -<?php if (file_exists($d_whitelistdirty_path)): ?> -<p><?php print_info_box_np("The white list has been changed.<br>You must apply the changes in order for them to take effect.");?> -<?php endif; ?> - +<form action="/snort/snort_interfaces_whitelist.php" method="post"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr><td> <?php @@ -97,71 +85,68 @@ echo $snort_general_css; $tab_array[4] = array(gettext("Blocked"), false, "/snort/snort_blocked.php"); $tab_array[5] = array(gettext("Whitelists"), true, "/snort/snort_interfaces_whitelist.php"); $tab_array[6] = array(gettext("Suppress"), false, "/snort/snort_interfaces_suppress.php"); - $tab_array[7] = array(gettext("Help"), false, "/snort/help_and_info.php"); display_top_tabs($tab_array); ?> - </td> - </tr> - <tr> - <td class="tabcont"> - - <table width="100%" border="0" cellpadding="0" cellspacing="0"> - - <tr> - <td width="20%" class="listhdrr">File Name</td> - <td width="40%" class="listhdrr">Values</td> - <td width="40%" class="listhdr">Description</td> - <td width="10%" class="list"></td> - </tr> - <?php $i = 0; foreach ($a_whitelist as $list): ?> - <tr> - <td class="listlr" - ondblclick="document.location='snort_interfaces_whitelist_edit.php?id=<?=$i;?>';"> - <?=htmlspecialchars($list['name']);?></td> - <td class="listr" - ondblclick="document.location='snort_interfaces_whitelist_edit.php?id=<?=$i;?>';"> - <?php - $addresses = implode(", ", array_slice(explode(" ", $list['address']), 0, 10)); - echo $addresses; - if(count($addresses) < 10) { - echo " "; - } else { - echo "..."; - } - ?></td> - <td class="listbg" - ondblclick="document.location='snort_interfaces_whitelist_edit.php?id=<?=$i;?>';"> - <font color="#FFFFFF"> <?=htmlspecialchars($list['descr']);?> - </td> - <td valign="middle" nowrap class="list"> - <table border="0" cellspacing="0" cellpadding="1"> - <tr> - <td valign="middle"><a - href="snort_interfaces_whitelist_edit.php?id=<?=$i;?>"><img - src="/themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" - width="17" height="17" border="0" title="edit whitelist"></a></td> - <td><a - href="/snort/snort_interfaces_whitelist.php?act=del&id=<?=$i;?>" - onclick="return confirm('Do you really want to delete this whitelist? All elements that still use it will become invalid (e.g. snort rules will fall back to the default whitelist)!')"><img - src="/themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" - width="17" height="17" border="0" title="delete whitelist"></a></td> - </tr> - </table> - </td> - </tr> - <?php $i++; endforeach; ?> - <tr> - <td class="list" colspan="3"></td> - <td class="list"> - <table border="0" cellspacing="0" cellpadding="1"> - <tr> - <td valign="middle" width="17"> </td> - <td valign="middle"><a - href="snort_interfaces_whitelist_edit.php?id=<?php echo $id_gen;?> "><img - src="/themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" - width="17" height="17" border="0" title="add a new list"></a></td> - </tr> - </table> + </td> +</tr> +<tr> + <td class="tabcont"> + <table width="100%" border="0" cellpadding="6" cellspacing="0"> + <tr> + <td width="20%" class="listhdrr">File Name</td> + <td width="40%" class="listhdrr">Values</td> + <td width="40%" class="listhdr">Description</td> + <td width="10%" class="list"></td> + </tr> + <?php foreach ($a_whitelist as $i => $list): ?> + <tr> + <td class="listlr" + ondblclick="document.location='snort_interfaces_whitelist_edit.php?id=<?=$i;?>';"> + <?=htmlspecialchars($list['name']);?></td> + <td class="listr" + ondblclick="document.location='snort_interfaces_whitelist_edit.php?id=<?=$i;?>';"> + <?php + $addresses = implode(", ", array_slice(explode(" ", $list['address']), 0, 10)); + echo $addresses; + if(count($addresses) < 10) { + echo " "; + } else { + echo "..."; + } + ?></td> + <td class="listbg" + ondblclick="document.location='snort_interfaces_whitelist_edit.php?id=<?=$i;?>';"> + <font color="#FFFFFF"> <?=htmlspecialchars($list['descr']);?> + </td> + <td valign="middle" nowrap class="list"> + <table border="0" cellspacing="0" cellpadding="1"> + <tr> + <td valign="middle"><a + href="snort_interfaces_whitelist_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 whitelist"); ?>"></a></td> + <td><a + href="/snort/snort_interfaces_whitelist.php?act=del&id=<?=$i;?>" + onclick="return confirm('<?php echo gettext("Do you really want to delete this whitelist? All elements that still use it will become invalid (e.g. snort rules will fall back to the default whitelist)!"); ?>')"><img + src="/themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" + width="17" height="17" border="0" title="<?php echo gettext("delete whitelist"); ?>"></a></td> + </tr> + </table> + </td> + </tr> + <?php endforeach; ?> + <tr> + <td class="list" colspan="3"></td> + <td class="list"> + <table border="0" cellspacing="0" cellpadding="1"> + <tr> + <td valign="middle" width="17"> </td> + <td valign="middle"><a + href="snort_interfaces_whitelist_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 a new list"); ?>"></a></td> + </tr> + </table> </td> </tr> </table> @@ -169,21 +154,17 @@ echo $snort_general_css; </tr> </table> <br> -<table class="tabcont" width="100%" border="0" cellpadding="0" +<table width="100%" border="0" cellpadding="0" cellspacing="0"> - <td width="100%"><span class="vexpl"><span class="red"><strong>Note:</strong></span> - <p><span class="vexpl">Here you can create whitelist files for your - snort package rules.<br> - Please add all the ips or networks you want to protect against snort - block decisions.<br> - Remember that the default whitelist only includes local networks.<br> - Be careful, it is very easy to get locked out of you system.</span></p></td> + <td width="100%"><span class="vexpl"><span class="red"><strong><?php echo gettext("Note:"); ?></strong></span> + <p><span class="vexpl"><?php echo gettext("Here you can create whitelist files for your " . + "snort package rules."); ?><br> + <?php echo gettext("Please add all the ips or networks you want to protect against snort " . + "block decisions."); ?><br> + <?php echo gettext("Remember that the default whitelist only includes local networks."); ?><br> + <?php echo gettext("Be careful, it is very easy to get locked out of you system."); ?></span></p></td> </table> - </form> - -</div> - <?php include("fend.inc"); ?> </body> </html> diff --git a/config/snort/snort_interfaces_whitelist_edit.php b/config/snort/snort_interfaces_whitelist_edit.php index fe3c54a5..378530ba 100644 --- a/config/snort/snort_interfaces_whitelist_edit.php +++ b/config/snort/snort_interfaces_whitelist_edit.php @@ -1,48 +1,47 @@ <?php -/* $Id$ */ /* - firewall_aliases_edit.php - Copyright (C) 2004 Scott Ullrich - Copyright (C) 2011 Ermal Luci - All rights reserved. - - originially part of m0n0wall (http://m0n0.ch/wall) - Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. - All rights reserved. - - modified for the pfsense snort package - Copyright (C) 2009-2010 Robert Zelaya. - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. + * snort_interfaces_whitelist_edit.php + * Copyright (C) 2004 Scott Ullrich + * Copyright (C) 2011-2012 Ermal Luci + * All rights reserved. + * + * originially part of m0n0wall (http://m0n0.ch/wall) + * Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + * All rights reserved. + * + * modified for the pfsense snort package + * Copyright (C) 2009-2010 Robert Zelaya. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. */ require_once("guiconfig.inc"); -require_once("/usr/local/pkg/snort/snort_gui.inc"); require_once("/usr/local/pkg/snort/snort.inc"); +if (!is_array($config['installedpackages']['snortglobal']['whitelist'])) + $config['installedpackages']['snortglobal']['whitelist'] = array(); if (!is_array($config['installedpackages']['snortglobal']['whitelist']['item'])) $config['installedpackages']['snortglobal']['whitelist']['item'] = array(); - $a_whitelist = &$config['installedpackages']['snortglobal']['whitelist']['item']; $id = $_GET['id']; @@ -53,39 +52,32 @@ if (is_null($id)) { exit; } -/* gen uuid for each iface !inportant */ -if ($config['installedpackages']['snortglobal']['whitelist']['item'][$id]['uuid'] == '') { +if (empty($config['installedpackages']['snortglobal']['whitelist']['item'][$id]['uuid'])) { $whitelist_uuid = 0; while ($whitelist_uuid > 65535 || $whitelist_uuid == 0) { $whitelist_uuid = mt_rand(1, 65535); $pconfig['uuid'] = $whitelist_uuid; } -} else if ($config['installedpackages']['snortglobal']['whitelist']['item'][$id]['uuid'] != '') { +} else $whitelist_uuid = $config['installedpackages']['snortglobal']['whitelist']['item'][$id]['uuid']; -} - -$d_snort_whitelist_dirty_path = '/var/run/snort_whitelist.dirty'; /* returns true if $name is a valid name for a whitelist file name or ip */ function is_validwhitelistname($name) { if (!is_string($name)) - return false; + return false; if (!preg_match("/[^a-zA-Z0-9\.\/]/", $name)) - return true; + return true; return false; } - if (isset($id) && $a_whitelist[$id]) { - /* old settings */ $pconfig = array(); $pconfig['name'] = $a_whitelist[$id]['name']; $pconfig['uuid'] = $a_whitelist[$id]['uuid']; $pconfig['detail'] = $a_whitelist[$id]['detail']; - $pconfig['snortlisttype'] = $a_whitelist[$id]['snortlisttype']; $pconfig['address'] = $a_whitelist[$id]['address']; $pconfig['descr'] = html_entity_decode($a_whitelist[$id]['descr']); $pconfig['wanips'] = $a_whitelist[$id]['wanips']; @@ -93,12 +85,9 @@ if (isset($id) && $a_whitelist[$id]) { $pconfig['wandnsips'] = $a_whitelist[$id]['wandnsips']; $pconfig['vips'] = $a_whitelist[$id]['vips']; $pconfig['vpnips'] = $a_whitelist[$id]['vpnips']; - $addresses = explode(' ', $pconfig['address']); - $address = explode(" ", $addresses[0]); } if ($_POST['submit']) { - conf_mount_rw(); unset($input_errors); @@ -107,19 +96,13 @@ if ($_POST['submit']) { /* input validation */ $reqdfields = explode(" ", "name"); $reqdfieldsn = explode(",", "Name"); - do_input_validation($_POST, $reqdfields, $reqdfieldsn, &$input_errors); if(strtolower($_POST['name']) == "defaultwhitelist") - $input_errors[] = "Whitelist file names may not be named defaultwhitelist."; + $input_errors[] = gettext("Whitelist file names may not be named defaultwhitelist."); - $x = is_validwhitelistname($_POST['name']); - if (!isset($x)) { - $input_errors[] = "Reserved word used for whitelist file name."; - } else { - if (is_validwhitelistname($_POST['name']) == false) - $input_errors[] = "Whitelist file name may only consist of the characters a-z, A-Z and 0-9 _. Note: No Spaces. Press Cancel to reset."; - } + if (is_validwhitelistname($_POST['name']) == false) + $input_errors[] = gettext("Whitelist file name may only consist of the characters a-z, A-Z and 0-9 _. Note: No Spaces. Press Cancel to reset."); /* check for name conflicts */ foreach ($a_whitelist as $w_list) { @@ -127,52 +110,27 @@ if ($_POST['submit']) { continue; if ($w_list['name'] == $_POST['name']) { - $input_errors[] = "A whitelist file name with this name already exists."; + $input_errors[] = gettext("A whitelist file name with this name already exists."); break; } } - $isfirst = 0; - $address = ""; - $final_address_details .= ""; - /* add another entry code */ - for($x=0; $x<499; $x++) { - if (!empty($_POST["address{$x}"])) { - if ($is_first > 0) - $address .= " "; - $address .= $_POST["address{$x}"]; - if ($_POST["address_subnet{$x}"] <> "") - $address .= "" . $_POST["address_subnet{$x}"]; - - /* Compress in details to a single key, data separated by pipes. - Pulling details here lets us only pull in details for valid - address entries, saving us from having to track which ones to - process later. */ - $final_address_detail = mb_convert_encoding($_POST["detail{$x}"],'HTML-ENTITIES','auto'); - if ($final_address_detail <> "") - $final_address_details .= $final_address_detail; - else { - $final_address_details .= "Entry added" . " "; - $final_address_details .= date('r'); - } - $final_address_details .= "||"; - $is_first++; - } - } + if ($_POST['address']) + if (!is_alias($_POST['address'])) + $input_errors[] = gettext("A valid alias need to be provided"); if (!$input_errors) { $w_list = array(); /* post user input */ $w_list['name'] = $_POST['name']; $w_list['uuid'] = $whitelist_uuid; - $w_list['snortlisttype'] = $_POST['snortlisttype']; $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'] = $address; + $w_list['address'] = $_POST['address']; $w_list['descr'] = mb_convert_encoding($_POST['descr'],"HTML-ENTITIES","auto"); $w_list['detail'] = $final_address_details; @@ -188,227 +146,137 @@ if ($_POST['submit']) { header("Location: /snort/snort_interfaces_whitelist.php"); exit; - } else { - $pconfig['descr'] = mb_convert_encoding($_POST['descr'],"HTML-ENTITIES","auto"); - $pconfig['address'] = $address; - $pconfig['detail'] = $final_address_details; } - } $pgtitle = "Services: Snort: Whitelist: Edit $whitelist_uuid"; include_once("head.inc"); - ?> <body link="#0000CC" vlink="#0000CC" alink="#0000CC" > <?php include("fbegin.inc"); -echo $snort_general_css; +if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';} +if ($input_errors) print_input_errors($input_errors); +if ($savemsg) + print_info_box($savemsg); ?> -<script type="text/javascript" src="/javascript/row_helper.js"></script> - <input type='hidden' name='address_type' value='textbox' /> - <script type="text/javascript"> - - rowname[0] = "address"; - rowtype[0] = "textbox"; - rowsize[0] = "20"; - - rowname[1] = "detail"; - rowtype[1] = "textbox"; - rowsize[1] = "30"; +<script type="text/javascript" src="/javascript/autosuggest.js"> +</script> +<script type="text/javascript" src="/javascript/suggestions.js"> </script> - -<?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> - -<?php if ($input_errors) print_input_errors($input_errors); ?> -<div id="inputerrors"></div> - <form action="snort_interfaces_whitelist_edit.php" method="post" name="iform" id="iform"> -<?php - /* Display Alert message */ - if ($input_errors) - print_input_errors($input_errors); // TODO: add checks - - if ($savemsg) - print_info_box2($savemsg); - -?> - <table width="100%" border="0" cellpadding="0" cellspacing="0"> +<tr><td class="tabcont"> +<table width="100%" border="0" cellpadding="6" cellspacing="0"> <tr> - <td class="tabcont"> - - <table width="100%" border="0" cellpadding="6" cellspacing="0"> - <tr> - <td colspan="2" valign="top" class="listtopic">Add the name and - description of the file.</td> - </tr> - <tr> - <td valign="top" class="vncellreq2">Name</td> - <td class="vtable"><input name="name" type="text" id="name" - size="40" value="<?=htmlspecialchars($pconfig['name']);?>" /> <br /> - <span class="vexpl"> The list name may only consist of the - characters a-z, A-Z and 0-9. <span class="red">Note: </span> No - Spaces. </span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Description</td> - <td width="78%" class="vtable"><input name="descr" type="text" - id="descr" size="40" value="<?=$pconfig['descr'];?>" /> <br /> - <span class="vexpl"> You may enter a description here for your - reference (not parsed). </span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">List Type</td> - <td width="78%" class="vtable"> - - <div - style="padding: 5px; margin-top: 16px; margin-bottom: 16px; border: 1px dashed #ff3333; background-color: #eee; color: #000; font-size: 8pt;" - id="itemhelp"><strong>WHITELIST:</strong> This - list specifies addresses that Snort Package should not block.<br> - <br> - <strong>NETLIST:</strong> This list is for defining - addresses as $HOME_NET or $EXTERNAL_NET in the snort.conf file.</div> - - <select name="snortlisttype" class="formfld" id="snortlisttype"> - <?php - $interfaces4 = array('whitelist' => 'WHITELIST', 'netlist' => 'NETLIST'); - foreach ($interfaces4 as $iface4 => $ifacename4): ?> - <option value="<?=$iface4;?>" - <?php if ($iface4 == $pconfig['snortlisttype']) echo "selected"; ?>> - <?=htmlspecialchars($ifacename4);?></option> - <?php endforeach; ?> - </select> <span class="vexpl"> Choose the type of - list you will like see in your <span class="red">Interface Edit Tab</span>. - </span></td> - </tr> - <tr> - <td colspan="2" valign="top" class="listtopic">Add auto generated - ips.</td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">WAN IPs</td> - <td width="78%" class="vtable"><input name="wanips" type="checkbox" - id="wanips" size="40" value="yes" - <?php if($pconfig['wanips'] == 'yes'){ echo "checked";} if($pconfig['wanips'] == ''){ echo "checked";} ?> /> - <span class="vexpl"> Add WAN IPs to the list. </span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Wan Gateways</td> - <td width="78%" class="vtable"><input name="wangateips" - type="checkbox" id="wangateips" size="40" value="yes" - <?php if($pconfig['wangateips'] == 'yes'){ echo "checked";} if($pconfig['wangateips'] == ''){ echo "checked";} ?> /> - <span class="vexpl"> Add WAN Gateways to the list. </span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Wan DNS servers</td> - <td width="78%" class="vtable"><input name="wandnsips" - type="checkbox" id="wandnsips" size="40" value="yes" - <?php if($pconfig['wandnsips'] == 'yes'){ echo "checked";} if($pconfig['wandnsips'] == ''){ echo "checked";} ?> /> - <span class="vexpl"> Add WAN DNS servers to the list. </span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Virtual IP Addresses</td> - <td width="78%" class="vtable"><input name="vips" type="checkbox" - id="vips" size="40" value="yes" - <?php if($pconfig['vips'] == 'yes'){ echo "checked";} if($pconfig['vips'] == ''){ echo "checked";} ?> /> - <span class="vexpl"> Add Virtual IP Addresses to the list. </span></td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">VPNs</td> - <td width="78%" class="vtable"><input name="vpnips" type="checkbox" - id="vpnips" size="40" value="yes" - <?php if($pconfig['vpnips'] == 'yes'){ echo "checked";} if($pconfig['vpnips'] == ''){ echo "checked";} ?> /> - <span class="vexpl"> Add VPN Addresses to the list. </span></td> - </tr> - <tr> - <td colspan="2" valign="top" class="listtopic">Add your own custom - ips.</td> - </tr> - <tr> - <td width="22%" valign="top" class="vncellreq2"> - <div id="addressnetworkport">IP or CIDR items</div> - </td> - <td width="78%" class="vtable"> - <table id="maintable"> - <tbody> - <tr> - <td colspan="4"> - <div - style="padding: 5px; margin-top: 16px; margin-bottom: 16px; border: 1px dashed #ff3333; background-color: #eee; color: #000; font-size: 8pt;" - id="itemhelp">For <strong>WHITELIST's</strong> enter <strong>ONLY - IPs not CIDRs</strong>. Example: 192.168.4.1<br> - <br> - For <strong>NETLIST's</strong> you may enter <strong>IPs and - CIDRs</strong>. Example: 192.168.4.1 or 192.168.4.0/24</div> - </td> - </tr> - <tr> - <td> - <div id="onecolumn">IP or CIDR</div> - </td> - <td> - <div id="threecolumn">Add a Description or leave blank and a date - will be added.</div> - </td> - </tr> - - <?php - /* cleanup code */ - $counter = 0; - $address = $pconfig['address']; - if ($address <> ""): - $item = explode(" ", $address); - $item3 = explode("||", $pconfig['detail']); - foreach($item as $ww): - $address = $item[$counter]; - $item4 = $item3[$counter]; - ?> - <tr> - <td><input name="address<?php echo $counter; ?>" class="formfld unknown" type="text" id="address<?php echo $counter; ?>" size="30" value="<?=htmlspecialchars($address);?>" /></td> - <td><input name="detail<?php echo $counter; ?>" class="formfld unknown" type="text" id="address<?php echo $counter; ?>" size="50" value="<?=$item4;?>" /></td> - <td> - <?php echo "<input type=\"image\" src=\"/themes/".$g['theme']."/images/icons/icon_x.gif\" onclick=\"removeRow(this); return false;\" value=\"Delete\" />"; ?> - </td> - </tr> - <?php - $counter++; - - endforeach; endif; - ?> - </tbody> - </table> - <a onclick="javascript:addRowTo('maintable'); return false;" - href="#"><img border="0" - src="/themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" alt="" - title="add another entry" /> </a></td> - </tr> - <tr> - <td width="22%" valign="top"> </td> - <td width="78%"> - <input id="submit" name="submit" type="submit" class="formbtn" value="Save" /> - <input id="cancelbutton" name="cancelbutton" type="button" class="formbtn" value="Cancel" onclick="history.back()" /> - <input name="id" type="hidden" value="<?=$id;?>" /> - </td> - </tr> - </table> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Add the name and " . + "description of the file."); ?></td> + </tr> + <tr> + <td valign="top" class="vncellreq"><?php echo gettext("Name"); ?></td> + <td class="vtable"><input name="name" type="text" id="name" + size="40" value="<?=htmlspecialchars($pconfig['name']);?>" /> <br /> + <span class="vexpl"> <?php echo gettext("The list name may only consist of the " . + "characters a-z, A-Z and 0-9."); ?> <span class="red"><?php echo gettext("Note:"); ?> </span> + <?php echo gettext("No Spaces."); ?> </span></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Description"); ?></td> + <td width="78%" class="vtable"><input name="descr" type="text" + id="descr" size="40" value="<?=$pconfig['descr'];?>" /> <br /> + <span class="vexpl"> <?php echo gettext("You may enter a description here for your " . + "reference (not parsed)."); ?> </span></td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Add auto generated ips."); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("WAN IPs"); ?></td> + <td width="78%" class="vtable"><input name="wanips" type="checkbox" + id="wanips" size="40" value="yes" + <?php if($pconfig['wanips'] == 'yes'){ echo "checked";} if($pconfig['wanips'] == ''){ echo "checked";} ?> /> + <span class="vexpl"> <?php echo gettext("Add WAN IPs to the list."); ?> </span></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Wan Gateways"); ?></td> + <td width="78%" class="vtable"><input name="wangateips" + type="checkbox" id="wangateips" size="40" value="yes" + <?php if($pconfig['wangateips'] == 'yes'){ echo "checked";} if($pconfig['wangateips'] == ''){ echo "checked";} ?> /> + <span class="vexpl"> <?php echo gettext("Add WAN Gateways to the list."); ?> </span></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Wan DNS servers"); ?></td> + <td width="78%" class="vtable"><input name="wandnsips" + type="checkbox" id="wandnsips" size="40" value="yes" + <?php if($pconfig['wandnsips'] == 'yes'){ echo "checked";} if($pconfig['wandnsips'] == ''){ echo "checked";} ?> /> + <span class="vexpl"> <?php echo gettext("Add WAN DNS servers to the list."); ?> </span></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Virtual IP Addresses"); ?></td> + <td width="78%" class="vtable"><input name="vips" type="checkbox" + id="vips" size="40" value="yes" + <?php if($pconfig['vips'] == 'yes'){ echo "checked";} if($pconfig['vips'] == ''){ echo "checked";} ?> /> + <span class="vexpl"> <?php echo gettext("Add Virtual IP Addresses to the list."); ?> </span></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("VPNs"); ?></td> + <td width="78%" class="vtable"><input name="vpnips" type="checkbox" + id="vpnips" size="40" value="yes" + <?php if($pconfig['vpnips'] == 'yes'){ echo "checked";} if($pconfig['vpnips'] == ''){ echo "checked";} ?> /> + <span class="vexpl"> <?php echo gettext("Add VPN Addresses to the list."); ?> </span></td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Add your own custom ips."); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncellreq"> + <div id="addressnetworkport"><?php echo gettext("Alias of IP's"); ?></div> + </td> + <td width="78%" class="vtable"> + <input autocomplete="off" name="address" type="text" class="formfldalias" id="address" size="30" value="<?=htmlspecialchars($pconfig['address']);?>" /> + </td> + </tr> + <tr> + <td width="22%" valign="top"> </td> + <td width="78%"> + <input id="submit" name="submit" type="submit" class="formbtn" value="Save" /> + <input id="cancelbutton" name="cancelbutton" type="button" class="formbtn" value="Cancel" onclick="history.back()" /> + <input name="id" type="hidden" value="<?=$id;?>" /> </td> </tr> </table> +</td></tr> +</table> </form> - <script type="text/javascript"> - /* row and col adjust when you add extra entries */ - - field_counter_js = 3; - rows = 1; - totalrows = <?php echo $counter; ?>; - loaded = <?php echo $counter; ?>; - -</script> +<?php + $isfirst = 0; + $aliases = ""; + $addrisfirst = 0; + $aliasesaddr = ""; + if(isset($config['aliases']['alias']) && is_array($config['aliases']['alias'])) + foreach($config['aliases']['alias'] as $alias_name) { + if ($alias_name['type'] != "host" && $alias_name['type'] != "network") + continue; + if($addrisfirst == 1) $aliasesaddr .= ","; + $aliasesaddr .= "'" . $alias_name['name'] . "'"; + $addrisfirst = 1; + } +?> + + var addressarray=new Array(<?php echo $aliasesaddr; ?>); + +function createAutoSuggest() { +<?php + echo "objAlias = new AutoSuggestControl(document.getElementById('address'), new StateSuggestions(addressarray));\n"; +?> +} +setTimeout("createAutoSuggest();", 500); + +</script> <?php include("fend.inc"); ?> </body> </html> diff --git a/config/snort/snort_preprocessors.php b/config/snort/snort_preprocessors.php index 7f89d433..d59af640 100644 --- a/config/snort/snort_preprocessors.php +++ b/config/snort/snort_preprocessors.php @@ -1,39 +1,37 @@ <?php -/* $Id$ */ /* - snort_preprocessors.php - part of m0n0wall (http://m0n0.ch/wall) - - Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. - Copyright (C) 2008-2009 Robert Zelaya. - Copyright (C) 2011 Ermal Luci - 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. + * snort_preprocessors.php + * part of pfSense + * + * Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>. + * Copyright (C) 2008-2009 Robert Zelaya. + * Copyright (C) 2011-2012 Ermal Luci + * 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_gui.inc"); require_once("/usr/local/pkg/snort/snort.inc"); global $g; @@ -57,11 +55,9 @@ if (isset($id) && $a_nat[$id]) { /* new options */ $pconfig['perform_stat'] = $a_nat[$id]['perform_stat']; - $pconfig['def_ssl_ports_ignore'] = $a_nat[$id]['def_ssl_ports_ignore']; $pconfig['flow_depth'] = $a_nat[$id]['flow_depth']; $pconfig['max_queued_bytes'] = $a_nat[$id]['max_queued_bytes']; $pconfig['max_queued_segs'] = $a_nat[$id]['max_queued_segs']; - $pconfig['perform_stat'] = $a_nat[$id]['perform_stat']; $pconfig['http_inspect'] = $a_nat[$id]['http_inspect']; $pconfig['other_preprocs'] = $a_nat[$id]['other_preprocs']; $pconfig['ftp_preprocessor'] = $a_nat[$id]['ftp_preprocessor']; @@ -69,25 +65,19 @@ if (isset($id) && $a_nat[$id]) { $pconfig['sf_portscan'] = $a_nat[$id]['sf_portscan']; $pconfig['dce_rpc_2'] = $a_nat[$id]['dce_rpc_2']; $pconfig['dns_preprocessor'] = $a_nat[$id]['dns_preprocessor']; + $pconfig['sensitive_data'] = $a_nat[$id]['sensitive_data']; + $pconfig['ssl_preproc'] = $a_nat[$id]['ssl_preproc']; + $pconfig['pop_preproc'] = $a_nat[$id]['pop_preproc']; + $pconfig['imap_preproc'] = $a_nat[$id]['imap_preproc']; } -/* convert fake interfaces to real */ -$if_real = snort_get_real_interface($pconfig['interface']); -$snort_uuid = $pconfig['uuid']; - -/* alert file */ -$d_snortconfdirty_path = "/var/run/snort_conf_{$snort_uuid}_{$if_real}.dirty"; - if ($_POST) { - $natent = array(); $natent = $pconfig; /* if no errors write to conf */ if (!$input_errors) { /* post new options */ - $natent['perform_stat'] = $_POST['perform_stat']; - if ($_POST['def_ssl_ports_ignore'] != "") { $natent['def_ssl_ports_ignore'] = $_POST['def_ssl_ports_ignore']; }else{ $natent['def_ssl_ports_ignore'] = ""; } if ($_POST['flow_depth'] != "") { $natent['flow_depth'] = $_POST['flow_depth']; }else{ $natent['flow_depth'] = ""; } if ($_POST['max_queued_bytes'] != "") { $natent['max_queued_bytes'] = $_POST['max_queued_bytes']; }else{ $natent['max_queued_bytes'] = ""; } if ($_POST['max_queued_segs'] != "") { $natent['max_queued_segs'] = $_POST['max_queued_segs']; }else{ $natent['max_queued_segs'] = ""; } @@ -100,6 +90,10 @@ if ($_POST) { $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'; + $natent['sensitive_data'] = $_POST['sensitive_data'] ? 'on' : 'off'; + $natent['ssl_preproc'] = $_POST['ssl_preproc'] ? 'on' : 'off'; + $natent['pop_preproc'] = $_POST['pop_preproc'] ? 'on' : 'off'; + $natent['imap_preproc'] = $_POST['imap_preproc'] ? 'on' : 'off'; if (isset($id) && $a_nat[$id]) $a_nat[$id] = $natent; @@ -126,33 +120,16 @@ if ($_POST) { } } -$pgtitle = "Snort: Interface $id$if_real Preprocessors and Flow"; +$if_friendly = snort_get_friendly_interface($pconfig['interface']); +$pgtitle = "Snort: Interface {$if_real} Preprocessors and Flow"; include_once("head.inc"); - ?> -<body - link="#0000CC" vlink="#0000CC" alink="#0000CC"> +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> <?php include("fbegin.inc"); ?> -<?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> - -<?php -echo "{$snort_general_css}\n"; -?> - -<div class="body2"> - -<noscript> -<div class="alert" ALIGN=CENTER><img - src="../themes/<?php echo $g['theme']; ?>/images/icons/icon_alert.gif" /><strong>Please -enable JavaScript to view this content -</CENTER></div> -</noscript> +<?php if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';} -<form action="snort_preprocessors.php" method="post" - enctype="multipart/form-data" name="iform" id="iform"><?php - /* Display Alert message */ if ($input_errors) { @@ -160,232 +137,220 @@ enable JavaScript to view this content } if ($savemsg) { - print_info_box2($savemsg); + print_info_box($savemsg); } - ?> +?> +<form action="snort_preprocessors.php" method="post" + enctype="multipart/form-data" name="iform" id="iform"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr><td> <?php $tab_array = array(); - $tabid = 0; - $tab_array[$tabid] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); - $tabid++; - $tab_array[$tabid] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Servers"), false, "/snort/snort_define_servers.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Preprocessors"), true, "/snort/snort_preprocessors.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); + $tab_array[] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); + $tab_array[] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); + $tab_array[] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); + $tab_array[] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); + $tab_array[] = array(gettext("Variables"), false, "/snort/snort_define_servers.php?id={$id}"); + $tab_array[] = array(gettext("Preprocessors"), true, "/snort/snort_preprocessors.php?id={$id}"); + $tab_array[] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); display_top_tabs($tab_array); ?> </td></tr> +<tr><td class="tabcont"> +<table width="100%" border="0" cellpadding="6" cellspacing="0"> <tr> - <td class="tabcont"> - <table width="100%" border="0" cellpadding="6" cellspacing="0"> - <?php - /* display error code if there is no id */ - if($id == "") - { - echo " - <style type=\"text/css\"> - .noid { - position:absolute; - top:10px; - left:0px; - width:94%; - background:#FCE9C0; - background-position: 15px; - border-top:2px solid #DBAC48; - border-bottom:2px solid #DBAC48; - padding: 15px 10px 85% 50px; - } - </style> - <div class=\"alert\" ALIGN=CENTER><img src=\"../themes/{$g['theme']}/images/icons/icon_alert.gif\"/><strong>You can not edit options without an interface ID.</CENTER></div>\n"; - - } - ?> - <tr> - <td width="22%" valign="top"> </td> - <td width="78%"><span class="vexpl"><span class="red"><strong>Note: - </strong></span><br> - Rules may be dependent on preprocessors!<br> - Defaults will be used when there is no user input.<br></td> - </tr> - <tr> - <td colspan="2" valign="top" class="listtopic">Performance - Statistics</td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Enable</td> - <td width="78%" class="vtable"><input name="perform_stat" - type="checkbox" value="on" - <?php if ($pconfig['perform_stat']=="on") echo "checked"; ?> - onClick="enable_change(false)"> Performance Statistics for this - interface.</td> - </tr> - <tr> - <td colspan="2" valign="top" class="listtopic">HTTP Inspect Settings</td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Enable</td> - <td width="78%" class="vtable"><input name="http_inspect" - type="checkbox" value="on" - <?php if ($pconfig['http_inspect']=="on") echo "checked"; ?> - onClick="enable_change(false)"> Use HTTP Inspect to - Normalize/Decode and detect HTTP traffic and protocol anomalies.</td> - </tr> - <tr> - <td valign="top" class="vncell2">HTTP server flow depth</td> - <td class="vtable"> - <table cellpadding="0" cellspacing="0"> - <tr> - <td><input name="flow_depth" type="text" class="formfld" - id="flow_depth" size="5" - value="<?=htmlspecialchars($pconfig['flow_depth']);?>"> <strong>-1</strong> - to <strong>1460</strong> (<strong>-1</strong> disables HTTP - inspect, <strong>0</strong> enables all HTTP inspect)</td> - </tr> - </table> - Amount of HTTP server response payload to inspect. Snort's - performance may increase by adjusting this value.<br> - Setting this value too low may cause false negatives. Values above 0 - are specified in bytes. Default value is <strong>0</strong><br> - </td> - </tr> - <tr> - <td colspan="2" valign="top" class="listtopic">Stream5 Settings</td> - </tr> - <tr> - <td valign="top" class="vncell2">Max Queued Bytes</td> - <td class="vtable"> - <table cellpadding="0" cellspacing="0"> - <tr> - <td><input name="max_queued_bytes" type="text" class="formfld" - id="max_queued_bytes" size="5" - value="<?=htmlspecialchars($pconfig['max_queued_bytes']);?>"> - Minimum is <strong>1024</strong>, Maximum is <strong>1073741824</strong> - ( default value is <strong>1048576</strong>, <strong>0</strong> - means Maximum )</td> - </tr> - </table> - The number of bytes to be queued for reassembly for TCP sessions in - memory. Default value is <strong>1048576</strong><br> - </td> - </tr> - <tr> - <td valign="top" class="vncell2">Max Queued Segs</td> - <td class="vtable"> - <table cellpadding="0" cellspacing="0"> - <tr> - <td><input name="max_queued_segs" type="text" class="formfld" - id="max_queued_segs" size="5" - value="<?=htmlspecialchars($pconfig['max_queued_segs']);?>"> - Minimum is <strong>2</strong>, Maximum is <strong>1073741824</strong> - ( default value is <strong>2621</strong>, <strong>0</strong> means - Maximum )</td> - </tr> - </table> - The number of segments to be queued for reassembly for TCP sessions - in memory. Default value is <strong>2621</strong><br> - </td> - </tr> - <tr> - <td colspan="2" valign="top" class="listtopic">General Preprocessor - Settings</td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Enable <br> - RPC Decode and Back Orifice detector</td> - <td width="78%" class="vtable"><input name="other_preprocs" - type="checkbox" value="on" - <?php if ($pconfig['other_preprocs']=="on") echo "checked"; ?> - onClick="enable_change(false)"><br> - Normalize/Decode RPC traffic and detects Back Orifice traffic on the - network.</td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Enable <br> - FTP and Telnet Normalizer</td> - <td width="78%" class="vtable"><input name="ftp_preprocessor" - type="checkbox" value="on" - <?php if ($pconfig['ftp_preprocessor']=="on") echo "checked"; ?> - onClick="enable_change(false)"><br> - Normalize/Decode FTP and Telnet traffic and protocol anomalies.</td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Enable <br> - SMTP Normalizer</td> - <td width="78%" class="vtable"><input name="smtp_preprocessor" - type="checkbox" value="on" - <?php if ($pconfig['smtp_preprocessor']=="on") echo "checked"; ?> - onClick="enable_change(false)"><br> - Normalize/Decode SMTP protocol for enforcement and buffer overflows.</td> - </tr> - <tr> - <td width="22%" valign="top" class="vncell2">Enable <br> - Portscan Detection</td> - <td width="78%" class="vtable"><input name="sf_portscan" - type="checkbox" value="on" - <?php if ($pconfig['sf_portscan']=="on") echo "checked"; ?> - onClick="enable_change(false)"><br> - Detects various types of portscans and portsweeps.</td> - </tr> + <td width="22%" valign="top"> </td> + <td width="78%"><span class="vexpl"><span class="red"><strong<?php echo gettext("Note:"); ?>> + </strong></span><br> + <?php echo gettext("Rules may be dependent on preprocessors!"); ?><br> + <?php echo gettext("Defaults will be used when there is no user input."); ?><br></td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Performance Statistics"); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?></td> + <td width="78%" class="vtable"><input name="perform_stat" + type="checkbox" value="on" + <?php if ($pconfig['perform_stat']=="on") echo "checked"; ?> + onClick="enable_change(false)"> <?php echo gettext("Performance Statistics for this interface."); ?></td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("HTTP Inspect Settings"); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?></td> + <td width="78%" class="vtable"><input name="http_inspect" + type="checkbox" value="on" + <?php if ($pconfig['http_inspect']=="on") echo "checked"; ?> + onClick="enable_change(false)"> <?php echo gettext("Use HTTP Inspect to " . + "Normalize/Decode and detect HTTP traffic and protocol anomalies."); ?></td> + </tr> + <tr> + <td valign="top" class="vncell"><?php echo gettext("HTTP server flow depth"); ?></td> + <td class="vtable"> + <table cellpadding="0" cellspacing="0"> <tr> - <td width="22%" valign="top" class="vncell2">Enable <br> - DCE/RPC2 Detection</td> - <td width="78%" class="vtable"><input name="dce_rpc_2" - type="checkbox" value="on" - <?php if ($pconfig['dce_rpc_2']=="on") echo "checked"; ?> - onClick="enable_change(false)"><br> - The DCE/RPC preprocessor detects and decodes SMB and DCE/RPC - traffic.</td> + <td><input name="flow_depth" type="text" class="formfld" + id="flow_depth" size="5" + value="<?=htmlspecialchars($pconfig['flow_depth']);?>"> <?php echo gettext("<strong>-1</strong> " . + "to <strong>1460</strong> (<strong>-1</strong> disables HTTP " . + "inspect, <strong>0</strong> enables all HTTP inspect)"); ?></td> </tr> + </table> + <?php echo gettext("Amount of HTTP server response payload to inspect. Snort's " . + "performance may increase by adjusting this value."); ?><br> + <?php echo gettext("Setting this value too low may cause false negatives. Values above 0 " . + "are specified in bytes. Default value is <strong>0</strong>"); ?><br> + </td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("Stream5 Settings"); ?></td> + </tr> + <tr> + <td valign="top" class="vncell"><?php echo gettext("Max Queued Bytes"); ?></td> + <td class="vtable"> + <table cellpadding="0" cellspacing="0"> <tr> - <td width="22%" valign="top" class="vncell2">Enable <br> - DNS Detection</td> - <td width="78%" class="vtable"><input name="dns_preprocessor" - type="checkbox" value="on" - <?php if ($pconfig['dns_preprocessor']=="on") echo "checked"; ?> - onClick="enable_change(false)"><br> - The DNS preprocessor decodes DNS Response traffic and detects some - vulnerabilities.</td> + <td><input name="max_queued_bytes" type="text" class="formfld" + id="max_queued_bytes" size="5" + value="<?=htmlspecialchars($pconfig['max_queued_bytes']);?>"> + <?php echo gettext("Minimum is <strong>1024</strong>, Maximum is <strong>1073741824</strong> " . + "( default value is <strong>1048576</strong>, <strong>0</strong> " . + "means Maximum )"); ?></td> </tr> + </table> + <?php echo gettext("The number of bytes to be queued for reassembly for TCP sessions in " . + "memory. Default value is <strong>1048576</strong>"); ?><br> + </td> + </tr> + <tr> + <td valign="top" class="vncell"><?php echo gettext("Max Queued Segs"); ?></td> + <td class="vtable"> + <table cellpadding="0" cellspacing="0"> <tr> - <td width="22%" valign="top" class="vncell2">Define SSL_IGNORE</td> - <td width="78%" class="vtable"><input name="def_ssl_ports_ignore" - type="text" class="formfld" id="def_ssl_ports_ignore" size="40" - value="<?=htmlspecialchars($pconfig['def_ssl_ports_ignore']);?>"> <br> - <span class="vexpl"> Encrypted traffic should be ignored by Snort - for both performance reasons and to reduce false positives.<br> - Default: "443 465 563 636 989 990 992 993 994 995".</span> <strong>Please - use spaces and not commas.</strong></td> + <td><input name="max_queued_segs" type="text" class="formfld" + id="max_queued_segs" size="5" + value="<?=htmlspecialchars($pconfig['max_queued_segs']);?>"> + <?php echo gettext("Minimum is <strong>2</strong>, Maximum is <strong>1073741824</strong> " . + "( default value is <strong>2621</strong>, <strong>0</strong> means " . + "Maximum )"); ?></td> </tr> - <tr> - <td width="22%" valign="top"> </td> + </table> + <?php echo gettext("The number of segments to be queued for reassembly for TCP sessions " . + "in memory. Default value is <strong>2621</strong>"); ?><br> + </td> + </tr> + <tr> + <td colspan="2" valign="top" class="listtopic"><?php echo gettext("General Preprocessor Settings"); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> + <?php echo gettext("RPC Decode and Back Orifice detector"); ?></td> + <td width="78%" class="vtable"><input name="other_preprocs" + type="checkbox" value="on" + <?php if ($pconfig['other_preprocs']=="on") echo "checked"; ?> + onClick="enable_change(false)"><br> + <?php echo gettext("Normalize/Decode RPC traffic and detects Back Orifice traffic on the network."); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> + <?php echo gettext("FTP and Telnet Normalizer"); ?></td> + <td width="78%" class="vtable"><input name="ftp_preprocessor" + type="checkbox" value="on" + <?php if ($pconfig['ftp_preprocessor']=="on") echo "checked"; ?> + onClick="enable_change(false)"><br> + <?php echo gettext("Normalize/Decode FTP and Telnet traffic and protocol anomalies."); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> + <?php echo gettext("SMTP Normalizer"); ?></td> + <td width="78%" class="vtable"><input name="pop_preproc" + type="checkbox" value="on" + <?php if ($pconfig['pop_preproc']=="on") echo "checked"; ?> + onClick="enable_change(false)"><br> + <?php echo gettext("Normalize/Decode POP protocol for enforcement and buffer overflows."); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> + <?php echo gettext("SMTP Normalizer"); ?></td> + <td width="78%" class="vtable"><input name="imap_preproc" + type="checkbox" value="on" + <?php if ($pconfig['imap_preproc']=="on") echo "checked"; ?> + onClick="enable_change(false)"><br> + <?php echo gettext("Normalize/Decode IMAP protocol for enforcement and buffer overflows."); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> + <?php echo gettext("SMTP Normalizer"); ?></td> + <td width="78%" class="vtable"><input name="smtp_preprocessor" + type="checkbox" value="on" + <?php if ($pconfig['smtp_preprocessor']=="on") echo "checked"; ?> + onClick="enable_change(false)"><br> + <?php echo gettext("Normalize/Decode SMTP protocol for enforcement and buffer overflows."); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> + <?php echo gettext("Portscan Detection"); ?></td> + <td width="78%" class="vtable"><input name="sf_portscan" + type="checkbox" value="on" + <?php if ($pconfig['sf_portscan']=="on") echo "checked"; ?> + onClick="enable_change(false)"><br> + <?php echo gettext("Detects various types of portscans and portsweeps."); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> + <?php echo gettext("DCE/RPC2 Detection"); ?></td> + <td width="78%" class="vtable"><input name="dce_rpc_2" + type="checkbox" value="on" + <?php if ($pconfig['dce_rpc_2']=="on") echo "checked"; ?> + onClick="enable_change(false)"><br> + <?php echo gettext("The DCE/RPC preprocessor detects and decodes SMB and DCE/RPC traffic."); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> + <?php echo gettext("DNS Detection"); ?></td> + <td width="78%" class="vtable"><input name="dns_preprocessor" + type="checkbox" value="on" + <?php if ($pconfig['dns_preprocessor']=="on") echo "checked"; ?> + onClick="enable_change(false)"><br> + <?php echo gettext("The DNS preprocessor decodes DNS Response traffic and detects some vulnerabilities."); ?></td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> <?php echo gettext("SSL Data"); ?></td> + <td width="78%" class="vtable"> + <input name="ssl_preproc" type="checkbox" value="on" + <?php if ($pconfig['ssl_preproc']=="on") echo "checked"; ?> + onClick="enable_change(false)"><br> + <?php echo gettext("SSL data searches for irregularities during SSL protocol exchange"); ?> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncell"><?php echo gettext("Enable"); ?> <br> <?php echo gettext("Sensitive Data"); ?></td> + <td width="78%" class="vtable"> + <input name="sensitive_data" type="checkbox" value="on" + <?php if ($pconfig['sensitive_data']=="on") echo "checked"; ?> + onClick="enable_change(false)"><br> + <?php echo gettext("Sensisitive data searches for CC or SS# in data"); ?> + </td> + </tr> + <tr> + <td width="22%" valign="top"> </td> <td width="78%"> <input name="Submit" type="submit" class="formbtn" value="Save"> <input name="id" type="hidden" value="<?=$id;?>"></td> </tr> <tr> <td width="22%" valign="top"> </td> - <td width="78%"><span class="vexpl"><span class="red"><strong>Note:</strong></span> + <td width="78%"><span class="vexpl"><span class="red"><strong><?php echo gettext("Note:"); ?></strong></span> <br> - Please save your settings before you click Start. </td> + <?php echo gettext("Please save your settings before you click Start."); ?> </td> </tr> - </table> - </table> +</td></tr></table> </form> - -</div> - - <?php include("fend.inc"); ?> +<?php include("fend.inc"); ?> </body> </html> diff --git a/config/snort/snort_rules.php b/config/snort/snort_rules.php index 871eb39e..c8a38ddb 100644 --- a/config/snort/snort_rules.php +++ b/config/snort/snort_rules.php @@ -1,43 +1,45 @@ <?php /* - snort_rules.php - Copyright (C) 2004, 2005 Scott Ullrich - Copyright (C) 2008, 2009 Robert Zelaya - Copyright (C) 2011 Ermal Luci - 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. + * snort_rules.php + * + * Copyright (C) 2004, 2005 Scott Ullrich + * Copyright (C) 2008, 2009 Robert Zelaya + * Copyright (C) 2011 Ermal Luci + * 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_gui.inc"); require_once("/usr/local/pkg/snort/snort.inc"); global $g; +$snortdir = SNORTDIR; + if (!is_array($config['installedpackages']['snortglobal']['rule'])) $config['installedpackages']['snortglobal']['rule'] = array(); -$a_nat = &$config['installedpackages']['snortglobal']['rule']; +$a_rule = &$config['installedpackages']['snortglobal']['rule']; $id = $_GET['id']; if (isset($_POST['id'])) @@ -47,97 +49,12 @@ if (is_null($id)) { exit; } -if (isset($id) && $a_nat[$id]) { - $pconfig['enable'] = $a_nat[$id]['enable']; - $pconfig['interface'] = $a_nat[$id]['interface']; - $pconfig['rulesets'] = $a_nat[$id]['rulesets']; -} - -/* convert fake interfaces to real */ -$if_real = snort_get_real_interface($pconfig['interface']); -$iface_uuid = $a_nat[$id]['uuid']; - -/* Check if the rules dir is empy if so warn the user */ -/* TODO give the user the option to delete the installed rules rules */ -if (!is_dir("/usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules")) - exec("/bin/mkdir -p /usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules"); - -$isrulesfolderempty = exec("ls -A /usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules/*.rules"); -if ($isrulesfolderempty == "") { - $isrulesfolderempty = exec("ls -A /usr/local/etc/snort/rules/*.rules"); - if ($isrulesfolderempty == "") { - include_once("head.inc"); - include_once("fbegin.inc"); - - echo "<body link=\"#000000\" vlink=\"#000000\" alink=\"#000000\">"; - - if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';} - - echo "<table width=\"99%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n - <tr>\n - <td>\n"; - - $tab_array = array(); - $tabid = 0; - $tab_array[$tabid] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); - $tabid++; - $tab_array[$tabid] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Rules"), true, "/snort/snort_rules.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Servers"), false, "/snort/snort_define_servers.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); - display_top_tabs($tab_array); - echo "</td>\n - </tr>\n - <tr>\n - <td>\n - <div id=\"mainarea\">\n - <table id=\"maintable\" class=\"tabcont\" width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n - <tr>\n - <td>\n - # The rules directory is empty.\n - </td>\n - </tr>\n - </table>\n - </div>\n - </td>\n - </tr>\n - </table>\n - \n - </form>\n - \n - <p>\n\n"; - - echo "Please click on the Update Rules tab to install your selected rule sets."; - include("fend.inc"); - - echo "</body>"; - echo "</html>"; - - exit(0); - } else { - /* Make sure that we have the rules */ - mwexec("/bin/cp /usr/local/etc/snort/rules/*.rules /usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules", true); - } -} - -function get_middle($source, $beginning, $ending, $init_pos) { - $beginning_pos = strpos($source, $beginning, $init_pos); - $middle_pos = $beginning_pos + strlen($beginning); - $ending_pos = strpos($source, $ending, $beginning_pos); - $middle = substr($source, $middle_pos, $ending_pos - $middle_pos); - return $middle; -} - -function write_rule_file($content_changed, $received_file) -{ - @file_put_contents($received_file, implode("\n", $content_changed)); +if (isset($id) && $a_rule[$id]) { + $pconfig['enable'] = $a_rule[$id]['enable']; + $pconfig['interface'] = $a_rule[$id]['interface']; + $pconfig['rulesets'] = $a_rule[$id]['rulesets']; + if (!empty($a_rule[$id]['customrules'])) + $pconfig['customrules'] = base64_decode($a_rule[$id]['customrules']); } function load_rule_file($incoming_file) @@ -149,27 +66,32 @@ function load_rule_file($incoming_file) return explode("\n", $contents); } -$ruledir = "/usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules/"; -//$ruledir = "/usr/local/etc/snort/rules/"; -$dh = opendir($ruledir); -while (false !== ($filename = readdir($dh))) -{ - //only populate this array if its a rule file - $isrulefile = strstr($filename, ".rules"); - if ($isrulefile !== false) - $files[] = basename($filename); -} -sort($files); +/* convert fake interfaces to real */ +$if_real = snort_get_real_interface($pconfig['interface']); +$snort_uuid = $a_rule[$id]['uuid']; +$snortdownload = $config['installedpackages']['snortglobal']['snortdownload']; +$emergingdownload = $config['installedpackages']['snortglobal']['emergingthreats']; +$categories = explode("||", $pconfig['rulesets']); if ($_GET['openruleset']) - $rulefile = $_GET['openruleset']; + $currentruleset = $_GET['openruleset']; +else if ($_POST['openruleset']) + $currentruleset = $_POST['openruleset']; else - $rulefile = $ruledir.$files[0]; - -//Load the rule file -$splitcontents = load_rule_file($rulefile); + $currentruleset = $categories[0]; + +$ruledir = "{$snortdir}/snort_{$snort_uuid}_{$if_real}/rules"; +$rulefile = "{$ruledir}/{$currentruleset}"; +if ($currentruleset != 'custom.rules') { +if (!file_exists($rulefile)) { + $input_errors[] = "{$currentruleset} seems to be missing!!! Please go to the Category tab and save again the rule to regenerate it."; + $splitcontents = array(); +} else + //Load the rule file + $splitcontents = load_rule_file($rulefile); +} -if ($_GET['act'] == "toggle" && $_GET['ids']) { +if ($_GET['act'] == "toggle" && $_GET['ids'] && !empty($splitcontents)) { $lineid= $_GET['ids']; @@ -193,36 +115,65 @@ if ($_GET['act'] == "toggle" && $_GET['ids']) { $splitcontents[$lineid] = $tempstring; //write the new .rules file - write_rule_file($splitcontents, $rulefile); + @file_put_contents($rulefile, implode("\n", $splitcontents)); //write disable/enable sid to config.xml - $sid = get_middle($tempstring, 'sid:', ';', 0); + $sid = snort_get_rule_part($tempstring, 'sid:', ";", 0); if (is_numeric($sid)) { // rule_sid_on registers - if (!empty($a_nat[$id]['rule_sid_on'])) - $a_nat[$id]['rule_sid_on'] = str_replace("||enablesid $sid", "", $a_nat[$id]['rule_sid_on']); - if (!empty($a_nat[$id]['rule_sid_on'])) - $a_nat[$id]['rule_sid_off'] = str_replace("||disablesid $sid", "", $a_nat[$id]['rule_sid_off']); - if ($disabled === false) - $a_nat[$id]['rule_sid_off'] = "||disablesid $sid_off" . $a_nat[$id]['rule_sid_off']; - else - $a_nat[$id]['rule_sid_on'] = "||enablesid $sid_on" . $a_nat[$id]['rule_sid_on']; + $sidon = explode("||", $a_rule[$id]['rule_sid_on']); + if (!empty($sidon)) + $sidon = @array_flip($sidon); + $sidoff = explode("||", $a_rule[$id]['rule_sid_off']); + if (!empty($sidoff)) + $sidoff = @array_flip($sidoff); + if ($disabled) { + unset($sidoff["disablesid {$sid}"]); + $sidon["enablesid {$sid}"] = count($sidon); + } else { + unset($sidon["enablesid {$sid}"]); + $sidoff["disablesid {$sid}"] = count($sidoff); + } + + $a_rule[$id]['rule_sid_on'] = implode("||", array_flip($sidon)); + $a_rule[$id]['rule_sid_off'] = implode("||", array_flip($sidoff)); + write_config(); } - write_config(); - - header("Location: /snort/snort_rules.php?id={$id}&openruleset={$rulefile}"); + header("Location: /snort/snort_rules.php?id={$id}&openruleset={$currentruleset}"); exit; } -$currentruleset = basename($rulefile); - -$ifname = strtoupper($pconfig['interface']); +if ($_POST['customrules']) { + $a_rule[$id]['customrules'] = base64_encode($_POST['customrules']); + write_config(); + sync_snort_package_config(); + $output = ""; + $retcode = ""; + exec("snort -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/snort.conf -T 2>&1", $output, $retcode); + if (intval($retcode) != 0) { + $error = ""; + $start = count($output); + $end = $start - 4; + for($i = $start; $i > $end; $i--) + $error .= $output[$i]; + $input_errors[] = "Custom rules have errors:\n {$error}"; + } else { + header("Location: /snort/snort_rules.php?id={$id}&openruleset={$currentruleset}"); + exit; + } +} else if ($_POST) { + unset($a_rule[$id]['customrules']); + write_config(); + header("Location: /snort/snort_rules.php?id={$id}&openruleset={$currentruleset}"); + exit; +} require_once("guiconfig.inc"); include_once("head.inc"); -$pgtitle = "Snort: $id $iface_uuid $if_real Category: $currentruleset"; +$if_friendly = snort_get_friendly_interface($pconfig['interface']); +$pgtitle = "Snort: {$if_friendly} Category: $currentruleset"; ?> <body link="#0000CC" vlink="#0000CC" alink="#0000CC"> @@ -230,9 +181,16 @@ $pgtitle = "Snort: $id $iface_uuid $if_real Category: $currentruleset"; include("fbegin.inc"); if ($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';} -echo "{$snort_general_css}\n"; +/* Display message */ +if ($input_errors) { + print_input_errors($input_errors); // TODO: add checks +} + +if ($savemsg) { + print_info_box($savemsg); +} + ?> -<form action="snort_rules.php" method="post" name="iform" id="iform"> <script language="javascript" type="text/javascript"> function go() @@ -255,203 +213,205 @@ function popup(url) } </script> -<table style="table-layout:fixed;" width="99%" border="0" cellpadding="0" cellspacing="0"> +<form action="/snort/snort_rules.php" method="post" name="iform" id="iform"> +<table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr><td> <?php $tab_array = array(); - $tabid = 0; - $tab_array[$tabid] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); - $tabid++; - $tab_array[$tabid] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Rules"), true, "/snort/snort_rules.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Servers"), false, "/snort/snort_define_servers.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); + $tab_array[] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); + $tab_array[] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); + $tab_array[] = array(gettext("Categories"), false, "/snort/snort_rulesets.php?id={$id}"); + $tab_array[] = array(gettext("Rules"), true, "/snort/snort_rules.php?id={$id}"); + $tab_array[] = array(gettext("Variables"), false, "/snort/snort_define_servers.php?id={$id}"); + $tab_array[] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); + $tab_array[] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); display_top_tabs($tab_array); ?> </td></tr> <tr> <td> - <div id="mainarea2"> - <table id="maintable" class="tabcont" width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td class="listt" colspan="8"> - <br>Category: - <select id="selectbox" name="selectbox" class="formfld" onChange="go()"> - <?php - foreach ($files as $value) { - echo "<option value='?id={$id}&openruleset={$ruledir}{$value}' "; - if ($value === $currentruleset) - echo "selected"; - echo ">{$value}</option>\n"; - } - ?> - </select> - </td> - </tr> - <tr id="frheader"> - <td width="3%" class="list"> </td> - <td width="5%" class="listhdr">SID</td> - <td width="6%" class="listhdrr">Proto</td> - <td width="15%" class="listhdrr">Source</td> - <td width="10%" class="listhdrr">Port</td> - <td width="15%" class="listhdrr">Destination</td> - <td width="10%" class="listhdrr">Port</td> - <td width="32%" class="listhdrr">Message</td> - </tr> + <table class="tabcont" width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr> + <td width="3%" class="list"> </td> + <td class="listhdr" colspan="7"> + <br/>Category: + <select id="selectbox" name="selectbox" class="formselect" onChange="go()"> + <option value='?id=<?=$id;?>&openruleset=custom.rules'>custom.rules</option> <?php - foreach ( $splitcontents as $counter => $value ) - { - $disabled = "False"; - $comments = "False"; - $findme = "# alert"; //find string for disabled alerts - $disabled_pos = strstr($value, $findme); - - $counter2 = 1; - $sid = get_middle($value, 'sid:', ';', 0); - //check to see if the sid is numberical - if (!is_numeric($sid)) + $files = explode("||", $pconfig['rulesets']); + foreach ($files as $value) { + if ($snortdownload != 'on' && strstr($value, "snort")) continue; - - //if find alert is false, then rule is disabled - if ($disabled_pos !== false){ - $counter2 = $counter2+1; - $textss = "<span class=\"gray\">"; - $textse = "</span>"; - $iconb = "icon_block_d.gif"; - - $ischecked = ""; - } else { - $textss = $textse = ""; - $iconb = "icon_block.gif"; - - $ischecked = "checked"; - } - - $rule_content = explode(' ', $value); - - $protocol = $rule_content[$counter2];//protocol location - $counter2++; - $source = substr($rule_content[$counter2], 0, 20) . "...";//source location - $counter2++; - $source_port = $rule_content[$counter2];//source port location - $counter2 = $counter2+2; - $destination = substr($rule_content[$counter2], 0, 20) . "...";//destination location - $counter2++; - $destination_port = $rule_content[$counter2];//destination port location - - if (strstr($value, 'msg: "')) - $message = get_middle($value, 'msg: "', '";', 0); - else if (strstr($value, 'msg:"')) - $message = get_middle($value, 'msg:"', '";', 0); - - echo "<tr><td class=\"listt\"> $textss\n"; - ?> - <a href="?id=<?=$id;?>&openruleset=<?=$rulefile;?>&act=toggle&ids=<?=$counter;?>"><img - src="../themes/<?= $g['theme']; ?>/images/icons/<?=$iconb;?>" - width="10" height="10" border="0" - title="click to toggle enabled/disabled status"></a> - <!-- <input name="enable" type="checkbox" value="yes" <?= $ischecked; ?> onClick="enable_change(false)"> --> - <!-- TODO: add checkbox and save so that that disabling is nicer --> - <?php - echo "$textse - </td> - <td width='5%' class=\"listlr\"> - $textss - $sid - $textse - </td> - <td width='6%' class=\"listlr\"> - $textss - $protocol"; - echo "$textse - </td> - <td width='20%' class=\"listlr\"> - $textss - $source - $textse - </td> - <td width='5%' class=\"listlr\"> - $textss - $source_port - $textse - </td> - <td width='20%' class=\"listlr\"> - $textss - $destination - $textse - </td> - <td width='5%' class=\"listlr\"> - $textss - $destination_port - $textse - </td> - <td width='30%' class=\"listbg\"><font color=\"white\"> - $textss - $message - $textse - </td>"; - ?> - <td valign="middle" nowrap class="list"> - <table border="0" cellspacing="0" cellpadding="1"> - <tr> - <td><a href="javascript: void(0)" - onclick="popup('snort_rules_edit.php?id=<?=$id;?>&openruleset=<?=$rulefile;?>&ids=<?=$counter;?>')"><img - src="../themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" - title="edit rule" width="17" height="17" border="0"></a></td> - <!-- Codes by Quackit.com --> - </tr> - </table> - </td> - <?php + if ($emergingdownload != 'on' && strstr($value, "emerging")) + continue; + echo "<option value='?id={$id}&openruleset={$value}' "; + if ($value === $currentruleset) + echo "selected"; + echo ">{$value}</option>\n"; } ?> - + </select> + <br/> + </td> + <td width="5%" class="list"> </td> + </tr> +<?php if ($currentruleset == 'custom.rules' || empty($pconfig['rulesets'])): ?> + <tr> + <td width="3%" class="list"> </td> + <td valign="top" class="vtable"> + <input type='hidden' name='openruleset' value='custom.rules'> + <input type='hidden' name='id' value='<?=$id;?>'> + + <textarea wrap="on" cols="90" rows="50" name="customrules"><?=$pconfig['customrules'];?></textarea> + </td> + </tr> + <tr> + <td width="3%" class="list"> </td> + <td class="vtable"> + <input name="Submit" type="submit" class="formbtn" value="Save"> + <input type="button" class="formbtn" value="Cancel" onclick="history.back()"> + </td> + </tr> +<?php else: ?> + <tr> + <td width="3%" class="list"> </td> + <td colspan="7" class="listhdr" > </td> + <td width="5%" class="list"> </td> + </tr> + <tr id="frheader"> + <td width="3%" class="list"> </td> + <td width="7%" class="listhdr"><?php echo gettext("SID"); ?></td> + <td width="4%" class="listhdrr"><?php echo gettext("Proto"); ?></td> + <td width="15%" class="listhdrr"><?php echo gettext("Source"); ?></td> + <td width="10%" class="listhdrr"><?php echo gettext("Port"); ?></td> + <td width="15%" class="listhdrr"><?php echo gettext("Destination"); ?></td> + <td width="10%" class="listhdrr"><?php echo gettext("Port"); ?></td> + <td width="30%" class="listhdrr"><?php echo gettext("Message"); ?></td> + <td width="5%" class="list"> </td> + </tr> +<?php + foreach ( $splitcontents as $counter => $value ) + { + $disabled = "False"; + $comments = "False"; + $findme = "# alert"; //find string for disabled alerts + $disabled_pos = strstr($value, $findme); + + $counter2 = 1; + $sid = snort_get_rule_part($value, 'sid:', ';', 0); + //check to see if the sid is numberical + if (!is_numeric($sid)) + continue; + + //if find alert is false, then rule is disabled + if ($disabled_pos !== false){ + $counter2 = $counter2+1; + $textss = "<span class=\"gray\">"; + $textse = "</span>"; + $iconb = "icon_block_d.gif"; + + $ischecked = ""; + } else { + $textss = $textse = ""; + $iconb = "icon_block.gif"; + + $ischecked = "checked"; + } + + $rule_content = explode(' ', $value); + + $protocol = $rule_content[$counter2];//protocol location + $counter2++; + $source = substr($rule_content[$counter2], 0, 20) . "...";//source location + $counter2++; + $source_port = $rule_content[$counter2];//source port location + $counter2 = $counter2+2; + $destination = substr($rule_content[$counter2], 0, 20) . "...";//destination location + $counter2++; + $destination_port = $rule_content[$counter2];//destination port location + + if (strstr($value, 'msg: "')) + $message = snort_get_rule_part($value, 'msg: "', '";', 0); + else if (strstr($value, 'msg:"')) + $message = snort_get_rule_part($value, 'msg:"', '";', 0); + + echo "<tr><td width='3%' class='listt'> $textss + <a href='?id={$id}&openruleset={$currentruleset}&act=toggle&ids={$counter}'> + <img src='../themes/{$g['theme']}/images/icons/{$iconb}' + width='10' height='10' border='0' + title='" . gettext("click to toggle enabled/disabled status") . "'></a> + $textse + </td> + <td width='7%' class=\"listlr\"> + $textss $sid $textse + </td> + <td width='4%' class=\"listlr\"> + $textss $protocol $textse + </td> + <td width='15%' class=\"listlr\"> + $textss $source $textse + </td> + <td width='10%' class=\"listlr\"> + $textss $source_port $textse + </td> + <td width='15%' class=\"listlr\"> + $textss $destination $textse + </td> + <td width='10%' class=\"listlr\"> + $textss $destination_port $textse + </td> + <td width='30%' class=\"listbg\"><font color=\"white\"> + $textss $message $textse + </td>"; + ?> + <td width='5%' valign="middle" nowrap class="list"> + <table border="0" cellspacing="0" cellpadding="1"> + <tr> + <td><a href="javascript: void(0)" + onclick="popup('snort_rules_edit.php?id=<?=$id;?>&openruleset=<?=$currentruleset;?>')"><img + src="../themes/<?= $g['theme']; ?>/images/icons/icon_right.gif" + title="<?php echo gettext("edit rule"); ?>" width="17" height="17" border="0"></a></td> + <!-- Codes by Quackit.com --> + </tr> </table> </td> </tr> +<?php + + } +?> + + </table> + </td> +</tr> +<?php endif;?> +<tr> + <td colspan="9"> + <table class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> - <td class="listlr"> - <?php echo " <strong><span class='red'>There are {$counter} rules in this category. <br/><br/></span></strong>"; ?> - </td> + <td width="16"><img + src="../themes/<?= $g['theme']; ?>/images/icons/icon_block.gif" + width="11" height="11"></td> + <td><?php echo gettext("Rule Enabled"); ?></td> </tr> <tr> - <td> - <table class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="0"> - <tr> - <td width="16"><img - src="../themes/<?= $g['theme']; ?>/images/icons/icon_block.gif" - width="11" height="11"></td> - <td>Rule Enabled</td> - </tr> - <tr> - <td><img - src="../themes/<?= $g['theme']; ?>/images/icons/icon_block_d.gif" - width="11" height="11"></td> - <td nowrap>Rule Disabled</td> - </tr> - <tr> - <!-- TODO: add save and cancel for checkbox options --> - <!-- <td><pre><input name="Submit" type="submit" class="formbtn" value="Save"> <input type="button" class="formbtn" value="Cancel" onclick="history.back()"><pre></td> --> - </tr> - <tr> - <td colspan="10"> - <p><!--<strong><span class="red">Warning:<br/> </span></strong>Editing these r</p>--> - </td> - </tr> - </table> + <td><img + src="../themes/<?= $g['theme']; ?>/images/icons/icon_block_d.gif" + width="11" height="11"></td> + <td nowrap><?php echo gettext("Rule Disabled"); ?></td> + </tr> + <tr> + <td colspan="10"> + <p><!--<strong><span class="red">Warning:<br/> </span></strong>Editing these r</p>--> </td> </tr> </table> </td> </tr> </table> +</td> +</tr> +</table> </form> <?php include("fend.inc"); ?> </body> diff --git a/config/snort/snort_rules_edit.php b/config/snort/snort_rules_edit.php index 330630f4..809832ea 100644 --- a/config/snort/snort_rules_edit.php +++ b/config/snort/snort_rules_edit.php @@ -1,133 +1,77 @@ <?php /* - snort_rules_edit.php - Copyright (C) 2004, 2005 Scott Ullrich - Copyright (C) 2011 Ermal Luci - All rights reserved. - - Adapted for FreeNAS by Volker Theile (votdev@gmx.de) - Copyright (C) 2006-2009 Volker Theile - - Adapted for Pfsense Snort package by Robert Zelaya - Copyright (C) 2008-2009 Robert Zelaya - - Using dp.SyntaxHighlighter for syntax highlighting - http://www.dreamprojections.com/SyntaxHighlighter - Copyright (C) 2004-2006 Alex Gorbatchev. 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. + * snort_rules_edit.php + * + * Copyright (C) 2004, 2005 Scott Ullrich + * Copyright (C) 2011 Ermal Luci + * All rights reserved. + * + * Adapted for FreeNAS by Volker Theile (votdev@gmx.de) + * Copyright (C) 2006-2009 Volker Theile + * + * Adapted for Pfsense Snort package by Robert Zelaya + * Copyright (C) 2008-2009 Robert Zelaya + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. */ require_once("guiconfig.inc"); require_once("/usr/local/pkg/snort/snort.inc"); -require_once("/usr/local/pkg/snort/snort_gui.inc"); + +$snortdir = SNORTDIR; if (!is_array($config['installedpackages']['snortglobal']['rule'])) { $config['installedpackages']['snortglobal']['rule'] = array(); } -$a_nat = &$config['installedpackages']['snortglobal']['rule']; +$a_rule = &$config['installedpackages']['snortglobal']['rule']; $id = $_GET['id']; -if (isset($_POST['id'])) - $id = $_POST['id']; - -$ids = $_GET['ids']; -if (isset($_POST['ids'])) - $ids = $_POST['ids']; - -if (isset($id) && $a_nat[$id]) { - $pconfig['enable'] = $a_nat[$id]['enable']; - $pconfig['interface'] = $a_nat[$id]['interface']; - $pconfig['rulesets'] = $a_nat[$id]['rulesets']; +if (is_null($id)) { + header("Location: /snort/snort_interfaces.php"); + exit; } -//get rule id -$lineid = $_GET['ids']; -if (isset($_POST['ids'])) - $lineid = $_POST['ids']; +if (isset($id) && $a_rule[$id]) { + $pconfig['enable'] = $a_rule[$id]['enable']; + $pconfig['interface'] = $a_rule[$id]['interface']; + $pconfig['rulesets'] = $a_rule[$id]['rulesets']; +} +/* convert fake interfaces to real */ +$if_real = snort_get_real_interface($pconfig['interface']); +$snort_uuid = $a_rule[$id]['uuid']; $file = $_GET['openruleset']; -if (isset($_POST['openruleset'])) - $file = $_POST['openruleset']; //read file into string, and get filesize also chk for empty files $contents = ''; -if (filesize($file) > 0 ) - $contents = file_get_contents($file); - -//delimiter for each new rule is a new line -$delimiter = "\n"; - -//split the contents of the string file into an array using the delimiter -$splitcontents = explode($delimiter, $contents); -$findme = "# alert"; //find string for disabled alerts -$highlight = "yes"; -if (strstr($splitcontents[$lineid], $findme)) - $highlight = "no"; -if ($highlight == "no") - $splitcontents[$lineid] = substr($splitcontents[$lineid], 2); - -if (!function_exists('get_middle')) { - function get_middle($source, $beginning, $ending, $init_pos) { - $beginning_pos = strpos($source, $beginning, $init_pos); - $middle_pos = $beginning_pos + strlen($beginning); - $ending_pos = strpos($source, $ending, $beginning_pos); - $middle = substr($source, $middle_pos, $ending_pos - $middle_pos); - return $middle; - } +if (file_exists("{$snortdir}/snort_{$snort_uuid}_{$if_real}/rules/{$file}")) + $contents = file_get_contents("{$snortdir}/snort_{$snort_uuid}_{$if_real}/rules/{$file}"); +else { + header("Location: /snort/snort_rules.php?id={$id}&openruleset={$file}"); + exit; } -if ($_POST) { - if ($_POST['save']) { - - //copy string into file array for writing - if ($_POST['highlight'] == "yes") - $splitcontents[$lineid] = $_POST['code']; - else - $splitcontents[$lineid] = "# " . $_POST['code']; - - //write disable/enable sid to config.xml - $sid = get_middle($splitcontents[$lineid], 'sid:', ';', 0); - if (is_numeric($sid)) { - // rule_sid_on registers - if (!empty($a_nat[$id]['rule_sid_on'])) - $a_nat[$id]['rule_sid_on'] = str_replace("||enablesid $sid", "", $a_nat[$id]['rule_sid_on']); - if (!empty($a_nat[$id]['rule_sid_on'])) - $a_nat[$id]['rule_sid_off'] = str_replace("||disablesid $sid", "", $a_nat[$id]['rule_sid_off']); - if ($_POST['highlight'] == "yes") - $a_nat[$id]['rule_sid_on'] = "||enablesid $sid" . $a_nat[$id]['rule_sid_on']; - else - $a_nat[$id]['rule_sid_off'] = "||disablesid $sid" . $a_nat[$id]['rule_sid_off']; - } - - //write the new .rules file - @file_put_contents($file, implode($delimiter, $splitcontents)); - - write_config(); - - echo "<script> opener.window.location.reload(); window.close(); </script>"; - exit; - } -} +//split the contents of the string file into an array using the delimiter +$splitcontents = explode("\n", $contents); $pgtitle = array(gettext("Advanced"), gettext("File Editor")); @@ -136,45 +80,23 @@ $pgtitle = array(gettext("Advanced"), gettext("File Editor")); <?php include("head.inc");?> <body link="#000000" vlink="#000000" alink="#000000"> -<form action="snort_rules_edit.php" method="post"> <?php if ($savemsg) print_info_box($savemsg); ?> +<?php include("fbegin.inc");?> + +<form action="snort_rules_edit.php" method="post"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td class="tabcont"> - - - <table width="100%" cellpadding="9" cellspacing="9" bgcolor="#eeeeee"> + <table width="100%" cellpadding="0" cellspacing="6" bgcolor="#eeeeee"> <tr> <td> - <input name="save" type="submit" class="formbtn" id="save" value="save" /> - <input type='hidden' name='id' value='<?=$id;?>' /> - <input type='hidden' name='ids' value='<?=$ids;?>' /> - <input type='hidden' name='openruleset' value='<?=$file;?>' /> <input type="button" class="formbtn" value="Cancel" onclick="window.close()"> - <hr noshade="noshade" /> - Disable original rule :<br/> - - <input id="highlighting_enabled" name="highlight2" type="radio" value="yes" <?php if($highlight == "yes") echo " checked=\"checked\""; ?> /> - <label for="highlighting_enabled"><?=gettext("Enabled");?> </label> - <input id="highlighting_disabled" name="highlight2" type="radio" value="no" <?php if($highlight == "no") echo " checked=\"checked\""; ?> /> - <label for="highlighting_disabled"> <?=gettext("Disabled");?></label> </td> </tr> - <tr> - <td valign="top" class="label"> - <textarea wrap="off" style="width: 98%; margin: 7px;" - class="<?php echo $language; ?>:showcolumns" rows="3" - cols="66" name="code"><?=$splitcontents[$lineid];?></textarea> - </div> - </td> - </tr> <tr> <td valign="top" class="label"> <div style="background: #eeeeee;" id="textareaitem"><!-- NOTE: The opening *and* the closing textarea tag must be on the same line. --> - <textarea disabled - wrap="off" style="width: 98%; margin: 7px;" - class="<?php echo $language; ?>:showcolumns" rows="33" - cols="66" name="code2"><?=$contents;?></textarea> + <textarea wrap="off" rows="33" cols="90" name="code2"><?=$contents;?></textarea> </div> </td> </tr> diff --git a/config/snort/snort_rulesets.php b/config/snort/snort_rulesets.php index 313daea2..cfaa7d18 100644 --- a/config/snort/snort_rulesets.php +++ b/config/snort/snort_rulesets.php @@ -1,40 +1,41 @@ <?php -/* $Id$ */ /* - snort_rulesets.php - Copyright (C) 2006 Scott Ullrich - Copyright (C) 2009 Robert Zelaya - Copyright (C) 2011 Ermal Luci - 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. + * snort_rulesets.php + * + * Copyright (C) 2006 Scott Ullrich + * Copyright (C) 2009 Robert Zelaya + * Copyright (C) 2011 Ermal Luci + * 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_gui.inc"); require_once("/usr/local/pkg/snort/snort.inc"); global $g; +$snortdir = SNORTDIR; + if (!is_array($config['installedpackages']['snortglobal']['rule'])) { $config['installedpackages']['snortglobal']['rule'] = array(); } @@ -48,266 +49,310 @@ if (is_null($id)) { exit; } +function snort_remove_rules($files, $snortdir, $snort_uuid, $if_real) { + + if (empty($files)) + return; + + conf_mount_rw(); + foreach ($files as $file) { + @unlink("{$snortdir}/snort_{$snort_uuid}_{$if_real}/rules/{$file}"); + if (substr($file, -9) == ".so.rules") { + $slib = substr($file, 6, -6); + @unlink("{$snortdir}/snort_{$snort_uuid}_{$if_real}/dynamicrules/{$slib}"); + } + } + conf_mount_ro(); +} + +function snort_copy_rules($files, $snortdir, $snort_uuid, $if_real) { + + if (empty($files)) + return; + + conf_mount_rw(); + foreach ($files as $file) { + if (!file_exists("{$snortdir}/snort_{$snort_uuid}_{$if_real}/rules/{$file}")) + @copy("{$snortdir}/rules/{$file}", "{$snortdir}/snort_{$snort_uuid}_{$if_real}/rules/{$file}"); + if (substr($file, -9) == ".so.rules") { + $slib = substr($enabled_item, 6, -6); + if (!file_exists("{$snortdir}/snort_{$snort_uuid}_{$if_real}/dynamicrules/{$slib}")) + @copy("/usr/local/lib/snort/dynamicrules/{$file}", "{$snortdir}/snort_{$snort_uuid}_{$if_real}/dynamicrules/{$slib}"); + } + } + conf_mount_ro(); +} + if (isset($id) && $a_nat[$id]) { $pconfig['enable'] = $a_nat[$id]['enable']; $pconfig['interface'] = $a_nat[$id]['interface']; $pconfig['rulesets'] = $a_nat[$id]['rulesets']; - - /* convert fake interfaces to real */ - $if_real = snort_get_real_interface($pconfig['interface']); - - $iface_uuid = $a_nat[$id]['uuid']; } -$pgtitle = "Snort: Interface $id $iface_uuid $if_real Categories"; - - -/* Check if the rules dir is empy if so warn the user */ -/* TODO give the user the option to delete the installed rules rules */ -$isrulesfolderempty = exec("ls -A /usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules/*.rules"); -if ($isrulesfolderempty == "") { - $isrulesfolderempty = exec("ls -A /usr/local/etc/snort/rules/*.rules"); - if ($isrulesfolderempty == "") { - include_once("head.inc"); - include("fbegin.inc"); - - echo "<p class=\"pgtitle\">"; - if($pfsense_stable == 'yes'){echo $pgtitle;} - echo "</p>\n"; - - echo "<body link=\"#000000\" vlink=\"#000000\" alink=\"#000000\">"; - - echo " - <table width=\"99%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n - <tr><td>\n"; - - $tab_array = array(); - $tabid = 0; - $tab_array[$tabid] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); - $tabid++; - $tab_array[$tabid] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Categories"), true, "/snort/snort_rulesets.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Servers"), false, "/snort/snort_define_servers.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); - display_top_tabs($tab_array); - echo " - </td></tr> - <tr>\n - <td>\n - <div id=\"mainarea\">\n - <table id=\"maintable\" class=\"tabcont\" width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n - <tr>\n - <td>\n - # The rules directory is empty. /usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules \n - </td>\n - </tr>\n - </table>\n - </div>\n - </td>\n - </tr>\n - </table>\n - \n - </form>\n - \n - <p>\n\n"; - - echo "Please click on the Update Rules tab to install your selected rule sets. $isrulesfolderempty"; - include("fend.inc"); - - echo "</body>"; - echo "</html>"; - - exit(0); - } else { - /* Make sure that we have the rules */ - mwexec("/bin/cp /usr/local/etc/snort/rules/*.rules /usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules", true); - } -} +$if_real = snort_get_real_interface($pconfig['interface']); +$snort_uuid = $a_nat[$id]['uuid']; +$snortdownload = $config['installedpackages']['snortglobal']['snortdownload']; +$emergingdownload = $config['installedpackages']['snortglobal']['emergingthreats']; /* alert file */ -$d_snortconfdirty_path = "/var/run/snort_conf_{$iface_uuid}_{$if_real}.dirty"; if ($_POST["Submit"]) { $enabled_items = ""; - $isfirst = true; if (is_array($_POST['toenable'])) $enabled_items = implode("||", $_POST['toenable']); else $enabled_items = $_POST['toenable']; + + $oenabled = explode("||", $a_nat[$id]['rulesets']); + $nenabled = explode("||", $enabled_items); + $tormv = array_diff($oenabled, $nenabled); + snort_remove_rules($tormv, $snortdir, $snort_uuid, $if_real); $a_nat[$id]['rulesets'] = $enabled_items; + snort_copy_rules(explode("||", $enabled_items), $snortdir, $snort_uuid, $if_real); write_config(); sync_snort_package_config(); - 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_rulesets.php?id=$id"); exit; } -$enabled_rulesets = $a_nat[$id]['rulesets']; -if($enabled_rulesets) - $enabled_rulesets_array = split("\|\|", $enabled_rulesets); +if ($_POST['unselectall']) { + if (!empty($pconfig['rulesets'])) + snort_remove_rules(explode("||", $pconfig['rulesets']), $snortdir, $snort_uuid, $if_real); -include_once("head.inc"); + $a_nat[$id]['rulesets'] = ""; -?> + write_config(); + sync_snort_package_config(); -<body link="#000000" vlink="#000000" alink="#000000"> + header("Location: /snort/snort_rulesets.php?id=$id"); + exit; +} -<?php include("fbegin.inc"); ?> -<?if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> +if ($_POST['selectall']) { + $rulesets = array(); + if ($emergingdownload == 'on') { + $files = glob("{$snortdir}/rules/emerging*.rules"); + foreach ($files as $file) + $rulesets[] = basename($file); + } + if ($snortdownload == 'on') { + $files = glob("{$snortdir}/rules/snort*.rules"); + foreach ($files as $file) + $rulesets[] = basename($file); + } + snort_copy_rules($rulesets, $snortdir, $snort_uuid, $if_real); -<?php -echo "{$snort_general_css}\n"; -?> + $a_nat[$id]['rulesets'] = implode("||", $rulesets); + + write_config(); + sync_snort_package_config(); + + header("Location: /snort/snort_rulesets.php?id=$id"); + exit; +} -<div class="body2"> +$enabled_rulesets_array = explode("||", $a_nat[$id]['rulesets']); +include_once("head.inc"); +?> -<noscript> -<div class="alert" ALIGN=CENTER><img - src="../themes/<?php echo $g['theme']; ?>/images/icons/icon_alert.gif" /><strong>Please -enable JavaScript to view this content -</CENTER></div> -</noscript> +<body link="#000000" vlink="#000000" alink="#000000"> <?php +include("fbegin.inc"); +$if_friendly = snort_get_friendly_interface($pconfig['interface']); +$pgtitle = "Snort: Interface {$if_friendly} Categories"; -echo "<form action=\"snort_rulesets.php?id={$id}\" method=\"post\" name=\"iform\" id=\"iform\">"; - -?> <?php +if($pfsense_stable == 'yes'){echo '<p class="pgtitle">' . $pgtitle . '</p>';}?> +<?php /* Display message */ - if ($input_errors) { print_input_errors($input_errors); // TODO: add checks } if ($savemsg) { - print_info_box2($savemsg); -} - -if (file_exists($d_snortconfdirty_path)) { - echo '<p>'; - - if($savemsg) { - print_info_box_np2("{$savemsg}"); - }else{ - print_info_box_np2(' - The Snort configuration has changed and snort needs to be restarted on this interface.<br> - You must apply the changes in order for them to take effect.<br> - '); - } + print_info_box($savemsg); } ?> +<form action="snort_rulesets.php" method="post" name="iform" id="iform"> +<input type="hidden" name="id" id="id" value="<?=$id;?>" /> <table width="99%" border="0" cellpadding="0" cellspacing="0"> <tr><td> <?php $tab_array = array(); - $tabid = 0; - $tab_array[$tabid] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); - $tabid++; - $tab_array[$tabid] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Categories"), true, "/snort/snort_rulesets.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Servers"), false, "/snort/snort_define_servers.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); - $tabid++; - $tab_array[$tabid] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); + $tab_array[] = array(gettext("Snort Interfaces"), false, "/snort/snort_interfaces.php"); + $tab_array[] = array(gettext("If Settings"), false, "/snort/snort_interfaces_edit.php?id={$id}"); + $tab_array[] = array(gettext("Categories"), true, "/snort/snort_rulesets.php?id={$id}"); + $tab_array[] = array(gettext("Rules"), false, "/snort/snort_rules.php?id={$id}"); + $tab_array[] = array(gettext("Variables"), false, "/snort/snort_define_servers.php?id={$id}"); + $tab_array[] = array(gettext("Preprocessors"), false, "/snort/snort_preprocessors.php?id={$id}"); + $tab_array[] = array(gettext("Barnyard2"), false, "/snort/snort_barnyard.php?id={$id}"); display_top_tabs($tab_array); ?> </td></tr> - <tr> - <td> - <div id="mainarea2"> - <table id="maintable" class="tabcont" width="100%" border="0" - cellpadding="0" cellspacing="0"> - <tr> - <td> - <table id="sortabletable1" class="sortable" width="100%" border="0" - cellpadding="0" cellspacing="0"> - <tr id="frheader"> - <td width="5%" class="listhdrr">Enabled</td> - <td class="listhdrr"><?php if($snort_arch == 'x86'){echo 'Ruleset: Rules that end with "so.rules" are shared object rules.';}else{echo 'Shared object rules are "so.rules" and not available on 64 bit architectures.';}?></td> - <!-- <td class="listhdrr">Description</td> --> - </tr> - <?php - $dir = "/usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules/"; - $dh = opendir($dir); - while (false !== ($filename = readdir($dh))) { - $files[] = basename($filename); - } - sort($files); - foreach($files as $file) { - if(!stristr($file, ".rules")) - continue; - echo "<tr>\n"; - echo "<td align=\"center\" valign=\"top\">"; - if(is_array($enabled_rulesets_array)) - if(in_array($file, $enabled_rulesets_array)) { - $CHECKED = " checked=\"checked\""; - } else { - $CHECKED = ""; - } - else - $CHECKED = ""; - echo " \n<input type='checkbox' name='toenable[]' value='$file' {$CHECKED} />\n"; - echo "</td>\n"; - echo "<td>\n"; - echo "<a href='snort_rules.php?id={$id}&openruleset=/usr/local/etc/snort/snort_{$iface_uuid}_{$if_real}/rules/" . urlencode($file) . "'>{$file}</a>\n"; - echo "</td>\n</tr>\n\n"; - //echo "<td>"; - //echo "description"; - //echo "</td>"; - } +<tr> + <td> + <div id="mainarea"> + <table id="maintable" class="tabcont" width="100%" border="0" cellpadding="0" cellspacing="0"> +<?php + $isrulesfolderempty = glob("{$snortdir}/rules/*.rules"); + $iscfgdirempty = glob("{$snortdir}/snort_{$snort_uuid}_{$if_real}/rules/*.rules"); + if (empty($isrulesfolderempty) && empty($iscfgdirempty)): +?> + <tr> + <td> + <?php printf(gettext("# The rules directory is empty. %s/rules"), $snortdir); ?> <br/> + <?php echo gettext("Please go to the updates page to download/fetch the rules configured."); ?> + </td> + </tr> +<?php else: + $colspan = 6; + if ($emergingdownload != 'on') + $colspan -= 2; + if ($snortdownload != 'on') + $colspan -= 4; - ?> - </table> - </td> - </tr> - <tr> - <td> </td> - </tr> - <tr> - <td>Check the rulesets that you would like Snort to load at startup.</td> - </tr> +?> + <tr> + <td> + <table id="sortabletable1" class="sortable" width="100%" border="0" + cellpadding="0" cellspacing="0"> <tr> - <td> </td> + <td colspan="6" class="listtopic"><?php echo gettext("Check the rulesets that you would like Snort to load at startup."); ?><br/><br/></td> </tr> <tr> - <td><input value="Save" type="submit" name="Submit" id="Submit" /></td> + <td colspan="2" valign="center"><br/><input value="Save" type="submit" name="Submit" id="Submit" /><br/<br/></td> + <td colspan="2" valign="center"><br/><input value="Select All" type="submit" name="selectall" id="selectall" /><br/<br/></td> + <td colspan="2" valign="center"><br/><input value="Unselect All" type="submit" name="unselectall" id="selectall" /><br/<br/></td> </tr> - </table> - </div> - </td> - </tr> + <tr> <td colspan="6"> </td> </tr> + <tr id="frheader"> + <?php if ($emergingdownload == 'on'): ?> + <td width="5%" class="listhdrr"><?php echo gettext("Enabled"); ?></td> + <td width="25%" class="listhdrr"><?php echo gettext('Ruleset: Emerging Threats.');?></td> + <?php else: ?> + <td colspan="2" width="30%" class="listhdrr"><?php echo gettext("Emerging rules have not been enabled"); ?></td> + <?php endif; ?> + <?php if ($snortdownload == 'on'): ?> + <td width="5%" class="listhdrr"><?php echo gettext("Enabled"); ?></td> + <td width="25%" class="listhdrr"><?php echo gettext('Ruleset: Snort');?></td> + <td width="5%" class="listhdrr"><?php echo gettext("Enabled"); ?></td> + <td width="25%" class="listhdrr"><?php echo gettext('Ruleset: Snort SO');?></td> + <?php else: ?> + <td colspan="2" width="60%" class="listhdrr"><?php echo gettext("Snort rules have not been enabled"); ?></td> + <?php endif; ?> + </tr> + <?php + $emergingrules = array(); + $snortsorules = array(); + $snortrules = array(); + if (empty($isrulesfolderempty)) + $dh = opendir("{$snortdir}/snort_{$snort_uuid}_{$if_real}/rules/"); + else + $dh = opendir("{$snortdir}/rules/"); + while (false !== ($filename = readdir($dh))) { + $filename = basename($filename); + if (substr($filename, -5) != "rules") + continue; + if (strstr($filename, "emerging") && $emergingdownload == 'on') + $emergingrules[] = $filename; + else if (strstr($filename, "snort") && $snortdownload == 'on') { + if (strstr($filename, ".so.rules")) + $snortsorules[] = $filename; + else + $snortrules[] = $filename; + } + } + sort($emergingrules); + sort($snortsorules); + sort($snortrules); + $i = count($emergingrules); + if ($i < count($snortsorules)) + $i = count(snortsorules); + if ($i < count($snortrules)) + $i = count($snortrules); + + for ($j = 0; $j < $i; $j++) { + echo "<tr>\n"; + if (!empty($emergingrules[$j])) { + $file = $emergingrules[$j]; + echo "<td width='5%' class='listr' align=\"center\" valign=\"top\">"; + if(is_array($enabled_rulesets_array)) { + if(in_array($file, $enabled_rulesets_array)) + $CHECKED = " checked=\"checked\""; + else + $CHECKED = ""; + } else + $CHECKED = ""; + echo " \n<input type='checkbox' name='toenable[]' value='$file' {$CHECKED} />\n"; + echo "</td>\n"; + echo "<td class='listr' width='25%' >\n"; + if (empty($CHECKED)) + 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"; + + if (!empty($snortrules[$j])) { + $file = $snortrules[$j]; + echo "<td class='listr' width='5%' align=\"center\" valign=\"top\">"; + if(is_array($enabled_rulesets_array)) { + if(in_array($file, $enabled_rulesets_array)) + $CHECKED = " checked=\"checked\""; + else + $CHECKED = ""; + } else + $CHECKED = ""; + echo " \n<input type='checkbox' name='toenable[]' value='{$file}' {$CHECKED} />\n"; + echo "</td>\n"; + echo "<td class='listr' width='25%' >\n"; + if (empty($CHECKED)) + 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"; + if (!empty($snortsorules[$j])) { + $file = $snortsorules[$j]; + echo "<td class='listr' width='5%' align=\"center\" valign=\"top\">"; + if(is_array($enabled_rulesets_array)) { + if(in_array($file, $enabled_rulesets_array)) + $CHECKED = " checked=\"checked\""; + else + $CHECKED = ""; + } else + $CHECKED = ""; + echo " \n<input type='checkbox' name='toenable[]' value='{$file}' {$CHECKED} />\n"; + echo "</td>\n"; + echo "<td class='listr' width='25%' >\n"; + echo $file; + echo "</td>\n"; + } else + echo "<td class='listbggrey' width='30%' colspan='2'><br/></td>\n"; + echo "</tr>\n"; + } + ?> + </table> + </td> +</tr> +<tr> +<td colspan="6"> </td> +</tr> +<?php endif; ?> </table> - -</form> - -<p><b>NOTE:</b> You can click on a ruleset name to edit the ruleset.</p> - </div> - +</td> +</tr> +</table> +</form> <?php include("fend.inc"); -echo $snort_custom_rnd_box; ?> - </body> </html> diff --git a/config/squid-reverse/proxy_monitor.sh b/config/squid-reverse/proxy_monitor.sh index fa5a87bb..17de3997 100644 --- a/config/squid-reverse/proxy_monitor.sh +++ b/config/squid-reverse/proxy_monitor.sh @@ -27,6 +27,10 @@ # POSSIBILITY OF SUCH DAMAGE. # +if [ `pgrep -f "proxy_monitor.sh"|wc -l` -ge 1 ]; then + exit 0 +fi + set -e LOOP_SLEEP=55 @@ -41,7 +45,7 @@ sleep 5 # Squid monitor 1.2 while [ /bin/true ]; do if [ ! -f /var/run/squid_alarm ]; then - NUM_PROCS=`ps auxw | grep "[s]quid -D"|awk '{print $2}'| wc -l | awk '{ print $1 }'` + NUM_PROCS=`ps auxw | grep "[s]quid -f"|awk '{print $2}'| wc -l | awk '{ print $1 }'` if [ $NUM_PROCS -lt 1 ]; then # squid is down echo "Squid has exited. Reconfiguring filter." | \ @@ -54,7 +58,7 @@ while [ /bin/true ]; do touch /var/run/squid_alarm fi fi - NUM_PROCS=`ps auxw | grep "[s]quid -D"|awk '{print $2}'| wc -l | awk '{ print $1 }'` + NUM_PROCS=`ps auxw | grep "[s]quid -f"|awk '{print $2}'| wc -l | awk '{ print $1 }'` if [ $NUM_PROCS -gt 0 ]; then if [ -f /var/run/squid_alarm ]; then echo "Squid has resumed. Reconfiguring filter." | \ diff --git a/config/squid-reverse/squid.inc b/config/squid-reverse/squid.inc index 073468e5..b88de284 100644 --- a/config/squid-reverse/squid.inc +++ b/config/squid-reverse/squid.inc @@ -41,6 +41,7 @@ if(!function_exists("filter_configure")) require_once("filter.inc"); define('SQUID_CONFBASE', '/usr/local/etc/squid'); +define('SQUID_CONFFILE', SQUID_CONFBASE . '/squid.conf'); define('SQUID_BASE', '/var/squid/'); define('SQUID_ACLDIR', '/var/squid/acl'); define('SQUID_PASSWD', '/var/etc/squid.passwd'); @@ -85,6 +86,11 @@ function squid_chown_recursive($dir, $user, $group) { /* setup cache */ function squid_dash_z() { global $config; + + //Do nothing if there is no cache config + if (!is_array($config['installedpackages']['squidcache']['config'])) + return; + $settings = $config['installedpackages']['squidcache']['config'][0]; // If the cache system is null, there is no need to initialize the (irrelevant) cache dir. @@ -102,12 +108,12 @@ function squid_dash_z() { if(!is_dir($cachedir.'/00/')) { log_error("Creating squid cache subdirs in $cachedir"); - mwexec("/usr/local/sbin/squid -k shutdown"); + mwexec("/usr/local/sbin/squid -k shutdown -f " . SQUID_CONFFILE); sleep(5); - mwexec("/usr/local/sbin/squid -k kill"); + mwexec("/usr/local/sbin/squid -k kill -f " . SQUID_CONFFILE); // Double check permissions here, should be safe to recurse cache dir if it's small here. mwexec("/usr/sbin/chown -R proxy:proxy $cachedir"); - mwexec("/usr/local/sbin/squid -z"); + mwexec("/usr/local/sbin/squid -z -f " . SQUID_CONFFILE); } if(file_exists("/var/squid/cache/swap.state")) { @@ -291,11 +297,11 @@ function squid_install_command() { if (!is_service_running('squid')) { update_status("Starting... One moment please..."); log_error("Starting Squid"); - mwexec_bg("/usr/local/sbin/squid -D"); + mwexec_bg("/usr/local/sbin/squid -f " . SQUID_CONFFILE); } else { update_status("Reloading Squid for configuration sync... One moment please..."); log_error("Reloading Squid for configuration sync"); - mwexec("/usr/local/sbin/squid -k reconfigure"); + mwexec("/usr/local/sbin/squid -k reconfigure -f " . SQUID_CONFFILE); } /* restart proxy alarm scripts */ @@ -310,7 +316,10 @@ function squid_deinstall_command() { global $config, $g; $plswait_txt = "This operation may take quite some time, please be patient. Do not press stop or attempt to navigate away from this page during this process."; squid_install_cron(false); - $settings = &$config['installedpackages']['squidcache']['config'][0]; + if (is_array($config['installedpackages']['squidcache'])) + $settings = $config['installedpackages']['squidcache']['config'][0]; + else + $settings = array(); $cachedir =($settings['harddisk_cache_location'] ? $settings['harddisk_cache_location'] : '/var/squid/cache'); $logdir = ($settings['log_dir'] ? $settings['log_dir'] : '/var/squid/logs'); update_status("Removing swap.state ... One moment please..."); @@ -353,7 +362,10 @@ function squid_before_form_general($pkg) { function squid_validate_general($post, $input_errors) { global $config; - $settings = $config['installedpackages']['squid']['config'][0]; + if (is_array($config['installedpackages']['squid'])) + $settings = $config['installedpackages']['squid']['config'][0]; + else + $settings = array(); $port = ($settings['proxy_port'] ? $settings['proxy_port'] : 3128); $port = $post['proxy_port'] ? $post['proxy_port'] : $port; @@ -372,7 +384,7 @@ function squid_validate_general($post, $input_errors) { $log_rotate = trim($post['log_rotate']); if (!empty($log_rotate) && (!is_numeric($log_rotate) or ($log_rotate < 1))) - $input_errors[] = 'You must enter a valid number of days \'Log rotate\' field'; + $input_errors[] = 'You must enter a valid number of days in the \'Log rotate\' field'; $webgui_port = $config['system']['webgui']['port']; if(($config['system']['webgui']['port'] == "") && ($config['system']['webgui']['protocol'] == "http")) { @@ -480,10 +492,18 @@ function squid_validate_nac($post, $input_errors) { } foreach (array( 'unrestricted_hosts', 'banned_hosts') as $hosts) { - foreach (explode("\n", $post[$hosts]) as $host) { - $host = trim($host); - if (!empty($host) && !is_ipaddr($host)) - $input_errors[] = "The host '$host' is not a valid IP address"; + + if (preg_match_all("@([0-9.]+)(/[0-9.]+|)@",$_POST[$hosts],$matches)){ + for ($x=0;$x < count($matches[1]);$x++){ + if ($matches[2][$x] == ""){ + if (!is_ipaddr($matches[1][$x])) + $input_errors[] = "'{$matches[1][$x]}' is not a valid IP address"; + } + else{ + if (!is_subnet($matches[0][$x])) + $input_errors[] = "The subnet '{$matches[0][$x]}' is not a valid CIDR range"; + } + } } } @@ -536,7 +556,7 @@ function squid_validate_traffic($post, $input_errors) { if (!empty($post['quick_abort_pct'])) { $value = trim($post['quick_abort_pct']); if (!is_numeric($value) || ($value > 100)) - $input_errors[] = "The field 'Finish when remaining %' must contain a percentaged value"; + $input_errors[] = "The field 'Finish when remaining %' must contain a percentage"; } } @@ -656,24 +676,28 @@ function squid_install_cron($should_install) { if(!$config['cron']['item']) return; - $settings = $config['installedpackages']['squidcache']['config'][0]; + + if (is_array($config['installedpackages']['squidcache'])) + $settings = $config['installedpackages']['squidcache']['config'][0]; + else + $settings = array(); + $x=0; $rotate_job_id=-1; $swapstate_job_id=-1; foreach($config['cron']['item'] as $item) { if(strstr($item['task_name'], "squid_rotate_logs")) { - - $rotate_job_id = $x; - } elseif(strstr($item['task_name'], "squid_check_swapstate")) { - $swapstate_job_id = $x; + $rotate_job_id = $x; + } elseif(strstr($item['task_name'], "squid_check_swapstate")) { + $swapstate_job_id = $x; } $x++; } $need_write = false; switch($should_install) { case true: - $cachedir =($settings['harddisk_cache_location'] ? $settings['harddisk_cache_location'] : '/var/squid/cache'); - if($rotate_job_id < 0) { + $cachedir =($settings['harddisk_cache_location'] ? $settings['harddisk_cache_location'] : '/var/squid/cache'); + if($rotate_job_id < 0) { $cron_item = array(); $cron_item['task_name'] = "squid_rotate_logs"; $cron_item['minute'] = "0"; @@ -682,11 +706,12 @@ function squid_install_cron($should_install) { $cron_item['month'] = "*"; $cron_item['wday'] = "*"; $cron_item['who'] = "root"; - $cron_item['command'] = "/bin/rm {$cachedir}/swap.state; /usr/local/sbin/squid -k rotate"; + $cron_item['command'] = "/bin/rm {$cachedir}/swap.state; /usr/local/sbin/squid -k rotate -f " . SQUID_CONFFILE; + /* Add this cron_item as a new entry at the end of the item array. */ $config['cron']['item'][] = $cron_item; $need_write = true; - } - if($swapstate_job_id < 0) { + } + if($swapstate_job_id < 0) { $cron_item = array(); $cron_item['task_name'] = "squid_check_swapstate"; $cron_item['minute'] = "*/15"; @@ -696,37 +721,40 @@ function squid_install_cron($should_install) { $cron_item['wday'] = "*"; $cron_item['who'] = "root"; $cron_item['command'] = "/usr/local/pkg/swapstate_check.php"; + /* Add this cron_item as a new entry at the end of the item array. */ $config['cron']['item'][] = $cron_item; $need_write = true; - } - if ($need_write) { - $config['cron']['item'][] = $cron_item; + } + if ($need_write) { parse_config(true); write_config("Adding Squid Cron Jobs"); } - break; + break; case false: - if($rotate_job_id >= 0) { - unset($config['cron']['item'][$rotate_job_id]); - $need_write = true; - } - if($swapstate_job_id >= 0) { - unset($config['cron']['item'][$swapstate_job_id]); - $need_write = true; - } - if ($need_write) { - parse_config(true); - write_config("Removing Squid Cron Jobs"); - } - break; + if($rotate_job_id >= 0) { + unset($config['cron']['item'][$rotate_job_id]); + $need_write = true; + } + if($swapstate_job_id >= 0) { + unset($config['cron']['item'][$swapstate_job_id]); + $need_write = true; + } + if ($need_write) { + parse_config(true); + write_config("Removing Squid Cron Jobs"); + } + break; } configure_cron(); - } +} function squid_resync_general() { global $g, $config, $valid_acls; - $settings = $config['installedpackages']['squid']['config'][0]; + if (is_array($config['installedpackages']['squid'])) + $settings = $config['installedpackages']['squid']['config'][0]; + else + $settings=array(); $conf = "# This file is automatically generated by pfSense\n"; $conf .= "# Do not edit manually !\n"; @@ -743,31 +771,33 @@ function squid_resync_general() { $conf .= "http_port 127.0.0.1:" . $settings['proxy_port'] . " intercept\n"; } $icp_port = ($settings['icp_port'] ? $settings['icp_port'] : 7); - + $dns_v4_first= ($settings['dns_v4_first'] == "on" ? "on" : "off" ); $pidfile = "{$g['varrun_path']}/squid.pid"; - $language = ($settings['error_language'] ? $settings['error_language'] : 'English'); - $errordir = SQUID_CONFBASE . '/errors/' . $language; + $language = ($settings['error_language'] ? $settings['error_language'] : 'en'); $icondir = SQUID_CONFBASE . '/icons'; $hostname = ($settings['visible_hostname'] ? $settings['visible_hostname'] : 'localhost'); $email = ($settings['admin_email'] ? $settings['admin_email'] : 'admin@localhost'); $logdir = ($settings['log_dir'] ? $settings['log_dir'] : '/var/squid/logs'); - + if (! is_dir($logdir)){ + make_dirs($logdir); + squid_chown_recursive($logdir, 'proxy', 'proxy'); + } $logdir_cache = $logdir . '/cache.log'; $logdir_access = ($settings['log_enabled'] == 'on' ? $logdir . '/access.log' : '/dev/null'); $conf .= <<<EOD -icp_port $icp_port - -pid_filename $pidfile +icp_port {$icp_port} +dns_v4_first {$dns_v4_first} +pid_filename {$pidfile} cache_effective_user proxy cache_effective_group proxy -error_directory $errordir -icon_directory $icondir -visible_hostname $hostname -cache_mgr $email -access_log $logdir_access -cache_log $logdir_cache +error_default_language {$language} +icon_directory {$icondir} +visible_hostname {$hostname} +cache_mgr {$email} +access_log {$logdir_access} +cache_log {$logdir_cache} cache_store_log none sslcrtd_children 0 @@ -818,9 +848,11 @@ EOD; function squid_resync_cache() { global $config, $g; - - $settings = $config['installedpackages']['squidcache']['config'][0]; - + if (is_array($config['installedpackages']['squidcache'])) + $settings = $config['installedpackages']['squidcache']['config'][0]; + else + $settings = array(); + //apply cache settings $cachedir =($settings['harddisk_cache_location'] ? $settings['harddisk_cache_location'] : '/var/squid/cache'); $disk_cache_size = ($settings['harddisk_cache_size'] ? $settings['harddisk_cache_size'] : 100); $level1 = ($settings['level1_subdirs'] ? $settings['level1_subdirs'] : 16); @@ -832,16 +864,15 @@ function squid_resync_cache() { $memory_policy = ($settings['memory_replacement_policy'] ? $settings['memory_replacement_policy'] : 'heap GDSF'); $offline_mode = ($settings['enable_offline'] == 'on' ? 'on' : 'off'); $conf = ''; - if (!isset($settings['harddisk_cache_system'])) { - if ($g['platform'] == "nanobsd") { + if ($g['platform'] == "nanobsd" || !is_array ($config['installedpackages']['squidcache']['config'])) $disk_cache_system = 'null'; - } else { + else $disk_cache_system = 'ufs'; } - } else { + else{ $disk_cache_system = $settings['harddisk_cache_system']; - } + } #'null' storage type dropped. In-memory cache is always present. Remove all cache_dir options to prevent on-disk caching. if ($disk_cache_system != "null") { $disk_cache_opts = "cache_dir {$disk_cache_system} {$cachedir} {$disk_cache_size} {$level1} 256"; @@ -988,8 +1019,11 @@ function squid_resync_redirector() { function squid_resync_nac() { global $config, $valid_acls; - $port = ($settings['proxy_port'] ? $settings['proxy_port'] : 3128); - $settings = $config['installedpackages']['squidnac']['config'][0]; + $port = ($settings['proxy_port'] ? $settings['proxy_port'] : 3128); + if (is_array($config['installedpackages']['squidnac'])) + $settings = $config['installedpackages']['squidnac']['config'][0]; + else + $settings = array(); $webgui_port = $config['system']['webgui']['port']; $addtl_ports = $settings['addtl_ports']; $addtl_sslports = $settings['addtl_sslports']; @@ -1042,18 +1076,18 @@ EOD; http_access allow manager localhost EOD; - if(!empty($settings['ext_cachemanager'])) { - $extmgr = explode(";", ($settings['ext_cachemanager'])); - $count = 1; - $conf .= "\n# Allow external cache managers\n"; -// $conf .= "acl ext_manager src ".$settings['ext_cachemanager']."\n"; - foreach ($extmgr as $mgr) { - $conf .= "acl ext_manager_".$count." src "; - $conf .= $mgr." "; - $conf .= "\n"; - $conf .= "http_access allow manager ext_manager_".$count."\n"; - $count += 1; - }} + + if (is_array($config['installedpackages']['squidcache'])){ + $settings_ch = $config['installedpackages']['squidcache']['config'][0]; + if(!empty($settings_ch['ext_cachemanager'])) { + $extmgr = explode(";", ($settings_ch['ext_cachemanager'])); + $conf .= "\n# Allow external cache managers\n"; + foreach ($extmgr as $mgr) { + $conf .= "acl ext_manager src {$mgr}\n"; + } + $conf .= "http_access allow manager ext_manager\n"; + } + } $conf .= <<<EOD @@ -1073,14 +1107,21 @@ EOD; function squid_resync_traffic() { global $config, $valid_acls; + if(!is_array($valid_acls)) return; - $settings = $config['installedpackages']['squidtraffic']['config'][0]; + if (is_array($config['installedpackages']['squidtraffic'])) + $settings = $config['installedpackages']['squidtraffic']['config'][0]; + else + $settings = array(); + $conf = ''; - - if (!empty($settings['quick_abort_min']) || ($settings['quick_abort_min']) == "0") $conf .= "quick_abort_min {$settings['quick_abort_min']} KB\n"; - if (!empty($settings['quick_abort_max']) || ($settings['quick_abort_max']) == "0") $conf .= "quick_abort_max {$settings['quick_abort_max']} KB\n"; - if (!empty($settings['quick_abort_pct'])) $conf .= "quick_abort_pct {$settings['quick_abort_pct']}\n"; + if (!empty($settings['quick_abort_min']) || ($settings['quick_abort_min']) == "0") + $conf .= "quick_abort_min {$settings['quick_abort_min']} KB\n"; + if (!empty($settings['quick_abort_max']) || ($settings['quick_abort_max']) == "0") + $conf .= "quick_abort_max {$settings['quick_abort_max']} KB\n"; + if (!empty($settings['quick_abort_pct'])) + $conf .= "quick_abort_pct {$settings['quick_abort_pct']}\n"; $up_limit = ($settings['max_upload_size'] ? $settings['max_upload_size'] : 0); $down_limit = ($settings['max_download_size'] ? $settings['max_download_size'] : 0); @@ -1168,10 +1209,18 @@ function squid_resync_auth() { if (is_array($config['installedpackages']['squidauth']['config'])) $settings = $config['installedpackages']['squidauth']['config'][0]; + else + $settings = array(); + if (is_array($config['installedpackages']['squidnac']['config'])) $settingsnac = $config['installedpackages']['squidnac']['config'][0]; + else + $settingsnac = array(); + if (is_array($config['installedpackages']['squid']['config'])) $settingsconfig = $config['installedpackages']['squid']['config'][0]; + else + $settingsconfig = array(); $conf = ''; @@ -1196,9 +1245,9 @@ function squid_resync_auth() { } } - // Unrestricted hosts take precendence over blacklist + // Unrestricted hosts take precedence over blacklist if(! empty($settingsnac['unrestricted_hosts'])) { - if (squid_is_valid_acl('unrestricted_hosts')) { + if (squid_is_valid_acl('unrestricted_hosts') && $settings['unrestricted_auth']!= "on") { $conf .= "# These hosts do not have any restrictions\n"; $conf .= "http_access allow unrestricted_hosts\n"; } @@ -1210,7 +1259,7 @@ function squid_resync_auth() { } } - // Whitelist and blacklist also take precendence over other allow rules + // Whitelist and blacklist also take precedence over other allow rules if(! empty($settingsnac['whitelist'])) { if (squid_is_valid_acl('whitelist')) { $conf .= "# Always allow access to whitelist domains\n"; @@ -1319,7 +1368,10 @@ function squid_resync_users() { function squid_resync_msnt() { global $config; - $settings = $config['installedpackages']['squidauth']['config'][0]; + if (is_array($config['installedpackages']['squidauth'])) + $settings = $config['installedpackages']['squidauth']['config'][0]; + else + $settings = array(); $pdcserver = $settings['auth_server']; $bdcserver = str_replace(',',' ',$settings['msnt_secondary']); $ntdomain = $settings['auth_ntdomain']; @@ -1340,6 +1392,9 @@ function squid_resync() { $boot_process="on"; } + if (is_process_running('squid') && isset($boot_process)) + return; + conf_mount_rw(); foreach (array( SQUID_CONFBASE, SQUID_ACLDIR, @@ -1351,55 +1406,66 @@ function squid_resync() { chgrp($dir, 'proxy'); squid_chown_recursive($dir, 'proxy', 'proxy'); } - if (!isset($boot_process)){ - $conf = squid_resync_general() . "\n"; - $conf .= squid_resync_cache() . "\n"; - $conf .= squid_resync_redirector() . "\n"; - $conf .= squid_resync_upstream() . "\n"; - $conf .= squid_resync_nac() . "\n"; - $conf .= squid_resync_traffic() . "\n"; - $conf .= squid_resync_reverse() . "\n"; - $conf .= squid_resync_auth(); - squid_resync_users(); - squid_write_rcfile(); + $conf = squid_resync_general() . "\n"; + $conf .= squid_resync_cache() . "\n"; + $conf .= squid_resync_redirector() . "\n"; + $conf .= squid_resync_upstream() . "\n"; + $conf .= squid_resync_nac() . "\n"; + $conf .= squid_resync_traffic() . "\n"; + $conf .= squid_resync_reverse() . "\n"; + $conf .= squid_resync_auth(); + squid_resync_users(); + squid_write_rcfile(); + + if(!isset($boot_process)) squid_sync_on_changes(); - - #write config file - file_put_contents(SQUID_CONFBASE . '/squid.conf', $conf); - } + + #write config file + file_put_contents(SQUID_CONFBASE . '/squid.conf', $conf); /* make sure pinger is executable */ if(file_exists("/usr/local/libexec/squid/pinger")) exec("chmod a+x /usr/local/libexec/squid/pinger"); - - $log_dir = $config['installedpackages']['squid']['config'][0]['log_dir'].'/'; - - if(!is_dir($log_dir)) { - log_error("Creating squid log dir $log_dir"); - make_dirs($log_dir); - squid_chown_recursive($log_dir, 'proxy', 'proxy'); - } - - squid_dash_z(); - - if (!is_service_running('squid')) { - log_error("Starting Squid"); - mwexec("/usr/local/sbin/squid"); - } - else { - if (!isset($boot_process)){ - log_error("Reloading Squid for configuration sync"); - mwexec("/usr/local/sbin/squid -k reconfigure"); + $log_dir=""; + #check if squid is enabled + if (is_array($config['installedpackages']['squid']['config'])){ + if ($config['installedpackages']['squid']['config'][0]['active_interface']!= "") + $log_dir = $config['installedpackages']['squid']['config'][0]['log_dir'].'/'; + } + #check if squidreverse is enabled + else if (is_array($config['installedpackages']['squidreversegeneral']['config'])){ + if ($config['installedpackages']['squidreversegeneral']['config'][0]['reverse_interface'] != "") + $log_dir="/var/squid/logs/"; + } + #do not start squid if there is no log dir + if ($log_dir != ""){ + if(!is_dir($log_dir)) { + log_error("Creating squid log dir $log_dir"); + make_dirs($log_dir); + squid_chown_recursive($log_dir, 'proxy', 'proxy'); } + + squid_dash_z(); + + if (!is_service_running('squid')) { + log_error("Starting Squid"); + mwexec("/usr/local/sbin/squid -f " . SQUID_CONFFILE); + } + else { + if (!isset($boot_process)){ + log_error("Reloading Squid for configuration sync"); + mwexec("/usr/local/sbin/squid -k reconfigure -f " . SQUID_CONFFILE); + } + } + + // Sleep for a couple seconds to give squid a chance to fire up fully. + for ($i=0; $i < 10; $i++) { + if (!is_service_running('squid')) + sleep(1); + } + filter_configure(); } - - // Sleep for a couple seconds to give squid a chance to fire up fully. - for ($i=0; $i < 10; $i++) { - if (!is_service_running('squid')) - sleep(1); - } - filter_configure(); conf_mount_ro(); } @@ -1701,16 +1767,19 @@ function squid_generate_rules($type) { } function squid_write_rcfile() { + /* Declare a variable for the SQUID_CONFFILE constant. */ + /* Then the variable can be referenced easily in the Heredoc text that generates the rc file. */ + $squid_conffile_var = SQUID_CONFFILE; $rc = array(); $rc['file'] = 'squid.sh'; $rc['start'] = <<<EOD if [ -z "`ps auxw | grep "[s]quid "|awk '{print $2}'`" ];then - /usr/local/sbin/squid + /usr/local/sbin/squid -f $squid_conffile_var fi EOD; $rc['stop'] = <<<EOD -/usr/local/sbin/squid -k shutdown +/usr/local/sbin/squid -k shutdown -f $squid_conffile_var # Just to be sure... sleep 5 killall -9 squid 2>/dev/null @@ -1719,14 +1788,15 @@ killall pinger 2>/dev/null EOD; $rc['restart'] = <<<EOD if [ -z "`ps auxw | grep "[s]quid "|awk '{print $2}'`" ];then - /usr/local/sbin/squid + /usr/local/sbin/squid -f $squid_conffile_var else - /usr/local/sbin/squid -k reconfigure + /usr/local/sbin/squid -k reconfigure -f $squid_conffile_var fi EOD; conf_mount_rw(); write_rcfile($rc); + conf_mount_ro(); } /* Uses XMLRPC to synchronize the changes to a remote node */ @@ -1820,10 +1890,10 @@ function squid_do_xmlrpc_sync($sync_to_ip, $username, $password) { log_error("squid XMLRPC sync successfully completed with {$url}:{$port}."); } - /* tell squid to reload our settings on the destionation sync host. */ + /* tell squid to reload our settings on the destination sync host. */ $method = 'pfsense.exec_php'; $execcmd = "require_once('/usr/local/pkg/squid.inc');\n"; - $execcmd .= "sync_package_squid();"; + $execcmd .= "squid_resync();"; /* assemble xmlrpc payload */ $params = array( XML_RPC_encode($password), @@ -1851,4 +1921,4 @@ function squid_do_xmlrpc_sync($sync_to_ip, $username, $password) { } -?> +?>
\ No newline at end of file diff --git a/config/squid-reverse/squid.xml b/config/squid-reverse/squid.xml index 764011ea..943f3ed5 100644 --- a/config/squid-reverse/squid.xml +++ b/config/squid-reverse/squid.xml @@ -99,6 +99,10 @@ <url>/pkg.php?xml=squid_users.xml</url> </tab> <tab> + <text>Real time</text> + <url>/squid_monitor.php</url> + </tab> + <tab> <text>Sync</text> <url>/pkg_edit.php?xml=squid_sync.xml</url> </tab> @@ -194,6 +198,22 @@ <chmod>0755</chmod> <item>http://www.pfsense.org/packages/config/squid-reverse/swapstate_check.php</item> </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid-reverse/squid_monitor.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid-reverse/squid_monitor_data.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/squid-reverse/squid_log_parser.php</item> + </additional_files_needed> + <fields> <field> <name>Squid General Settings</name> @@ -251,7 +271,7 @@ <type>checkbox</type> </field> <field> - <fielddescr>Bypass proxy for Private Address Space (RFC 1918) destination</fielddescr> + <fielddescr>Bypass proxy for Private Address destination</fielddescr> <fieldname>private_subnet_proxy_off</fieldname> <description>Do not forward traffic to Private Address Space (RFC 1918) <b>destination</b> through the proxy server but directly through the firewall.</description> <type>checkbox</type> @@ -271,6 +291,12 @@ <size>70</size> </field> <field> + <fielddescr>Resolv dns v4 first</fielddescr> + <fieldname>dns_v4_first</fieldname> + <description><![CDATA[Enable this option to force dns v4 lookup first. This option is very usefull if you have problems to access https sites.]]></description> + <type>checkbox</type> + </field> + <field> <fielddescr>Use alternate DNS-servers for the proxy-server</fielddescr> <fieldname>dns_nameservers</fieldname> <description>If you want to use other DNS-servers than the DNS-forwarder, enter the IPs here, separated by semi-colons (;).</description> @@ -325,7 +351,7 @@ <fieldname>error_language</fieldname> <description>Select the language in which the proxy server will display error messages to users.</description> <type>select</type> - <default_value>English</default_value> + <default_value>en</default_value> </field> <field> <fielddescr>Disable X-Forward</fielddescr> @@ -408,7 +434,7 @@ </custom_php_validation_command> <custom_php_resync_config_command> squid_resync(); - exec("/bin/rm -f /usr/local/etc/rc.d/squid"); + unlink_if_exists("/usr/local/etc/rc.d/squid"); </custom_php_resync_config_command> <custom_php_install_command> update_status("Checking Squid cache... One moment please..."); diff --git a/config/squid-reverse/squid_auth.xml b/config/squid-reverse/squid_auth.xml index 43cbe7ea..307669c5 100644 --- a/config/squid-reverse/squid_auth.xml +++ b/config/squid-reverse/squid_auth.xml @@ -80,6 +80,10 @@ <url>/pkg.php?xml=squid_users.xml</url> </tab> <tab> + <text>Real time</text> + <url>/squid_monitor.php</url> + </tab> + <tab> <text>Sync</text> <url>/pkg_edit.php?xml=squid_sync.xml</url> </tab> diff --git a/config/squid-reverse/squid_cache.xml b/config/squid-reverse/squid_cache.xml index c00322cf..7f371f49 100644 --- a/config/squid-reverse/squid_cache.xml +++ b/config/squid-reverse/squid_cache.xml @@ -80,6 +80,10 @@ <url>/pkg.php?xml=squid_users.xml</url> </tab> <tab> + <text>Real time</text> + <url>/squid_monitor.php</url> + </tab> + <tab> <text>Sync</text> <url>/pkg_edit.php?xml=squid_sync.xml</url> </tab> diff --git a/config/squid-reverse/squid_log_parser.php b/config/squid-reverse/squid_log_parser.php new file mode 100755 index 00000000..f6cd7de8 --- /dev/null +++ b/config/squid-reverse/squid_log_parser.php @@ -0,0 +1,57 @@ +#!/usr/local/bin/php -q +<?php +/* ========================================================================== */ +/* + squid_log_parser.php + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Marcello Coutinho + Copyright (C) 2012 Carlos Cesario - carloscesario@gmail.com + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + +# ------------------------------------------------------------------------------ +# Simple Squid Log parser to rewrite line with date/time human readable +# Usage: cat /var/squid/log/access.log | parser_squid_log.php +# ------------------------------------------------------------------------------ + +$logline = fopen("php://stdin", "r"); +while(!feof($logline)) { + $line = fgets($logline); + $line = rtrim($line); + if ($line != "") { + $fields = explode(' ', $line); + // Apply date format + $fields[0] = date("d.m.Y H:i:s",$fields[0]); + foreach($fields as $field) { + // Write the Squid log line with date/time human readable + echo "{$field} "; + } + echo "\n"; + } +} +fclose($logline); +?>
\ No newline at end of file diff --git a/config/squid-reverse/squid_monitor.php b/config/squid-reverse/squid_monitor.php index cbcc8918..22d7dfcc 100644 --- a/config/squid-reverse/squid_monitor.php +++ b/config/squid-reverse/squid_monitor.php @@ -1,162 +1,192 @@ <?php -/* $Id$ */ /* ========================================================================== */ /* - squid_monitor.php - part of pfSense (http://www.pfSense.com) - Copyright (C) 2012 ccesario @ pfsense forum - All rights reserved. - + squid_monitor.php + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Marcello Coutinho + Copyright (C) 2012 Carlos Cesario - carloscesario@gmail.com + All rights reserved. + */ /* ========================================================================== */ /* - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. */ /* ========================================================================== */ - require_once("/etc/inc/util.inc"); require_once("/etc/inc/functions.inc"); require_once("/etc/inc/pkg-utils.inc"); require_once("/etc/inc/globals.inc"); - require_once("guiconfig.inc"); - - $pfSversion = str_replace("\n", "", file_get_contents("/etc/version")); if(strstr($pfSversion, "1.2")) - $one_two = true; + $one_two = true; $pgtitle = "Status: Proxy Monitor"; include("head.inc"); ?> <body link="#0000CC" vlink="#0000CC" alink="#0000CC"> + <?php include("fbegin.inc"); ?> <?php if($one_two): ?> -<p class="pgtitle"><?=$pgtitle?></font></p> + + <p class="pgtitle"><?=$pgtitle?></font></p> + <?php endif; ?> <?php if ($savemsg) print_info_box($savemsg); ?> -<!-- Function to call squid logs --> +<!-- Function to call programs logs --> <script language="JavaScript"> - function ShowLog(content,url,program) + function showLog(content,url,program) { - var v_maxlines = $('maxlines').getValue(); - var v_strfilter = $('strfilter').getValue(); - var pars = 'maxlines='+escape(v_maxlines) + '&strfilter=' + escape(v_strfilter) + '&program=' + escape(program); - new Ajax.Updater(content,url, { - method: 'post', - parameters: pars, - onSuccess: function() { - window.setTimeout( ShowLog(content,url,program), 100 ); - } - }); - } - - + new PeriodicalExecuter(function(pe) { + new Ajax.Updater(content, url, { + method: 'post', + asynchronous: true, + evalScripts: true, + parameters: { maxlines: $('maxlines').getValue(), + strfilter: $('strfilter').getValue(), + program: program } + }) + }, 1) + } </script> - - -<table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td id="mainarea"> - <div class="tabcont"> - <div id="param"> - <form id="paramsForm" name="paramsForm" method="post"> - <table width="100%" border="0" cellpadding=5" cellspacing="0"> - <tr> - <td width="15%" valign="top" class="vncell"><?php echo "Max lines:"; ?></td> - <td width="85%" class="vtable"> - <select name="maxlines" id="maxlines"> - <option value="5">5 lines</option> - <option value="10" selected="selected">10 lines</option> - <option value="15">15 lines</option> - <option value="20">20 lines</option> - <option value="25">25 lines</option> - <option value="30">30 lines</option> - </select> - <br/> - <span class="vexpl"> - <?php echo "Max. lines to be displayed."; ?> - </span> - </td> - </tr> - <tr> - <td width="15%" valign="top" class="vncell"><?php echo "String filter:"; ?></td> - <td width="85%" class="vtable"> - <input name="strfilter" type="text" class="formfld unknown" id="strfilter" size="50" value=""> - <br/> - <span class="vexpl"> - <?php echo "Enter the string filter: eg. username or ip addr or url."; ?> - </span> - </td> - </tr> - </table> - </form> - </div> - - <form> - <table width="100%" border="0" cellpadding="0" cellspacing="0"> - <tr> - <td colspan="2" valign="top" class="listtopic"> - <center> - Squid Proxy - </center> - </td> - </tr> +<div id="mainlevel"> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr><td> + <?php + $tab_array = array(); + if ($_REQUEST["menu"]=="reverse"){ + $tab_array[] = array(gettext("General"), false, "/pkg_edit.php?xml=squid_reverse_general.xml&id=0"); + $tab_array[] = array(gettext("Web Servers"), false, "/pkg.php?xml=squid_reverse_peer.xml"); + $tab_array[] = array(gettext("Mappings"), false, "/pkg.php?xml=squid_reverse_uri.xml"); + $tab_array[] = array(gettext("Real time"), true, "/squid_monitor.php?menu=reverse"); + $tab_array[] = array(gettext("Sync"), false, "/pkg_edit.php?xml=squid_reverse_sync.xml"); + } + else{ + $tab_array[] = array(gettext("General"), false, "/pkg_edit.php?xml=squid.xml&id=0"); + $tab_array[] = array(gettext("Remote Cache"), false, "/pkg.php?xml=squid_upstream.xml"); + $tab_array[] = array(gettext("Local Cache"), false, "/pkg_edit.php?xml=squid_cache.xml&id=0"); + $tab_array[] = array(gettext("ACLs"), false, "/pkg_edit.php?xml=squid_nac.xml&id=0"); + $tab_array[] = array(gettext("Traffic Mgmt"), false, "/pkg_edit.php?xml=squid_traffic.xml&id=0"); + $tab_array[] = array(gettext("Authentication"), false, "/pkg_edit.php?xml=squid_auth.xml&id=0"); + $tab_array[] = array(gettext("Users"), false, "/pkg.php?xml=squid_users.xml"); + $tab_array[] = array(gettext("Real time"), true, "/squid_monitor.php"); + $tab_array[] = array(gettext("Sync"), false, "/pkg_edit.php?xml=squid_sync.xml"); + } + display_top_tabs($tab_array); + ?> +</td></tr> + <tr> + <td> +<div id="mainarea" style="padding-top: 0px; padding-bottom: 0px; "> + <form id="paramsForm" name="paramsForm" method="post"> + <table class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="6"> + <tbody> + <tr> + <td width="22%" valign="top" class="vncellreq">Max lines:</td> + <td width="78%" class="vtable"> + <select name="maxlines" id="maxlines"> + <option value="5">5 lines</option> + <option value="10" selected="selected">10 lines</option> + <option value="15">15 lines</option> + <option value="20">20 lines</option> + <option value="25">25 lines</option> + <option value="30">30 lines</option> + </select> + <br/> + <span class="vexpl"> + <?=gettext("Max. lines to be displayed.");?> + </span> + </td> + </tr> + <tr> + <td width="22%" valign="top" class="vncellreq">String filter:</td> + <td width="78%" class="vtable"> + <input name="strfilter" type="text" class="formfld search" id="strfilter" size="50" value=""> + <br/> + <span class="vexpl"> + <?=gettext("Enter a grep like string/pattern to filterlog.");?><br> + <?=gettext("eg. username, ip addr, url.");?><br> + <?=gettext("Use <b>!</b> to invert the sense of matching, to select non-matching lines.");?> + </span> + </td> + </tr> + </tbody> + </table> + </form> + + <!-- Squid Table --> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tbody> + <tr> + <td> + <table class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> - <td> - <table iD="squidView" width="100%" border="0" cellpadding="0" cellspacing="0"> - <script language="JavaScript"> - ShowLog('squidView', 'squid_monitor_data.php','squid'); - </script> - </table> - </td> - </tr> - <tr> - <td colspan="2" valign="top" class="listtopic"> - <center> - SquidGuard - </center> - </td> + <td colspan="6" class="listtopic"><center><?=gettext("Squid Logs"); ?><center></td> </tr> + <tbody id="squidView"> + <script language="JavaScript"> + // Call function to show squid log + showLog('squidView', 'squid_monitor_data.php','squid'); + </script> + </tbody> + </table> + </td> + </tr> + </tbody> + </table> +<?php if ($_REQUEST["menu"]!="reverse"){?> + <!-- SquidGuard Table --> + <table width="100%" border="0" cellpadding="0" cellspacing="0"> + <tbody> + <tr> + <td> + <table class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> - <td> - <table id="sguardView" width="100%" border="0" cellpadding="5" cellspacing="0"> - <script language="JavaScript"> - ShowLog('sguardView', 'squid_monitor_data.php','sguard'); - </script> - </table> - </td> + <td colspan="5" class="listtopic"><center><?=gettext("SquidGuard Logs"); ?><center></td> </tr> + <tbody id="sguardView"> + <script language="JavaScript"> + // Call function to show squidGuard log + showLog('sguardView', 'squid_monitor_data.php','sguard'); + </script> + </tbody> </table> - </form> - </div> - </td> - </tr> + </td> + </tr> + </tbody> + </table> +</div> +<?php }?> +</td> +</tr> </table> +</div> + <?php include("fend.inc"); @@ -164,4 +194,3 @@ include("fend.inc"); </body> </html> - diff --git a/config/squid-reverse/squid_monitor_data.php b/config/squid-reverse/squid_monitor_data.php index 46280446..7e27919d 100644 --- a/config/squid-reverse/squid_monitor_data.php +++ b/config/squid-reverse/squid_monitor_data.php @@ -1,136 +1,175 @@ -<?php -/* $Id$ */ +<?php /* ========================================================================== */ /* - squid_monitor_data.php - part of pfSense (http://www.pfSense.com) - Copyright (C) 2012 ccesario @ pfsense forum - All rights reserved. - + squid_monitor_data.php + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Marcello Coutinho + Copyright (C) 2012 Carlos Cesario - carloscesario@gmail.com + All rights reserved. + */ /* ========================================================================== */ /* - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. */ /* ========================================================================== */ +# ------------------------------------------------------------------------------ +# Defines +# ------------------------------------------------------------------------------ +require_once("guiconfig.inc"); + +# ------------------------------------------------------------------------------ +# Requests +# ------------------------------------------------------------------------------ if ($_POST) { - switch (strtolower($_POST['program'])) { + # Actions + $filter = preg_replace('/(@|!|>|<)/',"",htmlspecialchars($_POST['strfilter'])); + $program = strtolower($_POST['program']); + switch ($program) { case 'squid': - showSquid(); - break; - case 'sguard'; - showSGuard(); - break; + // Define log file + $log='/var/squid/logs/access.log'; + //show table headers + show_tds(array("Date","IP","Status","Address","User","Destination")); + //fetch lines + $logarr=fetch_log($log); + // Print lines + foreach ($logarr as $logent) { + // Split line by space delimiter + $logline = preg_split("/\s+/", $logent); + + // Apply date format to first line + //$logline[0] = date("d.m.Y H:i:s",$logline[0]); + + // Word wrap the URL + $logline[7] = htmlentities($logline[7]); + $logline[7] = html_autowrap($logline[7]); + + // Remove /(slash) in destination row + $logline_dest = preg_split("/\//", $logline[9]); + + // Apply filter and color + // Need validate special chars + if ($filter != "") + $logline = preg_replace("@($filter)@i","<spam><font color='red'>$1</font></span>",$logline); + echo "<tr valign=\"top\">\n"; + echo "<td class=\"listlr\" nowrap>{$logline[0]} {$logline[1]}</td>\n"; + echo "<td class=\"listr\">{$logline[3]}</td>\n"; + echo "<td class=\"listr\">{$logline[4]}</td>\n"; + echo "<td class=\"listr\" width=\"*\">{$logline[7]}</td>\n"; + echo "<td class=\"listr\">{$logline[8]}</td>\n"; + echo "<td class=\"listr\">{$logline_dest[1]}</td>\n"; + echo "</tr>\n"; + } + break; + case 'sguard'; + $log='/var/squidGuard/log/block.log'; + //show table headers + show_tds(array("Date-Time","ACL","Address","Host","User")); + //fetch lines + $logarr=fetch_log($log); + foreach ($logarr as $logent) { + // Split line by space delimiter + $logline = preg_split("/\s+/", $logent); + + // Apply time format + $logline[0] = date("d.m.Y", strtotime($logline[0])); + + // Word wrap the URL + $logline[4] = htmlentities($logline[4]); + $logline[4] = html_autowrap($logline[4]); + + + // Apply filter color + // Need validate special chars + if ($filter != "") + $logline = preg_replace("@($filter)@i","<spam><font color='red'>$1</font></span>",$logline); + + + echo "<tr>\n"; + echo "<td class=\"listlr\" nowrap>{$logline[0]} {$logline[1]}</td>\n"; + echo "<td class=\"listr\">{$logline[3]}</td>\n"; + echo "<td class=\"listr\" width=\"*\">{$logline[4]}</td>\n"; + echo "<td class=\"listr\">{$logline[5]}</td>\n"; + echo "<td class=\"listr\">{$logline[6]}</td>\n"; + echo "</tr>\n"; + } + break; } } - - -// Show Squid Logs -function showSquid() { - echo "<tr>"; - echo "<td class=\"listhdrr\">Date</td>"; - echo "<td class=\"listhdrr\">IP</td>"; - echo "<td class=\"listhdrr\">Status</td>"; - echo "<td class=\"listhdrr\">Address</td>"; - echo "<td class=\"listhdrr\">User</td>"; - echo "<td class=\"listhdrr\">Destination</td>"; - echo "</tr>"; - - // Get Data from form post - $lines = $_POST['maxlines']; - $filter = $_POST['strfilter']; - - if ($filter != "") { - $exprfilter = "| grep -i $filter"; - } else { - $exprfilter = ""; - } - - // TODO FIX: - // Remove the hard link (maybe, get from config) - // - exec("tail -r -n $lines /var/squid/logs/access.log $exprfilter",$logarr); - - foreach ($logarr as $logent) { - $logline = preg_split("/\s+/", $logent); - - if ($filter != "") - $logline = preg_replace("/$filter/","<spam style='color:red'>$filter</spam>",$logline); - - echo "<tr>\n"; - echo "<td class=\"listr\">".date("d/m/y H:i:s",$logline[0])."</td>\n"; - echo "<td class=\"listr\">".$logline[2]."</td>\n"; - echo "<td class=\"listr\">".$logline[3]."</td>\n"; - echo "<td class=\"listr\" nowrap>".$logline[6]."</td>\n"; - echo "<td class=\"listr\">".$logline[7]."</td>\n"; - echo "<td class=\"listr\">".$logline[8]."</td>\n"; - echo "</tr>\n"; - } +# ------------------------------------------------------------------------------ +# Functions +# ------------------------------------------------------------------------------ + +// From SquidGuard Package +function html_autowrap($cont) +{ + # split strings + $p = 0; + $pstep = 25; + $str = $cont; + $cont = ''; + for ( $p = 0; $p < strlen($str); $p += $pstep ) { + $s = substr( $str, $p, $pstep ); + if ( !$s ) break; + $cont .= $s . "<wbr/>"; + } + return $cont; } -// Show SquidGuard Logs -function showSGuard() { - - echo "<tr>"; - echo "<td class=\"listhdrr\">Date</td>"; - echo "<td class=\"listhdrr\">Hour</td>"; - echo "<td class=\"listhdrr\">ACL</td>"; - echo "<td class=\"listhdrr\">Address</td>"; - echo "<td class=\"listhdrr\">Host</td>"; - echo "<td class=\"listhdrr\">User</td>"; - echo "</tr>"; - - - // Get Data from form post +// Show Squid Logs +function fetch_log($log){ + global $filter,$program; + // Get Data from form post $lines = $_POST['maxlines']; - $filter = $_POST['strfilter']; - - if ($filter != "") { - $exprfilter = "| grep -i $filter"; - } else { - $exprfilter = ""; + if (preg_match("/!/",htmlspecialchars($_POST['strfilter']))) + $grep_arg="-iv"; + else + $grep_arg="-i"; + + //Check program to execute or no the parser + if($program == "squid") + $parser = "| php -q squid_log_parser.php"; + else + $parser = ""; + + // Get logs based in filter expression + if($filter != "") { + exec("tail -2000 {$log} | /usr/bin/grep {$grep_arg} " . escapeshellarg($filter). " | tail -r -n {$lines} {$parser} " , $logarr); } - - // TODO FIX: - // Remove the hard link (maybe, get from config) - // - exec("tail -r -n $lines /var/squidGuard/log/block.log $exprfilter",$logarr); - - foreach ($logarr as $logent) { - $logline = preg_split("/\s+/", $logent); - - if ($filter != "") - $logline = preg_replace("/$filter/","<spam style='color:red'>$filter</spam>",$logline); - - echo "<tr>\n"; - echo "<td class=\"listr\">".$logline[0]."</td>\n"; - echo "<td class=\"listr\">".$logline[1]."</td>\n"; - echo "<td class=\"listr\">".$logline[3]."</td>\n"; - echo "<td class=\"listr\">".$logline[4]."</td>\n"; - echo "<td class=\"listr\">".$logline[5]."</td>\n"; - echo "<td class=\"listr\">".$logline[6]."</td>\n"; - echo "</tr>\n"; + else { + exec("tail -r -n {$lines} {$log} {$parser}", $logarr); } + // return logs + return $logarr; +}; + +function show_tds($tds){ + echo "<tr valign='top'>\n"; + foreach ($tds as $td){ + echo "<td class='listhdrr'>".gettext($td)."</td>\n"; + } + echo "</tr>\n"; } ?> diff --git a/config/squid-reverse/squid_nac.xml b/config/squid-reverse/squid_nac.xml index c951b6f3..bc4a278e 100644 --- a/config/squid-reverse/squid_nac.xml +++ b/config/squid-reverse/squid_nac.xml @@ -80,6 +80,10 @@ <url>/pkg.php?xml=squid_users.xml</url> </tab> <tab> + <text>Real time</text> + <url>/squid_monitor.php</url> + </tab> + <tab> <text>Sync</text> <url>/pkg_edit.php?xml=squid_sync.xml</url> </tab> @@ -101,7 +105,7 @@ <field> <fielddescr>Unrestricted IPs</fielddescr> <fieldname>unrestricted_hosts</fieldname> - <description>Enter each unrestricted IP address on a new line that is not to be filtered out by the other access control directives set in this page.</description> + <description>Enter unrestricted IP address / network(in CIDR format) on a new line that is not to be filtered out by the other access control directives set in this page.</description> <type>textarea</type> <cols>50</cols> <rows>5</rows> @@ -110,7 +114,7 @@ <field> <fielddescr>Banned host addresses</fielddescr> <fieldname>banned_hosts</fieldname> - <description>Enter each IP address on a new line that is not to be allowed to use the proxy.</description> + <description>Enter each IP address / network(in CIDR format) on a new line that is not to be allowed to use the proxy.</description> <type>textarea</type> <cols>50</cols> <rows>5</rows> diff --git a/config/squid-reverse/squid_ng.inc b/config/squid-reverse/squid_ng.inc index 03f6d48c..b0604b02 100644 --- a/config/squid-reverse/squid_ng.inc +++ b/config/squid-reverse/squid_ng.inc @@ -796,11 +796,11 @@ function global_write_squid_config() touch($squidconfig); } /* end function write_squid_config */ -function custom_php_install_command() { +function squid3_custom_php_install_command() { /* write initial static config for transparent proxy */ write_static_squid_config(); - touch("/tmp/custom_php_install_command"); + touch("/tmp/squid3_custom_php_install_command"); /* make sure this all exists, see: * http://forum.pfsense.org/index.php?topic=23.msg2391#msg2391 @@ -903,7 +903,7 @@ function custom_php_install_command() { start_service("squid"); } -function custom_php_deinstall_command() { +function squid3_custom_php_deinstall_command() { update_output_window("Stopping proxy service..."); stop_service("squid"); sleep(1); diff --git a/config/squid-reverse/squid_ng.xml b/config/squid-reverse/squid_ng.xml index 5d956387..142536d6 100644 --- a/config/squid-reverse/squid_ng.xml +++ b/config/squid-reverse/squid_ng.xml @@ -255,13 +255,13 @@ start_service("squid"); </custom_add_php_command_late> <custom_php_install_command> - custom_php_install_command(); + squid3_custom_php_install_command(); write_static_squid_config(); mwexec("/usr/local/sbin/squid -k reconfigure"); start_service("squid"); </custom_php_install_command> <custom_php_deinstall_command> - custom_php_deinstall_command(); + squid3_custom_php_deinstall_command(); stop_service("squid"); </custom_php_deinstall_command> </packagegui> diff --git a/config/squid-reverse/squid_reverse.inc b/config/squid-reverse/squid_reverse.inc index b208b7b1..21b6c668 100644 --- a/config/squid-reverse/squid_reverse.inc +++ b/config/squid-reverse/squid_reverse.inc @@ -79,7 +79,7 @@ function squid_resync_reverse() { $conf .= "http_port {$real_ifaces[$i][0]}:{$http_port} accel defaultsite={$http_defsite} vhost\n"; //HTTPS if (!empty($settings['reverse_https'])) - $conf .= "https_port {$real_ifaces[$i][0]}:{$https_port} accel cert={$reverse_crt} key={$reverse_key} defaultsite={$https_defsite}\n"; + $conf .= "https_port {$real_ifaces[$i][0]}:{$https_port} accel cert={$reverse_crt} key={$reverse_key} defaultsite={$https_defsite} vhost\n"; } } @@ -91,7 +91,7 @@ function squid_resync_reverse() { $conf .= "http_port {$reip}:{$http_port} accel defaultsite={$http_defsite} vhost\n"; //HTTPS if (!empty($settings['reverse_https'])) - $conf .= "https_port {$reip}:{$https_port} accel cert={$reverse_crt} key={$reverse_key} defaultsite={$https_defsite}\n"; + $conf .= "https_port {$reip}:{$https_port} accel cert={$reverse_crt} key={$reverse_key} defaultsite={$https_defsite} vhost\n"; } } @@ -104,10 +104,10 @@ function squid_resync_reverse() { foreach ($reverse_peers as $rp){ if ($rp['enable'] =="on" && $rp['name'] !="" && $rp['ip'] !="" && $rp['port'] !=""){ $conf_peer = "#{$rp['description']}\n"; - $conf_peer .= "cache_peer {$rp['ip']} parent {$rp['port']} 0 proxy-only no-query originserver login=PASS "; + $conf_peer .= "cache_peer {$rp['ip']} parent {$rp['port']} 0 proxy-only no-query no-digest originserver login=PASS "; if($rp['protocol'] == 'HTTPS') $conf_peer .= "ssl sslflags=DONT_VERIFY_PEER front-end-https=auto "; - $conf_peer .= "name={$rp['name']}\n\n"; + $conf_peer .= "name=rvp_{$rp['name']}\n\n"; // add peer only if reverse proxy is enabled for http if($rp['protocol'] == 'HTTP' && $settings['reverse_http'] =="on"){ @@ -116,8 +116,10 @@ function squid_resync_reverse() { } // add peer only if if reverse proxy is enabled for https if($rp['protocol'] == 'HTTPS' && $settings['reverse_https'] =="on"){ - $conf .= $conf_peer; - array_push($active_peers,$rp['name']); + if (!in_array($rp['name'],$active_peers)){ + $conf .= $conf_peer; + array_push($active_peers,$rp['name']); + } } } } @@ -150,14 +152,18 @@ function squid_resync_reverse() { if ($rm['enable'] == "on" && $rm['name']!="" && $rm['peers']!=""){ if (is_array($rm['row'])) foreach ($rm['row'] as $uri){ - $url_regex=($uri['vhost'] == ''?$settings['reverse_external_fqdn']:$uri['vhost']); - $conf .= "acl {$rm['name']} url_regex -i {$url_regex}/{$uri['uri']}.*$\n"; - $cache_peer_never_direct_conf .= "never_direct allow {$rm['name']}\n"; - $http_access_conf .= "http_access allow {$rm['name']}\n"; - foreach (explode(',',$rm['peers']) as $map_peer) - if (in_array($map_peer,$active_peers)){ - $cache_peer_allow_conf .= "cache_peer_access {$map_peer} allow {$rm['name']}\n"; - $cache_peer_deny_conf .= "cache_peer_access {$map_peer} deny allsrc\n"; + $url_regex=($uri['uri'] == '' ? $settings['reverse_external_fqdn'] : $uri['uri'] ); + //$conf .= "acl rvm_{$rm['name']} url_regex -i {$uri['uri']}{$url_regex}.*$\n"; + $conf .= "acl rvm_{$rm['name']} url_regex -i {$url_regex}\n"; + if($rm['name'] != $last_rm_name){ + $cache_peer_never_direct_conf .= "never_direct allow rvm_{$rm['name']}\n"; + $http_access_conf .= "http_access allow rvm_{$rm['name']}\n"; + foreach (explode(',',$rm['peers']) as $map_peer) + if (in_array($map_peer,$active_peers)){ + $cache_peer_allow_conf .= "cache_peer_access rvp_{$map_peer} allow rvm_{$rm['name']}\n"; + $cache_peer_deny_conf .= "cache_peer_access rvp_{$map_peer} deny allsrc\n"; + } + $last_rm_name=$rm['name']; } } } diff --git a/config/squid-reverse/squid_reverse.xml b/config/squid-reverse/squid_reverse.xml index ae0c0e8a..ce09f8e7 100644 --- a/config/squid-reverse/squid_reverse.xml +++ b/config/squid-reverse/squid_reverse.xml @@ -84,6 +84,10 @@ <url>/pkg.php?xml=squid_users.xml</url> </tab> <tab> + <text>Real time</text> + <url>/squid_monitor.php</url> + </tab> + <tab> <text>Sync</text> <url>/pkg_edit.php?xml=squid_sync.xml</url> </tab> diff --git a/config/squid-reverse/squid_reverse_general.xml b/config/squid-reverse/squid_reverse_general.xml index ff74b9d5..ec0bcb7a 100644 --- a/config/squid-reverse/squid_reverse_general.xml +++ b/config/squid-reverse/squid_reverse_general.xml @@ -64,6 +64,10 @@ <url>/pkg.php?xml=squid_reverse_uri.xml</url> </tab> <tab> + <text>Real time</text> + <url>/squid_monitor.php?menu=reverse</url> + </tab> + <tab> <text>Sync</text> <url>/pkg_edit.php?xml=squid_reverse_sync.xml&id=0</url> </tab> diff --git a/config/squid-reverse/squid_reverse_peer.xml b/config/squid-reverse/squid_reverse_peer.xml index fb853eb3..6341567e 100644 --- a/config/squid-reverse/squid_reverse_peer.xml +++ b/config/squid-reverse/squid_reverse_peer.xml @@ -64,6 +64,10 @@ <url>/pkg.php?xml=squid_reverse_uri.xml</url> </tab> <tab> + <text>Real time</text> + <url>/squid_monitor.php?menu=reverse</url> + </tab> + <tab> <text>Sync</text> <url>/pkg_edit.php?xml=squid_reverse_sync.xml&id=0</url> </tab> diff --git a/config/squid-reverse/squid_reverse_sync.xml b/config/squid-reverse/squid_reverse_sync.xml index d666d4e8..408f14f1 100755 --- a/config/squid-reverse/squid_reverse_sync.xml +++ b/config/squid-reverse/squid_reverse_sync.xml @@ -59,6 +59,10 @@ <url>/pkg.php?xml=squid_reverse_uri.xml</url> </tab> <tab> + <text>Real time</text> + <url>/squid_monitor.php?menu=reverse</url> + </tab> + <tab> <text>Sync</text> <url>/pkg_edit.php?xml=squid_reverse_sync.xml&id=0</url> <active/> diff --git a/config/squid-reverse/squid_reverse_uri.xml b/config/squid-reverse/squid_reverse_uri.xml index a7a5a6d6..81c9af3b 100644 --- a/config/squid-reverse/squid_reverse_uri.xml +++ b/config/squid-reverse/squid_reverse_uri.xml @@ -64,6 +64,10 @@ <active/> </tab> <tab> + <text>Real time</text> + <url>/squid_monitor.php?menu=reverse</url> + </tab> + <tab> <text>Sync</text> <url>/pkg_edit.php?xml=squid_reverse_sync.xml&id=0</url> </tab> @@ -131,16 +135,12 @@ <type>rowhelper</type> <rowhelper> <rowhelperfield> - <fielddescr>URI</fielddescr> + <fielddescr><![CDATA[<strong>Url regex to match</strong><br><br> + Samples: .mydomain.com .mydomain.com/test<br> + www.mydomain.com http://www.mydomain.com/ ^http://www.mydomain.com/.*$]]></fielddescr> <fieldname>uri</fieldname> <type>input</type> - <size>25</size> - </rowhelperfield> - <rowhelperfield> - <fielddescr>[http://|https://]vhost fqdn(optional)</fielddescr> - <fieldname>vhost</fieldname> - <type>input</type> - <size>40</size> + <size>70</size> </rowhelperfield> </rowhelper> </field> diff --git a/config/squid-reverse/squid_sync.xml b/config/squid-reverse/squid_sync.xml index c581d2c5..62a726f4 100755 --- a/config/squid-reverse/squid_sync.xml +++ b/config/squid-reverse/squid_sync.xml @@ -75,6 +75,10 @@ <url>/pkg.php?xml=squid_users.xml</url> </tab> <tab> + <text>Real time</text> + <url>/squid_monitor.php</url> + </tab> + <tab> <text>Sync</text> <url>/pkg_edit.php?xml=squid_sync.xml</url> <active/> diff --git a/config/squid-reverse/squid_traffic.xml b/config/squid-reverse/squid_traffic.xml index b1799cce..62269792 100644 --- a/config/squid-reverse/squid_traffic.xml +++ b/config/squid-reverse/squid_traffic.xml @@ -80,6 +80,10 @@ <url>/pkg.php?xml=squid_users.xml</url> </tab> <tab> + <text>Real time</text> + <url>/squid_monitor.php</url> + </tab> + <tab> <text>Sync</text> <url>/pkg_edit.php?xml=squid_sync.xml</url> </tab> diff --git a/config/squid-reverse/squid_upstream.xml b/config/squid-reverse/squid_upstream.xml index 126a0710..049d301c 100644 --- a/config/squid-reverse/squid_upstream.xml +++ b/config/squid-reverse/squid_upstream.xml @@ -81,6 +81,10 @@ <url>/pkg.php?xml=squid_users.xml</url> </tab> <tab> + <text>Real time</text> + <url>/squid_monitor.php</url> + </tab> + <tab> <text>Sync</text> <url>/pkg_edit.php?xml=squid_sync.xml</url> </tab> diff --git a/config/squid-reverse/squid_users.xml b/config/squid-reverse/squid_users.xml index 295ce4fa..791a5fa9 100644 --- a/config/squid-reverse/squid_users.xml +++ b/config/squid-reverse/squid_users.xml @@ -82,6 +82,10 @@ <active/> </tab> <tab> + <text>Real time</text> + <url>/squid_monitor.php</url> + </tab> + <tab> <text>Sync</text> <url>/pkg_edit.php?xml=squid_sync.xml</url> </tab> diff --git a/config/squid/squid.inc b/config/squid/squid.inc index ba0943f7..30f3884c 100644 --- a/config/squid/squid.inc +++ b/config/squid/squid.inc @@ -39,7 +39,14 @@ require_once('service-utils.inc'); if(!function_exists("filter_configure")) require_once("filter.inc"); -define('SQUID_CONFBASE', '/usr/local/etc/squid'); +$pf_version=substr(trim(file_get_contents("/etc/version")),0,3); +if ($pf_version > 2.0) + define('SQUID_LOCALBASE', '/usr/pbi/squid-' . php_uname("m")); +else + define('SQUID_LOCALBASE','/usr/local'); + + +define('SQUID_CONFBASE',SQUID_LOCALBASE . '/etc/squid'); define('SQUID_BASE', '/var/squid/'); define('SQUID_ACLDIR', '/var/squid/acl'); define('SQUID_PASSWD', '/var/etc/squid.passwd'); @@ -94,12 +101,12 @@ function squid_dash_z() { if(!is_dir($cachedir.'/00/')) { log_error("Creating squid cache subdirs in $cachedir"); - mwexec("/usr/local/sbin/squid -k shutdown"); + mwexec(SQUID_LOCALBASE . "/sbin/squid -k shutdown"); sleep(5); - mwexec("/usr/local/sbin/squid -k kill"); + mwexec(SQUID_LOCALBASE . "/sbin/squid -k kill"); // Double check permissions here, should be safe to recurse cache dir if it's small here. mwexec("/usr/sbin/chown -R proxy:proxy $cachedir"); - mwexec("/usr/local/sbin/squid -z"); + mwexec(SQUID_LOCALBASE . "/sbin/squid -z"); } if(file_exists("/var/squid/cache/swap.state")) { @@ -204,12 +211,12 @@ function squid_install_command() { update_status("Creating squid cache pools... One moment please..."); squid_dash_z(); /* make sure pinger is executable */ - if(file_exists("/usr/local/libexec/squid/pinger")) - exec("/bin/chmod a+x /usr/local/libexec/squid/pinger"); - if(file_exists("/usr/local/etc/rc.d/squid")) - exec("/bin/rm /usr/local/etc/rc.d/squid"); + if(file_exists(SQUID_LOCALBASE . "/libexec/squid/pinger")) + exec("/bin/chmod a+x " . SQUID_LOCALBASE . "/libexec/squid/pinger"); + if(file_exists(SQUID_LOCALBASE . "/etc/rc.d/squid")) + exec("/bin/rm " . SQUID_LOCALBASE . "/etc/rc.d/squid"); squid_write_rcfile(); - exec("chmod a+rx /usr/local/libexec/squid/dnsserver"); + exec("chmod a+rx " . SQUID_LOCALBASE . "/libexec/squid/dnsserver"); if(file_exists("/usr/local/pkg/swapstate_check.php")) exec("/bin/chmod a+x /usr/local/pkg/swapstate_check.php"); @@ -235,11 +242,11 @@ function squid_install_command() { if (!is_service_running('squid')) { update_status("Starting... One moment please..."); log_error("Starting Squid"); - mwexec_bg("/usr/local/sbin/squid -D"); + mwexec_bg(SQUID_LOCALBASE . "/sbin/squid -D"); } else { update_status("Reloading Squid for configuration sync... One moment please..."); log_error("Reloading Squid for configuration sync"); - mwexec("/usr/local/sbin/squid -k reconfigure"); + mwexec(SQUID_LOCALBASE . "/sbin/squid -k reconfigure"); } /* restart proxy alarm scripts */ @@ -567,7 +574,7 @@ function squid_install_cron($should_install) { $cron_item['month'] = "*"; $cron_item['wday'] = "*"; $cron_item['who'] = "root"; - $cron_item['command'] = "/bin/rm {$cachedir}/swap.state; /usr/local/sbin/squid -k rotate"; + $cron_item['command'] = "/bin/rm {$cachedir}/swap.state; " . SQUID_LOCALBASE . "/sbin/squid -k rotate"; $config['cron']['item'][] = $cron_item; $need_write = true; } @@ -1042,19 +1049,19 @@ function squid_resync_auth() { $prompt = ($settings['auth_prompt'] ? $settings['auth_prompt'] : 'Please enter your credentials to access the proxy'); switch ($auth_method) { case 'local': - $conf .= 'auth_param basic program /usr/local/libexec/squid/ncsa_auth ' . SQUID_PASSWD . "\n"; + $conf .= 'auth_param basic program ' . SQUID_LOCALBASE . '/libexec/squid/ncsa_auth ' . SQUID_PASSWD . "\n"; break; case 'ldap': $port = (isset($settings['auth_server_port']) ? ":{$settings['auth_server_port']}" : ''); $password = (isset($settings['ldap_pass']) ? "-w {$settings['ldap_pass']}" : ''); - $conf .= "auth_param basic program /usr/local/libexec/squid/squid_ldap_auth -v {$settings['ldap_version']} -b {$settings['ldap_basedomain']} -D {$settings['ldap_user']} $password -f \"{$settings['ldap_filter']}\" -u {$settings['ldap_userattribute']} -P {$settings['auth_server']}$port\n"; + $conf .= "auth_param basic program " . SQUID_LOCALBASE . "/libexec/squid/squid_ldap_auth -v {$settings['ldap_version']} -b {$settings['ldap_basedomain']} -D {$settings['ldap_user']} $password -f \"{$settings['ldap_filter']}\" -u {$settings['ldap_userattribute']} -P {$settings['auth_server']}$port\n"; break; case 'radius': $port = (isset($settings['auth_server_port']) ? "-p {$settings['auth_server_port']}" : ''); - $conf .= "auth_param basic program /usr/local/libexec/squid/squid_radius_auth -w {$settings['radius_secret']} -h {$settings['auth_server']} $port\n"; + $conf .= "auth_param basic program " . SQUID_LOCALBASE . "/libexec/squid/squid_radius_auth -w {$settings['radius_secret']} -h {$settings['auth_server']} $port\n"; break; case 'msnt': - $conf .= "auth_param basic program /usr/local/libexec/squid/msnt_auth\n"; + $conf .= "auth_param basic program " . SQUID_LOCALBASE . "/libexec/squid/msnt_auth\n"; squid_resync_msnt(); break; } @@ -1134,8 +1141,8 @@ function squid_resync() { squid_write_rcfile(); /* make sure pinger is executable */ - if(file_exists("/usr/local/libexec/squid/pinger")) - exec("chmod a+x /usr/local/libexec/squid/pinger"); + if(file_exists(SQUID_LOCALBASE . "/libexec/squid/pinger")) + exec("chmod a+x " . SQUID_LOCALBASE . "/libexec/squid/pinger"); foreach (array( SQUID_CONFBASE, SQUID_ACLDIR, @@ -1158,10 +1165,10 @@ function squid_resync() { if (!is_service_running('squid')) { log_error("Starting Squid"); - mwexec("/usr/local/sbin/squid -D"); + mwexec(SQUID_LOCALBASE . "/sbin/squid -D"); } else { log_error("Reloading Squid for configuration sync"); - mwexec("/usr/local/sbin/squid -k reconfigure"); + mwexec(SQUID_LOCALBASE . "/sbin/squid -k reconfigure"); } // Sleep for a couple seconds to give squid a chance to fire up fully. @@ -1437,15 +1444,16 @@ function squid_generate_rules($type) { function squid_write_rcfile() { $rc = array(); + $SQUID_LOCALBASE = SQUID_LOCALBASE; $rc['file'] = 'squid.sh'; $rc['start'] = <<<EOD if [ -z "`ps auxw | grep "[s]quid -D"|awk '{print $2}'`" ];then - /usr/local/sbin/squid -D + {$SQUID_LOCALBASE}/sbin/squid -D fi EOD; $rc['stop'] = <<<EOD -/usr/local/sbin/squid -k shutdown +{$SQUID_LOCALBASE}/sbin/squid -k shutdown # Just to be sure... sleep 5 killall -9 squid 2>/dev/null @@ -1454,13 +1462,14 @@ killall pinger 2>/dev/null EOD; $rc['restart'] = <<<EOD if [ -z "`ps auxw | grep "[s]quid -D"|awk '{print $2}'`" ];then - /usr/local/sbin/squid -D + {$SQUID_LOCALBASE}/sbin/squid -D else - /usr/local/sbin/squid -k reconfigure + {$SQUID_LOCALBASE}/sbin/squid -k reconfigure fi EOD; conf_mount_rw(); write_rcfile($rc); + conf_mount_ro(); } ?> diff --git a/config/squid3/proxy_monitor.sh b/config/squid3/proxy_monitor.sh index fa5a87bb..00430018 100644 --- a/config/squid3/proxy_monitor.sh +++ b/config/squid3/proxy_monitor.sh @@ -27,6 +27,11 @@ # POSSIBILITY OF SUCH DAMAGE. # +if [ `pgrep -f "proxy_monitor.sh"|wc -l` -ge 1 ]; then + exit 0 +fi + + set -e LOOP_SLEEP=55 diff --git a/config/squid3/squid.xml b/config/squid3/squid.xml index f82cf81a..ea13625e 100644 --- a/config/squid3/squid.xml +++ b/config/squid3/squid.xml @@ -249,7 +249,7 @@ <fieldname>error_language</fieldname> <description>Select the language in which the proxy server will display error messages to users.</description> <type>select</type> - <default_value>English</default_value> + <default_value>en</default_value> </field> <field> <fielddescr>Disable X-Forward</fielddescr> diff --git a/config/squidGuard/squidguard_configurator.inc b/config/squidGuard/squidguard_configurator.inc index c69ef0ee..cd5eaadb 100644 --- a/config/squidGuard/squidguard_configurator.inc +++ b/config/squidGuard/squidguard_configurator.inc @@ -1543,11 +1543,10 @@ if(!function_exists("is_url")) { function is_url($url) { if (empty($url)) return false; - if (eregi("^http://", $url)) return true; - if (eregi("^https://", $url)) return true; + if (preg_match("/^(http|https):\/\//i", $url)) return true; if (strstr("blank", $url)) return true; if (strstr("blank_img", $url)) return true; - if (eregi("^((30[1235]{1})|(40[0-9]{1})|(41[0-7]{1})|(50[0-5]{1}))", $url)) return true; # http error code 30x, 4xx, 50x. + if (preg_match("/^((30[1235]{1})|(40[0-9]{1})|(41[0-7]{1})|(50[0-5]{1}))/i", $url)) return true; # http error code 30x, 4xx, 50x. return false; } } @@ -1558,7 +1557,7 @@ function is_dest_url($url) $fmt = "[a-zA-Z0-9_-]"; if (empty($url)) return false; - if (eregi("^(($fmt){1,}\.){1,}($fmt){2,}(/(.[^\*][^ ])*)", $url)) return true; + if (preg_match("/^(($fmt){1,}\.){1,}($fmt){2,}(\/(.[^\*][^ ])*)/i", $url)) return true; return false; } # ------------------------------------------------------------------------------ @@ -1603,8 +1602,8 @@ function is_ipaddr_valid($val) function is_domain_valid($domain) { $dm_fmt = "([a-z0-9\-]{1,})"; - $dm_fmt = "^(($dm_fmt{1,}\.){1,}$dm_fmt{2,})+$"; # example: (my.)(super.)(domain.)com - return is_string($domain) && eregi($dm_fmt, trim($domain)); + $dm_fmt = "/^(($dm_fmt{1,}\.){1,}$dm_fmt{2,})+$/i"; # example: (my.)(super.)(domain.)com + return is_string($domain) && preg_match($dm_fmt, trim($domain)); } # ------------------------------------------------------------------------------ @@ -1612,8 +1611,8 @@ function is_domain_valid($domain) # ------------------------------------------------------------------------------ function is_username($username) { - $unm_fmt = "^\'[a-zA-Z_0-9\.\-]{1,}\'$"; - return is_string($username) && eregi($unm_fmt, trim($username)); + $unm_fmt = "/^\'[a-zA-Z_0-9\.\-]{1,}\'$/i"; + return is_string($username) && preg_match($unm_fmt, trim($username)); } # ------------------------------------------------------------------------------ # check name @@ -1627,7 +1626,7 @@ function check_name_format ($name, $input_errors) $elog[] = " Size of name '$val' must be between [2..16]."; # All symbols must be [a-zA-Z_0-9\-] First symbol = letter. - if (!eregi("^([a-zA-Z]{1})([a-zA-Z_0-9\-]+)$", $val)) + if (!preg_match("/^([a-zA-Z]{1})([a-zA-Z_0-9\-]+)$/i", $val)) $elog[] = " Invalid name $name. Valid name symbols: ['a-Z', '_', '0-9', '-']. First symbol must be a letter."; # update log @@ -1784,15 +1783,15 @@ function check_date($date) { $err = ''; $val = trim($date); - $dtfmt = "([0-9]{4})\.([0-9]{2})\.([0-9]{2})"; + $dtfmt = "/^([0-9]{4})\.([0-9]{2})\.([0-9]{2})/i"; # check date range - if (eregi("^{$dtfmt}-{$dtfmt}$", $val)) { + if (preg_match("{$dtfmt}-{$dtfmt}$", $val)) { $val = explode("-", str_replace(".", '', $val)); if (intval($val[0]) >= intval($val[1])) $err .= "Invalid date range, begin range must be less than the end. {$val[0]} - {$val[1]}"; } - elseif (!eregi("^(([0-9]{4})|[*])\.(([0-9]{2})|[*])\.(([0-9]{2})|[*])$", $val)) { + elseif (!preg_match("/^(([0-9]{4})|[*])\.(([0-9]{2})|[*])\.(([0-9]{2})|[*])$/i", $val)) { $err .= "Bad date format."; } @@ -1815,7 +1814,7 @@ function check_time($time) if (empty($time)) return ''; # time range format: 'HH:MM-HH:MM' - if (!eregi("^([0-2][0-9])\:([0-5][0-9])-([0-2][0-9])\:([0-5][0-9])$", $time)) + if (!preg_match("/^([0-2][0-9])\:([0-5][0-9])-([0-2][0-9])\:([0-5][0-9])$/i", $time)) $err = "Invalid time range '$time'. You must use 'HH:MM-HH:MM' time range format. "; else { $tms = str_replace("-", "\n", $time); diff --git a/config/sshdcond/sshdcond.inc b/config/sshdcond/sshdcond.inc new file mode 100644 index 00000000..2caa39cc --- /dev/null +++ b/config/sshdcond/sshdcond.inc @@ -0,0 +1,254 @@ +<?php + +/* ========================================================================== */ +/* + sshdcond.inc + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Marcello Coutinho + Copyright (C) 2012 Han Van (namezero@afim.info) + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + require_once("config.inc"); + require_once("util.inc"); + +function restart_sshd(){ + #backup /etc/sshd before any change + $etc_sshd="/etc/sshd"; + $pfsense_version=preg_replace("/\s/","",file_get_contents("/etc/version")); + if (!file_exists('/root/'.$pfsense_version.'.sshd.backup')){ + copy ($etc_sshd,'/root/'.$pfsense_version.'.sshd.backup'); + } + + #patch /etc/sshd if need + $sshd_file=file($etc_sshd); + $sshd_new_file=""; + foreach ($sshd_file as $line){ + if (preg_match('/sshconf .= "Port/',$line)){ + $sshd_new_file.= $line; + $sshd_new_file.= "\t".'if(file_exists("/etc/ssh/sshd_extra")){$sshconf.=file_get_contents("/etc/ssh/sshd_extra");}'."\n"; + } + elseif(!preg_match('/sshd_extra/',$line)){ + $sshd_new_file.= $line; + } + } + file_put_contents($etc_sshd,$sshd_new_file,LOCK_EX); + mwexec_bg($etc_sshd); + } + +function sshdcond_custom_php_install_command(){ + global $g, $config; + + conf_mount_rw(); + + // We need to generate an outfile for our extra commands + // The patched g_szSSHDFileGenerate php file then reads and appends that config + $fd = fopen("/etc/ssh/sshd_extra", 'w'); + fclose($fd); + + conf_mount_ro(); + } + +function sshdcond_custom_php_deinstall_command(){ + global $g, $config; + + conf_mount_rw(); + + // 1. Delete our config file + unlink_if_exists("/etc/ssh/sshd_extra"); + + // 2. Re-run sshd config generation script + restart_sshd(); + + conf_mount_ro(); + } + +function sshdcond_custom_php_write_config(){ + global $g, $config; + + # detect boot process + if (is_array($_POST)){ + if (!preg_match("/\w+/",$_POST['__csrf_magic'])) + return; + } + + $sshd_extra=""; + if (is_array($config['installedpackages']['sshdcond']['config'])){ + // Mount Read-only + conf_mount_rw(); + + // Read config + foreach ($config['installedpackages']['sshdcond']['config'] as $sshdcond){ + if ($sshdcond['enable'] && is_array($sshdcond['row'])){ + $sshd_extra.= "Match {$sshdcond['matchtype']} {$sshdcond['matchvalue']}\n"; + foreach ($sshdcond['row'] as $sshd){ + //check if there is spaces on sshd value + if(preg_match ("/\s+/",$sshd['sshdvalue'])) + $sshd['sshdvalue']='"'.$sshd['sshdvalue'].'"'; + + //check if value is not empty + if($sshd['sshdvalue']!="") + $sshd_extra.="\t {$sshd['sshdoption']} {$sshd['sshdvalue']}\n"; + + //apply file permission if option is ChrootDirectory + if ($sshd['sshdoption']=="ChrootDirectory" && file_exists($sshd['sshdvalue'])){ + chown($sshd['sshdvalue'], 'root'); + chgrp($sshd['sshdvalue'], 'operator'); + } + } + } + } + } + + //Save /etc/ssh/sshd_extra + file_put_contents("/etc/ssh/sshd_extra",$sshd_extra,LOCK_EX); + + + + // Restart sshd + restart_sshd(); + + // Mount Read-only + conf_mount_ro(); + + //sync config with other pfsense servers + sshdcond_sync_on_changes(); + } + +/* Uses XMLRPC to synchronize the changes to a remote node */ +function sshdcond_sync_on_changes() { + global $config, $g; + + if (is_array($config['installedpackages']['sshdcondsync'])) + if (!$config['installedpackages']['sshdcondsync']['config'][0]['synconchanges']) + return; + + log_error("[sshdcond] xmlrpc sync is starting."); + foreach ($config['installedpackages']['sshdcondsync']['config'] as $rs ){ + foreach($rs['row'] as $sh){ + $sync_to_ip = $sh['ipaddress']; + $password = $sh['password']; + if($password && $sync_to_ip) + sshdcond_do_xmlrpc_sync($sync_to_ip, $password); + } + } + log_error("[sshdcond] xmlrpc sync is ending."); +} + +/* Do the actual XMLRPC sync */ +function sshdcond_do_xmlrpc_sync($sync_to_ip, $password) { + global $config, $g; + + if(!$password) + return; + + if(!$sync_to_ip) + return; + + $username='admin'; + $xmlrpc_sync_neighbor = $sync_to_ip; + if($config['system']['webgui']['protocol'] != "") { + $synchronizetoip = $config['system']['webgui']['protocol']; + $synchronizetoip .= "://"; + } + $port = $config['system']['webgui']['port']; + /* if port is empty lets rely on the protocol selection */ + if($port == "") { + if($config['system']['webgui']['protocol'] == "http") + $port = "80"; + else + $port = "443"; + } + $synchronizetoip .= $sync_to_ip; + + /* xml will hold the sections to sync */ + $xml = array(); + $xml['sshdcond'] = $config['installedpackages']['sshdcond']; + /* assemble xmlrpc payload */ + $params = array( + XML_RPC_encode($password), + XML_RPC_encode($xml) + ); + + /* set a few variables needed for sync code borrowed from filter.inc */ + $url = $synchronizetoip; + log_error("Beginning sshdcond XMLRPC sync to {$url}:{$port}."); + $method = 'pfsense.merge_installedpackages_section_xmlrpc'; + $msg = new XML_RPC_Message($method, $params); + $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); + $cli->setCredentials($username, $password); + if($g['debug']) + $cli->setDebug(1); + /* send our XMLRPC message and timeout after 250 seconds */ + $resp = $cli->send($msg, "250"); + if(!$resp) { + $error = "A communications error occurred while attempting sshdcond XMLRPC sync with {$url}:{$port}."; + log_error($error); + file_notice("sync_settings", $error, "sshdcond Settings Sync", ""); + } elseif($resp->faultCode()) { + $cli->setDebug(1); + $resp = $cli->send($msg, "250"); + $error = "An error code was received while attempting sshdcond XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); + log_error($error); + file_notice("sync_settings", $error, "sshdcond Settings Sync", ""); + } else { + log_error("sshdcond XMLRPC sync successfully completed with {$url}:{$port}."); + } + + /* tell sshdcond to reload our settings on the destionation sync host. */ + $method = 'pfsense.exec_php'; + $execcmd = "require_once('/usr/local/pkg/sshdcond.inc');\n"; + $execcmd .= "sshdcond_custom_php_write_config();"; + /* assemble xmlrpc payload */ + $params = array( + XML_RPC_encode($password), + XML_RPC_encode($execcmd) + ); + + log_error("sshdcond XMLRPC reload data {$url}:{$port}."); + $msg = new XML_RPC_Message($method, $params); + $cli = new XML_RPC_Client('/xmlrpc.php', $url, $port); + $cli->setCredentials($username, $password); + $resp = $cli->send($msg, "250"); + if(!$resp) { + $error = "A communications error occurred while attempting sshdcond XMLRPC sync with {$url}:{$port} (pfsense.exec_php)."; + log_error($error); + file_notice("sync_settings", $error, "sshdcond Settings Sync", ""); + } elseif($resp->faultCode()) { + $cli->setDebug(1); + $resp = $cli->send($msg, "250"); + $error = "An error code was received while attempting sshdcond XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString(); + log_error($error); + file_notice("sync_settings", $error, "sshdcond Settings Sync", ""); + } else { + log_error("sshdcond XMLRPC reload data success with {$url}:{$port} (pfsense.exec_php)."); + } +} + ?>
\ No newline at end of file diff --git a/config/sshdcond/sshdcond.xml b/config/sshdcond/sshdcond.xml new file mode 100644 index 00000000..eeb35d75 --- /dev/null +++ b/config/sshdcond/sshdcond.xml @@ -0,0 +1,197 @@ +<?xml version="1.0" encoding="utf-8" ?> +<packagegui> +<copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + sshdcond.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Marcello Coutinho + Copyright (C) 2012 Han Van (namezero@afim.info) + All rights reserved. + + Based on m0n0wall (http://m0n0.ch/wall) + Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>. + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + + <name>sshdcond</name> + <version>1.0</version> + <title>SSH Conditional</title> + <description>SSH Conditional blocks</description> + <savetext>Save</savetext> + <include_file>/usr/local/pkg/sshdcond.inc</include_file> + + <menu> + <name>SSH Conditions</name> + <tooltiptext>Configure SSH conditional exceptions</tooltiptext> + <section>Services</section> + <url>/pkg.php?xml=sshdcond.xml</url> + </menu> + <configpath>installedpackages->package->sshdcond</configpath> + + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>755</chmod> + <item>http://www.pfsense.com/packages/config/sshdcond/sshdcond.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>755</chmod> + <item>http://www.pfsense.com/packages/config/sshdcond/sshdcond_sync.xml</item> + </additional_files_needed> + <tabs> + <tab> + <text>General</text> + <url>/pkg.php?xml=sshdcond.xml</url> + <active/> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=sshdcond_sync.xml</url> + </tab> + </tabs> + <adddeleteeditpagefields> + <columnitem> + <fielddescr>Status</fielddescr> + <fieldname>enable</fieldname> + </columnitem> + <columnitem> + <fielddescr>Match Type</fielddescr> + <fieldname>matchtype</fieldname> + </columnitem> + <columnitem> + <fielddescr>Match Value</fielddescr> + <fieldname>matchvalue</fieldname> + </columnitem> + </adddeleteeditpagefields> + <fields> + <field> + <type>listtopic</type> + <name>Conditional SSH Options</name> + <fieldname>temp</fieldname> + </field> + <field> + <fielddescr>Enable</fielddescr> + <fieldname>enable</fieldname> + <type>checkbox</type> + <description>Enable this ssh conditional option for specified options.</description> + </field> + <field> + <fielddescr>Match Type</fielddescr> + <fieldname>matchtype</fieldname> + <description>See Match keyword at http://www.manpagez.com/man/5/sshd_config/ for options</description> + <type>select</type> + <options> + <option><name>User</name><value>User</value></option> + <option><name>Group</name><value>Group</value></option> + <option><name>Host</name><value>Host</value></option> + <option><name>Address</name><value>Address</value></option> + </options> + <required/> + </field> + <field> + <fielddescr>Match Value</fielddescr> + <fieldname>matchvalue</fieldname> + <description>Insert Match Value. Do not use spaces or special characters.</description> + <type>input</type> + <size>40</size> + <required/> + </field> + <field> + <fielddescr>Match Config</fielddescr> + <fieldname>none</fieldname> + <type>rowhelper</type> + <rowhelper> + <rowhelperfield> + <fielddescr>sshd option</fielddescr> + <fieldname>sshdoption</fieldname> + <type>select</type> + <options> + <option><name>AllowAgentForwarding</name><value>AllowAgentForwarding</value></option> + <option><name>AllowTcpForwarding</name><value>AllowTcpForwarding</value></option> + <option><name>AuthorizedKeysFile</name><value>AuthorizedKeysFile</value></option> + <option><name>AuthorizedPrincipalsFile</name><value>AuthorizedPrincipalsFile</value></option> + <option><name>Banner</name><value>Banner</value></option> + <option><name>ChrootDirectory</name><value>ChrootDirectory</value></option> + <option><name>ForceCommand</name><value>ForceCommand</value></option> + <option><name>GatewayPorts</name><value>GatewayPorts</value></option> + <option><name>GSSAPIAuthentication</name><value>GSSAPIAuthentication</value></option> + <option><name>HostbasedAuthentication</name><value>HostbasedAuthentication</value></option> + <option><name>HostbasedUsesNameFromPacketOnly</name><value>HostbasedUsesNameFromPacketOnly</value></option> + <option><name>KbdInteractiveAuthentication</name><value>KbdInteractiveAuthentication</value></option> + <option><name>KerberosAuthentication</name><value>KerberosAuthentication</value></option> + <option><name>MaxAuthTries</name><value>MaxAuthTries</value></option> + <option><name>MaxSessions</name><value>MaxSessions</value></option> + <option><name>PasswordAuthentication</name><value>PasswordAuthentication</value></option> + <option><name>PermitEmptyPasswords</name><value>PermitEmptyPasswords</value></option> + <option><name>PermitOpen</name><value>PermitOpen</value></option> + <option><name>PermitRootLogin</name><value>PermitRootLogin</value></option> + <option><name>PermitTunnel</name><value>PermitTunnel</value></option> + <option><name>PubkeyAuthentication</name><value>PubkeyAuthentication</value></option> + <option><name>RhostsRSAAuthentication</name><value>RhostsRSAAuthentication</value></option> + <option><name>RSAAuthentication</name><value>RSAAuthentication</value></option> + <option><name>X11DisplayOffset</name><value>X11DisplayOffset</value></option> + <option><name>X11Forwarding</name><value>X11Forwarding</value></option> + <option><name>X11UseLocalHost</name><value>X11UseLocalHost</value></option> + </options> + <required/> + </rowhelperfield> + <rowhelperfield> + <fielddescr>sshd value</fielddescr> + <fieldname>sshdvalue</fieldname> + <type>input</type> + <size>60</size> + <required/> + </rowhelperfield> + </rowhelper> + </field> + </fields> + + <custom_delete_php_command> + sshdcond_custom_php_write_config(); + </custom_delete_php_command> + <custom_add_php_command> + sshdcond_custom_php_write_config(); + </custom_add_php_command> + <custom_php_install_command> + sshdcond_custom_php_install_command(); + </custom_php_install_command> + <custom_php_deinstall_command> + sshdcond_custom_php_deinstall_command(); + </custom_php_deinstall_command> + <custom_php_resync_config_command> + sshdcond_custom_php_write_config(); + </custom_php_resync_config_command> + <custom_php_command_before_form> + unset($_POST['temp']); + </custom_php_command_before_form> + +</packagegui>
\ No newline at end of file diff --git a/config/sshdcond/sshdcond_sync.xml b/config/sshdcond/sshdcond_sync.xml new file mode 100755 index 00000000..2bd4a26b --- /dev/null +++ b/config/sshdcond/sshdcond_sync.xml @@ -0,0 +1,97 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "./schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="./xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + sshdcond_sync.xml + part of the sarg package for pfSense + Copyright (C) 2012 Marcello Coutinho + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>sshdcondsync</name> + <version>1.0</version> + <title>SSH Conditional - Sync</title> + <include_file>/usr/local/pkg/sshdcond.inc</include_file> + <tabs> + <tab> + <text>General</text> + <url>/pkg.php?xml=sshdcond.xml</url> + </tab> + <tab> + <text>Sync</text> + <url>/pkg_edit.php?xml=sshdcond_sync.xml</url> + <active/> + </tab> + </tabs> + <fields> + <field> + <name>XMLRPC Sync</name> + <type>listtopic</type> + </field> + <field> + <fielddescr>Automatically sync configuration changes</fielddescr> + <fieldname>synconchanges</fieldname> + <description>Automatically sync changes to the hosts defined below.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>Remote Server</fielddescr> + <fieldname>none</fieldname> + <type>rowhelper</type> + <rowhelper> + <rowhelperfield> + <fielddescr>IP Address</fielddescr> + <fieldname>ipaddress</fieldname> + <description>IP Address of remote server</description> + <type>input</type> + <size>20</size> + </rowhelperfield> + <rowhelperfield> + <fielddescr>Password</fielddescr> + <fieldname>password</fieldname> + <description>Password for remote server.</description> + <type>password</type> + <size>20</size> + </rowhelperfield> + </rowhelper> + </field> + </fields> + <custom_php_validation_command> + </custom_php_validation_command> + <custom_php_resync_config_command> + sshdcond_custom_php_write_config(); + </custom_php_resync_config_command> +</packagegui> diff --git a/config/syslog-ng/syslog-ng.inc b/config/syslog-ng/syslog-ng.inc new file mode 100644 index 00000000..b56cef39 --- /dev/null +++ b/config/syslog-ng/syslog-ng.inc @@ -0,0 +1,432 @@ +<?php +/* $Id$ */ +/* + syslog-ng.inc + Copyright (C) 2012 Lance Leger + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. +*/ + +require_once('globals.inc'); +require_once('config.inc'); +require_once('util.inc'); +require_once('pfsense-utils.inc'); +require_once('pkg-utils.inc'); +require_once('service-utils.inc'); + +if(!function_exists("filter_configure")) + require_once("filter.inc"); + +function syslogng_get_real_interface_address($interface) { + $interface = convert_friendly_interface_to_real_interface_name($interface); + $line = trim(shell_exec("ifconfig $interface | grep inet | grep -v inet6 | awk '{ print \$2, \$4 }'")); + list($ip, $netmask) = explode(" ", $line); + + return array($ip, long2ip(hexdec($netmask))); +} + +function syslogng_install_command() { + conf_mount_rw(); + syslogng_install_cron(true); + conf_mount_ro(); + syslogng_resync(); +} + +function syslogng_deinstall_command() { + conf_mount_rw(); + exec("/usr/local/etc/rc.d/syslog-ng.sh stop"); + unlink_if_exists("/usr/local/etc/rc.d/syslog-ng.sh"); + syslogng_install_cron(false); + conf_mount_ro(); + filter_configure(); +} + +function syslogng_validate_general($post, $input_errors) { + global $config; + + $objects = $config['installedpackages']['syslogngadvanced']['config']; + + if(empty($post['interfaces'])) { + $input_errors[] = 'You must select at least one interface in \'Interfaces\' field'; + } else { + $post['interfaces'] = implode(",", $post['interfaces']); + } + + if(!is_port($post['default_port'])) + $input_errors[] = 'You must enter a valid port number in the \'Default Port\' field'; + + $sockstat = trim(shell_exec("sockstat -l -P " . $post['default_protocol'] . " -p " . $post['default_port'] . " | grep -v ^USER | grep -v syslog-ng")); + if(!empty($sockstat)) + $input_errors[] = 'The port specified in the \'Default Port\' field is already in use'; + + if(!preg_match("/^\\/[^?*:;{}\\\\]+[^\\/]$/", $post['default_logdir'])) { + $input_errors[] = 'You must enter a valid directory in the \'Default Log Directory\' field'; + } elseif($post['default_logdir'] == "/var/log") { + $input_errors[] = 'You must enter a valid directory in the \'Default Log Directory\' field -- /var/log is reserved for pfSense'; + } + + if(!preg_match("/^[^\\/?*:;{}\\\\]+$/", $post['default_logfile'])) + $input_errors[] = 'You must enter a valid file in the \'Default Log File\' field'; + + $default_objects = syslogng_build_default_objects($post); + + if(empty($objects)) { + $objects = $default_objects; + } else { + $objects = syslogng_merge_objects($objects, $default_objects); + } + + if($errors = syslogng_test_object_syntax($objects)) + $input_errors[] = "Syslog-ng syntax test failed:\n" . $errors; +} + +function syslogng_validate_advanced($post, $input_errors) { + global $config; + + $objects = $config['installedpackages']['syslogngadvanced']['config']; + + if($post['objectname'] == '_DEFAULT') { + $input_errors[] = 'Creation or modification of \'_DEFAULT\' objects not permitted. Change default settings under \'General\' tab.'; + } + + $new_object[] = array("objecttype"=>$post['objecttype'], "objectname"=>$post['objectname'], "objectparameters"=>$post['objectparameters']); + + if(empty($objects)) { + $objects = $new_object; + } else { + $objects = syslogng_merge_objects($objects, $new_object); + } + + if($errors = syslogng_test_object_syntax($objects)) + $input_errors[] = "Syslog-ng syntax test failed:\n" . $errors; +} + +function syslogng_install_cron($should_install) { + global $config, $g; + + if($g['booting']==true) + return; + + if(!$config['cron']['item']) + return; + + $x=0; + $rotate_job_id=-1; + $rotate_is_installed = false; + + foreach($config['cron']['item'] as $item) { + if(strstr($item['task_name'], "syslogng_rotate_logs")) { + $rotate_job_id = $x; + } + $x++; + } + $need_write = false; + switch($should_install) { + case true: + if($rotate_job_id < 0) { + $cron_item = array(); + $cron_item['task_name'] = "syslogng_rotate_logs"; + $cron_item['minute'] = "0"; + $cron_item['hour'] = "*"; + $cron_item['mday'] = "*"; + $cron_item['month'] = "*"; + $cron_item['wday'] = "*"; + $cron_item['who'] = "root"; + $cron_item['command'] = "/usr/bin/nice -n20 /usr/local/sbin/logrotate /usr/local/etc/logrotate.conf"; + $config['cron']['item'][] = $cron_item; + $need_write = true; + } + if($need_write) { + parse_config(true); + write_config("Adding syslog-ng Cron Jobs"); + } + break; + case false: + if($rotate_job_id >= 0) { + unset($config['cron']['item'][$rotate_job_id]); + $need_write = true; + } + if($need_write) { + parse_config(true); + write_config("Removing syslog-ng Cron Jobs"); + } + break; + } + configure_cron(); +} + +function syslogng_build_default_objects($settings) { + $default_objects = array(); + + $interfaces = $settings['interfaces']; + $default_protocol = $settings['default_protocol']; + $default_port = $settings['default_port']; + $default_logdir = $settings['default_logdir']; + $default_logfile = $settings['default_logfile']; + + $default_objects[0] = array("objecttype"=>"source", "objectname"=>"_DEFAULT", "objectparameters"=>"{ internal(); syslog(transport($default_protocol) port($default_port)"); + foreach (explode(",", $interfaces) as $interface) { + $interface_address = syslogng_get_real_interface_address($interface); + if($interface_address[0]) { + $default_objects[0]['objectparameters'] .= " ip({$interface_address[0]})"; + } + } + $default_objects[0]['objectparameters'] .= "); };"; + $default_objects[1] = array("objecttype"=>"destination", "objectname"=>"_DEFAULT", "objectparameters"=>"{ file(\"$default_logdir/$default_logfile\"); };"); + $default_objects[2] = array("objecttype"=>"log", "objectname"=>"_DEFAULT", "objectparameters"=>"{ source(_DEFAULT); destination(_DEFAULT); };"); + + return $default_objects; +} + + +function syslogng_merge_objects($objects1, $objects2) +{ + foreach($objects2 as $object2) { + $match = 0; + foreach($objects1 as &$object1) { + if(($object2['objecttype'] == $object1['objecttype']) && ($object2['objectname'] == $object1['objectname'])) { + $object1 = $object2; + $match = 1; + } + } + if($match == 0) + array_push($objects1, $object2); + } + + return $objects1; +} + +function syslogng_test_object_syntax($objects) { + exec("mv /usr/local/etc/syslog-ng.conf /usr/local/etc/syslog-ng.conf.backup"); + syslogng_build_conf($objects); + $errors = trim(shell_exec('/usr/local/sbin/syslog-ng --syntax-only 2>&1')); + exec("mv /usr/local/etc/syslog-ng.conf /usr/local/etc/syslog-ng.conf.tested"); + exec("mv /usr/local/etc/syslog-ng.conf.backup /usr/local/etc/syslog-ng.conf"); + + return $errors; +} + +function syslogng_get_log_files($objects) { + $log_files = array(); + + foreach($objects as $object) { + if($object['objecttype'] == 'destination') { + preg_match("/file\(['\"]([^'\"]*)['\"]/", $object['objectparameters'], $match); + if($match) { + $log_file = $match[1]; + array_push($log_files, $log_file); + } + } + } + + return $log_files; +} + +function syslogng_build_conf($objects) { + $conf = "# This file is automatically generated by pfSense\n"; + $conf .= "# Do not edit manually !\n"; + $conf .= "@version:3.3\n"; + + foreach($objects as $object) { + if($object['objecttype'] == 'log' || $object['objecttype'] == 'options') { + $conf .= $object['objecttype'] . " " . $object['objectparameters'] . "\n"; + } else { + $conf .= $object['objecttype'] . " " . $object['objectname'] . " " . $object['objectparameters'] . "\n"; + } + } + + file_put_contents('/usr/local/etc/syslog-ng.conf', $conf); +} + +function syslogng_build_logrotate_conf($settings, $objects) { + $conf = "# This file is automatically generated by pfSense\n"; + $conf .= "# Do not edit manually !\n"; + + $compress_archives = $settings['compress_archives']; + $compress_type = $settings['compress_type']; + $archive_frequency = $settings['archive_frequency']; + $max_archives = $settings['max_archives']; + + $log_files = syslogng_get_log_files($objects); + + foreach($log_files as $log_file) { + $conf .= "$log_file "; + } + + $conf .= "{\n"; + $conf .= "\trotate $max_archives\n"; + $conf .= "\t$archive_frequency\n"; + + if($compress_archives == 'on') { + $conf .= "\tcompress\n"; + if($compress_type == 'bz2') { + $conf .= "\tcompresscmd bzip2\n"; + } + } + + $conf .= "\tpostrotate\n"; + $conf .= "\t\tkill -s HUP `cat /var/run/syslog-ng.pid`\n"; + $conf .= "\tendscript\n"; + $conf .= "}\n"; + + file_put_contents('/usr/local/etc/logrotate.conf', $conf); +} + +function syslogng_generate_rules($type) { + global $config; + + $settings = $config['installedpackages']['syslogng']['config'][0]; + + $interfaces = ($settings['interfaces'] ? $settings['interfaces'] : 'lan'); + $default_protocol = ($settings['default_protocol'] ? $settings['default_protocol'] : 'udp'); + $default_port = ($settings['default_port'] ? $settings['default_port'] : 5140); + + $rules = ""; + switch($type) { + case 'rule': + foreach ($interfaces as $interface) { + $rules .= "pass in quick on $interface proto $default_protocol from any to !($interface) port $default_port no state label\n"; + } + break; + } + + return $rules; +} + +function syslogng_resync() { + global $config; + conf_mount_rw(); + + $settings = $config['installedpackages']['syslogng']['config'][0]; + $objects = $config['installedpackages']['syslogngadvanced']['config']; + + if(!isset($settings['enable'])) + $settings['enable'] = 'off'; + if(!isset($settings['interfaces'])) + $settings['interfaces'] = 'lan'; + if(!isset($settings['default_protocol'])) + $settings['default_protocol'] = 'udp'; + if(!isset($settings['default_port'])) + $settings['default_port'] = 5140; + if(!isset($settings['default_logdir'])) + $settings['default_logdir'] = '/var/syslog-ng'; + if(!isset($settings['default_logfile'])) + $settings['default_logfile'] = 'default.log'; + if(!isset($settings['archive_frequency'])) + $settings['archive_frequency'] = 'daily'; + if(!isset($settings['compress_archives'])) + $settings['compress_archives'] = 'on'; + if(!isset($settings['compress_type'])) + $settings['compress_type'] = 'gz'; + if(!isset($settings['max_archives'])) + $settings['max_archives'] = 30; + + $default_objects = syslogng_build_default_objects($settings); + + if(empty($objects)) { + $objects = $default_objects; + } else { + $objects = syslogng_merge_objects($objects, $default_objects); + } + + $sort = array(); + foreach($objects as $k=>$v) { + $sort['objecttype'][$k] = $v['objecttype']; + $sort['objectname'][$k] = $v['objectname']; + } + array_multisort($sort['objecttype'], SORT_ASC, $sort['objectname'], SORT_ASC, $objects); + + syslogng_build_conf($objects); + syslogng_build_logrotate_conf($settings, $objects); + + $config['installedpackages']['syslogng']['config'][0] = $settings; + $config['installedpackages']['syslogngadvanced']['config'] = $objects; + + if($settings['enable'] == 'on') { + if(!file_exists($settings['default_logdir'])) { + exec("mkdir -p " . $settings['default_logdir']); + } + + syslogng_write_rcfile(); + + if(!is_service_running('syslog-ng')) { + log_error("Starting syslog-ng"); + exec("/usr/local/etc/rc.d/syslog-ng.sh start"); + } else { + log_error("Reloading syslog-ng for configuration sync"); + exec("/usr/local/etc/rc.d/syslog-ng.sh restart"); + } + + // Sleep for a couple seconds to give syslog-ng a chance to fire up fully. + for ($i=0; $i < 10; $i++) { + if(!is_service_running('syslog-ng')) + sleep(1); + } + } else { + if(is_service_running('syslog-ng')) { + log_error("Stopping syslog-ng"); + exec("/usr/local/etc/rc.d/syslog-ng.sh stop"); + + unlink_if_exists("/usr/local/etc/rc.d/syslog-ng.sh"); + } + } + + write_config(); + conf_mount_ro(); + filter_configure(); +} + +function syslogng_write_rcfile() { + $rc = array(); + $pid_file = "/var/run/syslog-ng.pid"; + $rc['file'] = 'syslog-ng.sh'; + $rc['start'] = <<<EOD +if [ -z "`ps auxw | grep "syslog-ng" | grep -v "syslog-ng.sh"`" ]; then + /usr/local/sbin/syslog-ng -p {$pid_file} +fi + +EOD; + $rc['stop'] = <<<EOD +if [ -s "{$pid_file}" ]; then + kill `cat {$pid_file}` 2>/dev/null +fi +# Just in case pid file didn't exist or process is still running... +sleep 5 +killall -9 syslog-ng 2>/dev/null + +EOD; + $rc['restart'] = <<<EOD +if [ -z "`ps auxw | grep "syslog-ng" | grep -v "syslog-ng.sh"`" ]; then + /usr/local/sbin/syslog-ng -p {$pid_file} +elif [ -s "{$pid_file}" ]; then + kill -s HUP `cat {$pid_file}` 2>/dev/null +else + killall -9 syslog-ng 2>/dev/null + /usr/local/sbin/syslog-ng -p {$pid_file} +fi + +EOD; + conf_mount_rw(); + write_rcfile($rc); +} +?>
\ No newline at end of file diff --git a/config/syslog-ng/syslog-ng.xml b/config/syslog-ng/syslog-ng.xml new file mode 100644 index 00000000..dbdd4a8d --- /dev/null +++ b/config/syslog-ng/syslog-ng.xml @@ -0,0 +1,192 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + syslog-ng.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Lance Leger + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>Syslog-ng</name> + <version>3.3.4_1</version> + <title>Services: Syslog-ng</title> + <include_file>/usr/local/pkg/syslog-ng.inc</include_file> + <menu> + <name>Syslog-ng</name> + <tooltiptext>Setup Syslog-ng</tooltiptext> + <section>Services</section> + <url>/syslog-ng_log_viewer.php</url> + </menu> + <service> + <name>syslog-ng</name> + <rcfile>syslog-ng.sh</rcfile> + <executable>syslog-ng</executable> + </service> + <tabs> + <tab> + <text>General</text> + <url>/pkg_edit.php?xml=syslog-ng.xml&id=0</url> + <active/> + </tab> + <tab> + <text>Advanced</text> + <url>/pkg.php?xml=syslog-ng_advanced.xml</url> + </tab> + <tab> + <text>Log Viewer</text> + <url>/syslog-ng_log_viewer.php</url> + </tab> + </tabs> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.com/packages/config/syslog-ng/syslog-ng.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/syslog-ng/syslog-ng_advanced.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.org/packages/config/syslog-ng/syslog-ng_log_viewer.php</item> + </additional_files_needed> + <fields> + <field> + <fielddescr>Enable</fielddescr> + <fieldname>enable</fieldname> + <type>checkbox</type> + <description>Select this option to enable syslog-ng</description> + </field> + <field> + <fielddescr>Interface Selection</fielddescr> + <fieldname>interfaces</fieldname> + <type>interfaces_selection</type> + <description>Select interfaces you want to listen on</description> + <required/> + <multiple/> + </field> + <field> + <fielddescr>Default Protocol</fielddescr> + <fieldname>default_protocol</fieldname> + <description>Select the default protocol you want to listen on</description> + <type>select</type> + <value>udp</value> + <options> + <option><name>UDP</name><value>udp</value></option> + <option><name>TCP</name><value>tcp</value></option> + </options> + <required/> + </field> + <field> + <fielddescr>Default Port</fielddescr> + <fieldname>default_port</fieldname> + <type>input</type> + <description>Enter default port number you want to listen on</description> + <default_value>514</default_value> + <required/> + </field> + <field> + <fielddescr>Default Log Directory</fielddescr> + <fieldname>default_logdir</fieldname> + <type>input</type> + <description>Enter default log directory (no trailing slash)</description> + <default_value>/var/syslog-ng</default_value> + <required/> + </field> + <field> + <fielddescr>Default Log File</fielddescr> + <fieldname>default_logfile</fieldname> + <type>input</type> + <description>Enter default log file</description> + <default_value>default.log</default_value> + <required/> + </field> + <field> + <fielddescr>Archive Frequency</fielddescr> + <fieldname>archive_frequency</fieldname> + <description>Select the frequency to archive (rotate) log files</description> + <type>select</type> + <value>daily</value> + <options> + <option><name>Daily</name><value>daily</value></option> + <option><name>Weekly</name><value>weekly</value></option> + <option><name>Monthly</name><value>monthly</value></option> + </options> + <required/> + </field> + <field> + <fielddescr>Compress Archives</fielddescr> + <fieldname>compress_archives</fieldname> + <type>checkbox</type> + <description>Select this option to compress archived log files</description> + </field> + <field> + <fielddescr>Compress Type</fielddescr> + <fieldname>compress_type</fieldname> + <description>Select the type of compression for archived log files</description> + <type>select</type> + <value>gz</value> + <options> + <option><name>Gzip</name><value>gz</value></option> + <option><name>Bzip2</name><value>bz2</value></option> + </options> + </field> + <field> + <fielddescr>Max Archives</fielddescr> + <fieldname>max_archives</fieldname> + <type>input</type> + <description>Enter the number of max archived log files</description> + <default_value>30</default_value> + <required/> + </field> + </fields> + <custom_php_validation_command> + syslogng_validate_general($_POST, &$input_errors); + </custom_php_validation_command> + <custom_php_resync_config_command> + syslogng_resync(); + </custom_php_resync_config_command> + <custom_php_install_command> + syslogng_install_command(); + </custom_php_install_command> + <custom_php_deinstall_command> + syslogng_deinstall_command(); + </custom_php_deinstall_command> + <filter_rules_needed>syslogng_generate_rules</filter_rules_needed> +</packagegui> diff --git a/config/syslog-ng/syslog-ng_advanced.xml b/config/syslog-ng/syslog-ng_advanced.xml new file mode 100644 index 00000000..36a02a07 --- /dev/null +++ b/config/syslog-ng/syslog-ng_advanced.xml @@ -0,0 +1,135 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "./schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="./xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + syslog-ng_advanced.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Lance Leger + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>Describe your package here</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>Syslog-ng Advanced</name> + <version>0.1.0</version> + <title>Services: Syslog-ng Advanced</title> + <include_file>/usr/local/pkg/syslog-ng.inc</include_file> + <delete_string>An object has been deleted.</delete_string> + <addedit_string>An object has been created/modified.</addedit_string> + <menu> + <name>Syslog-ng</name> + <tooltiptext>Setup Syslog-ng</tooltiptext> + <section>Services</section> + </menu> + <tabs> + <tab> + <text>General</text> + <url>/pkg_edit.php?xml=syslog-ng.xml&id=0</url> + </tab> + <tab> + <text>Advanced</text> + <url>/pkg.php?xml=syslog-ng_advanced.xml</url> + <active/> + </tab> + <tab> + <text>Log Viewer</text> + <url>/syslog-ng_log_viewer.php</url> + </tab> + </tabs> + <adddeleteeditpagefields> + <columnitem> + <fielddescr>Object Type</fielddescr> + <fieldname>objecttype</fieldname> + </columnitem> + <columnitem> + <fielddescr>Object Name</fielddescr> + <fieldname>objectname</fieldname> + </columnitem> + <columnitem> + <fielddescr>Description</fielddescr> + <fieldname>description</fieldname> + </columnitem> + </adddeleteeditpagefields> + <fields> + <field> + <fielddescr>Object Name</fielddescr> + <fieldname>objectname</fieldname> + <description>Enter the object name</description> + <type>input</type> + <required/> + </field> + <field> + <fielddescr>Object Type</fielddescr> + <fieldname>objecttype</fieldname> + <description>Select the object type</description> + <type>select</type> + <value></value> + <options> + <option><name>Options</name><value>options</value></option> + <option><name>Source</name><value>source</value></option> + <option><name>Destination</name><value>destination</value></option> + <option><name>Log</name><value>log</value></option> + <option><name>Filter</name><value>filter</value></option> + <option><name>Parser</name><value>parser</value></option> + <option><name>Rewrite</name><value>rewrite</value></option> + <option><name>Template</name><value>template</value></option> + </options> + <required/> + </field> + <field> + <fielddescr>Object Parameters</fielddescr> + <fieldname>objectparameters</fieldname> + <description>Enter the object parameters</description> + <type>textarea</type> + <cols>65</cols> + <rows>5</rows> + <required/> + </field> + <field> + <fielddescr>Description</fielddescr> + <fieldname>description</fieldname> + <description>Enter the description for this item</description> + <type>input</type> + </field> + </fields> + <custom_delete_php_command> + syslogng_resync(); + </custom_delete_php_command> + <custom_php_validation_command> + syslogng_validate_advanced($_POST, &$input_errors); + </custom_php_validation_command> + <custom_php_resync_config_command> + syslogng_resync(); + </custom_php_resync_config_command> +</packagegui>
\ No newline at end of file diff --git a/config/syslog-ng/syslog-ng_log_viewer.php b/config/syslog-ng/syslog-ng_log_viewer.php new file mode 100644 index 00000000..c8183f14 --- /dev/null +++ b/config/syslog-ng/syslog-ng_log_viewer.php @@ -0,0 +1,167 @@ +<?php +/* $Id$ */ +/* ========================================================================== */ +/* + syslog-ng_log_viewer.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Lance Leger + 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("guiconfig.inc"); +require("/usr/local/pkg/syslog-ng.inc"); + +$objects = $config['installedpackages']['syslogngadvanced']['config']; +$default_logdir = $config['installedpackages']['syslogng']['config'][0]['default_logdir']; +$default_logfile = $config['installedpackages']['syslogng']['config'][0]['default_logfile']; +$compress_archives = $config['installedpackages']['syslogng']['config'][0]['compress_archives']; +$compress_type = $config['installedpackages']['syslogng']['config'][0]['compress_type']; + +if($_POST['logfile']) + $logfile = $_POST['logfile']; +else + $logfile = $default_logdir . "/" . $default_logfile; + +if($_POST['limit']) + $limit = intval($_POST['limit']); +else + $limit = "10"; + +if($_POST['archives']) + $archives = true; + +if($_POST['filter']) + $filter = $_POST['filter']; + +if($_POST['not']) + $not = true; + +$log_messages = array(); +if(file_exists($logfile) && (filesize($logfile) > 0)) { + $grep = "grep -ih"; + + if(($compress_archives == 'on') && glob($logfile . "*" . $compress_type) && $archives) { + if($compress_type == 'bz2') { + $grep = "bzgrep -ih"; + } else { + $grep = "zgrep -ih"; + } + } + + if(isset($filter) && $not) { + $grepcmd = "$grep -v '$filter' $logfile"; + } else { + $grepcmd = "$grep '$filter' $logfile"; + } + + if($archives) + $grepcmd = $grepcmd . "*"; + + $log_lines = trim(shell_exec("$grepcmd | wc -l")); + $log_output = trim(shell_exec("$grepcmd | sort -M | tail -n $limit")); + + if(!empty($log_output)) { + $log_messages = explode("\n", $log_output); + $log_messages_count = sizeof($log_messages); + } +} + +$pgtitle = "Services: Syslog-ng Log Viewer"; +include("head.inc"); +?> +<body link="#000000" vlink="#000000" alink="#000000"> +<?php include("fbegin.inc"); ?> +<?php if ($savemsg) print_info_box($savemsg); ?> +<form action="syslog-ng_log_viewer.php" method="post" name="iform"> +<table width="99%" border="0" cellpadding="0" cellspacing="0"> + <tr><td> +<?php + $tab_array = array(); + $tab_array[] = array("General", false, "/pkg_edit.php?xml=syslog-ng.xml&id=0"); + $tab_array[] = array("Advanced", false, "/pkg.php?xml=syslog-ng_advanced.xml"); + $tab_array[] = array("Log Viewer", true, "/syslog-ng_log_viewer.php"); + display_top_tabs($tab_array); +?> + </td></tr> + <tr><td> + <div id="mainarea"> + <table id="maintable" name="maintable" class="tabcont" width="100%" border="0" cellpadding="0" cellspacing="0"> + <tr><td> + + <table> + <tr><td width="22%">Log File</td><td width="78%"><select name="logfile"> + <?php + $log_files = syslogng_get_log_files($objects); + foreach($log_files as $log_file) { + if($log_file == $logfile) { + echo "<option value=\"$log_file\" selected=\"selected\">$log_file</option>\n"; + } else { + echo "<option value=\"$log_file\">$log_file</option>\n"; + } + } + ?> + </select></td></tr> + <tr><td width="22%">Limit</td><td width="78%"><select name="limit"> + <?php + $limit_options = array("10", "20", "50"); + foreach($limit_options as $limit_option) { + if($limit_option == $limit) { + echo "<option value=\"$limit_option\" selected=\"selected\">$limit_option</option>\n"; + } else { + echo "<option value=\"$limit_option\">$limit_option</option>\n"; + } + } + ?> + </select></td></tr> + <tr><td width="22%">Include Archives</td><td width="78%"><input type="checkbox" name="archives" <?php if($archives) echo " CHECKED"; ?> /></td></tr> + <tr><td colspan="2"> + <table class="tabcont" width="100%" border="0" cellspacing="0" cellpadding="0"> + <?php + if(!empty($log_messages)) { + echo "<tr><td class=\"listtopic\">Showing $log_messages_count of $log_lines messages</td></tr>\n"; + foreach($log_messages as $log_message) { + echo "<tr><td class=\"listr\">$log_message</td></tr>\n"; + } + } else { + echo "<tr><td><span class=\"red\">No log messages found or log file is empty.</span></td></tr>\n"; + } + ?> + </table> + </td></tr> + <tr><td width="22%">Filter</td><td width="78%"><input name="filter" value="<?=$filter?>" /></td></tr> + <tr><td width="22%">Inverse Filter (NOT)</td><td width="78%"><input type="checkbox" name="not" <?php if($not) echo " CHECKED"; ?> /></td></tr> + <tr><td colspan="2"><input type="submit" value="Refresh" /></td></tr> + </table> + + </td></tr> + </table> + </div> + </td></tr> +</table> +</form> +<?php include("fend.inc"); ?> +</body>
\ No newline at end of file diff --git a/config/systempatches/patches.inc b/config/systempatches/patches.inc new file mode 100644 index 00000000..d17e3614 --- /dev/null +++ b/config/systempatches/patches.inc @@ -0,0 +1,142 @@ +<?php +/* + patches.inc + Copyright (C) 2012 Jim Pingle + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. +*/ + +require_once("globals.inc"); +require_once("util.inc"); + +$git_root_url = "http://github.com/bsdperimeter/pfsense/commit/"; +$patch_suffix = ".patch"; +$patch_dir = "/var/patches"; +$patch_cmd = "/usr/bin/patch"; + +function patch_commit($patch, $action, $test=false, $fulldetail=false) { + global $patch_dir, $patch_cmd, $patch_suffix; + $directory = empty($patch['basedir']) ? "/" : $patch['basedir']; + $filename = '-i ' . $patch_dir . '/' . $patch['uniqid'] . $patch_suffix; + $check = ($test) ? "--check" : ""; + $force = ($action == "revert") ? "-f" : "-t"; + $direction = ($action == "revert") ? "--reverse" : "--forward"; + $whitespace = $patch['ignorewhitespace'] ? "--ignore-whitespace" : ""; + $pathstrip = '-p' . $patch['pathstrip']; + $full_patch_command = "{$patch_cmd} --directory={$directory} {$force} {$pathstrip} {$filename} {$check} {$direction} {$whitespace}"; + patch_write($patch); + if (!$fulldetail) + $output = (mwexec($full_patch_command, true) == 0); + else + $output = $full_patch_command . "\n\n" . shell_exec($full_patch_command . ' 2>&1'); + patch_erase($patch); + return $output; +} + +/* Attempt to apply a patch */ +function patch_apply($patch) { + return patch_commit($patch, "apply", false); +} + +/* Attempt to revert a patch */ +function patch_revert($patch) { + return patch_commit($patch, "revert", false); +} + +/* Test if a patch would apply cleanly */ +function patch_test_apply($patch, $fulldetail=false) { + return patch_commit($patch, "apply", true, $fulldetail); +} + +/* Test if a patch would revert cleanly */ +function patch_test_revert($patch, $fulldetail=false) { + return patch_commit($patch, "revert", true, $fulldetail); +} + +/* Fetch a patch from a URL or github */ +function patch_fetch(& $patch) { + $url = patch_fixup_url($patch['location']); + $text = @file_get_contents($url); + if (empty($text)) { + return false; + } else { + $patch['patch'] = base64_encode($text); + write_config("Fetched patch {$patch['descr']}"); + return true; + } +} + +/* Write a patch file out to $patch_dir */ +function patch_write($patch) { + global $patch_dir, $patch_suffix; + if (!file_exists($patch_dir)) { + safe_mkdir($patch_dir); + } + if (empty($patch['patch'])) { + return false; + } else { + $text = base64_decode($patch['patch']); + $filename = $patch_dir . '/' . $patch['uniqid'] . $patch_suffix; + return (file_put_contents($filename, $text) > 0); + } +} + +function patch_erase($patch) { + global $patch_dir, $patch_suffix; + if (!file_exists($patch_dir)) { + return true; + } + $filename = $patch_dir . '/' . $patch['uniqid'] . $patch_suffix; + return @unlink($filename); +} + +/* Detect a github URL or commit ID and fix it up */ +function patch_fixup_url($url) { + global $git_root_url, $patch_suffix; + // If it's a commit id then prepend git url, and add .patch + if (is_commit_id($url)) { + $url = $git_root_url . $url . $patch_suffix; + } elseif (is_URL($url)) { + $urlbits = explode("/", $url); + if (substr($urlbits[2], -10) == "github.com") { + // If it's a github url and does not already end in .patch, add it + if (substr($url, -strlen($patch_suffix)) != $patch_suffix) { + // Make sure it's really a URL to a commit id before adding .patch + if (is_commit_id(array_pop($urlbits))) { + $url .= $patch_suffix; + } + } + } + } + return $url; +} + +function is_commit_id($str) { + return preg_match("/^[0-9a-f]{5,40}$/", $str); +} + +function is_github_url($url) { + $urlbits = explode("/", $url); + return (substr($urlbits[2], -10) == "github.com"); +} +?>
\ No newline at end of file diff --git a/config/systempatches/system_patches.php b/config/systempatches/system_patches.php new file mode 100644 index 00000000..2cb6abf9 --- /dev/null +++ b/config/systempatches/system_patches.php @@ -0,0 +1,287 @@ +<?php +/* + system_patches.php + Copyright (C) 2012 Jim Pingle + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. +*/ +/* + pfSense_MODULE: system +*/ + +##|+PRIV +##|*IDENT=page-system-patches +##|*NAME=System: Patches +##|*DESCR=Allow access to the 'System: Patches' page. +##|*MATCH=system_patches.php* +##|-PRIV + +require("guiconfig.inc"); +require_once("functions.inc"); +require_once("itemid.inc"); +require_once("patches.inc"); + +if (!is_array($config['installedpackages']['patches']['item'])) + $config['installedpackages']['patches']['item'] = array(); + +$a_patches = &$config['installedpackages']['patches']['item']; + +/* if a custom message has been passed along, lets process it */ +if ($_GET['savemsg']) + $savemsg = $_GET['savemsg']; + +if ($_POST) { + $pconfig = $_POST; + if ($_POST['apply']) { + write_config(); + } +} + +if ($_GET['act'] == "del") { + if ($a_patches[$_GET['id']]) { + unset($a_patches[$_GET['id']]); + write_config(); + header("Location: system_patches.php"); + exit; + } +} + +if (($_GET['act'] == "fetch") && ($a_patches[$_GET['id']])) { + $savemsg = patch_fetch(& $a_patches[$_GET['id']]) ? gettext("Patch Fetched Successfully") : gettext("Patch Fetch Failed"); +} +if (($_GET['act'] == "test") && ($a_patches[$_GET['id']])) { + $savemsg = patch_test_apply($a_patches[$_GET['id']]) ? gettext("Patch can be applied cleanly") : gettext("Patch can NOT be applied cleanly"); + $savemsg .= " (<a href=\"system_patches.php?id={$_GET['id']}&fulltest=apply\">" . gettext("detail") . "</a>)"; + $savemsg .= empty($savemsg) ? "" : "<br/>"; + $savemsg .= patch_test_revert($a_patches[$_GET['id']]) ? gettext("Patch can be reverted cleanly") : gettext("Patch can NOT be reverted cleanly"); + $savemsg .= " (<a href=\"system_patches.php?id={$_GET['id']}&fulltest=revert\">" . gettext("detail") . "</a>)"; +} +if (($_GET['fulltest']) && ($a_patches[$_GET['id']])) { + if ($_GET['fulltest'] == "apply") { + $fulldetail = patch_test_apply($a_patches[$_GET['id']], true); + } elseif ($_GET['fulltest'] == "revert") { + $fulldetail = patch_test_revert($a_patches[$_GET['id']], true); + } +} +if (($_GET['act'] == "apply") && ($a_patches[$_GET['id']])) { + $savemsg = patch_apply($a_patches[$_GET['id']]) ? gettext("Patch applied successfully") : gettext("Patch could NOT be applied!"); +} +if (($_GET['act'] == "revert") && ($a_patches[$_GET['id']])) { + $savemsg = patch_revert($a_patches[$_GET['id']]) ? gettext("Patch reverted successfully") : gettext("Patch could NOT be reverted!"); +} + + +if (isset($_POST['del_x'])) { + /* delete selected patches */ + if (is_array($_POST['patch']) && count($_POST['patch'])) { + foreach ($_POST['patch'] as $patchi) { + unset($a_patches[$patchi]); + } + write_config(); + header("Location: system_patches.php"); + exit; + } +} else { + /* yuck - IE won't send value attributes for image buttons, while Mozilla does - so we use .x/.y to find move button clicks instead... */ + unset($movebtn); + foreach ($_POST as $pn => $pd) { + if (preg_match("/move_(\d+)_x/", $pn, $matches)) { + $movebtn = $matches[1]; + break; + } + } + /* move selected patches before this patch */ + if (isset($movebtn) && is_array($_POST['patch']) && count($_POST['patch'])) { + $a_patches_new = array(); + + /* copy all patches < $movebtn and not selected */ + for ($i = 0; $i < $movebtn; $i++) { + if (!in_array($i, $_POST['patch'])) + $a_patches_new[] = $a_patches[$i]; + } + + /* copy all selected patches */ + for ($i = 0; $i < count($a_patches); $i++) { + if ($i == $movebtn) + continue; + if (in_array($i, $_POST['patch'])) + $a_patches_new[] = $a_patches[$i]; + } + + /* copy $movebtn patch */ + if ($movebtn < count($a_patches)) + $a_patches_new[] = $a_patches[$movebtn]; + + /* copy all patches > $movebtn and not selected */ + for ($i = $movebtn+1; $i < count($a_patches); $i++) { + if (!in_array($i, $_POST['patch'])) + $a_patches_new[] = $a_patches[$i]; + } + $a_patches = $a_patches_new; + write_config(); + header("Location: system_patches.php"); + return; + } +} + +$pgtitle = array(gettext("System"),gettext("Patches")); +include("head.inc"); + +echo "<script type=\"text/javascript\" language=\"javascript\" src=\"/javascript/domTT/domLib.js\"></script>"; +echo "<script type=\"text/javascript\" language=\"javascript\" src=\"/javascript/domTT/domTT.js\"></script>"; +echo "<script type=\"text/javascript\" language=\"javascript\" src=\"/javascript/domTT/behaviour.js\"></script>"; +echo "<script type=\"text/javascript\" language=\"javascript\" src=\"/javascript/domTT/fadomatic.js\"></script>"; + +?> +<link rel="stylesheet" href="/javascript/chosen/chosen.css" /> +<body link="#000000" vlink="#000000" alink="#000000"> +<?php include("fbegin.inc"); ?> +<form action="system_patches.php" method="post" name="iform"> +<script type="text/javascript" language="javascript" src="/javascript/row_toggle.js"></script> +<?php if ($savemsg) print_info_box($savemsg); ?> +<table width="100%" border="0" cellpadding="0" cellspacing="0"> +<tr><td><div id="mainarea"> +<table class="tabcont" width="100%" border="0" cellpadding="0" cellspacing="0"> +<tr><td colspan="8" align="center"> +<?php echo gettext("This page allows you to add patches, either from the official code repository or ones pasted in from e-mail or other sources."); ?> +<br/><br/> +<strong><?php echo gettext("Use with caution!"); ?></strong> +<br/><br/> +<?php if (!empty($fulldetail)): ?> +</td></tr> +<tr><td></td><td colspan="7" align="left">Output of full patch <?php echo $_GET['fulltest']; ?> test: +<pre><?php echo $fulldetail; ?></pre> +<a href="system_patches.php">Close</a><br/><br/> +<?php endif; ?> +</td></tr> +<tr id="frheader"> +<td width="5%" class="list"> </td> +<td width="5%" class="listhdrr"><?=gettext("Description");?></td> +<td width="65%" class="listhdrr"><?=gettext("URL/ID");?></td> +<td width="5%" class="listhdrr"><?=gettext("Fetch");?></td> +<td width="5%" class="listhdrr"><?=gettext("Test");?></td> +<td width="5%" class="listhdrr"><?=gettext("Apply");?></td> +<td width="5%" class="listhdr"><?=gettext("Revert");?></td> +<td width="5%" class="list"> +<table border="0" cellspacing="0" cellpadding="1"> + <tr><td width="17"> + <?php if (count($a_patches) == 0): ?> + <img src="./themes/<?= $g['theme']; ?>/images/icons/icon_x_d.gif" width="17" height="17" title="<?=gettext("delete selected patches");?>" border="0"> + <?php else: ?> + <input name="del" type="image" src="./themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" width="17" height="17" title="<?=gettext("delete selected patches"); ?>" onclick="return confirm('<?=gettext("Do you really want to delete the selected patches?");?>')"> + <?php endif; ?> + </td> + <td><a href="system_patches_edit.php"><img src="/themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" width="17" height="17" border="0" title="<?=gettext("add new patch"); ?>"></a></td> + </tr> +</table> +</td> +</tr> + +<?php +$npatches = $i = 0; +foreach ($a_patches as $thispatch): + $can_apply = patch_test_apply($thispatch); + $can_revert = patch_test_revert($thispatch); + +?> + <tr valign="top" id="fr<?=$npatches;?>"> + <td class="listt"><input type="checkbox" id="frc<?=$npatches;?>" name="patch[]" value="<?=$i;?>" onClick="fr_bgcolor('<?=$npatches;?>')" style="margin: 0; padding: 0; width: 15px; height: 15px;"></td> + <td class="listlr" onClick="fr_toggle(<?=$npatches;?>)" id="frd<?=$npatches;?>" ondblclick="document.location='system_patches_edit.php?id=<?=$npatches;?>';"> + <?=$thispatch['descr'];?> + </td> + <td class="listr" onClick="fr_toggle(<?=$npatches;?>)" id="frd<?=$npatches;?>" ondblclick="document.location='system_patches_edit.php?id=<?=$npatches;?>';"> + + <?php + if (!empty($thispatch['location'])) + echo $thispatch['location']; + elseif (!empty($thispatch['patch'])) + echo gettext("Saved Patch"); + ?> + </td> + <td class="listr" onClick="fr_toggle(<?=$npatches;?>)" id="frd<?=$npatches;?>" ondblclick="document.location='system_patches_edit.php?id=<?=$npatches;?>';"> + <?php if (empty($thispatch['patch'])): ?> + <a href="system_patches.php?id=<?=$i;?>&act=fetch"><?php echo gettext("Fetch"); ?></a> + <?php elseif (!empty($thispatch['location'])): ?> + <a href="system_patches.php?id=<?=$i;?>&act=fetch"><?php echo gettext("Re-Fetch"); ?></a> + <?php endif; ?> + </td> + <td class="listr" onClick="fr_toggle(<?=$npatches;?>)" id="frd<?=$npatches;?>" ondblclick="document.location='system_patches_edit.php?id=<?=$npatches;?>';"> + <?php if (!empty($thispatch['patch'])): ?> + <a href="system_patches.php?id=<?=$i;?>&act=test"><?php echo gettext("Test"); ?></a> + <?php endif; ?> + </td> + <td class="listr" onClick="fr_toggle(<?=$npatches;?>)" id="frd<?=$npatches;?>" ondblclick="document.location='system_patches_edit.php?id=<?=$npatches;?>';"> + <?php if ($can_apply): ?> + <a href="system_patches.php?id=<?=$i;?>&act=apply"><?php echo gettext("Apply"); ?></a> + <?php endif; ?> + </td> + <td class="listr" onClick="fr_toggle(<?=$npatches;?>)" id="frd<?=$npatches;?>" ondblclick="document.location='system_patches_edit.php?id=<?=$npatches;?>';"> + <?php if ($can_revert): ?> + <a href="system_patches.php?id=<?=$i;?>&act=revert"><?php echo gettext("Revert"); ?></a> + <?php endif; ?> + </td> + <td valign="middle" class="list" nowrap> + <table border="0" cellspacing="0" cellpadding="1"> + <tr> + <td><input onmouseover="fr_insline(<?=$npatches;?>, true)" onmouseout="fr_insline(<?=$npatches;?>, false)" name="move_<?=$i;?>" src="/themes/<?= $g['theme']; ?>/images/icons/icon_left.gif" title="<?=gettext("move selected patches before this patch");?>" height="17" type="image" width="17" border="0"></td> + <td><a href="system_patches_edit.php?id=<?=$i;?>"><img src="/themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" width="17" height="17" border="0" title="<?=gettext("edit patch"); ?>"></a></td> + </tr> + <tr> + <td align="center" valign="middle"><a href="system_patches.php?act=del&id=<?=$i;?>" onclick="return confirm('<?=gettext("Do you really want to delete this patch?");?>')"><img src="./themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" width="17" height="17" border="0" title="<?=gettext("delete patch");?>"></a></td> + <td></td> + </tr> + </table> + </td></tr> +<?php $i++; $npatches++; endforeach; ?> + <tr> + <td class="list" colspan="7"></td> + <td class="list" valign="middle" nowrap> + <table border="0" cellspacing="0" cellpadding="1"> + <tr> + <td><?php if ($npatches == 0): ?><img src="/themes/<?= $g['theme']; ?>/images/icons/icon_left_d.gif" width="17" height="17" title="<?=gettext("move selected patches to end"); ?>" border="0"><?php else: ?><input name="move_<?=$i;?>" type="image" src="/themes/<?= $g['theme']; ?>/images/icons/icon_left.gif" width="17" height="17" title="<?=gettext("move selected patches to end");?>" border="0"><?php endif; ?></td> + </tr> + <tr> + <td width="17"> + <?php if (count($a_patches) == 0): ?> + <img src="./themes/<?= $g['theme']; ?>/images/icons/icon_x_d.gif" width="17" height="17" title="<?=gettext("delete selected patches");?>" border="0"> + <?php else: ?> + <input name="del" type="image" src="./themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" width="17" height="17" title="<?=gettext("delete selected patches"); ?>" onclick="return confirm('<?=gettext("Do you really want to delete the selected patches?");?>')"> + <?php endif; ?> + </td> + <td><a href="system_patches_edit.php"><img src="/themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" width="17" height="17" border="0" title="<?=gettext("add new patch"); ?>"></a></td> + </tr> + </table> + </td> + </tr> + <tr><td></td><td colspan="6"> + <?php echo gettext("NOTE: Each patch is tested, and the appropriate action is shown. If neither 'Apply' or 'Revert' shows up, the patch cannot be used (check the pathstrip and whitespace options)."); ?> + <br/><br/> + <?php echo gettext("Use the 'Test' link to see if a patch can be applied or reverted. You can reorder patches so that higher patches apply later than lower patches."); ?> + </td><td></td></tr> + </table> +</div></td></tr> +</table> +</form> +<?php include("fend.inc"); ?> +</body> +</html> diff --git a/config/systempatches/system_patches_edit.php b/config/systempatches/system_patches_edit.php new file mode 100644 index 00000000..a4038b05 --- /dev/null +++ b/config/systempatches/system_patches_edit.php @@ -0,0 +1,223 @@ +<?php +/* + system_patches_edit.php + Copyright (C) 2012 Jim Pingle + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. +*/ +/* + pfSense_MODULE: system +*/ + +##|+PRIV +##|*IDENT=page-system-patches-edit +##|*NAME=System: Edit Patches +##|*DESCR=Allow access to the 'System: Edit Patches' page. +##|*MATCH=system_patches_edit.php* +##|-PRIV + +require("guiconfig.inc"); +require_once("itemid.inc"); +require_once("patches.inc"); + +if (!is_array($config['installedpackages']['patches']['item'])) { + $config['installedpackages']['patches']['item'] = array(); +} +$a_patches = &$config['installedpackages']['patches']['item']; + +$id = $_GET['id']; +if (isset($_POST['id'])) + $id = $_POST['id']; + +if (isset($_GET['dup'])) { + $id = $_GET['dup']; + $after = $_GET['dup']; +} + +if (isset($id) && $a_patches[$id]) { + $pconfig['descr'] = $a_patches[$id]['descr']; + $pconfig['location'] = $a_patches[$id]['location']; + $pconfig['patch'] = $a_patches[$id]['patch']; + $pconfig['pathstrip'] = $a_patches[$id]['pathstrip']; + $pconfig['basedir'] = $a_patches[$id]['basedir']; + $pconfig['ignorewhitespace'] = isset($a_patches[$id]['ignorewhitespace']); + $pconfig['autoapply'] = isset($a_patches[$id]['autoapply']); + $pconfig['uniqid'] = $a_patches[$id]['uniqid']; +} + +if (isset($_GET['dup'])) + unset($id); + +unset($input_errors); + +if ($_POST) { + $pconfig = $_POST; + + /* input validation */ + if(empty($_POST['location'])) { + $reqdfields = explode(" ", "patch"); + $reqdfieldsn = array(gettext("Patch Contents")); + } else { + $reqdfields = explode(" ", "descr location"); + $reqdfieldsn = array(gettext("Description"),gettext("URL/Commit ID")); + } + + do_input_validation($_POST, $reqdfields, $reqdfieldsn, &$input_errors); + + if (!empty($_POST['location']) && !is_commit_id($_POST['location']) && !is_URL($_POST['location'])) { + $input_errors[] = gettext("The supplied commit ID/URL appears to be invalid."); + } + if (!is_numeric($_POST['pathstrip'])) { + $input_errors[] = gettext("Path Strip Count must be numeric!"); + } + if (!empty($_POST['basedir']) && (!file_exists($_POST['basedir']) || !is_dir($_POST['basedir']))) { + $input_errors[] = gettext("Base Directory must exist and be a directory!"); + } + + if (!$input_errors) { + $thispatch = array(); + + $thispatch['descr'] = $_POST['descr']; + $thispatch['location'] = patch_fixup_url($_POST['location']); + if (!empty($_POST['patch'])) { + /* Strip DOS style carriage returns from textarea input */ + $thispatch['patch'] = base64_encode(str_replace("\r", "", $_POST['patch'])); + } + if (is_github_url($thispatch['location']) && ($_POST['pathstrip'] == 0)) + $thispatch['pathstrip'] = 1; + else + $thispatch['pathstrip'] = $_POST['pathstrip']; + $thispatch['basedir'] = empty($_POST['basedir']) ? "/" : $_POST['basedir']; + $thispatch['ignorewhitespace'] = isset($_POST['ignorewhitespace']); + $thispatch['autoapply'] = isset($_POST['autoapply']); + if (empty($_POST['uniqid'])) { + $thispatch['uniqid'] = uniqid(); + } else { + $thispatch['uniqid'] = $_POST['uniqid']; + } + + // Update the patch entry now + if (isset($id) && $a_patches[$id]) + $a_patches[$id] = $thispatch; + else { + if (is_numeric($after)) + array_splice($a_patches, $after+1, 0, array($thispatch)); + else + $a_patches[] = $thispatch; + } + + write_config(); + header("Location: system_patches.php"); + return; + } +} + +$pgtitle = array(gettext("System"),gettext("Patches"), gettext("Edit")); +include("head.inc"); + +?> +<link rel="stylesheet" href="/pfCenter/javascript/chosen/chosen.css" /> +</head> + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC"> +<script src="/pfCenter/javascript/chosen/chosen.proto.js" type="text/javascript"></script> + +<?php +include("fbegin.inc"); ?> +<?php if ($input_errors) print_input_errors($input_errors); ?> +<form action="system_patches_edit.php" method="post" name="iform" id="iform"> +<table width="100%" border="0" cellpadding="6" cellspacing="0"> +<tr> + <td colspan="2" valign="top" class="listtopic"><?=gettext("Edit Patch Entry"); ?></td> +</tr> +<tr> + <td width="22%" valign="top" class="vncellreq"><strong><?=gettext("Description"); ?></strong></td> + <td width="78%" class="vtable"> + <input name="descr" type="text" class="formfld unknown" id="descr" size="40" value="<?=htmlspecialchars($pconfig['descr']);?>"> + <br> <span class="vexpl"><?=gettext("Enter a description here for your reference."); ?></span></td> +</tr> +<tr> + <td width="22%" valign="top" class="vncell"><?=gettext("URL/Commit ID"); ?></td> + <td width="78%" class="vtable"> + <input name="location" type="text" class="formfld unknown" id="location" size="40" value="<?=htmlspecialchars($pconfig['location']);?>"> + <br> <span class="vexpl"><?=gettext("Enter a URL to a patch, or a commit ID from the main github repository (NOT the tools or packages repos!)."); ?></span></td> +</tr> +<tr> + <td width="22%" valign="top" class="vncell"><?=gettext("Patch Contents"); ?></td> + <td width="78%" class="vtable"> + <textarea name="patch" class="" id="patch" ROWS="15" COLS="70" wrap="off"><?=base64_decode($pconfig['patch']);?></textarea> + <br> <span class="vexpl"><?=gettext("The contents of the patch. You can paste a patch here, or enter a URL/commit ID above, it can then be fetched into here automatically."); ?></span></td> +</tr> +<tr> + <td width="22%" valign="top" class="vncell"><?=gettext("Path Strip Count:"); ?></td> + <td width="78%" class="vtable"> + <select name="pathstrip" class="formselect" id="pathstrip"> +<?php for ($i = 0; $i < 20; $i++): ?> + <option value="<?=$i;?>" <?php if ($i == $pconfig['pathstrip']) echo "selected"; ?>><?=$i;?></option> +<?php endfor; ?> + </select> + </td> +</tr> +<tr> + <td width="22%" valign="top" class="vncell"><?=gettext("Base Directory"); ?></td> + <td width="78%" class="vtable"> + <input name="basedir" type="text" class="formfld unknown" id="basedir" size="40" value="<?=htmlspecialchars($pconfig['basedir']);?>"> + <br> <span class="vexpl"><?=gettext("Enter the base directory for the patch, default is /. Patches from github are all based in /. Custom patches may need a full path here such as /usr/local/www/"); ?></span></td> +</tr> +<tr> + <td width="22%" valign="top" class="vncell"><?=gettext("Ignore Whitespace"); ?></td> + <td width="78%" class="vtable"> + <input name="ignorewhitespace" type="checkbox" id="ignorewhitespace" value="yes" <?php if ($pconfig['ignorewhitespace']) echo "checked"; ?>> + <strong><?=gettext("Ignore Whitespace"); ?></strong><br /> + <span class="vexpl"><?=gettext("Set this option to ignore whitespace in the patch."); ?></span> + </td> +</tr> +<!-- This isn't ready yet +<tr> + <td width="22%" valign="top" class="vncell"><?=gettext("Auto Apply"); ?></td> + <td width="78%" class="vtable"> + <input name="autoapply" type="checkbox" id="autoapply" value="yes" <?php if ($pconfig['autoapply']) echo "checked"; ?>> + <strong><?=gettext("Auto-Apply Patch"); ?></strong><br /> + <span class="vexpl"><?=gettext("Set this option to apply the patch automatically when possible, useful for patches to survive after firmware updates."); ?></span> + </td> +</tr> +--> +<tr> + <td width="22%" valign="top"> </td> + <td width="78%">Patch id: <?php echo $pconfig['uniqid']; ?></td> +</tr> +<tr> + <td width="22%" valign="top"> </td> + <td width="78%"> + <input name="Submit" type="submit" class="formbtn" value="<?=gettext("Save"); ?>"> <input type="button" class="formbtn" value="<?=gettext("Cancel"); ?>" onclick="history.back()"> + <?php if (isset($id) && $a_patches[$id]): ?> + <input name="id" type="hidden" value="<?=htmlspecialchars($id);?>"> + <input name="uniqid" type="hidden" value="<?=htmlspecialchars($pconfig['uniqid']);?>"> + <?php endif; ?> + </td> +</tr> +</table> +</form> +<?php include("fend.inc"); ?> +</body> +</html> diff --git a/config/systempatches/systempatches.xml b/config/systempatches/systempatches.xml new file mode 100644 index 00000000..3730c84f --- /dev/null +++ b/config/systempatches/systempatches.xml @@ -0,0 +1,66 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "../schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="../xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* ========================================================================== */ +/* + systempatches.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2012 Jim Pingle + All rights reserved. +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>System Patches</description> + <requirements>None</requirements> + <faq>Applies patches supplied by the user to the firewall.</faq> + <name>System Patches</name> + <version>0.5</version> + <title>System: Patches</title> + <menu> + <name>Patches</name> + <tooltiptext></tooltiptext> + <section>System</section> + <url>/system_patches.php</url> + </menu> + <additional_files_needed> + <prefix>/usr/local/www/</prefix> + <chmod>644</chmod> + <item>http://www.pfsense.com/packages/config/systempatches/system_patches.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/</prefix> + <chmod>644</chmod> + <item>http://www.pfsense.com/packages/config/systempatches/system_patches_edit.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>644</chmod> + <item>http://www.pfsense.com/packages/config/systempatches/patches.inc</item> + </additional_files_needed> +</packagegui>
\ No newline at end of file diff --git a/config/tinc/pkg_tinc.inc b/config/tinc/pkg_tinc.inc new file mode 100644 index 00000000..b5b223b0 --- /dev/null +++ b/config/tinc/pkg_tinc.inc @@ -0,0 +1,11 @@ +<?php + +global $shortcuts; + +$shortcuts['tinc'] = array(); +$shortcuts['tinc']['main'] = "pkg_edit.php?xml=tinc_config.xml"; +$shortcuts['tinc']['status'] = "status_tinc.php"; +$shortcuts['tinc']['log'] = "diag_pkglogs.php?pkg=tinc"; +$shortcuts['tinc']['service'] = "tinc"; + +?> diff --git a/config/tinc/status_tinc.php b/config/tinc/status_tinc.php new file mode 100644 index 00000000..725ccce6 --- /dev/null +++ b/config/tinc/status_tinc.php @@ -0,0 +1,70 @@ +<?php + +$pgtitle = array(gettext("Status"), "tinc"); +require("guiconfig.inc"); + +function tinc_status_1() { + exec("/usr/local/sbin/tincd --config=/usr/local/etc/tinc -kUSR1"); + usleep(500000); + exec("/usr/sbin/clog /var/log/tinc.log | sed -e 's/.*tinc\[.*\]: //'",$result); + $i=0; + foreach($result as $line) + { + if(preg_match("/Connections:/",$line)) + $begin=$i; + if(preg_match("/End of connections./",$line)) + $end=$i; + $i++; + } + $output=""; + $i=0; + foreach($result as $line) + { + if($i >= $begin && $i<= $end) + $output .= $line . "\n"; + $i++; + } + return $output; +} + +function tinc_status_2() { + exec("/usr/local/sbin/tincd --config=/usr/local/etc/tinc -kUSR2"); + usleep(500000); + exec("/usr/sbin/clog /var/log/tinc.log | sed -e 's/.*tinc\[.*\]: //'",$result); + $i=0; + foreach($result as $line) + { + if(preg_match("/Statistics for Generic BSD tun device/",$line)) + $begin=$i; + if(preg_match("/End of subnet list./",$line)) + $end=$i; + $i++; + } + $output=""; + $i=0; + foreach($result as $line) + { + if($i >= $begin && $i<= $end) + $output .= $line . "\n"; + $i++; + } + return $output; +} + +$shortcut_section = "tinc"; +include("head.inc"); ?> + +<body link="#0000CC" vlink="#0000CC" alink="#0000CC" onload="<?=$jsevents["body"]["onload"];?>"> +<?php include("fbegin.inc"); ?> + +Connection list:<BR> +<pre> +<?php print tinc_status_1(); ?> +</pre> +<BR> +Virtual network device statistics, all known nodes, edges and subnets:<BR> +<pre> +<?php print tinc_status_2(); ?> +</pre> + +<?php include("fend.inc"); ?> diff --git a/config/tinc/tinc.inc b/config/tinc/tinc.inc new file mode 100644 index 00000000..697e2932 --- /dev/null +++ b/config/tinc/tinc.inc @@ -0,0 +1,162 @@ +<?php + +function tinc_save() { + conf_mount_rw(); + config_lock(); + exec("/bin/mv -f /usr/local/etc/tinc /usr/local/etc/tinc.old"); + safe_mkdir("/usr/local/etc/tinc"); + safe_mkdir("/usr/local/etc/tinc/hosts"); + exec("touch /usr/local/etc/tinc/WARNING-ENTIRE_DIRECTORY_ERASED_ON_SAVE_FROM_GUI"); + $tincconf = $GLOBALS['config']['installedpackages']['tinc']['config'][0]; + $fout = fopen("/usr/local/etc/tinc/tinc.conf","w"); + fwrite($fout, "name=".$tincconf['name']."\n"); + fwrite($fout, "AddressFamily=".$tincconf['addressfamily']."\n"); + if(!is_array($GLOBALS['config']['installedpackages']['tinchosts']['config'])) { $GLOBALS['config']['installedpackages']['tinchosts']['config']=Array(); } + foreach($GLOBALS['config']['installedpackages']['tinchosts']['config'] as $host) { + if($host['connect']) + { + fwrite($fout, "ConnectTo=" . $host['name'] . "\n"); + } + + $_output = "Address=".$host['address']."\n"; + $_output .= "Subnet=".$host['subnet']."\n"; + $_output .= base64_decode($host['extra'])."\n"; + $_output .= base64_decode($host['cert_pub'])."\n"; + file_put_contents('/usr/local/etc/tinc/hosts/'.$host['name'],$_output); + if($host['host_up']) + { + file_put_contents('/usr/local/etc/tinc/hosts/'.$host['name'].'-up',base64_decode($host['host_up'])."\n"); + chmod('/usr/local/etc/tinc/hosts/'.$host['name'].'-up', 0744); + } + if($host['host_down']) + { + file_put_contents('/usr/local/etc/tinc/hosts/'.$host['name'].'-down',base64_decode($host['host_down'])."\n"); + chmod('/usr/local/etc/tinc/hosts/'.$host['name'].'-down', 0744); + } + } + fwrite($fout, base64_decode($tincconf['extra'])."\n"); + fclose($fout); + $_output = "Subnet=" . $tincconf['localsubnet'] . "\n"; + $_output .= base64_decode($tincconf['host_extra']) . "\n"; + $_output .= base64_decode($tincconf['cert_pub']) . "\n"; + file_put_contents('/usr/local/etc/tinc/hosts/' . $tincconf['name'],$_output); + file_put_contents('/usr/local/etc/tinc/rsa_key.priv',base64_decode($tincconf['cert_key'])."\n"); + chmod("/usr/local/etc/tinc/rsa_key.priv", 0600); + if($tincconf['tinc_up']) + { + $_output = base64_decode($tincconf['tinc_up']) . "\n"; + } + else + { + $_output = "ifconfig \$INTERFACE " . $tincconf['localip'] . " netmask " . $tincconf['vpnnetmask'] . "\n"; + $_output .= "ifconfig \$INTERFACE group tinc\n"; + } + file_put_contents('/usr/local/etc/tinc/tinc-up',$_output); + chmod("/usr/local/etc/tinc/tinc-up", 0744); + if($tincconf['tinc_down']) + { + file_put_contents('/usr/local/etc/tinc/tinc-down',base64_decode($tincconf['tinc_down']) . "\n"); + chmod("/usr/local/etc/tinc/tinc-down", 0744); + } + if($tincconf['host_up']) + { + file_put_contents('/usr/local/etc/tinc/host-up',base64_decode($tincconf['host_up']) . "\n"); + chmod("/usr/local/etc/tinc/host-up", 0744); + } + if($tincconf['host_down']) + { + file_put_contents('/usr/local/etc/tinc/host-down',base64_decode($tincconf['host_down']) . "\n"); + chmod("/usr/local/etc/tinc/host-down", 0744); + } + if($tincconf['subnet_up']) + { + file_put_contents('/usr/local/etc/tinc/subnet-up',base64_decode($tincconf['subnet_up']) . "\n"); + chmod("/usr/local/etc/tinc/subnet-up", 0744); + } + if($tincconf['subnet_down']) + { + file_put_contents('/usr/local/etc/tinc/subnet-down',base64_decode($tincconf['subnet_down']) . "\n"); + chmod("/usr/local/etc/tinc/subnet-down", 0744); + } + system("/usr/local/etc/rc.d/tinc.sh restart 2>/dev/null"); + rmdir_recursive("/usr/local/etc/tinc.old"); + conf_mount_ro(); + config_unlock(); +} + +function tinc_install() { + safe_mkdir("/usr/local/etc/tinc"); + safe_mkdir("/usr/local/etc/tinc/hosts"); + $_rcfile['file']='tinc.sh'; + $_rcfile['start'].="/usr/local/sbin/tincd --config=/usr/local/etc/tinc\n\t"; + $_rcfile['stop'].="/usr/local/sbin/tincd --kill \n\t"; + write_rcfile($_rcfile); + unlink_if_exists("/usr/local/etc/rc.d/tincd"); + clear_log_file("/var/log/tinc.log"); + + conf_mount_rw(); + config_lock(); + + /* Create Interface Group */ + if (!is_array($GLOBALS['config']['ifgroups']['ifgroupentry'])) + $GLOBALS['config']['ifgroups']['ifgroupentry'] = array(); + + $a_ifgroups = &$GLOBALS['config']['ifgroups']['ifgroupentry']; + $ifgroupentry = array(); + $ifgroupentry['members'] = ''; + $ifgroupentry['descr'] = 'tinc mesh VPN interface group'; + $ifgroupentry['ifname'] = 'tinc'; + $a_ifgroups[] = $ifgroupentry; + + /* XXX: Do not remove this. */ + mwexec("/bin/rm -f /tmp/config.cache"); + + write_config(); + + conf_mount_ro(); + config_unlock(); +} + +function tinc_deinstall() { + /* Remove Interface Group */ + conf_mount_rw(); + config_lock(); + if (!is_array($GLOBALS['config']['ifgroups']['ifgroupentry'])) + $GLOBALS['config']['ifgroups']['ifgroupentry'] = array(); + + $a_ifgroups = &$GLOBALS['config']['ifgroups']['ifgroupentry']; + + $myid=-1; + $i = 0; + foreach ($a_ifgroups as $ifgroupentry) + { + if($ifgroupentry['ifname']=='tinc') + { + $myid=$i; + break; + } + $i++; + } + + if ($myid >= 0 && $a_ifgroups[$myid]) + { + $members = explode(" ", $a_ifgroups[$_GET['id']]['members']); + foreach ($members as $ifs) + { + $realif = get_real_interface($ifs); + if ($realif) + mwexec("/sbin/ifconfig {$realif} -group " . $a_ifgroups[$_GET['id']]['ifname']); + } + unset($a_ifgroups[$myid]); + mwexec("/bin/rm -f /tmp/config.cache"); + write_config(); + } + conf_mount_ro(); + config_unlock(); + + rmdir_recursive("/var/tmp/tinc"); + rmdir_recursive("/usr/local/etc/tinc*"); + unlink_if_exists("/usr/local/etc/rc.d/tinc.sh"); +} + +?> diff --git a/config/tinc/tinc.xml b/config/tinc/tinc.xml new file mode 100644 index 00000000..90581513 --- /dev/null +++ b/config/tinc/tinc.xml @@ -0,0 +1,103 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "./schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="./xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + tinc.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2007-2008 Scott Ullrich + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>A self-contained VPN solution designed to connect multiple sites together in a secure way.</description> + <requirements>Describe your package requirements here</requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>tinc</name> + <version>1.0.19</version> + <title>VPN: tinc</title> + <!-- Menu is where this packages menu will appear --> + <menu> + <name>tinc</name> + <tooltiptext>tinc is a mesh VPN daemon.</tooltiptext> + <section>VPN</section> + <configfile>tinc_config.xml</configfile> + <url>/pkg_edit.php?xml=tinc_config.xml</url> + </menu> + <menu> + <name>tincd</name> + <tooltiptext>Status of tinc VPN Daemon</tooltiptext> + <section>Status</section> + <url>/status_tinc.php</url> + </menu> + + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.com/packages/config/tinc/tinc.inc</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.com/packages/config/tinc/tinc_config.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/pkg/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.com/packages/config/tinc/tinc_hosts.xml</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/</prefix> + <chmod>0755</chmod> + <item>http://www.pfsense.com/packages/config/tinc/status_tinc.php</item> + </additional_files_needed> + <additional_files_needed> + <prefix>/usr/local/www/shortcuts/</prefix> + <chmod>0644</chmod> + <item>http://www.pfsense.com/packages/config/tinc/pkg_tinc.inc</item> + </additional_files_needed> + + <service> + <name>tinc</name> + <rcfile>tinc.sh</rcfile> + <executable>tincd</executable> + <description>tinc mesh VPN</description> + </service> + <include_file>/usr/local/pkg/tinc.inc</include_file> + + <custom_php_install_command> + tinc_install(); + </custom_php_install_command> + <custom_php_deinstall_command> + tinc_deinstall(); + </custom_php_deinstall_command> + +</packagegui> diff --git a/config/tinc/tinc_config.xml b/config/tinc/tinc_config.xml new file mode 100644 index 00000000..3878450f --- /dev/null +++ b/config/tinc/tinc_config.xml @@ -0,0 +1,209 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "./schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="./xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + tinc_config.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2007-2008 Scott Ullrich + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + <name>tinc</name> + <version>1.0.19</version> + <title>VPN: tinc</title> + + <!-- configpath gets expanded out automatically and config items will be + stored in that location --> + <configpath>['installedpackages']['package']['$packagename']['config']</configpath> + + <tabs> + <tab> + <text>Config</text> + <url>/pkg_edit.php?xml=tinc_config.xml</url> + <active/> + </tab> + <tab> + <text>Hosts</text> + <url>/pkg.php?xml=tinc_hosts.xml</url> + </tab> + </tabs> + <advanced_options>enabled</advanced_options> + <fields> + <field> + <fielddescr>Name</fielddescr> + <fieldname>name</fieldname> + <description>This is the name which identifies this tinc daemon. It must be unique for the virtual private network this daemon will connect to.</description> + <type>input</type> + </field> + <field> + <fielddescr>Local IP</fielddescr> + <fieldname>localip</fieldname> + <description>IP Address of local tunnel interface. This is often the same IP as your routers LAN address, for example 192.168.2.1</description> + <type>input</type> + </field> + <field> + <fielddescr>Local Subnet</fielddescr> + <fieldname>localsubnet</fieldname> + <description>Subnet behind this router that should be advertised to the mesh. This is usually your LAN subnet, for example 192.168.2.0/24</description> + <type>input</type> + </field> + <field> + <fielddescr>VPN Netmask</fielddescr> + <fieldname>vpnnetmask</fieldname> + <description>This is the Netmask that defines what traffic is routed to the VPNs tunnel interface. It is usually broader then your local netmask, for example 255.255.0.0</description> + <type>input</type> + </field> + <field> + <fielddescr>AddressFamily</fielddescr> + <fieldname>addressfamily</fieldname> + <description>This option affects the address family of listening and outgoing sockets. If "any" is selected, then depending on the operating system both IPv4 and IPv6 or just IPv6 listening sockets will be created.</description> + <type>select</type> + <options> + <option> + <name>ipv4</name> + <value>ipv4</value> + </option> + <option> + <name>ipv6</name> + <value>ipv6</value> + </option> + <option> + <name>any</name> + <value>any</value> + </option> + </options> + </field> + <field> + <fielddescr>RSA private key</fielddescr> + <fieldname>cert_key</fieldname> + <description>RSA private key used for this host. Include the BEGIN and END lines. <br></description> + <type>textarea</type> + <encoding>base64</encoding> + <rows>7</rows> + <cols>65</cols> + </field> + <field> + <fielddescr>RSA public key</fielddescr> + <fieldname>cert_pub</fieldname> + <description>RSA public key used for this host. Include the BEGIN and END lines. <br></description> + <type>textarea</type> + <encoding>base64</encoding> + <rows>7</rows> + <cols>65</cols> + </field> + <field> + <fielddescr>Extra Tinc Parameters</fielddescr> + <fieldname>extra</fieldname> + <description>Anything entered here will be added at the end of the tinc.conf configuration file. <br></description> + <type>textarea</type> + <encoding>base64</encoding> + <rows>8</rows> + <cols>65</cols> + <advancedfield/> + </field> + <field> + <fielddescr>Extra Host Parameters</fielddescr> + <fieldname>host_extra</fieldname> + <description>Anything entered here will be added just prior to the public certiciate in the host configuration file for this machine. <br></description> + <type>textarea</type> + <encoding>base64</encoding> + <rows>8</rows> + <cols>65</cols> + <advancedfield/> + </field> + <field> + <fielddescr>Interface Up Script</fielddescr> + <fieldname>tinc_up</fieldname> + <description>This script is executed right after the tinc daemon has connected to the virtual network device. By default a tinc-up file is created that brings up the tinc interface with the IP Address and Netmask specified above and adds it to the tinc interface group. Entering a value here complely replaces the default script so be sure to bring up the interface in this script.</description> + <type>textarea</type> + <encoding>base64</encoding> + <rows>8</rows> + <cols>65</cols> + <advancedfield/> + </field> + <field> + <fielddescr>Interface Down Script</fielddescr> + <fieldname>tinc_down</fieldname> + <description>This script is executed right before the tinc daemon is going to close.</description> + <type>textarea</type> + <encoding>base64</encoding> + <rows>8</rows> + <cols>65</cols> + <advancedfield/> + </field> + <field> + <fielddescr>Host Up Script</fielddescr> + <fieldname>host_up</fieldname> + <description>This script is executed when any host becomes reachable.</description> + <type>textarea</type> + <encoding>base64</encoding> + <rows>8</rows> + <cols>65</cols> + <advancedfield/> + </field> + <field> + <fielddescr>Host Down Script</fielddescr> + <fieldname>host_down</fieldname> + <description>This script is executed when any host becomes unreachable.</description> + <type>textarea</type> + <encoding>base64</encoding> + <rows>8</rows> + <cols>65</cols> + <advancedfield/> + </field> + <field> + <fielddescr>Subnet Up Script</fielddescr> + <fieldname>subnet_up</fieldname> + <description>This script is executed when any subnet becomes reachable.</description> + <type>textarea</type> + <encoding>base64</encoding> + <rows>8</rows> + <cols>65</cols> + <advancedfield/> + </field> + <field> + <fielddescr>Subnet Down Script</fielddescr> + <fieldname>subnet_down</fieldname> + <description>This script is executed when any subnet becomes unreachable.</description> + <type>textarea</type> + <encoding>base64</encoding> + <rows>8</rows> + <cols>65</cols> + <advancedfield/> + </field> + </fields> + <include_file>/usr/local/pkg/tinc.inc</include_file> + <custom_php_resync_config_command> + tinc_save(); + </custom_php_resync_config_command> +</packagegui> diff --git a/config/tinc/tinc_hosts.xml b/config/tinc/tinc_hosts.xml new file mode 100644 index 00000000..7741b7be --- /dev/null +++ b/config/tinc/tinc_hosts.xml @@ -0,0 +1,167 @@ +<?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE packagegui SYSTEM "./schema/packages.dtd"> +<?xml-stylesheet type="text/xsl" href="./xsl/package.xsl"?> +<packagegui> + <copyright> + <![CDATA[ +/* $Id$ */ +/* ========================================================================== */ +/* + tinc_hosts.xml + part of pfSense (http://www.pfSense.com) + Copyright (C) 2007-2009 Scott Ullrich + All rights reserved. + */ +/* ========================================================================== */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + */ +/* ========================================================================== */ + ]]> + </copyright> + <description>tinc Hosts</description> + <requirements></requirements> + <faq>Currently there are no FAQ items provided.</faq> + <name>tinchosts</name> + <version>1.0.19</version> + <title>VPN: tinc - Hosts</title> + <!-- configpath gets expanded out automatically and config items will be + stored in that location --> + <configpath>['installedpackages']['package']['$packagename']['config']</configpath> + + <tabs> + <tab> + <text>Config</text> + <url>/pkg_edit.php?xml=tinc_config.xml</url> + </tab> + <tab> + <text>Hosts</text> + <url>/pkg.php?xml=tinc_hosts.xml</url> + <active/> + </tab> + </tabs> + <advanced_options>enabled</advanced_options> + + <!-- adddeleteeditpagefields items will appear on the first page where you can add / delete or edit + items. An example of this would be the nat page where you add new nat redirects --> + <adddeleteeditpagefields> + <columnitem> + <fielddescr>Name</fielddescr> + <fieldname>name</fieldname> + </columnitem> + <columnitem> + <fielddescr>Address</fielddescr> + <fieldname>address</fieldname> + </columnitem> + <columnitem> + <fielddescr>Subnet</fielddescr> + <fieldname>subnet</fieldname> + </columnitem> + <columnitem> + <fielddescr>Connect at Startup</fielddescr> + <fieldname>connect</fieldname> + <type>checkbox</type> + </columnitem> + + </adddeleteeditpagefields> + <!-- fields gets invoked when the user adds or edits a item. the following items + will be parsed and rendered for the user as a gui with input, and selectboxes. --> + <fields> + <field> + <fielddescr>Name</fielddescr> + <fieldname>name</fieldname> + <description>Name of this host.</description> + <type>input</type> + </field> + <field> + <fielddescr>Address</fielddescr> + <fieldname>address</fieldname> + <description>IP address or hostname of server.</description> + <type>input</type> + </field> + <field> + <fielddescr>Subnet</fielddescr> + <fieldname>subnet</fieldname> + <description>Subnet behind host (like 192.168.254.0/24)</description> + <type>input</type> + <size>50</size> + </field> + <field> + <fielddescr>Connect at Startup</fielddescr> + <fieldname>connect</fieldname> + <description>Try to connect to this host when tinc starts.</description> + <type>checkbox</type> + </field> + <field> + <fielddescr>RSA public key</fielddescr> + <fieldname>cert_pub</fieldname> + <description>RSA public key used for this host. Include the BEGIN and END lines.<br></description> + <type>textarea</type> + <encoding>base64</encoding> + <rows>7</rows> + <cols>65</cols> + </field> + <field> + <fielddescr>Extra Parameters</fielddescr> + <fieldname>extra</fieldname> + <description>Anything entered here will be added just prior to the public certiciate in the host configuration file. <br></description> + <type>textarea</type> + <encoding>base64</encoding> + <rows>8</rows> + <cols>65</cols> + <advancedfield/> + </field> + <field> + <fielddescr>Host Up Script</fielddescr> + <fieldname>host_up</fieldname> + <description>This script will be run when this host becomes reachable. <br></description> + <type>textarea</type> + <encoding>base64</encoding> + <rows>8</rows> + <cols>65</cols> + <advancedfield/> + </field> + <field> + <fielddescr>Host Down Script</fielddescr> + <fieldname>host_down</fieldname> + <description>This script will be run when this host becomes unreachable. <br></description> + <type>textarea</type> + <encoding>base64</encoding> + <rows>8</rows> + <cols>65</cols> + <advancedfield/> + </field> + </fields> + <include_file>/usr/local/pkg/tinc.inc</include_file> + <custom_add_php_command> + </custom_add_php_command> + <custom_php_resync_config_command> + tinc_save(); + </custom_php_resync_config_command> + <custom_php_command_before_form> + </custom_php_command_before_form> + <custom_php_after_form_command> + </custom_php_after_form_command> + <custom_delete_php_command> + tinc_save(); + </custom_delete_php_command> +</packagegui> diff --git a/config/tinydns/tinydns.inc b/config/tinydns/tinydns.inc index f6b9b556..70e149e1 100644 --- a/config/tinydns/tinydns.inc +++ b/config/tinydns/tinydns.inc @@ -53,33 +53,13 @@ function tinydns_custom_php_install_command() { log_error("Could not open /usr/local/etc/rc.d/svscan.sh for writing."); return; } - + // Ensure svscan.sh has a+rx exec("chmod a+rx /usr/local/etc/rc.d/svscan.sh"); - - $ipaddress = $config['installedpackages']['tinydns']['config'][0]['ipaddress']; - - $minsegment = "10240"; - $maxfilesize = "10240"; - $maxsegment = "20480"; - $maxfd = "100"; - $maxchild = "40"; - - if($config['installedpackages']['tinydns']['config'][0]['minsegment']) - $minsegment = $config['installedpackages']['tinydns']['config'][0]['minsegment']; - if($config['installedpackages']['tinydns']['config'][0]['maxfilesize']) - $maxfilesize = $config['installedpackages']['tinydns']['config'][0]['maxfilesize']; - - if($config['installedpackages']['tinydns']['config'][0]['maxsegment']) - $maxsegment = $config['installedpackages']['tinydns']['config'][0]['maxsegment']; - - if($config['installedpackages']['tinydns']['config'][0]['maxfd']) - $maxfd = $config['installedpackages']['tinydns']['config'][0]['maxfd']; - - if($config['installedpackages']['tinydns']['config'][0]['maxchild']) - $maxchild = $config['installedpackages']['tinydns']['config'][0]['maxchild']; + $ipaddress = $config['installedpackages']['tinydns']['config'][0]['ipaddress']; + $enableipmonitoring = $config['installedpackages']['tinydns']['config'][0]['enableipmonitoring']; if($config['installedpackages']['tinydns']['config'][0]['refreshinterval']) $refreshinterval = $config['installedpackages']['tinydns']['config'][0]['refreshinterval']; @@ -97,6 +77,7 @@ rcvar=`set_rcvar` command="/usr/local/bin/svscan" svscan_enable=\${svscan_enable-"YES"} svscan_servicedir=\${svscan_servicedir-"{$g['varrun_path']}/service"} +logdir="/var/log/svscan" start_cmd="svscan_start" stop_postcmd="svscan_stop_post" @@ -107,10 +88,18 @@ required_dirs="\${svscan_servicedir}" svscan_start () { echo "Starting svscan." + mkdir -p \$logdir /usr/bin/env \ PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ - /usr/sbin/daemon -f /bin/sh -c "\$command \$svscan_servicedir 2>&1 | /usr/local/bin/readproctitle service errors: ................................................................................................................................................................................................................................................................................................................................................................................................................ &" > /dev/null + /usr/sbin/daemon -f /bin/sh -c "\$command \$svscan_servicedir 2>&1 | /usr/local/bin/multilog t \$logdir" > /dev/null +EOD; +if ($enableipmonitoring) { + $svscan .= <<<EOD minicron {$refreshinterval} {$g['varrun_path']}/ping_hosts.pid "/etc/ping_hosts.sh; cd {$g['varetc_path']}/tinydns/root && /usr/local/bin/tinydns-data" +EOD; +} +$svscan .= <<<EOD + } svscan_stop_post () { @@ -130,9 +119,11 @@ EOD; <?php require_once(\"/usr/local/pkg/tinydns.inc\"); tinydns_custom_php_changeip_command(); - tinydns_create_zone_file(); - tinydns_setup_ping_items(); -?> + tinydns_create_zone_file();\n"; + if ($enableipmonitoring) { + $start .= "tinydns_setup_ping_items();\n"; + } + $start .= "?> ENDPHP\n"; $stop = ""; @@ -636,7 +627,9 @@ function tinydns_sync_on_changes() { tinydns_do_xmlrpc_sync($sync_to_ip, $password); } tinydns_create_zone_file(); - tinydns_setup_ping_items(); + if ($config['installedpackages']['tinydns']['config'][0]['enableipmonitoring']) { + tinydns_setup_ping_items(); + } log_error("[tinydns] tinydns_xmlrpc_sync.php is ending."); } @@ -704,7 +697,9 @@ function tinydns_do_xmlrpc_sync($sync_to_ip, $password) { $execcmd = "require_once('/usr/local/pkg/tinydns.inc');\n"; $execcmd .= "tinydns_custom_php_changeip_command();\n"; $execcmd .= "tinydns_create_zone_file();\n"; - $execcmd .= "tinydns_setup_ping_items();\n"; + if ($config['installedpackages']['tinydns']['config'][0]['enableipmonitoring']) { + $execcmd .= "tinydns_setup_ping_items();\n"; + } /* assemble xmlrpc payload */ $params = array( @@ -1139,7 +1134,17 @@ function tinydns_dnscache_forwarding_servers($index) { exec("rm -R {$g['varetc_path']}/dnscache/root/servers/"); exec("/bin/mkdir -p {$g['varetc_path']}/dnscache{$index}/root/servers/"); if (intval($config['version']) >= 6) - exec("/bin/cat {$g['varetc_path']}/nameserver_* > {$g['varetc_path']}/dnscache{$index}/root/servers/@"); + if (file_exists("{$g['varetc_path']}/nameserver_*")) { + exec("/bin/cat {$g['varetc_path']}/nameserver_* > {$g['varetc_path']}/dnscache{$index}/root/servers/@"); + } else { + $fw = fopen("{$g['varetc_path']}/dnscache{$index}/root/servers/@", "w"); + if (! $fw) { + printf("Error: cannot open dnscache/root/servers/@ in tinydns_register_forwarding_servers().\n"); + return 1; + } + fwrite($fw, $config['system']['dnsserver'][0]); + fclose($fw); + } else { $fr = fopen("{$g['varetc_path']}/resolv.conf.dnscache", "r"); if (! $fr) { diff --git a/config/tinydns/tinydns.xml b/config/tinydns/tinydns.xml index fba16905..546980f1 100644 --- a/config/tinydns/tinydns.xml +++ b/config/tinydns/tinydns.xml @@ -194,7 +194,7 @@ <fieldname>regdhcpstatic</fieldname> <description>Register static DHCP leases with TinyDNS server using the Fully Qualified Domain Name specified in System: General.</description> <type>checkbox</type> - </field> + </field> <field> <fielddescr>Register DHCP leases with server</fielddescr> <fieldname>regdhcp</fieldname> @@ -203,8 +203,14 @@ </field> <field> <type>listtopic</type> - <name>Monitoring IP refresh interval</name> - <fieldname>temp</fieldname> + <name>IP Monitoring</name> + <fieldname>temp</fieldname> + </field> + <field> + <fielddescr>Enable IP monitoring</fielddescr> + <fieldname>enableipmonitoring</fieldname> + <description>Wheather or not to monitor IP address</description> + <type>checkbox</type> </field> <field> <fielddescr>Refresh Interval</fielddescr> @@ -215,7 +221,7 @@ <field> <type>listtopic</type> <name>Sync TinyDNS settings via XMLRPC</name> - <fieldname>temp</fieldname> + <fieldname>temp</fieldname> </field> <field> <fielddescr>XMLRPC Sync</fielddescr> @@ -249,46 +255,6 @@ </rowhelperfield> </rowhelper> </field> - <field> - <type>listtopic</type> - <name>Advanced tunables (OPTIONAL)</name> - <fieldname>temp</fieldname> - </field> - <field> - <fielddescr>Minimum segment size</fielddescr> - <fieldname>minsegment</fieldname> - <description>Recommended size: 10240 or larger.</description> - <type>input</type> - <value>10240</value> - </field> - <field> - <fielddescr>Maximum file size</fielddescr> - <fieldname>maxfilesize</fieldname> - <description>Recommended size: 10240 or larger.</description> - <type>input</type> - <value>10240</value> - </field> - <field> - <fielddescr>Max Segment size</fielddescr> - <fieldname>maxsegment</fieldname> - <description>Recommended size: 20480 or larger.</description> - <type>input</type> - <value>20480</value> - </field> - <field> - <fielddescr>Maximum file descriptors</fielddescr> - <fieldname>maxfd</fieldname> - <description>Recommended size: 100 or larger.</description> - <type>input</type> - <value>100</value> - </field> - <field> - <fielddescr>Maximum children processes</fielddescr> - <fieldname>maxchild</fieldname> - <description>Recommended size: 40 or larger.</description> - <type>input</type> - <value>40</value> - </field> </fields> <custom_delete_php_command> tinydns_custom_php_changeip_command(); diff --git a/config/varnish3/varnish.inc b/config/varnish3/varnish.inc index 9e78d41f..9d38161e 100644 --- a/config/varnish3/varnish.inc +++ b/config/varnish3/varnish.inc @@ -5,6 +5,7 @@ part of pfSense (http://www.pfSense.com) Copyright (C) 2010 Scott Ullrich <sullrich@gmail.com> Copyright (C) 2011 Marcello Coutinho + Copyright (C) 2012 Marcio Carlos Antao All rights reserved. */ /* ========================================================================== */ @@ -129,8 +130,7 @@ function varnish_get_url_mappings_txt() { if($url['grace']) $directo_grace_time.=($url['grace']=="0s"?"return(pass);":"set req.grace=".$url['grace'].";"); $fieldtype = ($url['fieldtype']?$url['fieldtype']:"=="); - $req=($url['directorurl2']?"url":"http.host"); - $director_prefix=($url['directorurl'] && $url['directorurl2']?"^http://":""); + $director_prefix=($url['directorurl'] && $url['directorurl2']?"^http://":""); #check url if ( $url['directorurl'] || $url['directorurl2'] || $catch_all == "unset" ){ if ( $url['directorurl']== "" && $url['directorurl2']== "" ){ @@ -142,9 +142,25 @@ function varnish_get_url_mappings_txt() { else{ if(!$isfirst) $urlmappings .= "\telse "; - $urlmappings .= "if (req.$req $fieldtype ".'"'.$url['directorurl'].$url['directorurl2'].'") {'."\n"; - #check failover + if(!$url['directorurl']) { + $urlmappings .= "if (req.url $fieldtype ".'"^'.$url['directorurl2'].'") {'."\n"; + } + else if (!$url['directorurl2']) { + $urlmappings .= "if (req.http.host $fieldtype ".'"'.$url['directorurl'].'") {'."\n"; + } + else { + $urlmappings .= "if (req.http.host $fieldtype ".'"'.$url['directorurl'].'"'." && req.url $fieldtype ".'"^'.$url['directorurl2'].'") {'."\n"; + } + $urlbackend = "\t\t\tset req.backend = ".$url['directorname'].";"; + #check rewrite options + if($url['rewritehost']) { + $urlmappings .= "\t\t\tset req.http.host = regsub(req.http.host, ".'"'.$url['directorurl'].'",'.'"'.$url['rewritehost'].'")'.";\n"; + } + if ($url['rewriteurl']) { + $urlmappings .= "\t\t\tset req.url = regsub(req.url, ".'"'.$url['directorurl2'].'",'.'"^'.$url['rewriteurl'].'")'.";\n"; + } + #check failover if ($url['failover'] && $url['failover'] != $url['directorname']){ $tabs=($url['grace']?"\n\t\t\t":""); $urlfailover = "\t\t\tset req.backend = ".$url['failover'].";"; diff --git a/config/varnish3/varnish_lb_directors.xml b/config/varnish3/varnish_lb_directors.xml index 994320f3..345dae51 100644 --- a/config/varnish3/varnish_lb_directors.xml +++ b/config/varnish3/varnish_lb_directors.xml @@ -111,6 +111,14 @@ <fielddescr>URL</fielddescr> <fieldname>directorurl2</fieldname> </columnitem> + <columnitem> + <fielddescr>Rewrite Host</fielddescr> + <fieldname>rewritehost</fieldname> + </columnitem> + <columnitem> + <fielddescr>Rewrite url</fielddescr> + <fieldname>rewriteurl</fieldname> + </columnitem> <columnitem> <fielddescr>Type</fielddescr> @@ -168,6 +176,20 @@ <type>input</type> <size>40</size> </field> + <field> + <fielddescr>Rewrite Host</fielddescr> + <fieldname>rewritehost</fieldname> + <description>Hint image.mysite.com</description> + <type>input</type> + <size>40</size> + </field> + <field> + <fielddescr>Rewrite URL</fielddescr> + <fieldname>rewriteurl</fieldname> + <description>Hint /images</description> + <type>input</type> + <size>40</size> + </field> <field> <fielddescr>Req Grace</fielddescr> <fieldname>grace</fieldname> diff --git a/config/varnish64/varnish.inc b/config/varnish64/varnish.inc index a7009c7d..ec7ef0c4 100644 --- a/config/varnish64/varnish.inc +++ b/config/varnish64/varnish.inc @@ -5,6 +5,7 @@ part of pfSense (http://www.pfSense.com) Copyright (C) 2010 Scott Ullrich <sullrich@gmail.com> Copyright (C) 2011 Marcello Coutinho + Copyright (C) 2012 Marcio Carlos Antão All rights reserved. */ /* ========================================================================== */ @@ -129,8 +130,7 @@ function varnish_get_url_mappings_txt() { if($url['grace']) $directo_grace_time.=($url['grace']=="0s"?"return(pass);":"set req.grace=".$url['grace'].";"); $fieldtype = ($url['fieldtype']?$url['fieldtype']:"=="); - $req=($url['directorurl2']?"url":"http.host"); - $director_prefix=($url['directorurl'] && $url['directorurl2']?"^http://":""); + $director_prefix=($url['directorurl'] && $url['directorurl2']?"^http://":""); #check url if ( $url['directorurl'] || $url['directorurl2'] || $catch_all == "unset" ){ if ( $url['directorurl']== "" && $url['directorurl2']== "" ){ @@ -139,12 +139,30 @@ function varnish_get_url_mappings_txt() { $catch_all = "set"; $isfirst = false; } - else{ + else{ + if(!$isfirst) $urlmappings .= "\telse "; - $urlmappings .= "if (req.$req $fieldtype ".'"'.$url['directorurl'].$url['directorurl2'].'") {'."\n"; - #check failover + if(!$url['directorurl']) { + $urlmappings .= "if (req.url $fieldtype ".'"^'.$url['directorurl2'].'") {'."\n"; + } + else if (!$url['directorurl2']) { + $urlmappings .= "if (req.http.host $fieldtype ".'"'.$url['directorurl'].'") {'."\n"; + } + else { + $urlmappings .= "if (req.http.host $fieldtype ".'"'.$url['directorurl'].'"'." && req.url $fieldtype ".'"^'.$url['directorurl2'].'") {'."\n"; + } + $urlbackend = "\t\t\tset req.backend = ".$url['directorname'].";"; + + #check rewrite + if ($url['rewritehost']) { + $urlmappings .= "\t\t\tset req.http.host = regsub(req.http.host, ".'"'.$url['directorurl'].'",'.'"'.$url['rewritehost'].'")'.";\n"; + } + if ($url['rewriteurl']) { + $urlmappings .= "\t\t\tset req.url = regsub(req.url, ".'"'.$url['directorurl2'].'",'.'"^'.$url['rewriteurl'].'")'.";\n"; + } + #check failover if ($url['failover'] && $url['failover'] != $url['directorname']){ $tabs=($url['grace']?"\n\t\t\t":""); $urlfailover = "\t\t\tset req.backend = ".$url['failover'].";"; diff --git a/config/varnish64/varnish_lb_directors.xml b/config/varnish64/varnish_lb_directors.xml index 994320f3..4c46414e 100644 --- a/config/varnish64/varnish_lb_directors.xml +++ b/config/varnish64/varnish_lb_directors.xml @@ -111,7 +111,14 @@ <fielddescr>URL</fielddescr> <fieldname>directorurl2</fieldname> </columnitem> - + <columnitem> + <fielddescr>Rewrite Host</fielddescr> + <fieldname>rewritehost</fieldname> + </columnitem> + <columnitem> + <fielddescr>Rewrite url</fielddescr> + <fieldname>rewriteurl</fieldname> + </columnitem> <columnitem> <fielddescr>Type</fielddescr> <fieldname>directortype</fieldname> @@ -168,6 +175,21 @@ <type>input</type> <size>40</size> </field> + <field> + <fielddescr>Rewrite Host</fielddescr> + <fieldname>rewritehost</fieldname> + <description>Hint image.mysite.com</description> + <type>input</type> + <size>40</size> + </field> + <field> + <fielddescr>Rewrite URL</fielddescr> + <fieldname>rewriteurl</fieldname> + <description>Hint /images</description> + <type>input</type> + <size>40</size> + </field> + <field> <fielddescr>Req Grace</fielddescr> <fieldname>grace</fieldname> diff --git a/config/widget-antivirus/antivirus_status.widget.php b/config/widget-antivirus/antivirus_status.widget.php index bcd057b3..c08ffeb8 100644 --- a/config/widget-antivirus/antivirus_status.widget.php +++ b/config/widget-antivirus/antivirus_status.widget.php @@ -36,7 +36,12 @@ require_once("pfsense-utils.inc"); require_once("functions.inc"); define('PATH_CLAMDB', '/var/db/clamav'); -define('PATH_HAVPLOG', '/var/log/havp/access.log'); +$pfSversion = str_replace("\s", "", file_get_contents("/etc/version")); +if(preg_match("/^2.0/",$pfSversion)) + define('PATH_HAVPLOG', '/var/log/havp/access.log'); +else + define('PATH_HAVPLOG', '/var/log/access.log'); + define('PATH_AVSTATUS', '/var/tmp/havp.status'); diff --git a/config/widget-snort/snort_alerts.inc b/config/widget-snort/snort_alerts.inc deleted file mode 100644 index 74adb4bb..00000000 --- a/config/widget-snort/snort_alerts.inc +++ /dev/null @@ -1,16 +0,0 @@ -<?php - -require_once("globals.inc"); -require_once("includes/snort_alerts.inc.php"); - -$snort_alerts_title = "Snort Alerts"; -$snort_alerts_title_link = "snort/snort_alerts.php"; - -$snort_alerts_logfile = "{$g['varlog_path']}/snort/alert"; -$nentries = 10; -$snort_alerts = get_snort_alerts($snort_alerts_logfile, $nentries); - -/* AJAX related routines */ -handle_snort_ajax($snort_alerts_logfile, $nentries = 10); - -?> diff --git a/config/widget-snort/snort_alerts.inc.php b/config/widget-snort/snort_alerts.inc.php deleted file mode 100644 index b56ac02c..00000000 --- a/config/widget-snort/snort_alerts.inc.php +++ /dev/null @@ -1,93 +0,0 @@ -<? -function get_snort_alerts($snort_alerts, $nentries, $tail = 20) { - global $config, $g; - $logarr = ""; - /* Always do a reverse tail, to be sure we're grabbing the 'end' of the alerts. */ - exec("/usr/bin/tail -r -n {$tail} {$snort_alerts}", $logarr); - - $snortalerts = array(); - - $counter = 0; - - foreach ($logarr as $logent) { - if($counter >= $nentries) - break; - - $alert = parse_snort_alert_line($logent); - if ($alert != "") { - $counter++; - $snortalerts[] = $alert; - } - - } - /* Since the rules are in reverse order, flip them around if needed based on the user's preference */ - return isset($config['syslog']['reverse']) ? $snortalerts : array_reverse($snortalerts); -} - -function parse_snort_alert_line($line) { - $log_split = ""; - $datesplit = ""; - preg_match("/^(.*)\s+\[\*\*\]\s+\[(\d+\:\d+:\d+)\]\s(.*)\s(.*)\s+\[\*\*\].*\s+\[Priority:\s(\d+)\]\s{(.*)}\s+(.*)\s->\s(.*)$/U", $line, $log_split); - - list($all, $alert['time'], $alert['rule'], $alert['category'], $alert['descr'], - $alert['priority'], $alert['proto'], $alert['src'], $alert['dst']) = $log_split; - - $usableline = true; - - if(trim($alert['src']) == "") - $usableline = false; - if(trim($alert['dst']) == "") - $usableline = false; - - if($usableline == true) { - preg_match("/^(\d+)\/(\d+)-(\d+\:\d+\:\d+).\d+$/U", $alert['time'], $datesplit); - $now_time = strtotime("now"); - $checkdate = $datesplit[1] . "/" . $datesplit[2] . "/" . date("Y"); - $fulldate = $datesplit[2] . "/" . $datesplit[1] . "/" . date("Y"); - $logdate = $checkdate . " " . $datesplit[3]; - if ($now_time < strtotime($logdate)) { - $fulldate = $datesplit[2] . "/" . $datesplit[1] . "/" . ((int)date("Y") - 1); - } - - $alert['dateonly'] = $fulldate; - $alert['timeonly'] = $datesplit[3]; - $alert['category'] = strtoupper( substr($alert["category"],0 , 1) ) . strtolower( substr($alert["category"],1 ) ); - return $alert; - } else { - if($g['debug']) { - log_error("There was a error parsing line: $line. Please report to mailing list or forum."); - } - return ""; - } -} - -/* AJAX specific handlers */ -function handle_snort_ajax($snort_alerts_logfile, $nentries = 5, $tail = 50) { - if($_GET['lastsawtime'] or $_POST['lastsawtime']) { - if($_GET['lastsawtime']) - $lastsawtime = $_GET['lastsawtime']; - if($_POST['lastsawtime']) - $lastsawtime = $_POST['lastsawtime']; - /* compare lastsawrule's time stamp to alert logs. - * afterwards return the newer records so that client - * can update AJAX interface screen. - */ - $new_rules = ""; - $snort_alerts = get_snort_alerts($snort_alerts_logfile, $nentries); - foreach($snort_alerts as $log_row) { - $time_regex = ""; - preg_match("/.*([0-9][0-9])\/([0-9][0-9])-([0-9][0-9]:[0-9][0-9]:[0-9][0-9]).*/", $log_row['time'], $time_regex); - $logdate = $time_regex[1] . "/" . $time_regex[2] . "/" . date("Y") . " " . $time_regex[3]; - //preg_match("/.*([0-9][0-9])\/([0-9][0-9])-([0-9][0-9]:[0-9][0-9]:[0-9][0-9]).*/", $testsplit[1], $time_regex); - // preg_match("/.*([0-9][0-9]:[0-9][0-9]:[0-9][0-9]).*/", $log_row['time'], $time_regex); - $row_time = strtotime($logdate); - $now_time = strtotime("now"); - if($row_time > $lastsawtime and $row_time <= $nowtime) { - $new_rules .= "{$log_row['time']}||{$log_row['priority']}||{$log_row['category']}||{$log_row['src']}||{$log_row['dst']}||" . time() . "||{$log_row['timeonly']}||{$log_row['dateonly']}" . "||\n"; - } - } - echo $new_rules; - exit; - } -} -?>
\ No newline at end of file diff --git a/config/widget-snort/snort_alerts.js b/config/widget-snort/snort_alerts.js index 0cc76ab1..0c2d9ca6 100644 --- a/config/widget-snort/snort_alerts.js +++ b/config/widget-snort/snort_alerts.js @@ -1,63 +1,10 @@ -snortlastsawtime = '<?php echo time(); ?>'; var snortlines = Array(); var snorttimer; var snortupdateDelay = 25500; var snortisBusy = false; var snortisPaused = false; -<?php - if(isset($config['syslog']['reverse'])) - echo "var isReverse = true;\n"; - else - echo "var isReverse = false;\n"; -?> - -if (typeof getURL == 'undefined') { - getURL = function(url, callback) { - if (!url) - throw 'No URL for getURL'; - try { - if (typeof callback.operationComplete == 'function') - callback = callback.operationComplete; - } catch (e) {} - if (typeof callback != 'function') - throw 'No callback function for getURL'; - var http_request = null; - if (typeof XMLHttpRequest != 'undefined') { - http_request = new XMLHttpRequest(); - } - else if (typeof ActiveXObject != 'undefined') { - try { - http_request = new ActiveXObject('Msxml2.XMLHTTP'); - } catch (e) { - try { - http_request = new ActiveXObject('Microsoft.XMLHTTP'); - } catch (e) {} - } - } - if (!http_request) - throw 'Both getURL and XMLHttpRequest are undefined'; - http_request.onreadystatechange = function() { - if (http_request.readyState == 4) { - callback( { success : true, - content : http_request.responseText, - contentType : http_request.getResponseHeader("Content-Type") } ); - } - } - http_request.open('GET', url, true); - http_request.send(null); - } -} - -function snort_alerts_fetch_new_rules() { - if(snortisPaused) - return; - if(snortisBusy) - return; - snortisBusy = true; - getURL('widgets/helpers/snort_alerts_helper.php?lastsawtime=' + snortlastsawtime, snort_alerts_fetch_new_rules_callback); -} function snort_alerts_fetch_new_rules_callback(callback_data) { if(snortisPaused) return; @@ -75,8 +22,6 @@ function snort_alerts_fetch_new_rules_callback(callback_data) { line = '<td width="30%" class="listr" >' + row_split[6] + '<br>' + row_split[7]+ '</td>'; line += '<td width="40%" class="listr" >' + row_split[3] + '<br>' + row_split[4] + '</td>'; line += '<td width="40%" class="listr" >' + 'Pri : ' + row_split[1] + '<br>' + 'Cat : ' + row_split[2] + '</td>'; - snortlastsawtime = row_split[5]; - //alert(row_split[0]); new_data_to_add[new_data_to_add.length] = line; } snort_alerts_update_div_rows(new_data_to_add); @@ -131,7 +76,7 @@ function snort_alerts_update_div_rows(data) { } } /* rechedule AJAX interval */ - //snorttimer = setInterval('snort_alerts_fetch_new_rules()', snortupdateDelay); + snorttimer = setInterval('snort_alerts_fetch_new_rules()', snortupdateDelay); } function snort_alerts_toggle_pause() { if(snortisPaused) { diff --git a/config/widget-snort/snort_alerts.widget.php b/config/widget-snort/snort_alerts.widget.php index c2622dc7..6d6193d8 100644 --- a/config/widget-snort/snort_alerts.widget.php +++ b/config/widget-snort/snort_alerts.widget.php @@ -2,6 +2,7 @@ /* snort_alerts.widget.php Copyright (C) 2009 Jim Pingle + mod 24-07-2012 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -26,43 +27,105 @@ */ global $config, $g; +/* array sorting */ +function sksort(&$array, $subkey="id", $sort_ascending=false) { + if (count($array)) { + $temp_array[key($array)] = array_shift($array); + }; + + foreach ($array as $key => $val){ + $offset = 0; + $found = false; + foreach ($temp_array as $tmp_key => $tmp_val) { + if (!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey])) { + $temp_array = array_merge((array)array_slice($temp_array,0,$offset), array($key => $val), array_slice($temp_array,$offset)); + $found = true; + }; + $offset++; + }; + if (!$found) $temp_array = array_merge($temp_array, array($key => $val)); + }; + + if ($sort_ascending) { + $array = array_reverse($temp_array); + } else $array = $temp_array; +}; + +/* check if firewall widget variable is set */ +if (!isset($nentries)) $nentries = 5; + +/* retrieve snort variables */ +require_once("/usr/local/pkg/snort/snort.inc"); +if (!is_array($config['installedpackages']['snortglobal']['rule'])) + $config['installedpackages']['snortglobal']['rule'] = array(); +$a_instance = &$config['installedpackages']['snortglobal']['rule']; + +/* read log file(s) */ +$counter=0; +foreach ($a_instance as $instanceid => $instance) { + $snort_uuid = $a_instance[$instanceid]['uuid']; + $if_real = snort_get_real_interface($a_instance[$instanceid]['interface']); + + /* make sure alert file exists */ + if (file_exists("/var/log/snort/snort_{$if_real}{$snort_uuid}/alert")) { + exec("tail -n{$nentries} /var/log/snort/snort_{$if_real}{$snort_uuid}/alert > /tmp/alert_{$snort_uuid}"); + if (file_exists("/tmp/alert_{$snort_uuid}")) { + $tmpblocked = array_flip(snort_get_blocked_ips()); + + /* 0 1 2 3 4 5 6 7 8 9 10 11 12 */ + /* File format timestamp,sig_generator,sig_id,sig_rev,msg,proto,src,srcport,dst,dstport,id,classification,priority */ + $fd = fopen("/tmp/alert_{$snort_uuid}", "r"); + while (($fields = fgetcsv($fd, 1000, ',', '"')) !== FALSE) { + if(count($fields) < 11) + continue; + + $snort_alerts[$counter]['instanceid'] = $a_instance[$instanceid]['interface']; + $snort_alerts[$counter]['timestamp'] = $fields[0]; + $snort_alerts[$counter]['timeonly'] = substr($fields[0], 6, -8); + $snort_alerts[$counter]['dateonly'] = substr($fields[0], 0, -17); + $snort_alerts[$counter]['src'] = $fields[6]; + $snort_alerts[$counter]['srcport'] = $fields[7]; + $snort_alerts[$counter]['dst'] = $fields[8]; + $snort_alerts[$counter]['dstport'] = $fields[9]; + $snort_alerts[$counter]['priority'] = $fields[12]; + $snort_alerts[$counter]['category'] = $fields[11]; + $counter++; + }; + fclose($fd); + @unlink("/tmp/alert_{$snort_uuid}"); + }; + }; +}; + +/* sort the array */ +if (isset($config['syslog']['reverse'])) { + sksort($snort_alerts, 'timestamp', false); +} else { + sksort($snort_alerts, 'timestamp', true); +}; + +/* display the result */ ?> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tbody> <tr class="snort-alert-header"> - <td width="30%" class="widgetsubheader" >Date</td> + <td width="30%" class="widgetsubheader" >IF/Date</td> <td width="40%" class="widgetsubheader">Src/Dst</td> <td width="40%" class="widgetsubheader">Details</td> </tr> <?php $counter=0; if (is_array($snort_alerts)) { - foreach ($snort_alerts as $alert) { ?> - - <?php - if(isset($config['syslog']['reverse'])) { - /* honour reverse logging setting */ - if($counter == 0) - $activerow = " id=\"snort-firstrow\""; - else - $activerow = ""; - - } else { - /* non-reverse logging */ - if($counter == count($snort_alerts) - 1) - $activerow = " id=\"snort-firstrow\""; - else - $activerow = ""; - } - ?> - - <tr class="snort-alert-entry" <?php echo $activerow; ?>> - <td width="30%" class="listr"><?= $alert['timeonly'] . '<br>' . $alert['dateonly'] ?></td> - <td width="40%" class="listr"><?= $alert["src"] . '<br>' . $alert["dst"] ?></td> - <td width="40%" class="listr"><?= 'Pri : ' . $alert["priority"] . '<br>' . 'Cat : ' . $alert['category'] ?></td> - </tr> -<?php $counter++; + foreach ($snort_alerts as $alert) { + echo(" <tr class='snort-alert-entry'" . $activerow . "> + <td width='30%' class='listr'>" . $alert['instanceid'] . "<br>" . $alert['timeonly'] . " " . $alert['dateonly'] . "</td> + <td width='40%' class='listr'>" . $alert['src'] . ":" . $alert['srcport'] . "<br>" . $alert['dst'] . ":" . $alert['dstport'] . "</td> + <td width='40%' class='listr'>Pri : " . $alert['priority'] . "<br>Cat : " . $alert['category'] . "</td> + </tr>"); + $counter++; + if($counter >= $nentries) break; } -} ?> +}; +?> </tbody> -</table> +</table>
\ No newline at end of file diff --git a/config/widget-snort/snort_alerts_helper.php b/config/widget-snort/snort_alerts_helper.php deleted file mode 100644 index b49af1d8..00000000 --- a/config/widget-snort/snort_alerts_helper.php +++ /dev/null @@ -1,13 +0,0 @@ -<?php -require_once("globals.inc"); -require_once("guiconfig.inc"); -require_once("includes/snort_alerts.inc.php"); - -$snort_alerts_logfile = "{$g['varlog_path']}/snort/alert"; -$nentries = 5; -handle_snort_ajax($snort_alerts_logfile, $nentries); - -?> -<script src="/javascript/scriptaculous/prototype.js" type="text/javascript"></script> -<script src="/javascript/scriptaculous/scriptaculous.js" type="text/javascript"></script> -<script src="/widgets/javascript/snort_alerts.js" type="text/javascript"></script> diff --git a/config/widget-snort/widget-snort.inc b/config/widget-snort/widget-snort.inc deleted file mode 100644 index 584e5f2d..00000000 --- a/config/widget-snort/widget-snort.inc +++ /dev/null @@ -1,13 +0,0 @@ -<?php - -function widget_snort_uninstall() { - - unlink("/usr/local/www/includes/snort_alerts.inc.php"); - unlink("/usr/local/www/widgets/helpers/snort_alerts_helper.php"); - unlink("/usr/local/www/widgets/include/snort_alerts.inc"); - unlink("/usr/local/www/widgets/javascript/snort_alerts.js"); - unlink("/usr/local/www/widgets/widgets/snort_alerts.widget.php"); - -} - -?>
\ No newline at end of file diff --git a/config/widget-snort/widget-snort.xml b/config/widget-snort/widget-snort.xml index 1644181c..785ac5b1 100644 --- a/config/widget-snort/widget-snort.xml +++ b/config/widget-snort/widget-snort.xml @@ -46,29 +46,8 @@ <requirements>Dashboard package and Snort</requirements> <faq>Currently there are no FAQ items provided.</faq> <name>widget-snort</name> - <version>0.2</version> + <version>0.5</version> <title>Widget - Snort</title> - <include_file>/usr/local/pkg/widget-snort.inc</include_file> - <additional_files_needed> - <prefix>/usr/local/pkg/</prefix> - <chmod>077</chmod> - <item>http://www.pfsense.com/packages/config/widget-snort/widget-snort.inc</item> - </additional_files_needed> - <additional_files_needed> - <prefix>/usr/local/www/includes/</prefix> - <chmod>0644</chmod> - <item>http://www.pfsense.com/packages/config/widget-snort/snort_alerts.inc.php</item> - </additional_files_needed> - <additional_files_needed> - <prefix>/usr/local/www/widgets/helpers/</prefix> - <chmod>0644</chmod> - <item>http://www.pfsense.com/packages/config/widget-snort/snort_alerts_helper.php</item> - </additional_files_needed> - <additional_files_needed> - <prefix>/usr/local/www/widgets/include/</prefix> - <chmod>0644</chmod> - <item>http://www.pfsense.com/packages/config/widget-snort/snort_alerts.inc</item> - </additional_files_needed> <additional_files_needed> <prefix>/usr/local/www/widgets/javascript/</prefix> <chmod>0644</chmod> @@ -79,7 +58,4 @@ <chmod>0644</chmod> <item>http://www.pfsense.com/packages/config/widget-snort/snort_alerts.widget.php</item> </additional_files_needed> - <custom_php_deinstall_command> - widget_snort_uninstall(); - </custom_php_deinstall_command> </packagegui> diff --git a/config/zabbix-agent/zabbix-agent.xml b/config/zabbix-agent/zabbix-agent.xml index 9714e6ea..ce0e2339 100644 --- a/config/zabbix-agent/zabbix-agent.xml +++ b/config/zabbix-agent/zabbix-agent.xml @@ -1,158 +1,168 @@ <?xml version="1.0" encoding="utf-8"?> <packagegui> - <name>zabbixagent</name> - <title>Services: Zabbix Agent</title> - <category>Monitoring</category> - <version>1.0</version> - <addedit_string>Zabbix Agent has been created/modified.</addedit_string> - <delete_string>Zabbix Agent has been deleted.</delete_string> - <restart_command>/usr/local/etc/rc.d/zabbix_agentd.sh restart</restart_command> - <menu> - <name>Zabbix Agent</name> - <tooltiptext>Setup Zabbix Agent specific settings</tooltiptext> - <section>Services</section> - <url>/pkg_edit.php?xml=zabbix-agent.xml&id=0</url> - </menu> - <service> - <name>zabbix_agentd</name> - <rcfile>zabbix_agentd.sh</rcfile> - <executable>zabbix_agentd</executable> - <description>Zabbix Agent runs on a host being monitored. The agent provides host's performance and availability information for Zabbix Server.</description> - </service> - <tabs> - <tab> - <text>Settings</text> - <url>/pkg_edit.php?xml=zabbix-agent.xml&id=0</url> - <active /> - </tab> - </tabs> - <fields> - <field> - <fielddescr>Server</fielddescr> - <fieldname>server</fieldname> - <description>List of comma delimited IP addresses (or hostnames) of ZABBIX servers</description> - <value>127.0.0.1</value> - <type>input</type> - <size>60</size> - <required>true</required> - </field> - <field> - <fielddescr>Server Port</fielddescr> - <fieldname>serverport</fieldname> - <description>Server port for sending active check (generally 10051)</description> - <value>10051</value> - <type>input</type> - <size>60</size> - <required>true</required> - </field> - <field> - <fielddescr>Hostname</fielddescr> - <fieldname>hostname</fieldname> - <description>Unique hostname. Required for active checks and must match hostname as configured on the Zabbix server (case sensitive).</description> - <value>localhost</value> - <type>input</type> - <size>60</size> - <required>true</required> - </field> - <field> - <fielddescr>Listen IP</fielddescr> - <fieldname>listenip</fieldname> - <value>0.0.0.0</value> - <type>input</type> - <size>60</size> - <required>true</required> - <description>Listen IP for connections from the server (generally 0.0.0.0 for all interfaces)</description> - </field> - <field> - <fielddescr>Listen Port</fielddescr> - <fieldname>listenport</fieldname> - <value>10050</value> - <type>input</type> - <size>60</size> - <required>true</required> - <description>Listen port for connections from the server (generally 10050)</description> - </field> - <field> - <fielddescr>Refresh Active Checks</fielddescr> - <fieldname>refreshactchecks</fieldname> - <value>120</value> - <type>input</type> - <size>60</size> - <required>false</required> - <description>The agent will refresh list of active checks once per 120 (default) seconds.</description> - </field> - <field> - <fielddescr>Timeout</fielddescr> - <fieldname>timeout</fieldname> - <value>3</value> - <type>input</type> - <size>60</size> - <required>true</required> - <description>Timeout (default 3). Do not spend more that Timeout seconds on getting requested value (1-255). The agent does not kill timeouted User Parameters processes!</description> - </field> - <field> - <fielddescr>Disable active checks</fielddescr> - <fieldname>disableactive</fieldname> - <type>checkbox</type> - <description>The agent will work only in passive mode listening for server. (generally net set)</description> - </field> - <field> - <fielddescr>Disable passive checks</fielddescr> - <fieldname>disablepassive</fieldname> - <type>checkbox</type> - <description>The agent will not listen on any TCP port. Only active checks will be processed. (generally not set)</description> - </field> - <field> - <fielddescr>User Parameters</fielddescr> - <fieldname>userparams</fieldname> - <encoding>base64</encoding> - <value></value> - <type>textarea</type> - <rows>5</rows> - <cols>50</cols> - <required>false</required> - <description>User-defined parameter to monitor. There can be several user-defined parameters. Value has form, example: UserParameter=users,who|wc -l</description> - </field> - </fields> + <name>zabbixagent</name> + <title>Services: Zabbix Agent</title> + <category>Monitoring</category> + <version>1.1</version> + <addedit_string>Zabbix Agent has been created/modified.</addedit_string> + <delete_string>Zabbix Agent has been deleted.</delete_string> + <restart_command>/usr/local/etc/rc.d/zabbix_agentd.sh restart</restart_command> + <menu> + <name>Zabbix Agent</name> + <tooltiptext>Setup Zabbix Agent specific settings</tooltiptext> + <section>Services</section> + <url>/pkg_edit.php?xml=zabbix-agent.xml&id=0</url> + </menu> + <service> + <name>zabbix_agentd</name> + <rcfile>zabbix_agentd.sh</rcfile> + <executable>zabbix_agentd</executable> + <description>Zabbix Agent runs on a host being monitored. The agent provides host's performance and availability information for Zabbix Server.</description> + </service> + <tabs> + <tab> + <text>Settings</text> + <url>/pkg_edit.php?xml=zabbix-agent.xml&id=0</url> + <active /> + </tab> + </tabs> + <fields> + <field> + <fielddescr>Server</fielddescr> + <fieldname>server</fieldname> + <description>List of comma delimited IP addresses (or hostnames) of ZABBIX servers</description> + <value>127.0.0.1</value> + <type>input</type> + <size>60</size> + <required>true</required> + </field> + <field> + <fielddescr>Server Port</fielddescr> + <fieldname>serverport</fieldname> + <description>Server port for sending active check (generally 10051)</description> + <value>10051</value> + <type>input</type> + <size>60</size> + <required>true</required> + </field> + <field> + <fielddescr>Hostname</fielddescr> + <fieldname>hostname</fieldname> + <description>Unique hostname. Required for active checks and must match hostname as configured on the Zabbix server (case sensitive).</description> + <value>localhost</value> + <type>input</type> + <size>60</size> + <required>true</required> + </field> + <field> + <fielddescr>Listen IP</fielddescr> + <fieldname>listenip</fieldname> + <value>0.0.0.0</value> + <type>input</type> + <size>60</size> + <required>true</required> + <description>Listen IP for connections from the server (generally 0.0.0.0 for all interfaces)</description> + </field> + <field> + <fielddescr>Listen Port</fielddescr> + <fieldname>listenport</fieldname> + <value>10050</value> + <type>input</type> + <size>60</size> + <required>true</required> + <description>Listen port for connections from the server (generally 10050)</description> + </field> + <field> + <fielddescr>Refresh Active Checks</fielddescr> + <fieldname>refreshactchecks</fieldname> + <value>120</value> + <type>input</type> + <size>60</size> + <required>false</required> + <description>The agent will refresh list of active checks once per 120 (default) seconds.</description> + </field> + <field> + <fielddescr>Timeout</fielddescr> + <fieldname>timeout</fieldname> + <value>3</value> + <type>input</type> + <size>60</size> + <required>true</required> + <description>Timeout (default 3). Do not spend more that Timeout seconds on getting requested value (1-255). The agent does not kill timeouted User Parameters processes!</description> + </field> + <field> + <fielddescr>Disable active checks</fielddescr> + <fieldname>disableactive</fieldname> + <type>checkbox</type> + <description>The agent will work only in passive mode listening for server. (generally net set)</description> + </field> + <field> + <fielddescr>Disable passive checks</fielddescr> + <fieldname>disablepassive</fieldname> + <type>checkbox</type> + <description>The agent will not listen on any TCP port. Only active checks will be processed. (generally not set)</description> + </field> + <field> + <fielddescr>User Parameters</fielddescr> + <fieldname>userparams</fieldname> + <encoding>base64</encoding> + <value></value> + <type>textarea</type> + <rows>5</rows> + <cols>50</cols> + <required>false</required> + <description>User-defined parameter to monitor. There can be several user-defined parameters. Value has form, example: UserParameter=users,who|wc -l</description> + </field> + </fields> <custom_php_install_command> <![CDATA[ - global $config, $g; + global $config, $g; - mwexec("mkdir -p /var/log/zabbix/"); - mwexec("mkdir -p /var/run/zabbix/"); + $pfs_version = substr(trim(file_get_contents("/etc/version")),0,3); + switch ($pfs_version) { + case "1.2": + case "2.0": + define('ZABBIX_AGENT_BASE','/usr/local'); + break; + default: + define('ZABBIX_AGENT_BASE', '/usr/pbi/zabbix-agent-' . php_uname("m")); + } - conf_mount_rw(); + mwexec("mkdir -p /var/log/zabbix/"); + mwexec("mkdir -p /var/run/zabbix/"); - /* create a few directories and ensure the sample files are in place */ - exec("/bin/mkdir -p /usr/local/etc/zabbix"); - exec("/bin/mkdir -p /var/log/zabbix"); - exec("/bin/mkdir -p /var/run/zabbix"); + conf_mount_rw(); - exec("/bin/rm -f /usr/local/etc/rc.d/zabbix_agentd"); + /* create a few directories and ensure the sample files are in place */ + exec("/bin/mkdir -p " . ZABBIX_AGENT_BASE . "/etc/zabbix"); + exec("/bin/mkdir -p /var/log/zabbix"); + exec("/bin/mkdir -p /var/run/zabbix"); - $start = "/bin/mkdir -p /var/log/zabbix\n"; - $start .= "/usr/sbin/chown -R zabbix:zabbix /var/log/zabbix\n"; + exec("/bin/rm -f " . ZABBIX_AGENT_BASE . "/etc/rc.d/zabbix_agentd"); - $start .= "/bin/mkdir -p /var/run/zabbix\n"; - $start .= "/usr/sbin/chown -R zabbix:zabbix /var/run/zabbix\n"; + $start = "/bin/mkdir -p /var/log/zabbix\n"; + $start .= "/usr/sbin/chown -R zabbix:zabbix /var/log/zabbix\n"; - $start .= "echo \"Starting Zabbix Agent\"...\n"; + $start .= "/bin/mkdir -p /var/run/zabbix\n"; + $start .= "/usr/sbin/chown -R zabbix:zabbix /var/run/zabbix\n"; - /* start zabbix agent */ - $start .= "/usr/local/sbin/zabbix_agentd\n"; + $start .= "echo \"Starting Zabbix Agent\"...\n"; - $stop = "echo \"Stopping Zabbix Agent\"\n"; - $stop .= "/usr/bin/killall zabbix_agentd\n"; - /* write out rc.d start/stop file */ - write_rcfile(array( - "file" => "zabbix_agentd.sh", - "start" => "{$start}", - "restart" => "$stop\n" . "sleep 5\n" . "{$start}", - "stop" => "$stop" - ) - ); + /* start zabbix agent */ + $start .= ZABBIX_AGENT_BASE . "/sbin/zabbix_agentd\n"; - conf_mount_ro(); + $stop = "echo \"Stopping Zabbix Agent\"\n"; + $stop .= "/usr/bin/killall zabbix_agentd\n"; + /* write out rc.d start/stop file */ + write_rcfile(array( + "file" => "zabbix_agentd.sh", + "start" => "{$start}", + "restart" => "$stop\n" . "sleep 5\n" . "{$start}", + "stop" => "$stop" + ) + ); + + conf_mount_ro(); ]]> </custom_php_install_command> <custom_php_command_before_form></custom_php_command_before_form> @@ -160,86 +170,94 @@ <custom_php_after_form_command></custom_php_after_form_command> <custom_php_validation_command> <![CDATA[ - global $_POST; - - $ListenIP=$_POST['listenip']; - if (!preg_match("/^(?:\d{1,3}\.){3}\d{1,3}$/", $ListenIP)) { - $input_errors[]='Listen IP is not ip-adress.'; - } - - $ListenPort=$_POST['listenport']; - if (!preg_match("/^\d+$/", $ListenPort)) { - $input_errors[]='Listen Port is not numeric.'; - } - - $ServerPort=$_POST['serverport']; - if (!preg_match("/^\d+$/", $ServerPort)) { - $input_errors[]='Server Port is not numeric.'; - } - - $RefreshActiveChecks=$_POST['refreshactchecks']; - if (!preg_match("/^\d+$/", $RefreshActiveChecks)) { - $input_errors[]='Refresh Active Checks is not numeric.'; - } - - $Timeout=$_POST['timeout']; - if (!preg_match("/^\d+$/", $Timeout)) { - $input_errors[]='Timeout is not numeric.'; - } - ]]> + global $_POST; + $pfs_version = substr(trim(file_get_contents("/etc/version")),0,3); + switch ($pfs_version) { + case "1.2": + case "2.0": + define('ZABBIX_AGENT_BASE','/usr/local'); + break; + default: + define('ZABBIX_AGENT_BASE', '/usr/pbi/zabbix-agent-' . php_uname("m")); + } + + $ListenIP=$_POST['listenip']; + if (!preg_match("/^(?:\d{1,3}\.){3}\d{1,3}$/", $ListenIP)) { + $input_errors[]='Listen IP is not ip-adress.'; + } + + $ListenPort=$_POST['listenport']; + if (!preg_match("/^\d+$/", $ListenPort)) { + $input_errors[]='Listen Port is not numeric.'; + } + + $ServerPort=$_POST['serverport']; + if (!preg_match("/^\d+$/", $ServerPort)) { + $input_errors[]='Server Port is not numeric.'; + } + + $RefreshActiveChecks=$_POST['refreshactchecks']; + if (!preg_match("/^\d+$/", $RefreshActiveChecks)) { + $input_errors[]='Refresh Active Checks is not numeric.'; + } + + $Timeout=$_POST['timeout']; + if (!preg_match("/^\d+$/", $Timeout)) { + $input_errors[]='Timeout is not numeric.'; + } + ]]> </custom_php_validation_command> <custom_add_php_command></custom_add_php_command> <custom_php_resync_config_command> - <![CDATA[ - conf_mount_rw(); - global $config; - global $g; - - $Server=$config['installedpackages']['zabbixagent']['config'][0]['server']; - $ServerPort=$config['installedpackages']['zabbixagent']['config'][0]['serverport']; - $Hostname=$config['installedpackages']['zabbixagent']['config'][0]['hostname']; - $ListenIP=$config['installedpackages']['zabbixagent']['config'][0]['listenip']; - $ListenPort=$config['installedpackages']['zabbixagent']['config'][0]['listenport']; - $RefreshActChecks=$config['installedpackages']['zabbixagent']['config'][0]['refreshactchecks']; - $Timeout=$config['installedpackages']['zabbixagent']['config'][0]['timeout']; - $DisableActive=$config['installedpackages']['zabbixagent']['config'][0]['disableactive']; - $DisablePassive=$config['installedpackages']['zabbixagent']['config'][0]['disablepassive']; - $UserParams=base64_decode($config['installedpackages']['zabbixagent']['config'][0]['userparams']); - - $conf = "Server=$Server\n"; - $conf .= "ServerPort=$ServerPort\n"; - $conf .= "Hostname=$Hostname\n"; - $conf .= "ListenIP=$ListenIP\n"; - $conf .= "ListenPort=$ListenPort\n"; - $conf .= "StartAgents=5\n"; - $conf .= "RefreshActiveChecks=$RefreshActChecks\n"; - $conf .= "DebugLevel=3\n"; - $conf .= "PidFile=/var/run/zabbix/zabbix_agentd.pid\n"; - $conf .= "LogFile=/var/log/zabbix/zabbix_agentd.log\n"; - $conf .= "LogFileSize=1\n"; - $conf .= "Timeout=$Timeout\n"; - if (isset($DisableActive) && ($DisableActive == "on")) { - $conf .= "DisableActive=1\n"; - } - if (isset($DisablePassive) && ($DisablePassive == "on")) { - $conf .= "DisablePassive=1\n"; - } - $conf .= "$UserParams\n"; - - file_put_contents("/usr/local/etc/zabbix/zabbix_agentd.conf", $conf); - conf_mount_ro(); - - ]]> + <![CDATA[ + conf_mount_rw(); + global $config; + global $g; + + $Server=$config['installedpackages']['zabbixagent']['config'][0]['server']; + $ServerPort=$config['installedpackages']['zabbixagent']['config'][0]['serverport']; + $Hostname=$config['installedpackages']['zabbixagent']['config'][0]['hostname']; + $ListenIP=$config['installedpackages']['zabbixagent']['config'][0]['listenip']; + $ListenPort=$config['installedpackages']['zabbixagent']['config'][0]['listenport']; + $RefreshActChecks=$config['installedpackages']['zabbixagent']['config'][0]['refreshactchecks']; + $Timeout=$config['installedpackages']['zabbixagent']['config'][0]['timeout']; + $DisableActive=$config['installedpackages']['zabbixagent']['config'][0]['disableactive']; + $DisablePassive=$config['installedpackages']['zabbixagent']['config'][0]['disablepassive']; + $UserParams=base64_decode($config['installedpackages']['zabbixagent']['config'][0]['userparams']); + + $conf = "Server=$Server\n"; + $conf .= "ServerPort=$ServerPort\n"; + $conf .= "Hostname=$Hostname\n"; + $conf .= "ListenIP=$ListenIP\n"; + $conf .= "ListenPort=$ListenPort\n"; + $conf .= "StartAgents=5\n"; + $conf .= "RefreshActiveChecks=$RefreshActChecks\n"; + $conf .= "DebugLevel=3\n"; + $conf .= "PidFile=/var/run/zabbix/zabbix_agentd.pid\n"; + $conf .= "LogFile=/var/log/zabbix/zabbix_agentd.log\n"; + $conf .= "LogFileSize=1\n"; + $conf .= "Timeout=$Timeout\n"; + if (isset($DisableActive) && ($DisableActive == "on")) { + $conf .= "DisableActive=1\n"; + } + if (isset($DisablePassive) && ($DisablePassive == "on")) { + $conf .= "DisablePassive=1\n"; + } + $conf .= "$UserParams\n"; + + file_put_contents(ZABBIX_AGENT_BASE . "/etc/zabbix/zabbix_agentd.conf", $conf); + conf_mount_ro(); + + ]]> </custom_php_resync_config_command> <custom_php_deinstall_command> - <![CDATA[ - exec("/usr/bin/killall zabbix_agentd"); + <![CDATA[ + exec("/usr/bin/killall zabbix_agentd"); - exec("/bin/rm /usr/local/etc/rc.d/zabbix_agentd.sh"); + exec("/bin/rm " . ZABBIX_AGENT_BASE . "/etc/rc.d/zabbix_agentd.sh"); - exec("/bin/rm -r /var/log/zabbix/"); - exec("/bin/rm -r /var/run/zabbix/"); + exec("/bin/rm -r /var/log/zabbix/"); + exec("/bin/rm -r /var/run/zabbix/"); ]]> </custom_php_deinstall_command> -</packagegui> - +</packagegui>
\ No newline at end of file diff --git a/config/zabbix-proxy/zabbix-proxy.xml b/config/zabbix-proxy/zabbix-proxy.xml index fce266c6..ff4011b0 100644 --- a/config/zabbix-proxy/zabbix-proxy.xml +++ b/config/zabbix-proxy/zabbix-proxy.xml @@ -1,120 +1,130 @@ <?xml version="1.0" encoding="utf-8"?> <packagegui> - <name>zabbixproxy</name> - <title>Services: Zabbix Proxy</title> - <category>Monitoring</category> - <version>1.01</version> - <addedit_string>Zabbix Proxy has been created/modified.</addedit_string> - <delete_string>Zabbix Proxy has been deleted.</delete_string> - <restart_command>/usr/local/etc/rc.d/zabbix_proxy.sh restart</restart_command> - <menu> - <name>Zabbix Proxy</name> - <tooltiptext>Setup Zabbix Proxy specific settings</tooltiptext> - <section>Services</section> - <url>/pkg_edit.php?xml=zabbix-proxy.xml&id=0</url> - </menu> - <service> - <name>zabbix-proxy</name> - <rcfile>zabbix-proxy.sh</rcfile> - <executable>zabbix_proxy</executable> - </service> - <tabs> - <tab> - <text>Settings</text> - <url>/pkg_edit.php?xml=zabbix-proxy.xml&id=0</url> - <active /> - </tab> - </tabs> - <fields> - <field> - <fielddescr>Server</fielddescr> - <fieldname>server</fieldname> - <description>List of comma delimited IP addresses (or hostnames) of ZABBIX servers</description> - <default_value>127.0.0.1</default_value> - <type>input</type> - <size>100</size> - <required>true</required> - </field> - <field> - <fielddescr>Server Port</fielddescr> - <fieldname>serverport</fieldname> - <description>Server port (generally 10051)</description> - <default_value>10051</default_value> - <type>input</type> - <size>6</size> - <required>true</required> - </field> - <field> - <fielddescr>Hostname</fielddescr> - <fieldname>hostname</fieldname> - <description>Unique, case-sensitive proxy name. Make sure the proxy name is known to the server</description> - <default_value>localhost</default_value> - <type>input</type> - <size>100</size> - <required>true</required> - </field> - <field> - <fielddescr>Active Mode</fielddescr> - <fieldname>activemode</fieldname> - <description>Check to run Zabbix proxy in active mode (default)</description> - <default_value>on</default_value> - <type>checkbox</type> - <required>true</required> - </field> - <field> - <fielddescr>Config Frequency</fielddescr> - <fieldname>configfrequency</fieldname> - <description>How often the proxy retrieves configuration data from the Zabbix server in seconds. Ignored if the proxy runs in passive mode.</description> - <default_value>3600</default_value> - <type>input</type> - <size>10</size> - <required>true</required> - </field> - </fields> + <name>zabbixproxy</name> + <title>Services: Zabbix Proxy</title> + <category>Monitoring</category> + <version>1.1</version> + <addedit_string>Zabbix Proxy has been created/modified.</addedit_string> + <delete_string>Zabbix Proxy has been deleted.</delete_string> + <restart_command>/usr/local/etc/rc.d/zabbix_proxy.sh restart</restart_command> + <menu> + <name>Zabbix Proxy</name> + <tooltiptext>Setup Zabbix Proxy specific settings</tooltiptext> + <section>Services</section> + <url>/pkg_edit.php?xml=zabbix-proxy.xml&id=0</url> + </menu> + <service> + <name>zabbix-proxy</name> + <rcfile>zabbix-proxy.sh</rcfile> + <executable>zabbix_proxy</executable> + </service> + <tabs> + <tab> + <text>Settings</text> + <url>/pkg_edit.php?xml=zabbix-proxy.xml&id=0</url> + <active /> + </tab> + </tabs> + <fields> + <field> + <fielddescr>Server</fielddescr> + <fieldname>server</fieldname> + <description>List of comma delimited IP addresses (or hostnames) of ZABBIX servers</description> + <default_value>127.0.0.1</default_value> + <type>input</type> + <size>100</size> + <required>true</required> + </field> + <field> + <fielddescr>Server Port</fielddescr> + <fieldname>serverport</fieldname> + <description>Server port (generally 10051)</description> + <default_value>10051</default_value> + <type>input</type> + <size>6</size> + <required>true</required> + </field> + <field> + <fielddescr>Hostname</fielddescr> + <fieldname>hostname</fieldname> + <description>Unique, case-sensitive proxy name. Make sure the proxy name is known to the server</description> + <default_value>localhost</default_value> + <type>input</type> + <size>100</size> + <required>true</required> + </field> + <field> + <fielddescr>Active Mode</fielddescr> + <fieldname>activemode</fieldname> + <description>Check to run Zabbix proxy in active mode (default)</description> + <default_value>on</default_value> + <type>checkbox</type> + <required>true</required> + </field> + <field> + <fielddescr>Config Frequency</fielddescr> + <fieldname>configfrequency</fieldname> + <description>How often the proxy retrieves configuration data from the Zabbix server in seconds. Ignored if the proxy runs in passive mode.</description> + <default_value>3600</default_value> + <type>input</type> + <size>10</size> + <required>true</required> + </field> + </fields> <custom_php_install_command> <![CDATA[ - global $config, $g; + global $config, $g; + + $pfs_version = substr(trim(file_get_contents("/etc/version")),0,3); + switch ($pfs_version) { + case "1.2": + case "2.0": + define('ZABBIX_PROXY_BASE', '/usr/local'); + break; + default: + define('ZABBIX_PROXY_BASE', '/usr/pbi/zabbix-proxy-' . php_uname("m")); + } - mwexec("mkdir -p /var/log/zabbix/"); - mwexec("mkdir -p /var/run/zabbix/"); - mwexec("mkdir -p /var/db/zabbix/"); + mwexec("mkdir -p /var/log/zabbix/"); + mwexec("mkdir -p /var/run/zabbix/"); + mwexec("mkdir -p /var/db/zabbix/"); - conf_mount_rw(); + conf_mount_rw(); - /* create a few directories and ensure the sample files are in place */ - exec("/bin/mkdir -p /usr/local/etc/zabbix"); - exec("/bin/mkdir -p /var/log/zabbix"); - exec("/bin/mkdir -p /var/run/zabbix"); - exec("/bin/mkdir -p /var/db/zabbix"); + /* create a few directories and ensure the sample files are in place */ + exec("/bin/mkdir -p " . ZABBIX_PROXY_BASE . "/etc/zabbix"); + exec("/bin/mkdir -p /var/log/zabbix"); + exec("/bin/mkdir -p /var/run/zabbix"); + exec("/bin/mkdir -p /var/db/zabbix"); - exec("/bin/rm -f /usr/local/etc/rc.d/zabbix_proxy"); + exec("/bin/rm -f " . ZABBIX_PROXY_BASE . "/etc/rc.d/zabbix_proxy"); - $start = "/bin/mkdir -p /var/log/zabbix\n"; - $start .= "/usr/sbin/chown -R zabbix:zabbix /var/log/zabbix\n"; + $start = "/bin/mkdir -p /var/log/zabbix\n"; + $start .= "/usr/sbin/chown -R zabbix:zabbix /var/log/zabbix\n"; - $start .= "/bin/mkdir -p /var/run/zabbix\n"; - $start .= "/usr/sbin/chown -R zabbix:zabbix /var/run/zabbix\n"; + $start .= "/bin/mkdir -p /var/run/zabbix\n"; + $start .= "/usr/sbin/chown -R zabbix:zabbix /var/run/zabbix\n"; - $start .= "/bin/mkdir -p /var/db/zabbix\n"; - $start .= "/usr/sbin/chown -R zabbix:zabbix /var/db/zabbix\n"; + $start .= "/bin/mkdir -p /var/db/zabbix\n"; + $start .= "/usr/sbin/chown -R zabbix:zabbix /var/db/zabbix\n"; - $start .= "echo \"Starting Zabbix Proxy\"...\n"; + $start .= "echo \"Starting Zabbix Proxy\"...\n"; - /* start zabbix proxy */ - $start .= "/usr/local/sbin/zabbix_proxy\n"; + /* start zabbix proxy */ + $start .= ZABBIX_PROXY_BASE . "/sbin/zabbix_proxy\n"; - $stop = "echo \"Stopping Zabbix Proxy\"\n"; - $stop .= "kill `cat /var/run/zabbix/zabbix_proxy.pid`\n"; - /* write out rc.d start/stop file */ - write_rcfile(array( - "file" => "zabbix_proxy.sh", - "start" => "{$start}", - "restart" => "$stop\n" . "sleep 5\n" . "{$start}", - "stop" => "$stop" - ) - ); + $stop = "echo \"Stopping Zabbix Proxy\"\n"; + $stop .= "kill `cat /var/run/zabbix/zabbix_proxy.pid`\n"; + /* write out rc.d start/stop file */ + write_rcfile(array( + "file" => "zabbix_proxy.sh", + "start" => "{$start}", + "restart" => "$stop\n" . "sleep 5\n" . "{$start}", + "stop" => "$stop" + ) + ); - conf_mount_ro(); + conf_mount_ro(); ]]> </custom_php_install_command> <custom_php_command_before_form></custom_php_command_before_form> @@ -133,98 +143,107 @@ if (!preg_match("/^\d+$/", $ConfigFrequency)) { $input_errors[]='Config Frequency is not numeric.'; } - ]]> + ]]> </custom_php_validation_command> <custom_add_php_command></custom_add_php_command> <custom_php_resync_config_command> - <![CDATA[ - conf_mount_rw(); - global $config; - global $g; - $zabbixproxy_config = $config['installedpackages']['zabbixproxy']['config'][0]; - - $Server=$zabbixproxy_config['server']; - $ServerPort=$zabbixproxy_config['serverport']; - $Hostname=$zabbixproxy_config['hostname']; - $ListenPort=$zabbixproxy_config['listenport']; - $ConfigFrequency=$zabbixproxy_config['configfrequency']; - if(isset($zabbixproxy_config['activemode'])) { - $Mode="0"; /* active */ - } else { - $Mode="1"; /* passive */ - } + <![CDATA[ + conf_mount_rw(); + global $config, $g; + + $pfs_version = substr(trim(file_get_contents("/etc/version")),0,3); + switch ($pfs_version) { + case "1.2": + case "2.0": + define('ZABBIX_PROXY_BASE', '/usr/local'); + break; + default: + define('ZABBIX_PROXY_BASE', '/usr/pbi/zabbix-proxy-' . php_uname("m")); + } + $zabbixproxy_config = $config['installedpackages']['zabbixproxy']['config'][0]; + + $Server=$zabbixproxy_config['server']; + $ServerPort=$zabbixproxy_config['serverport']; + $Hostname=$zabbixproxy_config['hostname']; + $ListenPort=$zabbixproxy_config['listenport']; + $ConfigFrequency=$zabbixproxy_config['configfrequency']; + if(isset($zabbixproxy_config['activemode'])) { + $Mode="0"; /* active */ + } else { + $Mode="1"; /* passive */ + } - $conf = "Server=$Server\n"; - $conf .= "ServerPort=$ServerPort\n"; - $conf .= "Hostname=$Hostname\n"; - $conf .= "PidFile=/var/run/zabbix/zabbix_proxy.pid\n"; - $conf .= "DBName=/var/db/zabbix/proxy.db\n"; - $conf .= "LogFile=/var/log/zabbix/zabbix_proxy.log\n"; - $conf .= "ConfigFrequency=$ConfigFrequency\n"; - $conf .= "FpingLocation=/usr/local/sbin/fping\n"; - /* there's currently no fping6 (IPv6) dependency in the package, but if there was, the binary would likely also be in /usr/local/sbin */ - $conf .= "Fping6Location=/usr/local/sbin/fping6\n"; - $conf .= "ProxyMode=$Mode\n"; - - file_put_contents("/usr/local/etc/zabbix/zabbix_proxy.conf", $conf); - - $want_sysctls = array( - 'kern.ipc.shmall' => '2097152', - 'kern.ipc.shmmax' => '2147483648', - 'kern.ipc.semmsl' => '250' - ); - $sysctls = array(); - if (file_exists("/etc/sysctl.conf")) { - $sc = file_get_contents("/etc/sysctl.conf"); - $sc = explode("\n", $sc); - foreach ($sc as $num => $line) { - list($sysctl, $val) = explode("=", $line, 2); - if (array_key_exists($sysctl, $want_sysctls) || empty($sysctl)) - unset($sc[$num]); - } - } - foreach ($want_sysctls as $ws => $wv) { - $sc[] = "{$ws}={$wv}"; - exec("/sbin/sysctl {$ws}={$wv}"); + $conf = "Server=$Server\n"; + $conf .= "ServerPort=$ServerPort\n"; + $conf .= "Hostname=$Hostname\n"; + $conf .= "PidFile=/var/run/zabbix/zabbix_proxy.pid\n"; + $conf .= "DBName=/var/db/zabbix/proxy.db\n"; + $conf .= "LogFile=/var/log/zabbix/zabbix_proxy.log\n"; + $conf .= "ConfigFrequency=$ConfigFrequency\n"; + $conf .= "FpingLocation=/usr/local/sbin/fping\n"; + /* there's currently no fping6 (IPv6) dependency in the package, but if there was, the binary would likely also be in /usr/local/sbin */ + $conf .= "Fping6Location=/usr/local/sbin/fping6\n"; + $conf .= "ProxyMode=$Mode\n"; + + file_put_contents(ZABBIX_PROXY_BASE . "/etc/zabbix/zabbix_proxy.conf", $conf); + + $want_sysctls = array( + 'kern.ipc.shmall' => '2097152', + 'kern.ipc.shmmax' => '2147483648', + 'kern.ipc.semmsl' => '250' + ); + $sysctls = array(); + if (file_exists("/etc/sysctl.conf")) { + $sc = file_get_contents("/etc/sysctl.conf"); + $sc = explode("\n", $sc); + foreach ($sc as $num => $line) { + list($sysctl, $val) = explode("=", $line, 2); + if (array_key_exists($sysctl, $want_sysctls) || empty($sysctl)) + unset($sc[$num]); } - file_put_contents("/etc/sysctl.conf", implode("\n", $sc) . "\n"); - - $want_tunables = array( - 'kern.ipc.semopm' => '100', - 'kern.ipc.semmni' => '128', - 'kern.ipc.semmns' => '32000', - 'kern.ipc.shmmni' => '4096' - ); - $tunables = array(); - if (file_exists("/boot/loader.conf")) { - $lt = file_get_contents("/boot/loader.conf"); - $lt = explode("\n", $lt); - foreach ($lt as $num => $line) { - list($tunable, $val) = explode("=", $line, 2); - if (array_key_exists($tunable, $want_tunables) || empty($tunable)) - unset($lt[$num]); - } - } - foreach ($want_tunables as $wt => $wv) { - $lt[] = "{$wt}={$wv}"; + } + foreach ($want_sysctls as $ws => $wv) { + $sc[] = "{$ws}={$wv}"; + exec("/sbin/sysctl {$ws}={$wv}"); + } + file_put_contents("/etc/sysctl.conf", implode("\n", $sc) . "\n"); + + $want_tunables = array( + 'kern.ipc.semopm' => '100', + 'kern.ipc.semmni' => '128', + 'kern.ipc.semmns' => '32000', + 'kern.ipc.shmmni' => '4096' + ); + $tunables = array(); + if (file_exists("/boot/loader.conf")) { + $lt = file_get_contents("/boot/loader.conf"); + $lt = explode("\n", $lt); + foreach ($lt as $num => $line) { + list($tunable, $val) = explode("=", $line, 2); + if (array_key_exists($tunable, $want_tunables) || empty($tunable)) + unset($lt[$num]); } - file_put_contents("/boot/loader.conf", implode("\n", $lt) . "\n"); - chmod("/var/log/zabbix", 0755); - chmod("/var/run/zabbix", 0755); - conf_mount_ro(); + } + foreach ($want_tunables as $wt => $wv) { + $lt[] = "{$wt}={$wv}"; + } + file_put_contents("/boot/loader.conf", implode("\n", $lt) . "\n"); + chmod("/var/log/zabbix", 0755); + chmod("/var/run/zabbix", 0755); + conf_mount_ro(); - ]]> + ]]> </custom_php_resync_config_command> <custom_php_deinstall_command> - <![CDATA[ - exec("kill `cat /var/run/zabbix/zabbix_proxy.pid`"); + <![CDATA[ + exec("kill `cat /var/run/zabbix/zabbix_proxy.pid`"); - exec("/bin/rm /usr/local/etc/rc.d/zabbix_proxy.sh"); + exec("/bin/rm " . ZABBIX_PROXY_BASE . "/etc/rc.d/zabbix_proxy.sh"); - exec("/bin/rm -r /var/log/zabbix/"); - exec("/bin/rm -r /var/run/zabbix/"); - exec("/bin/rm -r /var/db/zabbix/"); + exec("/bin/rm -r /var/log/zabbix/"); + exec("/bin/rm -r /var/run/zabbix/"); + exec("/bin/rm -r /var/db/zabbix/"); ]]> </custom_php_deinstall_command> </packagegui>
\ No newline at end of file |