· 10 years ago · May 10, 2016, 01:15 AM
1#!/bin/bash
2
3#
4# Script: setup_snort ---rwh 2003,2004,2005,2009,2010,2011,2012,2013,2014
5
6# Version...
7SETUP_SNORT_VER="20.2";
8
9#
10# This script is used to setup the snort network Intrusion Detection System (IDS)
11# for the NST distribution. Default setting: A 64MB RAM Disk will be created for
12# snort's runtime directory @ /mnt/ram4/snort.
13#
14# Usage (see usage() function below):
15#
16
17#
18# Load vars from configuration:
19# NST config file...
20if [ -r "/etc/nst.conf" ]; then
21 . "/etc/nst.conf";
22else
23 echo;
24 echo "***ERROR*** Missing/unreadable configuration file: \"/etc/nst.conf\"...";
25 echo;
26 exit 3;
27fi
28
29
30# Vars:
31# =====
32PKG="snort";
33snort_VER="$(/bin/rpm --qf "%{version}" -q "${PKG}" 2> /dev/null;)";
34daq_VER="$(/bin/rpm --qf "%{version}" -q "daq" 2> /dev/null;)";
35barnyard2_VER="$(/bin/rpm --qf "%{version}" -q "barnyard2" 2> /dev/null;)";
36mysql_VER="$(/bin/rpm --qf "%{version}" -q "mariadb" 2> /dev/null;)";
37snort_utils_base_VER="$(/bin/rpm --qf "%{version}" -q "base-php4" 2> /dev/null;)";
38snort_utils_adodb_VER="$(/bin/rpm --qf "%{version}" -q "php-adodb" 2> /dev/null;)";
39pkgRulesSite="http://www.snort.org/pub-bin/downloads.cgi/Download/vrt_pr/snortrules-pr-2.4.tar.gz";
40
41pkgConfigFiles="classification.config \
42 generators \
43 gen-msg.map \
44 Makefile.am \
45 reference.config \
46 sid \
47 unicode.map \
48 snort.conf";
49
50customSnortScripts="ping_attack.sh snort_trigger.sh";
51
52#
53# Parameter vars...
54pkgRulesFetch="";
55interface="eth0";
56interfaceSpecified="false";
57snortCfgDir="/etc/snort_${interface}";
58dbHostname="localhost";
59dbPort="3306";
60dropPrevDb="false";
61sensorName="";
62collectorMode="false";
63alertDetail="full";
64firstSnortInstance="true";
65ramDevice="/dev/ram4";
66ramMntPt="";
67ramDiskSize="64";
68needRAMDisk="true";
69runtimeDir="";
70eraseRuntimeDir="false";
71signalType="";
72home_net="any"; # set default net: "any"...
73external_net="any"; # set default net: "any"...
74snort_options=""; # set any user options passed along to snort...
75snort_options_filename="snort_options";
76
77mysqlExtra="false" # default: don't install extra service entries...
78
79clear_cache="true"; # default: clear Snort archive rule set bundle cache on exit...
80
81CREATERAMDISK="/root/bin/create_ramdisk";
82
83SNORTRSCACHEDIR=""; # define the snort ruleset cache dir...
84
85
86# verbose mode: # on - more verbose
87# # off - less verbose
88verbose_mode="off";
89
90# setup_snort process type: 1 => setup a snort instance...
91# 2 => setup a backend MySQL database (collector mode)...
92# 3 => update rules for one or more snort instances
93# 4 => kill one or more snort instances...
94# 5 => list snort status...
95# 6 => signal a snort reload/dump...
96setup_snort_process_type=1; # Default: 1 - setup a snort instance...
97
98ARSI=0; # additional rules site index (ARSI)...
99URSI=0; # update rules site index (URSI)...
100SCLIL=""; # snort.conf last include line position...
101
102# arrays defined here for clarity...
103ARS=(); # Additional Rule Site array...
104URS=(); # Update Rule Site array...
105SIL=(); # Selected Interface List array...
106CIL=(); # Configured Interface List array...
107SCD=(); # Snort Configuration Directory array...
108SRD=(); # Snort Runtime rules Directory array...
109SSD=(); # Snort Shared runtime rules Directory array...
110
111
112# Functions:
113# ==========
114
115# ### pinfo ### This function prints out info if verbose mode set (printf sty print...)
116#
117# pinfo "text"
118#
119# parameter: "text" - text to print out...
120#
121pinfo() {
122 if [ "${verbose_mode}" = "on" ]; then
123 printf "${1}\n";
124 fi
125}
126
127
128# ### einfo ### This function prints out info if verbose mode set (echo style print...)
129#
130# einfo "text"
131#
132# parameter: "text" - text to print out...
133#
134einfo() {
135 if [ "${verbose_mode}" = "on" ]; then
136 echo "${1}";
137 fi
138}
139
140# ### show_usage_header ### This function shows the header usage...
141show_usage_header() {
142 cat << EOF
143
144Usage: $(basename "$0") -r <local> | -r <URL: base rule source>
145 [-ars <URL: additional rules site> ...] [-i <interface>]
146 [-d <database hostname>] [-p <database port>] [ -drop ]
147 [-s <sensor name>] [-a <full | fast>] [-rd <RAM device>]
148 [-rds <RAM disk size (MB)>] [-rmp <RAM mount point>]
149 [-rdir <runtime directory>] [--HOME_NET <network address>]
150 [--EXTERNAL_NET <network address>] [-ncc] [-x] [-e]
151 [-so <snort options>] [-v] [-h]
152
153 $(basename "$0") -c [-x] [-rd <RAM device>] [-rds <RAM disk size (MB)>]
154 [-rmp <RAM mount point>] [-rdir <runtime directory>]
155 [-p <database port>] [ -drop ] [-v]
156
157 $(basename "$0") -u [-i <interface>] [-il <interface list>]
158 -urs <URL: update rules site>
159 [-urs <URL: update rules site> ...] [-ncc] [-v]
160
161 $(basename "$0") -disable [-e] [-i <interface>] [-il <interface list>] [-v]
162
163 $(basename "$0") -l [-i <interface>] [-il <interface list>]
164
165 $(basename "$0") -sig <reload | dump> [-i <interface>]
166 [-il <interface list>] [-v]
167
168 $(basename "$0") -startup <enabled | disabled> -i <interface>
169
170Version: "${SETUP_SNORT_VER}"
171
172EOF
173}
174
175# ### show_usage_body ### This function shows the usage body...
176show_usage_body() {
177 cat << EOF
178Description:
179 The first form of this script: "-r" is used to setup an instance of the Snort Network
180 Intrusion Detection System (IDS) on a NST probe system. A Snort session can be used
181 with any configured interface [-i <interface>]. All associated alert and log events
182 will first be logged. A corresponding Barnyard2 process will then read the log and
183 send it to a MySQL database server on host [-d <database name>]. The default setting
184 is to create a 64MB RAM Disk at mount point: "/mnt/ram4" for MySQL, Barnyard2
185 and Snort data files. The manditory rules base source option: "-r" can be "<local>"
186 or a "<URL base rule source>".
187
188 For each Snort instance, a corresponding Barnyard2 configuration will be created.
189 If the database hostname [-d <database name>] is "localhost" (i.e. the default value),
190 a MySQL database server will be configured and started on this NST probe system for
191 immediate Snort usage. A PHP-based analysis engine: BASE (Basic Analysis and Security
192 Engine) will also be configured to search and process all security incidents
193 generated by Snort that are stored within the MySQL database.
194
195 End user access to BASE is via the Apache Web Server. One needs to make sure that an
196 instance of Apache is up and running on the NST probe system for proper access to
197 BASE generated Web pages. The following 2 examples demonstrate how one accesses
198 BASE's Web interface:
199
200 Example 1: Local Access (IP Address "localhost": 127.0.0.1)
201 NST probe running Snort, Barnyard2, MySQL, and BASE
202 Interface: "Firefox" browser using X Windows or VNC client, or the
203 "elinks" browser using the console or a SSH session.
204 URL: http://127.0.0.1/base
205
206 Example 2: Remote Access (IP Address of NST Probe running Snort, Barnyard2,
207 MySQL, and BASE: 10.21.33.44)
208 Interface: Any Web browser that supports SSL
209 URL: https://10.21.33.44/base
210
211 The second form of this script: "-c" can also be used to setup and run a backend
212 MySQL database server engine tailored with the BASE analysis engine for the
213 collection of remote Snort security incidents and log information (see the [-c]
214 parameter below). A federation of remote Snort IDS probes can be populated
215 throughout an Enterprise network computing evironment and be configured to send
216 any security incidents and log information to this database server.
217
218 The third form of this script: "-u" is used to update a selected list of
219 configured Snort instances "-il <interface list>" or all configured Snort
220 instances found on the probe system with updated Snort rule signatures. One or more
221 Snort rule sites: "-urs <URL: update rules site>" may be specified.
222
223 The forth form of this script: "-disable" is used to stop (kill) a list of Snort
224 running instances or all Snort instances running on the probe system and set their
225 Snort startup flag to 'Disabled'. Optionally one can choose to delete (erase: "-e")
226 the associated runtime directory and Snort configuration file for the selected list
227 of Snort instances specified by the interface list parameter: "-il <interface list>".
228 All remaining configured and enabled instances of Snort will be restarted when using
229 this option.
230
231 The fifth form of this script: "-l" is used to list the status of one or more Snort
232 instances configured on the NST probe system.
233
234 The sixth form of the script: "-sig" is used to either reload one or more Snort
235 instances ("reload") or dump stats ("dump") for all or a single Snort instance.
236
237 The seventh form of the script: "-startup" is used to set a flag within
238 both the snort and barnyard2 configuration files so that either the snort
239 systemd service: "snort.service" and the barnyard2 systemd service:
240 "barnyard2.service" can determine if the service can be 'enabled' or
241 'disabled' for the corresponding interface.
242
243
244 -r <local> | -r <URL base rule source> |
245 --rules <local> | --rules <local> <URL base rule source>
246 This manditory option specifies the first form of the "setup_snort" script. The
247 base rule source is required for determining which base Snort rule source to use:
248 local - a copy of the Snort rules that come with the NST distribution will be
249 transferred to read/write Snort runtime "rules" directory. Use this
250 method if one does not have access to the internet.
251 URL base rule source
252 - uses "wget" to obtain a Snort base signature rule set. The base rule
253 source must be in gzipped tar file format: "Ex: snortrules.tar.gz". The
254 base rules source archive must contain the following additional files:
255 "snort.conf", "sid-msg.map", "threshold.conf", "unicode.map",
256 "generators", "cgi-bin.list", "classification.config", "gen-msg.map",
257 "reference.config" and "sid".
258 Example: 1) "http://www.nst.org/snortrules/base_snortrules.tar.gz"
259 2) "https://user:password@10.10.10.25/snort/rules/base_snortrules.tar.gz"
260 ** Note: One can obtain a registered Snort Oinkmaster code from: "www.snort.org"
261 and create a "registered Snort Oinkcode URL" as the base Snort rule source.
262
263 -ars <URL: additional rules site> | --additional-rules-site <URL: additional rules site>
264 This optional parameter may be used one or more times to provided addition Snort
265 signature rules (archive rule set bundle) to the base Snort rules. The rules file
266 must be in a gzipped tar file format: "Ex: rules.tar.gz". Besides the individual
267 rule files, a signature to message map file (sid-msg.map) must also be included
268 with the archive rule set bundle. The additional rule files will be uncompressed
269 and put into the appropriate runtime rules directory. The signature to message map
270 file will be merged into the current Snort signature to message map file.
271 Example: 1) "-ars http://www.bleedingsnort.com/bleeding.rules.tar.gz"
272 2) "-ars file:///data1/snortrules/nst-snort-rules.tar.gz"
273 3) "-ars https://user:password@10.10.10.25/snort/rules/snortrules.tar.gz"
274 ** Note: An "include" entry for each additional rule file added will be made but
275 will be commented out. "Ex: #include \$RULE_PATH/nst-smtp.rules"
276
277 -c | --collector_mode
278 This option specifies the second form of the "setup_snort" script. It is used to
279 setup a MySQL database for the collection of remote Snort IDS probe's security
280 alert events and log information. This parameter is useful when setting up an IDS
281 architecture consisting of a federation of Snort probe sensors with a backend
282 MySQL server and BASE analysis engine.
283
284 -u | --update-rules
285 This option specifies the third form of the "setup_snort" script. The runtime
286 rules directory for one or all configured Snort instances will be updated from
287 rules sources (archive rule set bundles) specified by one or more update rule site
288 parameters: "-urs <URL: update rules site>".
289 The location of the runtime rules directory will be derived from the "snort.conf"
290 file associated with the selected network interfaces from the interface list
291 parameter "-il <interface list>". If no interface list parameter:
292 "-il <interface list>" was specified, then all configured Snort instances will have
293 their runtime rules directory updated. One can build a script using this Snort
294 update option and periodically freshen a running Snort instance via the "cron"
295 scheduler with the latest Snort rule signatures. Once the runtime rules directory
296 has been updated, a Snort reload signal: "-sig reload" needs to be sent to the
297 corresponding running Snort instance.
298 **Note: 1) This update option "-u" can only be used with a Snort instance that has
299 been configured.
300 2) The configured snort instance does not need to be running.
301 3) For all new rule files added during the update, each selected
302 configured snort instance will have their "snort.conf" file modified
303 with a commented out include rule file entry:
304 "#include \$RULE_PATH/*.rules" for the new rule file.
305 4) The Snort signature identifier to mapping file: "sid-msg.map" will also
306 be rebuilt.
307
308 -urs <URL: update rules site> | --update-rules-site <URL: update rules site>
309 This optional parameter may be used one or more times with the update Snort
310 rules paramter "-u" to provide updated Snort rules to one or more configured
311 Snort instances. See the additional Snort rules parameter above:
312 "-ars <URL: additional rules site>" for proper syntax.
313
314 -ncc | --no-clear-cache
315 This optional parameter will disable clearing the Snort specific caching of
316 downloaded rule set archive bundles. The default setting is to clear all downloaded
317 rule set archive bundles once the "setup_snort" script exits.
318
319 -i <interface> | --interface <interface>
320 Example Form: "p5p1"
321 Interface name for which Snort will perform intrusion detection: Ex: "eth1". This
322 is the associated network interface for a Snort instance.
323 Default: "eth0"
324
325 -il <interface list> | --interface-list <interface list>
326 Example Form: "em1,em2,p4p2"
327 A selected interface name list associated with configured Snort instances for Snort
328 rule set updates, Snort configuration instance removal, Snort configuration listing
329 and Snort process signaling for reload and dump actions. The interface list is a
330 comma or space separated list of interface names associated with already configured
331 Snort instances. The interface name list should be enclosed in double quotes ("").
332 Example: "eth0, p5p1 eth5 ath0"
333
334
335 -d <database hostname> | --db_hostname <database hostname>
336 This parameter sets the MySQL database hostname for alert events and log information
337 collection. It can be either an IP address or a name resolved through the naming
338 service "/etc/hosts" file or DNS.
339 ** Note 1: If the name of the database hostname is resolved to a remote host, a MySQL
340 database instance will not be started on this NST probe system.
341 ** Note 2: The password for the "root" MySQL database user can be found in file:
342 "/etc/nst.conf" using variable: "NSTCTMYSQLPASSWD".
343 ** Note 3: The password for the "snort" MySQL database user can be found in file:
344 "/etc/nst.conf" using variable: "NSTCTSNORTPASSWD".
345 Default: "localhost"
346
347 -p <database port> | --db_port <database port>
348 This sets the database port number that the MySQL server is listening on.
349 Default: "3306"
350
351 -drop | --drop_previous_database
352 This option will drop all previously configured Snort MySQL databases prior to
353 setting up new Snort IDS instance or Snort Collector. This includes both
354 the "snort" and "snort_archive" databases.
355
356 -s <sensor name> | --sensor_name <sensor name>
357 Use this parameter to identify the sensor name used by this Snort instance. This is
358 useful when many Snort sensors are logging to the same MySQL database. It will be
359 easier to distinguish between multiple sensors when using the BASE tool for viewing
360 alert and logged events.
361 ** Note: Do not use spaces within the <sensor name> Ex: "Sensor 1" => "Sensor_1"
362 Default: "IP address of the default Network Interface Device"
363
364 -a <full | fast> | --alert_detail <full | fast>
365 Used to set the detail of Snort alert and log events to the data base.
366 full - All alert information for an event will be logged.
367 fast - An abbreviated version of the alert event will be logged.
368 Default: "full"
369
370 -rd <RAM device> | --ram-device <RAM device>
371 Use this optional parameter to change the default RAM device that will be used for
372 this instance of Snort and the associated MySQL database files. Available RAM
373 device names on NST: "/dev/ram0 - /dev/ram9". A cooresponding mount point:
374 "/mnt/ram0 - /mnt/ram9" will be automatically selected for the RAM device. One can
375 use the following optional parameter: "-rmp <mount point>" to change mount point
376 location for the selected RAM device.
377 Default: "/dev/ram4"
378
379 -rds <RAM dsk size (MB)> | --ram-disk-size <RAM disk size (MB)>
380 Use this optional parameter to change the default RAM disk size in MegaBytes (MB)
381 that will be used for this instance of Snort and the associated MySQL database data
382 files.
383 Default: "64"
384 ** Note: Use a reasonable value and make sure you to not exceed your available
385 system RAM. The system memory utility: "free" can be used to help make
386 your determination.
387
388 -rmp <mount point> | --ram-mount-point <mount point>
389 Use this optional parameter to change the selected RAM device's: "-rd <RAM device>"
390 mount point for this instance of Snort and the associated MySQL database data files.
391 Default: "/mnt/ram4"
392
393 -rdir <runtime directory> | --runtime-directory <runtime directory>
394 One can use this optional parameter to force the "setup_snort" script to use an
395 existing runtime directory on a locally attached disk drive or a mounted network
396 file system and bypass the creation of a RAM disk. To do this, make sure the
397 directory initially exists prior to running this script.
398 Example: Mount Point: "/dev/hdc1" mount at: "/probe1" type ext3 (rw)
399 Directory: "/probe1/snort"
400 Use: "-rdir /probe1/snort" to create the top level
401 runtime directory structure for this instance of
402 Snort and the associated MySQL database (if needed).
403 Directory Structure: Snort => /probe1/snort/snort
404 mysql => /probe1/snort/var/lib/mysql (if needed)
405
406 -disable
407 This option specifies the forth form of the "setup_snort" script. If no interface
408 list parameter ("-il <interface list>") was specified, then all running Snort
409 instances will be stopped ("killed") and their Snort startup flag set to: 'Disabled'.
410 If a selected interface list ("-il <interface list>") was specified, then each
411 running Snort instance associated with an interface name in the interface list will
412 be stopped and their Snort startup flag will be set to 'Disabled'. Use the
413 "-startup" option to reenable starting a configured instance of Snort.
414
415 --HOME_NET <network address>
416 Use this option to set the local network address for your environment. The
417 "HOME_NET" variable within the "snort.conf" configuration file for the specified
418 network interface ("-i <interface>") will be set accordingly. The specified
419 <network address> needs to be in CDIR format and multiple network address may be
420 used.
421 Default: "any"
422 Example: 1) 10.221.22.0/24
423 2) [192.168.3.0/24,172.16.0.0/16]
424 3) \$eth0_ADDRESS
425 **Note: No spaces are permitted when multiple addresses are used.
426
427 --EXTERNAL_NET <network address>
428 Use this option to set the external network address for your environment. The
429 "EXTERNAL_NET" variable within the "snort.conf" configuration file for the specified
430 network interface ("-i <interface>") will be set accordingly. The specified
431 <network address> needs to be in CDIR format.
432 Default: "any"
433 Example: 1) 24.97.1.0/24
434 2) \$eth1_ADDRESS
435 3) !\$HOME_NET
436
437 -x | --extra-servies
438 This option installs the extra network services mapping values (protocols, services
439 and flags) into the Snort MySQL database. These tables are intended to supplement
440 the base tables required for database support in Snort in order to make data
441 more human readable.
442
443 -e | --erase
444 One can specify this parameter to erase the runtime directory and Snort
445 configuration file for a prior configured Snort instance.
446 If used with the first form, the setup script will try to erase any prior existing
447 runtime Snort setup directory and configuration file.
448 If used with the third form, the setup script will try to erase either one or more
449 Snort runtime directories and configuration files depending on the value of the
450 interface list parameter ("-il <interface list>").
451 ** Note: A particular Snort runtime directory will not be erased if it is being
452 shared with another Snort instance using a different network interface.
453 The Snort configuration file will always be removed. Only the directory
454 structure for Snort will be erased. The MySQL directory structure will
455 not be erased.
456
457 -l | --list-status
458 This option specifies the fifth form of the "setup_snort" script. The status for all
459 Snort instances including processes, configuration directories, runtime directories
460 and configured network interfaces are listed. If the interface list parameter
461 ("-il <interface list>") was specified, then only the status pertaining to the
462 selected interface names in the list is displayed.
463
464 -sig <reload | dump> | --signal <reload | dump>
465 This option specifies the sixth form of the "setup_snort" script. The "-sig reload"
466 option will cause one of more running Snort instances to reload their associated
467 configuration file. A "SIGHUP" signal is sent to one or more running Snort processes
468 resulting in closure of all opened files and restarting the Snort process. If no
469 ("-il <interface list>") parameter was specified, then all running Snort instances
470 will be sent the "SIGHUP" signal for reloading.
471 The "-sig dump" option will cause one of more running Snort instances to dump their
472 current statistics. The output of the statistics is controlled by how a Snort
473 process was initially executed. A "SIGUSR1" signal is sent to one of more Snort
474 instances to dump their current packet statistical information to the current shell,
475 console or syslogd(8) if in daemon mode ("-D" option to Snort). If no
476 ("-il <interface list>") parameter was specified, then all running Snort instances
477 will be sent the "SIGUSR1" signal to dump their statistics. If the Snort process is
478 run in daemon mode, the statistics will be typically dumped to the syslog
479 file: "/var/log/messages".
480
481 -so <snort options> | --snort-options <snort options>
482 Use this optional parameter to pass options to snort in the format used by
483 snort(8). This is useful when specifying options for which there is no separate
484 "setup_snort" command-line flag. A "snort_options" file will be created in the
485 associated Snort instance configuration directory. The following is an example
486 to enable the Snort Inline mode and exit Snort after 1000 packets are
487 captured: -so "-Q -n 1000".
488 ** Note: Double quotes are necessary when spaces exist between command-line
489 flags and values.
490
491 -startup <enabled | disabled>
492 This option specifies the seventh form of the "setup_snort" script. The
493 "-startup enabled" option will set a flag in both the Snort instance's configuration
494 file and the Barnyard2 configuration file for network interface "-i <interface>"
495 to be 'Enabled'. When this Snort instance is attempted to be started with
496 "systemctl start snort.service", it will detect that the flag is 'enabled'
497 and then proceed to startup the Snort instance. The "-startup disabled" option will
498 set a flag in both the snort instance's configuration file and the Barnyard2
499 configuration file for network interface "-i <interface>" to be 'disabled'.
500 When this Snort instance is attempted to be started with
501 "systemctl start snort.service", it will detect that the flag is 'Disabled'
502 and 'skip' starting up this instance of snort.
503
504 -v | --verbose
505 This optional switch will enable verbose output. Without this switch set, minimal
506 output from the execution of this script will be displayed.
507
508 -h | --help
509 Displays this help information.
510
511EOF
512}
513
514# ### show_usage ### This function show the script usage...
515show_usage() {
516 show_usage_header;
517 show_usage_body;
518}
519
520# ### show_short_usage ### This function show the script short usage...
521show_short_usage() {
522 show_usage_header;
523 cat << EOF
524-------------------------------------------------------------------------------
525
526*** For more detailed help use: $(basename "$0") -h
527
528EOF
529}
530
531# ### error_if_switch ### This function makes sure a cmd line switch does not come
532# before a value...
533error_if_switch() {
534
535 if [ "$(printf "%1.1s" ${1:--})" = "-" ]; then
536 echo;
537 echo "***ERROR*** '${1}' is not acceptable after ${2:-switch}"
538 show_short_usage
539 exit 10;
540 fi
541}
542
543# ### createSnortConfRuntimeRulesArrays ### This helper function creates 3 arrays:
544# SCD[] - snort configuration directories...
545# SRD[] - snort runtime rules directories...
546# SSD[] - snort shared runtime rules directories...
547#
548# ***Note: There is a one to one relationship between the SCD[] and the SRD[] array...
549#
550createSnortConfRuntimeRulesArrays() {
551 local i=0; # initialize index for array...
552
553 for d in $(/usr/bin/find /etc -type d -name "snort_*" 2> /dev/null | /bin/sort); do
554# create snort config and runtime rules directory pairs...
555 SCD[$i]=$d;
556 SRD[$i]=$(/bin/grep "^var RULE_PATH" "${d}/snort.conf" \
557 2> /dev/null | /bin/gawk -- '{print $3}');
558 ((i++)); # next index...
559 done
560
561# create snort shared runtime directories array...
562 i=0; # initialize index...
563 SSD[$i]=${SRD[0]}; # prime the shared rules directory...
564 ((i++)); # next index...
565 local dupFound="false";
566 for r in "${SRD[@]}"; do
567 dupFound="false"; # for each runtime rules dir start out duplicate not found...
568 for s in "${SSD[@]}"; do
569 if [ "${r}" = "${s}" ]; then
570 dupFound="true"; # signal duplicate found..
571 break; # duplicate found - break out...
572 fi
573 done
574 if [ "${dupFound}" = "false" ]; then
575 SSD[$i]=${r}; # add to shared runtime rules dir...
576 ((i++)); # next index...
577 fi
578 done
579
580 return 0;
581}
582
583# ### processInterfaceList ### This function initializes various interface arrays
584# based on the selected interface names from the user.
585# Selected interface names will be compared with already
586# known configured Snort interfaces. If there is a
587# discrepancy, this will cause an error condition and
588# termination of this script.
589processInterfaceList() {
590
591 local i=0; # local index var...
592 local found="false"; # local results var...
593
594 # initialize the selected interface list array...
595 #
596 # ***Note: The gawk script below processes the following:
597 # It is a handy way to initialize a bash array...
598 #
599 # "eth0,eth2,, eth4 ath0" => "eth0 eth2 eth4 ath0"
600 #
601 SIL=($(echo ${interface} | /bin/gawk 'BEGIN {i = 1; FS="[ ,]*";} {while (i <= NF) {print $i; i++}}'));
602
603 if [ ${#SCD[@]} -eq 0 ]; then # 1st instance case, nothing configured yet:
604 CIL=(); # clear array...
605 return 0;
606 fi
607 # establish current configured snort interfaces...
608 for c in ${SCD[@]}; do
609 CIL[${i}]="${c#*_}";
610 ((i++)); # increment index...
611 done
612 # new Snort instance case...
613 if [ ${setup_snort_process_type} -eq 1 ]; then
614 return 0; # return here after CIL[] was array created
615 fi
616 # if selected interfaces have been choosen...
617 if [ "${interfaceSpecified}" = "true" ]; then
618 # make sure each selected interface is a valid snort interface
619 for si in ${SIL[@]}; do
620 for c in ${CIL[@]}; do
621 if [ "$si" = "$c" ]; then
622 found="true"; # set match occurred...
623 fi
624 done
625 # error if selected interface is not a currently configured...
626 if [ "${found}" = "false" ]; then
627 echo;
628 echo "***ERROR*** Selected interface: \"${si}\" is not a currently configured Snort interface...";
629 echo;
630 exit 65;
631 else
632 found="false"; # reset results var...
633 fi
634 done
635 fi
636 # at this point array: SIL[] holds valid selected interface names...
637 return 0;
638}
639
640# ### setupSnortRulesetCacheDir ### This function sets up the snort ruleset cache dir
641# and assigns it to var: SNORTRSCACHEDIR
642#
643# Locations used: If this is a hard disk install:
644# (i.e. ${NSTHDDATADIR} exists)
645# then SNORTRSCACHEDIR="${NSTHDDATADIR}/${SNORTRSCACHENAME}"
646# typically: "/var/nst/snort_rs_cache"
647# -else-
648# If this is a LiveCD run:
649# then SNORTRSCACHEDIR="/tmp/${SNORTRSCACHENAME}"
650# typically: "/tmp/snort_rs_cache"
651setupSnortRulesetCacheDir() {
652 if [ -d "${NSTHDDATADIR}" ]; then
653 SNORTRSCACHEDIR="${NSTHDDATADIR}/${SNORTRSCACHENAME:-snort_rs_cache}";
654 else
655 SNORTRSCACHEDIR="/tmp/${SNORTRSCACHENAME:-snort_rs_cache}";
656 fi
657 if [ "${clear_cache}" = "true" ]; then
658 /bin/rm -fr "${SNORTRSCACHEDIR}"; # remove any previous occurence
659 fi
660 /bin/mkdir -p "${SNORTRSCACHEDIR}"; # try to create a new snort cache instance...
661
662 return 0;
663}
664
665# ### teardownSnortRulesetCacheDir ### This function tears down the snort ruleset
666# cache dir if allowed...
667teardownSnortRulesetCacheDir() {
668 pinfo;
669 if [ "${clear_cache}" = "true" ]; then
670 if [ -d "${SNORTRSCACHEDIR}" ]; then
671 pinfo "*** Clearing the Snort rule set cache directory: \"${SNORTRSCACHEDIR}\"...";
672 /bin/rm -fr "${SNORTRSCACHEDIR}"; # remove snort ruleset cache dir instance...
673 fi
674 else
675 pinfo "*** Preserving the Snort rule set cache directory: \"${SNORTRSCACHEDIR}\"...";
676 fi
677
678 return 0;
679}
680
681# ### commentURLPasswd ### This function will comment out the password field
682# if found in the URL passed to the function...
683#
684# commentURLPasswd <URL>
685#
686# URL format: "https://userid:password@host/path/filename"
687#
688# returns: commented out password field in URL:
689# "https://userid:########@host/path/filename"
690#
691commentURLPasswd() {
692 local url=""; # temp vars...
693
694 url="$(echo "${1}" | /bin/sed -e 's,://\([^:]*\):[^@]*@,://\1:########@,g')";
695 echo -n "${url}";
696
697 return 0;
698}
699
700# ### findLastIncludeLoc ### This function will find the next last rule include
701# line in "snort.conf" for insertion of the next
702# "#include $RULE_PATH/*.rules" entry...
703#
704# findLastIncludeLoc [snort configuration directory]
705#
706# returns: Next line number in file "snort.conf" after the last:
707# "include $RULE_PATH/*.rules"
708# -or-
709# "# include $RULE_PATH/*.rules" line.
710#
711findLastIncludeLoc() {
712 local lil; # last include line: "lil"
713 local clil; # commented last include line: "clil"
714 # default location of "snort.conf": "${pkgdir}/rules"
715 local scd=${1:-"${pkgDir}/rules"}
716 local scf="${scd}/snort.conf"
717 # generate reverse sorted array of include lines...
718 # first element is the: "lil"
719 lilArray=($(/bin/grep -ni "^include \$RULE_PATH" ${scf} | /bin/sort -gr | /bin/cut -d: -f1));
720 lil=${lilArray[0]};
721 # generate reverse sorted array of commented include lines...
722 # first element is the: "clil"
723 clilArray=($(/bin/grep -ni "^# include \$RULE_PATH" ${scf} | /bin/sort -gr | /bin/cut -d: -f1));
724 clil=${clilArray[0]};
725 # set snort.conf last include line position
726 if [ ${lil:-0} -gt ${clil:-0} ]; then
727 ((lil++)); # next position...
728 SCLIL=${lil};
729 else
730 ((clil++)); # next position...
731 SCLIL=${clil};
732 fi
733
734 return 0;
735}
736
737# ### wget_untar ### This function will download (wget) and untar the specified URL into
738# the specified runtime rules directory...
739#
740# Mod: 05_28_05 This function now uses PKB's "urlcache" script to reduce redundant
741# ruleset bundle downloads when multiple interfaces exist...
742#
743# wget_untar <URL: rules site> <runtime directory>
744#
745# ***Assumptions: 1) The rule file tar archive has all rule files located
746# under a "./rules/*.rules" subdirectory...
747#
748# Example: ./rules/nst-sort.rules
749#
750# 2) A "snort.conf" may be located under the "rules"
751# or "etc" directory...
752#
753# 3) The ${SNORTRSCACHEDIR} snort ruleset cache
754# directory is set prior to calling this function...
755#
756wget_untar() {
757 local rs=${1}; # set for better clarity within this function...
758 local rdir=${2}; # set for better clarity within this function...
759 local rsFullPath=""; # full path to downloaded ruleset bundle...
760 local rs_url=""; # rule source URL temp var...
761
762 cd ${rdir}; # work in the runtime directory...
763 # chk to set verbosity on tar command...
764 # Note: exclude any "so_rules" directories...
765 if [ "${verbose_mode}" = "off" ]; then
766 tarArgs="--exclude so_rules -xzf";
767 else
768 tarArgs="--exclude so_rules -xvzf";
769 fi
770
771 #
772 # if not a "FILE://" URL type, skip to using the urlcache utility...
773 if echo ${rs} | /bin/grep -qi "^FILE:"; then
774 rs=${rs#file://} # strip off URI...
775 if [ ! -f ${rs} ]; then
776 echo;
777 echo "***ERROR*** Local rule source: \"${rs}\" does not exist...";
778 echo;
779 exit 60;
780 fi
781 pinfo;
782 pinfo "*** Unarchive local Snort rules in runtime rules directory: \"${rdir}\"...";
783 einfo "/bin/tar ${tarArgs} - < \"${rs}\"";
784 if ! /bin/tar ${tarArgs} - < "${rs}"; then
785 echo;
786 echo "***ERROR*** Could not uncompress and unarchive the local ruleset bundle:"
787 echo " \"${rs}\"...";
788 echo;
789 exit 61;
790 fi
791 else
792# use the 'urlcache' utility to download ruleset archive bundles...
793 rs_url="$(commentURLPasswd "${rs}")";
794 runURLCache="/usr/bin/urlcache --mode file --cache-dir ${SNORTRSCACHEDIR} --url ${rs} --verbose"
795 echo_runURLCache="/usr/bin/urlcache --mode file --cache-dir ${SNORTRSCACHEDIR} --url ${rs_url} --verbose"
796 pinfo;
797 pinfo "*** Using the \"urlcache\" utility to obtain the Snort ruleset archive bundle...";
798 pinfo "${echo_runURLCache}";
799 cr="/tmp/cache_results";
800 if ! eval ${runURLCache} >| ${cr} 2>&1; then
801 echo;
802 echo "***ERROR*** Problem fetching the Snort ruleset archive bundle from site:";
803 echo " \"${rs_url}\" using the \"urlcache\" utility...";
804 echo;
805 /bin/cat ${cr};
806 echo;
807 exit 62;
808 else
809 if /bin/grep -q '^\*\*\*CACHED_FILE:' ${cr}; then
810 rsFullPath=$(/bin/grep '^\*\*\*CACHED_FILE:' ${cr} | /bin/sed -e 's/^\*\*\*CACHED_FILE: \(.*\)/\1/');
811 if [ "${verbose_mode}" = "on" ]; then
812 /bin/cat ${cr}; # display results from urlcache if verbose enabled...
813 fi
814 /bin/rm -f ${cr}; # cleanup - remove temp results file...
815 else
816 echo;
817 echo "***ERROR*** The \"***CACHED_FILE: \" prefix was not found in";
818 echo " the results from running the \"urlcache\" utility..."
819 echo;
820 /bin/rm -f ${cr}; # cleanup - remove temp results file...
821 /bin/rm -fr ${SNORTRSCACHEDIR}; # cleanup - remove bad cache dir...
822 exit 63;
823 fi
824 fi
825 pinfo;
826 pinfo "*** Unarchive Snort rules in runtime rules directory: \"${rdir}\"...";
827 einfo "/bin/tar ${tarArgs} - < \"${rsFullPath}\"";
828 if ! /bin/tar ${tarArgs} - < "${rsFullPath}"; then
829 echo;
830 echo "***ERROR*** Could not uncompress and unarchive the ruleset bundle:"
831 echo " \"${rsFullPath}\"...";
832 echo;
833 /bin/rm -fr ${SNORTRSCACHEDIR}; # cleanup - remove bad cache dir...
834 exit 64;
835 fi
836 fi
837
838 #
839 # Sourcefire VRT Certified Rules packaging started putting configs
840 # under an "etc" directory rather than the "rules" directory.
841 # So, we will now check to relocate the configs back to the "rules"
842 # directory...
843 if [ -d "${rdir}/etc" ]; then
844 pinfo;
845 pinfo "*** Found Snort configuration directory: \"${rdir}/etc\"";
846 pinfo "*** Relocating all files under: \"${rdir}/etc\" to directory: \"${rdir}/rules\"";
847 /bin/mv -f ${rdir}/etc/* "${rdir}/rules";
848 /bin/rmdir "${rdir}/etc";
849 fi
850
851 return 0;
852}
853
854# ### processAdditionalSnortRules ### This function will download and process additional
855# snort rule sets...
856#
857# ***Assumption: Format of a sid-msg.map filename: "SRCNAME-sid-msg.map"...
858#
859processAdditionalSnortRules() {
860 local ars=""; # temp var...
861 # initialize signature identifier to message mapping building...
862 if [ -f "${pkgDir}/rules/sid-msg.map" ]; then
863 /bin/cp -fp "${pkgDir}/rules/sid-msg.map" "${pkgDir}/rules/sid-msg.map.built";
864 else
865 #
866 # initialize a sid file if not found...
867 /bin/touch "${pkgDir}/rules/sid-msg.map.built";
868 fi
869 if [ ${ARSI} -gt 0 ]; then # only process if additional rule sites were specified...
870# download and untar additional rules...
871 for ar in "${ARS[@]}"; do
872 ars="$(commentURLPasswd "${ar}")";
873 pinfo;
874 pinfo "*** Fetching additional Snort rule definitions from:";
875 einfo " \"${ars}\"";
876 wget_untar "${ar}" "${pkgDir}";
877 done
878# merge in additional rules signature to message mappings...
879 for sm in $(/usr/bin/find ${pkgDir}/rules -type f -name "sid-msg.map"); do
880 pinfo;
881 pinfo "*** Merging signature identifiers to message mappings file:";
882 pinfo " \"${sm}\" into";
883 pinfo " Snort signature identifiers to message mapping file:";
884 pinfo " \"${pkgDir}/rules/sid-msg.map.built\"";
885 /bin/cat ${sm} >> "${pkgDir}/rules/sid-msg.map.built";
886 done
887#
888# Uniquely numeric sort the "sid-msg.map" file...
889 pinfo;
890 pinfo "*** Uniquely sorting the Snort signature identifiers to message mapping file:";
891 pinfo " \"${pkgDir}/rules/sid-msg.map.built\"";
892 /bin/sort -un "${pkgDir}/rules/sid-msg.map.built" > "${pkgDir}/rules/sid-msg.map.sbuilt";
893 /bin/mv -f "${pkgDir}/rules/sid-msg.map.sbuilt" "${pkgDir}/rules/sid-msg.map.built";
894
895# add commented rule entry for all snort rules not found in: "snort.conf"...
896 cd ${pkgDir}/rules;
897 findLastIncludeLoc; # find last include line in "snort.conf", set SCLIL...
898 pinfo;
899 pinfo "*** Adding the following commented includes to: \"${pkgDir}/rules/snort.conf\":"
900 for r in *.rules; do
901 if ! /bin/grep -q "include \$RULE_PATH/${r}" "${pkgDir}/rules/snort.conf"; then
902 /bin/sed -i -e $SCLIL'i\
903# include $RULE_PATH/'${r} "${pkgDir}/rules/snort.conf";
904 pinfo "# include \$RULE_PATH/${r}";
905 ((SCLIL++)); # next SCLIL...
906 fi
907 done
908 fi
909
910 return 0;
911}
912
913# ### fetchUpdatedSnortRules ### This function will fetch and unarchive updated
914# snort rule sets for the selected runtime directory...
915#
916# fetchUpdatedSnortRules <runtime directory>
917#
918# ***Assumption: Format of a sid-msg.map filename: "SRCNAME-sid-msg.map"...
919#
920fetchUpdatedSnortRules() {
921 local srd=${1}; # set for better clarity within function...
922 local urs=""; # update rule source...
923
924# download and untar additional rules...
925 for ur in "${URS[@]}"; do
926 urs="$(commentURLPasswd "${ur}")";
927 pinfo;
928 pinfo "*** Fetching updated Snort rule definitions from:";
929 einfo " \"${urs}\"";
930 wget_untar "${ur}" "${srd}";
931 done
932
933#
934# make sure or root ownership after rule set downloads...
935 /bin/chown -R root:root "${srd}";
936
937# initialize signature identifier to message mapping building
938 if [ -f "${srd}/rules/sid-msg.map" ]; then
939 /bin/cp -fp "${srd}/rules/sid-msg.map" "${srd}/rules/sid-msg.map.built";
940 else
941 #
942 # initial a sid file if not found...
943 /bin/touch "${srd}/rules/sid-msg.map.built";
944 fi
945
946# merge in additional rules signature to message mappings...
947 for sm in $(/usr/bin/find ${srd}/rules -type f -name "sid-msg.map"); do
948 pinfo;
949 pinfo "*** Merging signature identifiers to message mappings file:";
950 pinfo " \"${sm}\" into"
951 pinfo " Snort signature identifiers to message mapping file:";
952 pinfo " ${srd}/rules/sid-msg.map.built..."
953 /bin/cat ${sm} >> "${srd}/rules/sid-msg.map.built";
954 done
955#
956# Uniquely numeric sort the "sid-msg.map" file...
957 pinfo;
958 pinfo "*** Uniquely sorting the Snort signature identifiers to message mapping file:";
959 pinfo " \"${pkgDir}/rules/sid-msg.map.built\"";
960 /bin/sort -un "${pkgDir}/rules/sid-msg.map.built" > "${pkgDir}/rules/sid-msg.map.sbuilt";
961 /bin/mv -f "${pkgDir}/rules/sid-msg.map.sbuilt" "${pkgDir}/rules/sid-msg.map.built";
962
963 return 0;
964}
965
966# ### updateSnortConfig ### This function will updated the selected snort
967# configuration directory...
968#
969# updateSnortConfig <runtime directory> <snort config directory>
970#
971updateSnortConfig() {
972 local srd=${1}; # set for better clarity within this function...
973 local scd=${2}; # set for better clarity within this function...
974
975# transfer new signature identifier message mapping file to the snort config dir...
976 /bin/cp -fp ${srd}/rules/sid-msg.map.built "${scd}/sid-msg.map"
977
978# add commented rules for all snort rules not found in: "snort.conf"...
979 cd ${srd}/rules;
980 findLastIncludeLoc "${scd}"; # find last include line in "snort.conf", set SCLIL...
981 pinfo;
982 pinfo "*** Adding the following commented includes to: \"${scd}/snort.conf\":"
983 for r in *.rules; do
984 if ! /bin/grep "include \$RULE_PATH/${r}" "${scd}/snort.conf" &> /dev/null; then
985 /bin/sed -i -e $SCLIL'i\
986# include $RULE_PATH/'${r} "${scd}/snort.conf";
987 pinfo "# include \$RULE_PATH/${r}";
988 ((SCLIL++)); # next SCLIL...
989 fi
990 done
991
992 return 0;
993}
994
995# ### processUpdatedSnortRules ### This function will download and process updated
996# snort rule sets...
997#
998# ***Assumption: Format of a sid-msg.map filename: "SRCNAME-sid-msg.map"...
999#
1000processUpdatedSnortRules() {
1001
1002# check for at least one rule site definition to update from...
1003 if [ ${#URS[@]} -eq 0 ]; then
1004 echo;
1005 echo "***ERROR*** There are no Snort rule sites defined to update from.";
1006 echo " Use the: \"-urs <URL: update rules site>\" option...";
1007 show_short_usage;
1008 exit 56;
1009 fi
1010
1011 local srd; # local Snort rules runtime dir for interface...
1012 local i=0; # tmp index...
1013 local SRDU=(); # Snort Runtime Directory Updated...
1014 local srdFound="false"; # set true if runtime directory was already updated...
1015
1016 if [ "${interfaceSpecified}" = "true" ]; then
1017# create a temporary ruleset cache directory...
1018 setupSnortRulesetCacheDir;
1019# update rules for selected interfaces...
1020 for si in ${SIL[@]}; do # cycle thru each selected interface...
1021 # derive the snort runtime rules dir...
1022 srd=$(/bin/grep "^var RULE_PATH" "/etc/snort_${si}/snort.conf" \
1023 | /bin/gawk -- '{print $3}');
1024# check for skipping previously updated shared runtime dirs...
1025 for u in ${SRDU[@]}; do
1026 if [ "$srd" = "$u" ]; then
1027 srdFound="true"; # set match occurred...
1028 fi
1029 done
1030 if [ "${srdFound}" = "false" ]; then # if runtime dir has not been updated...
1031 if [ -d "/etc/snort_${si}" ]; then
1032# fetch and unarchive updated Snort rules for the selected interface...
1033 fetchUpdatedSnortRules "$(/usr/bin/dirname ${srd})";
1034# update "snort.conf" for the selected interface...
1035 updateSnortConfig "$(/usr/bin/dirname ${srd})" "/etc/snort_${si}"
1036 SRDU[${i}]="${srd}"; # add that this SRD has been updated...
1037 ((i++)); # next index...
1038 else
1039 echo;
1040 echo "***ERROR*** The selected interface: \"${si}\" has no associated";
1041 echo " Snort configuration to update...";
1042 echo;
1043 exit 57;
1044 fi
1045 else # a shared updated runtime dir was found, skipping...
1046 pinfo;
1047 pinfo "*** A Snort instance associated with interface: \"${si}\" has a shared";
1048 pinfo " runtime directory: \"${srd}\", skipping rule set update...";
1049 pinfo;
1050 srdFound="false"; # reset found flag...
1051 fi
1052 done
1053 else # update rules for all configured snort instances...
1054
1055# check for existence of snort configurations...
1056 if [ ${#SCD[@]} -eq 0 ]; then
1057 echo;
1058 echo "***ERROR*** There are no Snort configuration instances to update...";
1059 echo;
1060 exit 58;
1061 fi
1062
1063# create a temporary ruleset cache directory...
1064 setupSnortRulesetCacheDir;
1065
1066# fetch and unarchive updated Snort rules for each Snort shared runtime directories...
1067 for ssd in "${SSD[@]}"; do
1068 fetchUpdatedSnortRules "$(/usr/bin/dirname ${ssd})";
1069 done
1070# update "snort.conf" for each Snort configured instance...
1071 local i=0; # initialize index for array...
1072 for scd in "${SCD[@]}"; do
1073 updateSnortConfig "$(/usr/bin/dirname ${SRD[${i}]})" "${SCD[${i}]}";
1074 ((i++)); # next index...
1075 done
1076 fi
1077
1078# display verbose update info...
1079 pinfo;
1080 pinfo "*** The following Snort rules sites were used for this update:";
1081 for ur in "${URS[@]}"; do
1082 einfo "$(commentURLPasswd "${ur}")";
1083 done
1084
1085# delete downloaded updated Snort ruleset definition archives (bundles)...
1086 teardownSnortRulesetCacheDir;
1087
1088 echo;
1089 echo "*** Snort rule set updates completed successfully...";
1090 echo;
1091
1092 return 0;
1093}
1094
1095# ### sendHUPSig ### This function sends a "SIGHUP" to a snort process...
1096#
1097# sendHUPSig <pid>
1098#
1099sendHUPSig() {
1100 snortPID="${1}";
1101 pinfo;
1102 pinfo "*** Try to reload the Snort instance associated with process ID: \"${snortPID}\"..."
1103 reloadSig="/bin/kill -s HUP ${snortPID}";
1104 if [ "${verbose_mode}" = "off" ]; then
1105 reloadSig="${reloadSig} &> /dev/null";
1106 fi
1107 pinfo "${reloadSig}";
1108 /usr/bin/logger -tsnort "###SNORT RELOAD### was sent to snort process: \"${snortPID}\"..."
1109 if ! eval ${reloadSig}; then
1110 echo;
1111 echo "***ERROR*** Could not reload (\"SIGHUP\") Snort instance PID: \"${snortPID}\"...";
1112 echo;
1113 exit 25;
1114 else
1115 echo;
1116 echo "*** The Snort instance with process ID: \"${snortPID}\" was reloaded...";
1117 fi
1118
1119 return 0;
1120}
1121
1122# ### reloadSnort ### This function finds one of more snort instances for
1123# reloading their configuration file...
1124#
1125reloadSnort() {
1126 local reloadWait=8; # sleep time between sequential reloads...
1127 if [ "${interfaceSpecified}" = "true" ]; then
1128 #
1129 # Reload snort config for selected interfaces...
1130 for si in ${SIL[@]}; do # cycle thru each selected interface...
1131 if /usr/bin/pgrep -f "/usr/sbin/snort -D -c /etc/snort_${si}/snort.conf" &> "/dev/null"; then
1132 snortPID="$(/usr/bin/pgrep -f "/usr/sbin/snort -D -c /etc/snort_${si}/snort.conf")";
1133 sendHUPSig "${snortPID}";
1134 pinfo "Waiting ${reloadWait} seconds before next reload - needed for proper log file ordering...";
1135 /bin/sleep ${reloadWait}; # allow for proper order in log file...
1136 else
1137 echo;
1138 echo "*** There is no running Snort instance to \"reload\" for associated";
1139 echo " network interface: \"${si}\"...";
1140 echo;
1141 fi
1142 done
1143 echo;
1144 else # reload stats for all snort instances...
1145 #
1146 # chk to see if there are any running snort instances...
1147 if /usr/bin/pgrep -f "/usr/sbin/snort -D -c /etc/snort_" &> /dev/null; then
1148 /usr/bin/pgrep -f "/usr/sbin/snort -D -c /etc/snort_" | while read snortPID; do
1149 sendHUPSig "${snortPID}"; # reload for this snort process...
1150 pinfo "Waiting ${reloadWait} seconds before next reload - needed for proper log file ordering...";
1151 /bin/sleep ${reloadWait}; # allow for proper order in log file...
1152 done
1153 else
1154 echo;
1155 echo "*** There are no running Snort instances to \"reload\"...";
1156 echo;
1157 fi
1158 echo;
1159 fi
1160
1161 return 0;
1162}
1163
1164# ### sendUSR1Sig ### This function sends a "SIGUSR1" to a snort process...
1165#
1166# sendUSR1Sig <pid>
1167#
1168sendUSR1Sig() {
1169 snortPID="${1}";
1170 pinfo;
1171 pinfo "*** Try to dump statistics for Snort instance associated with process ID: \"${snortPID}\"..."
1172 dumpSig="/bin/kill -s USR1 ${snortPID}";
1173 if [ "${verbose_mode}" = "off" ]; then
1174 dumpSig="${dumpSig} &> /dev/null";
1175 fi
1176 pinfo "${dumpSig}";
1177 /usr/bin/logger -tsnort "###SNORT DUMP### was sent to snort process: \"${snortPID}\"..."
1178 if ! eval ${dumpSig}; then
1179 echo;
1180 echo "***ERROR*** Could not dump (\"SIGUSR1\") statistics for Snort instance PID: \"${snortPID}\"...";
1181 echo;
1182 exit 26;
1183 else
1184 echo;
1185 echo "*** The Snort instance with process: \"${snortPID}\" dumped statistics...";
1186 fi
1187
1188 return 0;
1189}
1190
1191# ### dumpSnort ### This function finds one of more snort instances to
1192# dump their statistical information...
1193#
1194dumpSnort() {
1195 local dumpWait=2; # wait time between sequential dumps...
1196 if [ "${interfaceSpecified}" = "true" ]; then
1197 # dump stats for the selected interfaces...
1198 for si in ${SIL[@]}; do # cycle thru each selected interface...
1199 if /bin/ps -ef | /bin/grep snort_${si} | /bin/grep -v "grep" &> /dev/null; then
1200 snortPID="$(/usr/bin/pgrep -f "/usr/sbin/snort -D -c /etc/snort_${si}/snort.conf")";
1201 pinfo;
1202 sendUSR1Sig "${snortPID}";
1203 pinfo "Waiting ${dumpWait} seconds before next dump - needed for proper ordering in log file...";
1204 /bin/sleep ${dumpWait}; # allow for proper order in log file...
1205 else
1206 echo;
1207 echo "*** There is no running Snort instance to \"dump\" statistics for associated";
1208 echo " network interface: \"${si}\"...";
1209 fi
1210 done
1211 echo;
1212 else # dump stats for all snort instances...
1213 #
1214 # chk to see if there are any running snort instances...
1215 if /usr/bin/pgrep -f "/usr/sbin/snort -D -c /etc/snort_" &> /dev/null; then
1216 /usr/bin/pgrep -f "/usr/sbin/snort -D -c /etc/snort_" | while read snortPID; do
1217 sendUSR1Sig "${snortPID}"; # dump stats for this snort process...
1218 pinfo "Waiting ${dumpWait} seconds before next dump - needed for proper ordering in log file...";
1219 /bin/sleep ${dumpWait}; # allow for proper order in log file...
1220 done
1221 else
1222 echo;
1223 echo "*** There are no running Snort instances to \"dump\" statistics...";
1224 echo;
1225 fi
1226 echo;
1227 fi
1228
1229 return 0;
1230}
1231
1232# ### setStartupFlagSnortConf <interface>
1233#
1234# This function will set the startup flag in a snort
1235# configuration file and in the barnyard2 configuration file
1236# for a specific network interface...
1237#
1238setStartupFlagSnortConf() {
1239 local net_int=${1};
1240
1241 #
1242 # Does a snort conf file exit?
1243 if [ ! -r "/etc/snort_${net_int}/snort.conf" ]; then
1244 echo;
1245 echo "***WARNING*** A Snort configuration file does not exist for this interface: \"${net_int}\"";
1246 echo;
1247 return 35;
1248 fi
1249
1250 #
1251 # Does a barnyard2 conf file exit?
1252 if [ ! -r "/etc/snort_${net_int}/barnyard2.conf" ]; then
1253 echo;
1254 echo "***WARNING*** A Barnyard2 configuration file does not exist for this interface: \"${net_int}\"";
1255 echo;
1256 return 37;
1257 fi
1258
1259 #
1260 # Has a flag already be set (Snort Conf)?
1261 if /bin/grep -q "^# NST: Startup snort:" "/etc/snort_${net_int}/snort.conf"; then
1262 #
1263 # Modify the current startup flag setting with new value..
1264 #
1265 # Be nice to user, if the word looks like 'disabled' then choose 'disabled' otherwise
1266 # everything else is 'enabled'...
1267 if echo "${startupFlag}" | grep -iq "disable"; then
1268 /bin/sed -i -e 's/^# NST: Startup snort: .*$/# NST: Startup snort: disabled/' \
1269 "/etc/snort_${net_int}/snort.conf";
1270 else
1271 /bin/sed -i -e 's/^# NST: Startup snort: .*$/# NST: Startup snort: enabled/' \
1272 "/etc/snort_${net_int}/snort.conf";
1273 fi
1274 else
1275 #
1276 # No startup flag has ever been set, add a startup flag to end of the conf file...
1277 if echo "${startupFlag}" | grep -iq "disable"; then
1278 echo "# NST: Startup snort: disabled" >> "/etc/snort_${net_int}/snort.conf";
1279 else
1280 echo "# NST: Startup snort: enabled" >> "/etc/snort_${net_int}/snort.conf";
1281 fi
1282 fi
1283
1284 #
1285 # Has a flag already be set (Barnyard2 Conf)?
1286 if /bin/grep -q "^# NST: Startup barnyard2:" "/etc/snort_${net_int}/barnyard2.conf"; then
1287 #
1288 # Modify the current startup flag setting with new value..
1289 #
1290 # Be nice to user, if the word looks like 'disabled' then choose 'disabled' otherwise
1291 # everything else is 'enabled'...
1292 if echo "${startupFlag}" | grep -iq "disable"; then
1293 /bin/sed -i -e 's/^# NST: Startup barnyard2: .*$/# NST: Startup barnyard2: disabled/' \
1294 "/etc/snort_${net_int}/barnyard2.conf";
1295 else
1296 /bin/sed -i -e 's/^# NST: Startup barnyard2: .*$/# NST: Startup barnyard2: enabled/' \
1297 "/etc/snort_${net_int}/barnyard2.conf";
1298 fi
1299 else
1300 #
1301 # No startup flag has ever been set, add a startup flag to end of the conf file...
1302 if echo "${startupFlag}" | grep -iq "disable"; then
1303 echo "# NST: Startup barnyard2: disabled" >> "/etc/snort_${net_int}/barnyard2.conf";
1304 else
1305 echo "# NST: Startup barnyard2: enabled" >> "/etc/snort_${net_int}/barnyard2.conf";
1306 fi
1307 fi
1308
1309 #
1310 # If verbose, check setting and print it out...
1311 if [ "${verbose_mode}" = "on" ]; then
1312 if /bin/grep -q "^# NST: Startup snort: disabled" "/etc/snort_${net_int}/snort.conf"; then
1313 printf "The Snort Startup flag is currently set to: \"Disabled\" for network interface: \"${net_int}\"\n";
1314 else
1315 printf "The Snort Startup flag is currently set to: \"Enabled\" for network interface: \"${net_int}\"\n";
1316 fi
1317 if /bin/grep -q "^# NST: Startup barnyard2: disabled" "/etc/snort_${net_int}/barnyard2.conf"; then
1318 printf "The Barnyard2 Startup flag is currently set to: \"Disabled\" for network interface: \"${net_int}\"\n";
1319 else
1320 printf "The Barnyard2 Startup flag is currently set to: \"Enabled\" for network interface: \"${net_int}\"\n";
1321 fi
1322 fi
1323
1324 return 0;
1325}
1326
1327# ### listSnortStatus ### This function lists the status of one of more snort instances...
1328#
1329listSnortStatus() {
1330 printf "\n";
1331 # list snort status for one selected interface...
1332 if [ \( "${interfaceSpecified}" = "true" \) -a \( ${#SIL[@]} -eq 1 \) ]; then
1333# snort config dir...
1334 printf "*** Snort Configuration Directory For \"${SIL[0]}\":\n";
1335 printf "*** ===== ============= ========= === =======\n";
1336 if [ -d "/etc/snort_${SIL[0]}" ]; then
1337 printf "/etc/snort_${SIL[0]}\n";
1338 printf "\n";
1339
1340# snort options...
1341 printf "*** Snort Options For \"${SIL[0]}\":\n";
1342 printf "*** ===== ======= === =======\n";
1343 if [ -r "/etc/snort_${SIL[0]}/${snort_options_filename}" ]; then
1344 printf -- "$(/bin/cat "/etc/snort_${SIL[0]}/${snort_options_filename}")\n";
1345 else
1346 printf "N/A\n";
1347 fi
1348 printf "\n";
1349
1350# unified2 info...
1351 local u2Info=""; # unified2 info...
1352 u2Info="$(/bin/grep "^output unified2:" /etc/snort_${SIL[0]}/snort.conf \
1353 2> /dev/null | /bin/gawk -- '{print $0}')";
1354 printf "*** Snort Unified2 Logging Information For \"${SIL[0]}\":\n";
1355 printf "*** ===== ======== ======= =========== === =======\n";
1356 printf "${u2Info}\n";
1357 printf "\n";
1358
1359# database info...
1360 local dbInfo=""; # database info...
1361 dbInfo="$(/bin/grep "^output database" /etc/snort_${SIL[0]}/barnyard2.conf \
1362 2> /dev/null | /bin/gawk -- '{print $8" "$9" "$10" "$11}')";
1363 printf "*** Barnyard2 Database Connectivity Information For \"${SIL[0]}\":\n";
1364 printf "*** ========= ======== ============ =========== === =======\n";
1365 printf "${dbInfo}\n";
1366 printf "\n";
1367
1368# startup flag (Snort)...
1369 printf "*** Snort Startup Flag:\n";
1370 printf "*** ===== ======= =====\n";
1371 if /bin/grep -q "^# NST: Startup snort: disabled" "/etc/snort_${SIL[0]}/snort.conf"; then
1372 printf "${SIL[0]}:\tDisabled\n";
1373 else
1374 printf "${SIL[0]}:\tEnabled\n";
1375 fi
1376 printf "\n";
1377
1378# startup flag (Barnyard2)...
1379 printf "*** Barnyard2 Startup Flag:\n";
1380 printf "*** ========= ======= =====\n";
1381 if /bin/grep -q "^# NST: Startup barnyard2: disabled" "/etc/snort_${SIL[0]}/barnyard2.conf"; then
1382 printf "${SIL[0]}:\tDisabled\n";
1383 else
1384 printf "${SIL[0]}:\tEnabled\n";
1385 fi
1386 printf "\n";
1387
1388# snort runtime dir...
1389 printf "*** Snort Runtime Directory For \"${SIL[0]}\":\n";
1390 printf "*** ===== ======= ========= === =======\n";
1391 snortRDirInt="$(/bin/grep "^var RULE_PATH" /etc/snort_${SIL[0]}/snort.conf \
1392 2> /dev/null | /bin/gawk -- '{print $3}')";
1393# strip off "rules" directory name...
1394 snortRDirInt="$(/usr/bin/dirname "${snortRDirInt}")";
1395 printf "${snortRDirInt}\n";
1396 else
1397 printf "### NO ### Snort configuration exists for this interface!!!\n";
1398 printf "\n";
1399 printf "*** Snort Unified2 Logging Information \"${SIL[0]}\":\n";
1400 printf "*** ===== ======== ======= =========== =======\n";
1401 printf "### NO ### Snort Unified2 logging information exist!!!\n";
1402 printf "\n";
1403 printf "*** Barnyard2 Database Connectivity Information \"${SIL[0]}\":\n";
1404 printf "*** ========= ======== ============ =========== =======\n";
1405 printf "### NO ### Barnyard2 database information exist!!!\n";
1406 printf "\n";
1407 printf "*** Snort Startup Flag \"${SIL[0]}\":\n";
1408 printf "*** ===== ======= ==== =======\n";
1409 printf "### NO ### Snort startup flag exist!!!\n";
1410 printf "\n";
1411 printf "*** Barnyard2 Startup Flag \"${SIL[0]}\":\n";
1412 printf "*** ========= ======= ==== =======\n";
1413 printf "### NO ### Barnyard2 startup flag exist!!!\n";
1414 printf "\n";
1415 printf "*** Snort Runtime Directory For \"${SIL[0]}\":\n";
1416 printf "*** ===== ======= ========= === =======\n";
1417 printf "### NO ### Snort runtime exists for this interface!!!\n";
1418 fi
1419
1420# snort.service and barnyard2.service systemctl...
1421 printf "\n";
1422 printf "*** systemctl Status For Snort/Barnyard2 Daemons:\n";
1423 printf "*** ========= ====== === =============== ========\n";
1424 /bin/systemctl status snort.service barnyard2.service;
1425
1426# snort/barnyard2 process...
1427 printf "\n";
1428 printf "*** Snort/Barnyard2 Process For \"${SIL[0]}\":\n";
1429 printf "*** =============== ======= === =======\n";
1430 if /bin/ps -ef | /bin/grep snort_${SIL[0]} | /bin/grep -v "grep" &> /dev/null; then
1431 snortProcess=$(/bin/ps -ef | /bin/grep snort_${SIL[0]} | /bin/grep -v "grep");
1432 printf "${snortProcess}\n";
1433 else
1434 printf "### NO ### Snort/Barnyard2 process exists for this interface!!!\n";
1435 fi
1436
1437# interface ifconfig...
1438 printf "\n";
1439 printf "*** ifconfig For \"${SIL[0]}\":\n";
1440 printf "*** ======== === =======\n";
1441 if /sbin/ifconfig ${SIL[0]} &> /dev/null; then
1442 /sbin/ifconfig ${SIL[0]};
1443 else
1444 printf "### NO ### device is found for this interface!!!\n";
1445 printf "\n";
1446 fi
1447
1448 else # list snort status for selected or all configured interfaces....
1449
1450# snort config dirs...
1451 printf "*** Snort Configuration Directories:\n";
1452 printf "*** ===== ============= ============\n";
1453
1454 local i=0; # tmp index var...
1455
1456 if [ ${#SCD[@]} -gt 0 ]; then
1457 if [ ${#SIL[@]} -gt 1 ]; then # print only for selected interfaces...
1458 for si in ${SIL[@]}; do
1459 printf "${si}:\t/etc/snort_${si}\n";
1460 done
1461 else # print snort config dirs all snort instances...
1462 i=0; # init index...
1463 for c in ${SCD[@]}; do
1464 printf "${CIL[${i}]}:\t${c}\n";
1465 ((i++)); # next snort instance...
1466 done
1467 fi
1468
1469# snort options...
1470 printf "\n";
1471 printf "*** Snort Options:\n";
1472 printf "*** ===== ========\n";
1473 if [ ${#SIL[@]} -gt 1 ]; then # print only for selected interfaces...
1474 for si in ${SIL[@]}; do
1475 if [ -r "/etc/snort_${si}/${snort_options_filename}" ]; then
1476 printf -- "$(/bin/cat "/etc/snort_${si}/${snort_options_filename}")\n";
1477 else
1478 printf "N/A\n";
1479 fi
1480 done
1481 else # print snort options for all snort instances...
1482 i=0; # init index...
1483 for c in ${SCD[@]}; do
1484 if [ -r "${c}/${snort_options_filename}" ]; then
1485 printf "${CIL[${i}]}:\t$(/bin/cat "${c}/${snort_options_filename}")\n";
1486 else
1487 printf "${CIL[${i}]}:\tN/A\n";
1488 fi
1489 ((i++)); # next snort instance...
1490 done
1491 fi
1492
1493# unified2 info...
1494 local u2Info=""; # unified2 info...
1495 printf "\n";
1496 printf "*** Snort Unified2 Logging Information:\n";
1497 printf "*** ===== ======== ======= ============\n";
1498 if [ ${#SIL[@]} -gt 1 ]; then # print only for selected interfaces...
1499 for si in ${SIL[@]}; do
1500 u2Info="$(/bin/grep "^output unified2:" "/etc/snort_${si}/snort.conf" \
1501 2> /dev/null | /bin/gawk -- '{print $0}')";
1502 printf "${si}:\t${u2Info}\n";
1503 done
1504 else # print dbinfo for all snort instances...
1505 i=0; # init index...
1506 for c in ${SCD[@]}; do
1507 u2Info="$(/bin/grep "^output unified2" "${c}/snort.conf" \
1508 2> /dev/null | /bin/gawk -- '{print $0}')";
1509 printf "${CIL[${i}]}:\t${u2Info}\n";
1510 ((i++)); # next snort instance...
1511 done
1512 fi
1513
1514# database info...
1515 local dbInfo=""; # database info...
1516 printf "\n";
1517 printf "*** Barnyard2 Database Connectivity Information:\n";
1518 printf "*** ========= ======== ============ ============\n";
1519 if [ ${#SIL[@]} -gt 1 ]; then # print only for selected interfaces...
1520 for si in ${SIL[@]}; do
1521 dbInfo="$(/bin/grep "^output database" "/etc/snort_${si}/barnyard2.conf" \
1522 2> /dev/null | /bin/gawk -- '{print $8" "$9" "$10" "$11}')";
1523 printf "${si}:\t${dbInfo}\n";
1524 done
1525 else # print dbinfo for all snort instances...
1526 i=0; # init index...
1527 for c in ${SCD[@]}; do
1528 dbInfo="$(/bin/grep "^output database" "${c}/barnyard2.conf" \
1529 2> /dev/null | /bin/gawk -- '{print $8" "$9" "$10" "$11}')";
1530 printf "${CIL[${i}]}:\t${dbInfo}\n";
1531 ((i++)); # next snort instance...
1532 done
1533 fi
1534
1535# startup flag (Snort)...
1536 local startupFlag=""; # startup flag info...
1537 printf "\n";
1538 printf "*** Snort Startup Flag:\n";
1539 printf "*** ===== ======= =====\n";
1540 if [ ${#SIL[@]} -gt 1 ]; then # print only for selected interfaces...
1541 for si in ${SIL[@]}; do
1542 if /bin/grep -q "^# NST: Startup snort: disabled" "/etc/snort_${si}/snort.conf"; then
1543 printf "${si}:\tDisabled\n";
1544 else
1545 printf "${si}:\tEnabled\n";
1546 fi
1547 done
1548 else # print startup flag info for all snort instances...
1549 i=0; # init index...
1550 for c in ${SCD[@]}; do
1551 if /bin/grep -q "^# NST: Startup snort: disabled" "${c}/snort.conf"; then
1552 printf "${CIL[${i}]}:\tDisabled\n";
1553 else
1554 printf "${CIL[${i}]}:\tEnabled\n";
1555 fi
1556 ((i++)); # next snort instance...
1557 done
1558 fi
1559
1560# startup flag (Barnyard2)...
1561 local startupFlag=""; # startup flag info...
1562 printf "\n";
1563 printf "*** Barnyard2 Startup Flag:\n";
1564 printf "*** ========= ======= =====\n";
1565 if [ ${#SIL[@]} -gt 1 ]; then # print only for selected interfaces...
1566 for si in ${SIL[@]}; do
1567 if /bin/grep -q "^# NST: Startup barnyard2: disabled" "/etc/snort_${si}/barnyard2.conf"; then
1568 printf "${si}:\tDisabled\n";
1569 else
1570 printf "${si}:\tEnabled\n";
1571 fi
1572 done
1573 else # print startup flag info for all barnyard2 instances...
1574 i=0; # init index...
1575 for c in ${SCD[@]}; do
1576 if /bin/grep -q "^# NST: Startup barnyard2: disabled" "${c}/barnyard2.conf"; then
1577 printf "${CIL[${i}]}:\tDisabled\n";
1578 else
1579 printf "${CIL[${i}]}:\tEnabled\n";
1580 fi
1581 ((i++)); # next snort instance...
1582 done
1583 fi
1584
1585# snort.service and barnyard2.service systemctl...
1586 printf "\n";
1587 printf "*** systemctl Status For Snort/Barnyard2 Daemons:\n";
1588 printf "*** ========= ====== === =============== ========\n";
1589 /bin/systemctl status snort.service barnyard2.service;
1590
1591# snort runtime dirs...
1592 local rd; # tmp runtime dir var....
1593 printf "\n";
1594 printf "*** Snort Runtime Directories:\n";
1595 printf "*** ===== ======= ============\n";
1596 if [ ${#SIL[@]} -gt 1 ]; then # print only for selected interfaces...
1597 for si in ${SIL[@]}; do
1598 rd=$(/bin/grep "^var RULE_PATH" "/etc/snort_${si}/snort.conf" | /bin/gawk -- '{print $3}');
1599 printf "${si}:\t${rd}\n";
1600 done
1601 else # print snort runtime dirs all snort instances...
1602 i=0; # init index...
1603 for r in ${SRD[@]}; do
1604 printf "${CIL[${i}]}:\t${r}\n";
1605 ((i++)); # next snort instance...
1606 done
1607 fi
1608 else
1609 printf "### NO ### Snort configuration directories exist!!!\n";
1610 printf "\n";
1611 printf "*** Snort Unified2 Logging Information:\n";
1612 printf "*** ===== ======== ======= ============\n";
1613 printf "### NO ### Snort Unified2 logging information exist!!!\n";
1614 printf "\n";
1615 printf "*** Barnyard2 Database Connectivity Information:\n";
1616 printf "*** ========= ======== ============ ============\n";
1617 printf "### NO ### Barnyard2 database information exist!!!\n";
1618 printf "\n";
1619 printf "*** Snort Startup Flag:\n";
1620 printf "*** ===== ======= =====\n";
1621 printf "### NO ### Snort startup flag exist!!!\n";
1622 printf "\n";
1623 printf "*** Barnyard2 Startup Flag:\n";
1624 printf "*** ========= ======= =====\n";
1625 printf "### NO ### Barnyard2 startup flag exist!!!\n";
1626 printf "\n";
1627 printf "*** Snort Runtime Directories:\n";
1628 printf "*** ===== ======= ============\n";
1629 printf "### NO ### Snort runtime directories exist!!!\n";
1630 fi
1631
1632# snort.service and barnyard2.service systemctl...
1633 printf "\n";
1634 printf "*** systemctl Status For Snort/Barnyard2 Daemons:\n";
1635 printf "*** ========= ====== === =============== ========\n";
1636 /bin/systemctl status snort.service barnyard2.service;
1637
1638# snort processes...
1639 processFound="false"; # set true if a snort process found...
1640 printf "\n";
1641 printf "*** Running Snort Processes:\n";
1642 printf "*** ======= ===== ==========\n";
1643 if [ ${#SIL[@]} -gt 1 ]; then # print only for selected interfaces...
1644 for si in ${SIL[@]}; do
1645 if /bin/ps -ef | /bin/grep "snort_${si}" | /bin/grep -v "grep" &> /dev/null; then
1646 local snortProcess=$(/bin/ps -ef | /bin/grep "snort_${si}" | /bin/grep -v "grep");
1647 printf "${snortProcess}\n";
1648 processFound="true";
1649 fi
1650 done
1651 if [ "${processFound}" = "false" ]; then
1652 printf "### NO ### Snort processes exist!!!\n";
1653 fi
1654 else # print all snort processes found...
1655 if /bin/ps -ef | /bin/grep "snort_" | /bin/grep -v "grep" &> /dev/null; then
1656 local snortProcesses=$(/bin/ps -ef | /bin/grep "snort_" | /bin/grep -v "grep");
1657 printf "${snortProcesses}\n";
1658 else
1659 printf "### NO ### Snort processes exist!!!\n";
1660 fi
1661 fi
1662
1663# interface ifconfig...
1664 printf "\n";
1665 printf "*** ifconfig For Configured Snort Instances:\n";
1666 printf "*** ======== === ========== ===== ==========\n";
1667 if [ ${#CIL[@]} -gt 0 ]; then
1668 if [ ${#SIL[@]} -gt 1 ]; then # print only for selected interfaces...
1669 for i in ${SIL[@]}; do
1670 if /sbin/ifconfig ${i} &> /dev/null; then
1671 /sbin/ifconfig ${i};
1672 else
1673 printf "### NO ### device is found for this interface: \"${i}\"!!!\n";
1674 fi
1675 done
1676 else
1677 for i in ${CIL[@]}; do
1678 if /sbin/ifconfig ${i} &> /dev/null; then
1679 /sbin/ifconfig ${i};
1680 else
1681 printf "### NO ### device is found for this interface: \"${i}\"!!!\n";
1682 fi
1683 done
1684 fi
1685 else
1686 printf "### NO ### configured interfaces for snort!!!\n";
1687 printf "\n";
1688 fi
1689 fi
1690 printf "*** MySQL Running Process Information:\n";
1691 printf "*** ===== ======= ======= ============\n";
1692 if /bin/ps -ef | /bin/grep mysql | /bin/grep -v "grep" &> /dev/null; then
1693 mysql=$(/bin/ps -ef | /bin/grep mysql | /bin/grep -v "grep");
1694 printf "${mysql}\n";
1695 else
1696 printf "### NO ### MySQL process running!!!\n";
1697 fi
1698 printf "\n";
1699
1700 return 0;
1701}
1702
1703# ### disableSnortInstance ### This function will disable and kill one or more running
1704# snort/barnyard2 instances...
1705#
1706disableSnortInstance() {
1707 #
1708 # Set Snort/Barnyard2 startup flags to 'Disabled'
1709 startupFlag="disabled";
1710
1711 pinfo "Current Running Snort/Barnyard2 Processes:";
1712 pinfo "======= ======= =============== ==========";
1713 if [ "${verbose_mode}" = "on" ]; then
1714 /bin/systemctl status snort.service barnyard2.service;
1715 fi
1716 pinfo;
1717
1718 if [ "${interfaceSpecified}" = "true" ]; then
1719 #
1720 # Disable snort instance for all selected interfaces...
1721 for si in ${SIL[@]}; do
1722 #
1723 # First disable the Snort/Barnyard2 startup flag...
1724 setStartupFlagSnortConf "${si}";
1725 done
1726 else
1727 #
1728 # Disable and all snort/barnyard2 instances...
1729 for d in $(/usr/bin/find /etc -type d -name "snort_*" 2> /dev/null); do
1730 local net_int="${d#*_}";
1731 setStartupFlagSnortConf "${net_int}";
1732 done
1733 fi
1734
1735 #
1736 # Now restart the remaining enabled and configured snort/barnyard2 instances...
1737 pinfo;
1738 pinfo "*** Using systemctl to restart the remaining configured and enabled Snort/Barnyard2 instances...";
1739 /bin/systemctl restart snort.service barnyard2.service;
1740 if [ "${verbose_mode}" = "on" ]; then
1741 /bin/systemctl status snort.service barnyard2.service;
1742 fi
1743
1744 return 0;
1745}
1746
1747# ### eraseSnortInstance ### This function will erase one or more snort runtime
1748# data directories and configuration files.
1749eraseSnortInstance() {
1750 if [ "${interfaceSpecified}" = "true" ]; then
1751# erase snort runtime/config dirs for selected interfaces...
1752 for si in ${SIL[@]}; do
1753
1754# derive path to the current snort runtime directory...
1755 local snortRDirInt="";
1756 snortRDirInt="$(/bin/grep "^var RULE_PATH" "/etc/snort_${si}/snort.conf" \
1757 2> /dev/null | /bin/gawk -- '{print $3}')";
1758# check for nonexistent snort configuration instance for selected interface...
1759 if [ -z "${snortRDirInt}" ]; then
1760 if [ -d "/etc/snort_${si}" ]; then
1761 pinfo;
1762 pinfo "*** Erasing snort configuration directory: \"/etc/snort_${si}\" for";
1763 pinfo " selected interface: \"${si}\"...";
1764 pinfo;
1765 /bin/rm -rf "/etc/snort_${si}";
1766 if [ "${verbose_mode}" = "off" ]; then # general msg for non-verbose mode...
1767 echo;
1768 echo "*** The snort configuration directory found for selected"
1769 echo " interface: \"${si}\" was erased..."
1770 echo;
1771 fi
1772 return 0;
1773 else
1774 echo;
1775 echo "*** A snort runtime/configuration directory was not found to erase for"
1776 echo " selected network interface: \"${si}\"..."
1777 echo;
1778 return 1;
1779 fi
1780 fi
1781
1782 local snortConfRDirPairs=""; # ${1}="snort cfg dir", ${2}="snort runtime dir" ...
1783 for d in $(/usr/bin/find /etc -type d -name "snort_*" 2> /dev/null); do
1784 # create snort config and runtime directory pairs...
1785 snortConfRDirPairs="${snortConfRDirPairs} ${d} $(/bin/grep "^var RULE_PATH" "${d}/snort.conf" | \
1786 /bin/gawk -- '{print $3}')"
1787 done
1788
1789# loop thru all configured snort interfaces to see if there are shared runtime directory resources...
1790#
1791# ***Note: A snort runtime directory for the selected network interface will not be erase if other
1792# configured snort instances share the same runtime directory...
1793#
1794 local snortSameRDirCnt=0; # cnt of same rdir resource sharing...
1795 local snortSameRDirList=""; # list of snort cfg dirs sharing same rdir...
1796 set ${snortConfRDirPairs}
1797 while [ ${#} -gt 0 ]; do
1798 if [ "${2}" = "${snortRDirInt}" ]; then
1799 (( snortSameRDirCnt = snortSameRDirCnt + 1)); # inc same rdir resource count...
1800 snortSameRDirList="${snortSameRDirList} ${1}";
1801 fi
1802 shift 2; # process next pair...
1803 done
1804 # strip off "rules" directory name...
1805 snortRDirInt="$(/usr/bin/dirname "${snortRDirInt}")";
1806
1807 if [ ${snortSameRDirCnt} -gt 1 ]; then # if cnt > 1 rdir resource shared...
1808 local intName # derived network interface name for a snort instance...
1809 pinfo;
1810 pinfo "*** Snort runtime directory: \"${snortRDirInt}\" for selected interface: \"${si}\"";
1811 pinfo " can not be erased. This is a shared resource with the following Snort instance(s):";
1812 for s in ${snortSameRDirList}; do # display same rdir resource list...
1813 if [ "${s}" != "/etc/snort_${si}" ]; then # don't display same...
1814 intName="${s#*_}";
1815 pinfo " Snort instance on interface: \"${intName}\"";
1816 fi
1817 done
1818 else # resource is not shared, ok to erase rdir for interface...
1819 if [ -d ${snortRDirInt} ]; then
1820 pinfo;
1821 pinfo "*** Erasing snort runtime directory: \"${snortRDirInt}\" for";
1822 pinfo " selected interface: \"${si}\"...";
1823 pinfo;
1824 /bin/rm -rf "${snortRDirInt}";
1825 else
1826 echo "*** Snort runtime directory: \"${snortRDirInt}\" NOT FOUND for selected interface: \"${si}\"!!!";
1827 fi
1828 fi
1829
1830 if [ -d "/etc/snort_${si}" ]; then # now erase snort config dir for interface...
1831 pinfo;
1832 pinfo "*** Erasing snort configuration directory: \"/etc/snort_${si}\" for";
1833 pinfo " selected interface: \"${si}\"...";
1834 pinfo;
1835 /bin/rm -rf "/etc/snort_${si}";
1836 fi
1837
1838 #
1839 # Remove all interface definitions for this sensor interface
1840 # in the barnyard2 systemd service conf file: "/etc/sysconfig/barnyard2"
1841 if [ -f "/etc/sysconfig/barnyard2" ]; then
1842 #
1843 # Source in the Barnyard2 systemd service conf file...
1844 source "/etc/sysconfig/barnyard2";
1845 #
1846 # Recalc the 'INTERFACES' variable...
1847 if [ -z "${INTERFACES}" ]; then
1848 INTERFACES="";
1849 else
1850 #
1851 # Remove the snort sensor network interface name from 'INTERFACES'...
1852 local nint=$(for i in ${INTERFACES}; do
1853 if ! (echo ${i} | /bin/grep -q "^${si}$";); then
1854 printf "${i} ";
1855 fi
1856 done;);
1857 INTERFACES="$(echo ${nint};)";
1858 fi
1859 #
1860 # Set the 'INTERFACES' var...
1861 /bin/sed -i -e 's,^[#]*INTERFACES=.*$,INTERFACES="'"${INTERFACES}"'",' \
1862 "/etc/sysconfig/barnyard2";
1863 #
1864 # Remove any previous Barnyard2 var definitions for this snort sensor interface...
1865 /bin/sed -i -e "/^# NSTBEGIN: ${si}$/,/^# NSTEND: ${si}$/d" \
1866 "/etc/sysconfig/barnyard2";
1867 pinfo;
1868 pinfo "*** Removing any snort sensor interface: \"${si}\" reference from the";
1869 pinfo " barnyard2 systemd service conf file: \"/etc/sysconfig/barnyard2\"";
1870 pinfo;
1871 fi
1872
1873 if [ "${verbose_mode}" = "off" ]; then # general msg for non-verbose mode...
1874 echo;
1875 echo "*** The snort runtime/configuration directories found for selected"
1876 echo " interface: \"${si}\" were erased..."
1877 echo;
1878 fi
1879 done
1880 else # erase all snort runtime and config data...
1881
1882 if [ \( ${#SRD[@]} -eq 0 \) -a \( "${#SCD[@]}" -eq 0 \) ]; then
1883 echo;
1884 echo "*** There were no snort runtime/configuration directories found to erase...";
1885 echo;
1886 return 2;
1887 fi
1888
1889 # strip off "rules" directory name...
1890 snortRDirList="$(for d in ${SRD[@]}; do /usr/bin/dirname "${d}"; done)";
1891
1892 local processList="${snortRDirList}";
1893
1894 pinfo;
1895 pinfo "List Of Snort Runtime Directories To Erase:";
1896 pinfo "==== == ===== ======= =========== == ======";
1897
1898 # loop thru and erase all snort config directories...
1899 while [ -n "${processList}" ]; do
1900 set ${processList};
1901 # erase snort runtime directory...
1902 if [ -d ${1} ]; then
1903 pinfo "Erasing directory: \"${1}\"";
1904 /bin/rm -rf "${1}";
1905 else
1906 echo "*** Snort runtime directory: \"${1}\" NOT FOUND!!!";
1907 fi
1908 # update snort runtime directories to process - remove last runtime dir from list...
1909 processList=$(for p in ${processList}; do echo ${p} | /bin/sed -e 's,^'${1}'$,,g'; done);
1910 done
1911
1912 # erase all snort config directories...
1913 pinfo;
1914 pinfo "List Of Snort Configuration Directories To Erase:";
1915 pinfo "==== == ===== ============= =========== == ======";
1916 for d in ${SCD[@]}; do
1917 if [ -d "${d}" ]; then # this chk is redundant I know but just in case...
1918 pinfo "Erasing directory: \"${d}\"";
1919 /bin/rm -rf "${d}";
1920 fi
1921 done
1922 pinfo;
1923
1924 #
1925 # Remove all interface definitions from the barnyard2
1926 # systemd service conf file: "/etc/sysconfig/barnyard2"
1927 if [ -f "/etc/sysconfig/barnyard2" ]; then
1928 #
1929 # Empty the 'INTERFACES' var...
1930 /bin/sed -i -e 's,^[#]*INTERFACES=.*$,INTERFACES="",' \
1931 "/etc/sysconfig/barnyard2";
1932 #
1933 # Remove all snort sensor interfaces...
1934 /bin/sed -i -e '/^# NSTBEGIN: .*$/,/^# NSTEND: .*$/d' \
1935 "/etc/sysconfig/barnyard2";
1936 pinfo "*** Removing All snort sensor interfaces from the barnyard2";
1937 pinfo " systemd service conf file: \"/etc/sysconfig/barnyard2\"";
1938 pinfo;
1939 fi
1940
1941 if [ "${verbose_mode}" = "off" ]; then # general msg for non-verbose mode...
1942 echo;
1943 echo "*** All Snort runtime/configuration directories found erased..."
1944 echo;
1945 fi
1946 fi
1947
1948 return 0;
1949}
1950
1951#
1952# ### init_snort_mysql ### This function creates the initial snort/snort_archive
1953# databases and a user: Snort. It first attempts to see if the "sort" and
1954# "snort_archive" databases exist. A check is also made to drop any previous
1955# configured Snort databases.
1956#
1957# Results of function:
1958# - A user "snort" password change can occur if the "snort" database exists
1959# but the fails logon with the current "snort" pasword. The password is
1960# then changed to the current "snort" pasword.
1961# - If only one Snort database was found: error and exit: 11
1962# - If both Snort databases were found: return with both found code: 1
1963# - If neither Snort databases were found: return with neither found code: 0
1964init_snort_mysql() {
1965
1966 #
1967 # check to drop any previous 'snort' IDS database...
1968 if [ "${dropPrevDb}" = "true" ]; then
1969 if /usr/bin/mysql -B -u root -p"${NSTCTMYSQLPASSWD}" -e "USE snort;" &> /dev/null; then
1970 dropSnortMySQLDb="/usr/bin/mysql -u root -p${NSTCTMYSQLPASSWD}"
1971 if [ "${verbose_mode}" = "off" ]; then
1972 dropSnortMySQLDb="${dropSnortMySQLDb} &> /dev/null"
1973 fi
1974 pinfo;
1975 pinfo "*** Dropping the previous MySQL Snort database: \"snort\"...";
1976 eval ${dropSnortMySQLDb} << EOF
1977# Drop MySQL database: "snort"...
1978drop database snort;
1979exit
1980EOF
1981 if [ ${?} -ne 0 ]; then
1982 echo;
1983 echo "***ERROR*** Could not drop the previous MySQL database: \"snort\"..."
1984 echo;
1985 exit 33;
1986 fi
1987 fi
1988 #
1989 # check to drop any previous 'snort_archive' IDS database...
1990 if /usr/bin/mysql -B -u root -p"${NSTCTMYSQLPASSWD}" -e "USE snort_archive;" &> /dev/null; then
1991 dropSnortMySQLDb="/usr/bin/mysql -u root -p${NSTCTMYSQLPASSWD}";
1992 if [ "${verbose_mode}" = "off" ]; then
1993 dropSnortMySQLDb="${dropSnortMySQLDb} &> /dev/null";
1994 fi
1995 pinfo;
1996 pinfo "*** Dropping the previous MySQL Snort database: \"snort_archive\"...";
1997 eval ${dropSnortMySQLDb} << EOF
1998# Drop MySQL database: "snort_archive"...
1999drop database snort_archive;
2000exit
2001EOF
2002 pinfo;
2003 if [ ${?} -ne 0 ]; then
2004 echo;
2005 echo "***ERROR*** Could not drop the previous MySQL database: \"snort_archive\"...";
2006 echo;
2007 exit 34;
2008 fi
2009 fi
2010 fi
2011
2012 #
2013 # check for snort MySQL password change...
2014 #
2015 # 1st: see if a 'snort' database exists...
2016 if /usr/bin/mysql -B -u root -p"${NSTCTMYSQLPASSWD}" -e "USE snort;" &> /dev/null; then
2017 #
2018 # 2nd: ok, the 'snort' database exists - can the 'snort' user login...
2019 if ! /usr/bin/mysql -B -u snort -p"${NSTCTSNORTPASSWD}" -e "USE snort;" &> /dev/null; then
2020 #
2021 # 3rd: ok, the user: 'snort' can not login - change the password...
2022 snortMySQLChgPasswd="/usr/bin/mysql -u root -p${NSTCTMYSQLPASSWD}";
2023 if [ "${verbose_mode}" = "off" ]; then
2024 snortMySQLChgPasswd="${snortMySQLChgPasswd} &> /dev/null";
2025 fi
2026 pinfo;
2027 pinfo "*** Changing the password for user: \"snort\"...";
2028 eval ${snortMySQLChgPasswd} << EOF
2029# change password to user: snort - local host...
2030SET PASSWORD FOR snort@localhost = PASSWORD('${NSTCTSNORTPASSWD}');
2031
2032# change password to user: snort - '%' host...
2033SET PASSWORD FOR snort@'%' = PASSWORD('${NSTCTSNORTPASSWD}');
2034EOF
2035 if [ ${?} -ne 0 ]; then
2036 echo;
2037 echo "***ERROR*** Could not change the password for user: \"snort\"...";
2038 echo;
2039 exit 31;
2040 fi
2041 #
2042 # finally: restart the 'MySQL' service after password change...
2043 pinfo;
2044 pinfo "*** Restart the MySQL server after changing the password for user: \"snort\"...";
2045 restartMySQL="/bin/systemctl restart mysqld.service";
2046 if [ "${verbose_mode}" = "off" ]; then
2047 restartMySQL="${restartMySQL} &> /dev/null";
2048 fi
2049 if ! eval ${restartMySQL}; then
2050 echo;
2051 echo "***ERROR*** Could not restart the MySQL daemon after changing the password for user: \"snort\"...";
2052 exit 32;
2053 fi
2054 pinfo;
2055 fi
2056 fi
2057
2058 #
2059 # use a 2 second settling time...
2060 /bin/sleep 2;
2061
2062 #
2063 # see if the Snort database is found...
2064 if /usr/bin/mysql -B -u snort -p"${NSTCTSNORTPASSWD}" -e "USE snort;" &> /dev/null; then
2065 snortDbOk=1;
2066 else
2067 snortDbOk=0;
2068 fi
2069
2070 #
2071 # see if snort_archive database is found...
2072 if /usr/bin/mysql -B -u snort -p"${NSTCTSNORTPASSWD}" -e "USE snort_archive;" &> /dev/null; then
2073 snort_archiveDbOk=1;
2074 else
2075 snort_archiveDbOk=0;
2076 fi
2077
2078 #
2079 # check for only one Snort database found...
2080 if ((snortDbOk ^ snort_archiveDbOk)); then
2081 echo;
2082 echo "***ERROR*** Prior MySQL database configuration for Snort was incorrect. Only"
2083 echo " one Snort database was found..."
2084 echo;
2085 exit 11;
2086 fi
2087
2088 #
2089 # check for databases found with prior configuration...
2090 if ((snortDbOk & snort_archiveDbOk)); then
2091 pinfo;
2092 pinfo "*** Prior MySQL databases for Snort detected..."
2093 #
2094 # return with no further Snort configuration needed...
2095 return 1;
2096 fi
2097
2098 #
2099 # no prior Snort databases detected, continue with Snort database initialization...
2100 snortMySQLInit="/usr/bin/mysql -u root -p${NSTCTMYSQLPASSWD}"
2101 if [ "${verbose_mode}" = "off" ]; then
2102 snortMySQLInit="${snortMySQLInit} > /dev/null 2>&1"
2103 fi
2104 pinfo "*** Status for snort database after initialization";
2105 pinfo " -and-";
2106 pinfo " Status for snort_archive database after initialization...";
2107 eval ${snortMySQLInit} << EOF
2108# create the snort database...
2109CREATE DATABASE snort;
2110
2111# start using the newly created database: snort...
2112USE snort;
2113
2114# MySQL status for the snort database
2115STATUS;
2116
2117# create a Snort user: snort
2118GRANT CREATE,INSERT,DELETE,UPDATE,SELECT ON snort.* TO snort@localhost;
2119
2120# assign password to user: snort
2121SET PASSWORD FOR snort@localhost = PASSWORD('${NSTCTSNORTPASSWD}');
2122
2123# allow remote access for user: "snort"
2124GRANT CREATE,INSERT,DELETE,UPDATE,SELECT ON snort.* TO snort@'%' IDENTIFIED BY '${NSTCTSNORTPASSWD}' WITH GRANT OPTION;
2125
2126# create the snort archive database...
2127CREATE DATABASE snort_archive;
2128
2129# start using the newly created database: snort_archive...
2130USE snort_archive;
2131
2132# MySQL status for the snort_archive database
2133STATUS;
2134
2135# grant permissions to user: snort for database: snort_archive
2136GRANT CREATE,INSERT,DELETE,UPDATE,SELECT ON snort_archive.* TO snort@localhost;
2137
2138# assign password to user: snort
2139SET PASSWORD FOR snort@localhost = PASSWORD('${NSTCTSNORTPASSWD}');
2140
2141# allow remote access for user: "snort"
2142GRANT CREATE,INSERT,DELETE,UPDATE,SELECT ON snort_archive.* TO snort@'%' IDENTIFIED BY '${NSTCTSNORTPASSWD}' WITH GRANT OPTION;
2143EOF
2144 if [ $? -ne 0 ]; then
2145 echo;
2146 echo "***ERROR*** Could not initialize the snort database: init_snort_mysql() ..."
2147 echo;
2148 exit 12;
2149 fi
2150# return with further Snort configuration needed...
2151 return 0;
2152}
2153
2154# ### createRAMDisk ### This function tries to create a RAM disk if necessary...
2155createRAMDisk() {
2156 if [ "${needRAMDisk}" = "true" ]; then
2157 pinfo;
2158 pinfo "*** Create a ${ramDiskSize}MByte RAM disk at mount point: \"${runtimeDir}\"..."
2159 createRAMDisk="${CREATERAMDISK} -s ${ramDiskSize} -d ${ramDevice} -m ${runtimeDir}"
2160 if [ "${verbose_mode}" = "off" ]; then
2161 createRAMDisk="${createRAMDisk} > /dev/null 2>&1"
2162 else
2163 createRAMDisk="${createRAMDisk} -v" # be verbose...
2164 fi
2165 pinfo "${createRAMDisk}"
2166 if ! eval ${createRAMDisk}; then
2167 echo;
2168 echo "***ERROR*** Could not create a RAM Disk, script: \"setup_mysql\" exiting..."
2169 echo;
2170 exit 13;
2171 fi
2172 else
2173 pinfo;
2174 pinfo "*** Using runtime directory: \"${runtimeDir}\" for Snort and MySQL data files..."
2175 fi
2176
2177 return 0;
2178}
2179
2180# ### Replace include rules in: "${pkgDir}/rules/snort.conf"
2181#
2182# If a Base Rule Set Bundle (e.g., Emerging Treats Pro)
2183# does not include a "snort.conf" file,
2184# it will be necessary to use the default snort config
2185# file: "/etc/snort/snort.conf" and replace the include rules
2186# with the new rules found in the Base Rule Set Bundle.
2187replaceSnortConfIncludeRules() {
2188
2189 #
2190 # Find rules from Base Rule Set Bundle...
2191 local AVAILABLE_RULES=();
2192 #
2193 # ***Special 1: Do not include IPS (samsnort) "*-BLOCK" rule sets from "Emerging Treats Pro"...
2194 if echo "${pkgRulesSite}" | /bin/grep -i -q 'emergingthreatspro'; then
2195 pinfo;
2196 pinfo "*** Detected Base Rule Set: \"Emerging Threats Pro\" - Not including '*-BLOCK' or 'scada*' rule sets...";
2197 AVAILABLE_RULES=($(cd "${pkgDir}/rules" && /bin/ls *.rules | \
2198 /bin/sed -e 's/\.rules//g' | /bin/grep -v -i -- '-block' | \
2199 /bin/grep -v -i -- '^scada' | /bin/sort -u));
2200 else
2201 AVAILABLE_RULES=($(cd "${pkgDir}/rules" && /bin/ls *.rules | /bin/sed -e 's/\.rules//g' | /bin/sort -u));
2202 fi
2203
2204 pinfo;
2205 pinfo "*** Replacing rules to include in: \"${pkgDir}/rules/snort.conf\"";
2206 #
2207 # First remove all included rules in distro "snort.conf"...
2208 /bin/sed -i -e '/^include \$RULE_PATH.*$/d' "${pkgDir}/rules/snort.conf";
2209 #
2210 # Include rules from Base Rule Set Bundle...
2211 for ((i=0; i < ${#AVAILABLE_RULES[*]}; i++)); do
2212 echo "include \$RULE_PATH/${AVAILABLE_RULES[${i}]}.rules" >> "${pkgDir}/rules/snort.conf";
2213 done
2214
2215 #
2216 # ***Special 2: Add any "Emerging Treats Pro" defined vars for rule set definitions...
2217 if echo "${pkgRulesSite}" | /bin/grep -i -q 'emergingthreatspro'; then
2218 pinfo;
2219 pinfo "*** Adding \"Emerging Threats Pro\" variable definitions to the Snort configuration file...";
2220 if [ -r "${pkgDir}/rules/etpro.conf" ]; then
2221 echo >> "${pkgDir}/rules/snort.conf";
2222 echo "# Emerging Threats Pro Variable Definitions" >> "${pkgDir}/rules/snort.conf";
2223 echo "# ======== ======= === ======== ===========" >> "${pkgDir}/rules/snort.conf";
2224 /bin/grep '^var ' "${pkgDir}/rules/etpro.conf" >> "${pkgDir}/rules/snort.conf";
2225 echo >> "${pkgDir}/rules/snort.conf";
2226 fi
2227 fi
2228
2229 return 0;
2230}
2231
2232# ### setupSnortCfg ### This function will setup the Snort configuration...
2233setupSnortCfg() {
2234
2235 # determine if this is the 1st Snort instance:
2236 # does a runtime rules directory exist?
2237 if [ -d "${pkgDir}/rules" ]; then
2238 firstSnortInstance="false"
2239 fi
2240
2241 # create a temporary ruleset cache directory...
2242 setupSnortRulesetCacheDir;
2243
2244 # if a Snort instance was already created: skip initial setup....
2245 if [ "${firstSnortInstance}" = "true" ]; then
2246
2247 cd "${runtimeDir}";
2248 # create directory structure for Snort rule definitions...
2249 /bin/mkdir -p "${pkgDir}";
2250 /bin/chmod 755 "${pkgDir}";
2251
2252 # copy any custom Snort scripts to the runtime directory...
2253 for t in ${customSnortScripts}; do
2254 /bin/cp -pf "/usr/share/${PKG}/contrib/${t}" "${pkgDir}";
2255 /bin/chmod 744 "${pkgDir}/${t}";
2256 done
2257 fi
2258
2259 #
2260 # install configuration templates for custom scripts like snort_triggers.sh
2261 # BUT, don't replace any existing configs (in case user already has some)
2262 for f in /usr/share/${PKG}/contrib/*.conf; do
2263 DST="/etc/$(basename "${f}")";
2264 if [ ! -f "${DST}" ]; then
2265 /bin/cp -pf "${f}" "${DST}";
2266 /bin/chmod 600 "${DST}";
2267 fi
2268 done
2269
2270 # Create a unique directory structure for Snort logs and alerts
2271 # based on the interface name.
2272 /bin/mkdir -p "${pkgDir}/logs_${interface}";
2273
2274 # create a /etc/${snortCfgDir} directory...
2275 /bin/mkdir -p "${snortCfgDir}";
2276 #
2277 # Check for local or URL base rule source (remote) fetching...
2278 if [ "${pkgRulesFetch}" = "remote" ]; then
2279 #
2280 # Only fetch rules for an initial Snort instance...
2281 if [ "${firstSnortInstance}" = "true" ]; then
2282 # fetch remote rules...
2283 pinfo "*** Using a \"URL rule source\" for base Snort signature definitions...";
2284 pinfo;
2285 brs="$(commentURLPasswd "${pkgRulesSite}")";
2286 pinfo "*** Fetching base Snort rule signature definitions from source:";
2287 einfo " \"${brs}\"";
2288 # download remote rules file and untar into current rules runtime directory....
2289 wget_untar "${pkgRulesSite}" "${pkgDir}";
2290 #
2291 # Use the default: "snort.conf" if one is not supplied...
2292 if [ ! -f "${pkgDir}/rules/snort.conf" ]; then
2293 if [ -f "/etc/snort/snort.conf" ]; then
2294 pinfo;
2295 pinfo "*** Copying latest \"snort.conf\" to: \"${pkgDir}/rules\"";
2296 cp -fp "/etc/snort/snort.conf" "${pkgDir}/rules";
2297 #
2298 # Replace include rules in: "${pkgDir}/rules/snort.conf"
2299 replaceSnortConfIncludeRules;
2300 fi
2301 fi
2302 fi
2303 #
2304 # Download and process any additional remote or local rules file...
2305 processAdditionalSnortRules;
2306 #
2307 # Copy latest config files to the ${snortCfgDir} directory...
2308 for c in ${pkgConfigFiles}; do
2309 if [ -f "${pkgDir}/rules/${c}" ]; then
2310 /bin/cp -p "${pkgDir}/rules/${c}" "${snortCfgDir}";
2311 fi
2312 done
2313 #
2314 # Make sure that a "gen-msg.map" file exists...
2315 if [ ! -f "${snortCfgDir}/gen-msg.map" ]; then
2316 /usr/bin/touch "${snortCfgDir}/gen-msg.map";
2317 fi
2318 #
2319 # Copy built: "sid-msg.map" for the snort config dir...
2320 /bin/cp -p "${pkgDir}/rules/sid-msg.map.built" "${snortCfgDir}/sid-msg.map";
2321 else
2322 #
2323 # Only copy local rules for an initial Snort instance...
2324 if [ "${firstSnortInstance}" = "true" ]; then
2325 #
2326 # Use local rules...
2327 pinfo "*** Using local base Snort rules definitions...";
2328 pinfo;
2329 pinfo "*** Copying base Snort's rule definitions from the NST distribution to: \"${pkgDir}/rules\"";
2330 pinfo "/bin/cp -rp /usr/share/snortrules/rules ${pkgDir}";
2331 /bin/cp -rp "/usr/share/snortrules/rules" "${pkgDir}";
2332 #
2333 # Use the latest "snort.conf" from the snort RPM pkg
2334 # (i.e, the latest version of snort)...
2335 if [ -f "/etc/snort/snort.conf" ]; then
2336 pinfo;
2337 pinfo "*** Copying latest \"snort.conf\" to: \"${pkgDir}/rules\"";
2338 cp -fp "/etc/snort/snort.conf" "${pkgDir}/rules";
2339 fi
2340 fi
2341 #
2342 # Download and process any additional remote or local rules file...
2343 processAdditionalSnortRules;
2344 # copy Snort's NST distribution config files to the ${snortCfgDir} directory...
2345 for c in ${pkgConfigFiles}; do
2346 if [ -f "${pkgDir}/rules/${c}" ]; then
2347 /bin/cp -p "${pkgDir}/rules/${c}" "${snortCfgDir}";
2348 fi
2349 done
2350 #
2351 # Make sure that a "gen-msg.map" file exists...
2352 if [ ! -f "${snortCfgDir}/gen-msg.map" ]; then
2353 /usr/bin/touch "${snortCfgDir}/gen-msg.map";
2354 fi
2355 #
2356 # Copy built: "sid-msg.map" for the snort config dir...
2357 /bin/cp -p "${pkgDir}/rules/sid-msg.map.built" "${snortCfgDir}/sid-msg.map";
2358 fi
2359
2360 #
2361 # Copy global "threshold" configuration file: "/etc/snort/threshold.conf"
2362 # to the current snort configuration directory...
2363 if [ -f "/etc/snort/threshold.conf" ]; then
2364 pinfo;
2365 pinfo "*** Copying global snort threshold file \"/etc/snort/threshold.conf\" to: \"${snortCfgDir}\"";
2366 cp -fp "/etc/snort/threshold.conf" "${snortCfgDir}";
2367 fi
2368
2369 # delete the temporary ruleset cache directory...
2370 teardownSnortRulesetCacheDir;
2371
2372 #
2373 # make sure of "root" ownership for config dir...
2374 /bin/chown -R root:root "${snortCfgDir}";
2375 #
2376 # make sure of "nstwui" ownership for runtime dir...
2377 /bin/chown -R nstwui:nstwui "${pkgDir}";
2378 /bin/chmod 755 "${pkgDir}/rules";
2379
2380 #
2381 # Change RULE_PATH to: "./rules" => absolutue path for Snort: ${pkgDir}/rules...
2382 /bin/sed -i -e 's,^.*var RULE_PATH.*,var RULE_PATH '${pkgDir}'/rules,' "${snortCfgDir}/snort.conf";
2383
2384 #
2385 # For the 'Reputation Preprocessor' also set these paths:
2386 /bin/sed -i -e 's,^.*var WHITE_LIST_PATH.*,var WHITE_LIST_PATH '${pkgDir}'/rules,' "${snortCfgDir}/snort.conf";
2387 #
2388 # Create a initial "white_list.rules" file...
2389 /bin/touch "${pkgDir}/rules/white_list.rules";
2390 /bin/sed -i -e 's,^.*var BLACK_LIST_PATH.*,var BLACK_LIST_PATH '${pkgDir}'/rules,' "${snortCfgDir}/snort.conf";
2391 #
2392 # Create a initial "black_list.rules" file...
2393 /bin/touch "${pkgDir}/rules/black_list.rules";
2394
2395 #
2396 # ***TEMPORARY TRANSITION PATCH: 2.4.x => 2.6.x***
2397 # comment out: "preprocessor xlink2state:"
2398 #/bin/sed -i -e 's/^preprocessor xlink2state: \(.*\)$/# preprocessor xlink2state: \1/' "${snortCfgDir}/snort.conf";
2399 #
2400 # Set proper directory for: "dynamicpreprocessor" - snort 2.6.x and above...
2401 #/bin/sed -i -e 's,/usr/local/lib/snort_dynamicpreprocessor,/usr/lib/snort_dynamicpreprocessor,' "${snortCfgDir}/snort.conf";
2402 #
2403 # Set proper library location for: "dynamicengine" - snort 2.6.x and above...
2404 #/bin/sed -i -e 's,^dynamicengine .*,dynamicengine /usr/lib/snort_dynamicengine/libsf_engine.so,' "${snortCfgDir}/snort.conf";
2405
2406 # set HOME_NET variable in "snort.conf" for associated interface...
2407 /bin/sed -i -e 's,^var HOME_NET.*,var HOME_NET '${home_net}',' \
2408 -e 's,^ipvar HOME_NET.*,ipvar HOME_NET '${home_net}',' "${snortCfgDir}/snort.conf";
2409
2410 # set EXTERNAL_NET variable in "snort.conf" for associated interface...
2411 /bin/sed -i -e 's,^var EXTERNAL_NET.*,var EXTERNAL_NET '${external_net}',' \
2412 -e 's,^ipvar EXTERNAL_NET.*,ipvar EXTERNAL_NET '${external_net}',' "${snortCfgDir}/snort.conf";
2413
2414 #
2415 # Set max values for 'compress_depth' and 'decompress_depth' in the
2416 # preprocessor: http_inspect
2417 #
2418 # Change occurred with snort: v2.9.0.5
2419 #
2420 # Updated the default 'snort.conf' to enable unlimited decompression
2421 # of gzipped HTTP server responses.
2422 /bin/sed -i -e 's,compress_depth [0-9]* decompress_depth [0-9]*,compress_depth 65535 decompress_depth 65535,' \
2423 "${snortCfgDir}/snort.conf";
2424
2425 # add default log directory config directive: "logdir"...
2426 /bin/sed -i -e '/^var RULE_PATH/a\
2427\
2428# Define location for Snort logging...\
2429config logdir: '${runtimeDir}/snort/logs_${interface} "${snortCfgDir}/snort.conf";
2430
2431# # add additional snort variables...
2432# /bin/sed -i -e '/^var HTTP_PORTS 80/a\
2433#\
2434# SSHD port definition...\
2435#var SSH_PORTS 22' "${snortCfgDir}/snort.conf";
2436
2437 # add "interface" config directive...
2438 /bin/sed -i -e '/^config logdir/a\
2439\
2440# Define snort IDS interface...\
2441config interface: '${interface} "${snortCfgDir}/snort.conf";
2442
2443 #
2444 # Comment out any "nolog" config directive (equivalent to -N cmd line option"...
2445 /bin/sed -i -e 's,^config nolog,#&,' "${snortCfgDir}/snort.conf";
2446
2447 # Enable 'unified2' plugin in ${snortCfgDir}/snort.conf...
2448 /bin/cat >> "${snortCfgDir}/snort.conf" << EOF
2449
2450# NST: Enable 'unified2' logging for barnyard2...
2451output unified2: filename snort.u2, limit 128
2452EOF
2453
2454 #
2455 # Currently not using dynamic rules libraries: comment all out...
2456 /bin/sed -i -e 's,^dynamicdetection \(.*\)$,#dynamicdetection \1,' \
2457 "${snortCfgDir}/snort.conf";
2458
2459 #
2460 # create the snort_options file...
2461 if [ -n "${snort_options}" ]; then
2462 echo -n "${snort_options}" >| "${snortCfgDir}/${snort_options_filename}";
2463 else
2464 /bin/touch "${snortCfgDir}/${snort_options_filename}";
2465 fi
2466 /bin/chmod 664 "${snortCfgDir}/${snort_options_filename}";
2467 /bin/chown root:root "${snortCfgDir}/${snort_options_filename}";
2468
2469 return 0;
2470}
2471
2472# ### setupBarnyard2Cfg ### This function will setup the Barnyard2 configuration...
2473setupBarnyard2Cfg() {
2474 #
2475 # Make sure that a snort config dir exist...
2476 if [ ! -d "${snortCfgDir}" ]; then
2477 echo;
2478 echo "***ERROR*** The snort configuration directory: \"${snortCfgDir}\" does not exist, exiting..."
2479 echo;
2480 exit 38;
2481 fi
2482
2483 pinfo;
2484 pinfo "*** Setting up a separate \"Barnyard2\" configuration for this instance of Snort: \"${snortCfgDir}/barnyard2.conf\"";
2485
2486 #
2487 # Get an NST disto base conf of "barnyard2.conf"
2488 cp -fp "/etc/barnyard2/barnyard2.conf" "${snortCfgDir}";
2489
2490 #
2491 # Set the initial state for NST WUI Snort/Barnard2/MySQL usage...
2492 #
2493 # Comment out all 'output' directives...
2494 /bin/sed -i -e 's,^output .*$,#&,' "${snortCfgDir}/barnyard2.conf";
2495 #
2496 # Make sure the 'input' directive is: "unified2"
2497 if ! /bin/grep -q '^input unified2' "${snortCfgDir}/barnyard2.conf"; then
2498 #
2499 # Comment out all 'input' directives...
2500 /bin/sed -i -e 's,^input .*$,#&,' "${snortCfgDir}/barnyard2.conf";
2501 #
2502 # Enable the 'input' directive for 'unified2' log format...
2503 /bin/cat >> "${snortCfgDir}/barnyard2.conf" << EOF
2504
2505# NST: Enable 'unified2' input...
2506input unified2
2507EOF
2508 fi
2509
2510 #
2511 # Set the 'hostname config' directive...
2512 local hn="$(/bin/hostname;)";
2513 /bin/sed -i -e "s,^[#]*config hostname:[ \t].*$,config hostname: ${hn}," "${snortCfgDir}/barnyard2.conf";
2514 #
2515 # Set the 'network interface name config' directive...
2516 /bin/sed -i -e "s,^[#]*config interface:[ \t].*$,config interface: ${interface}," "${snortCfgDir}/barnyard2.conf";
2517 #
2518 # Set the 'reference_file config' directive...
2519 /bin/sed -i -e "s,^[#]*config reference_file:[ \t].*$,config reference_file: ${snortCfgDir}/reference.config," \
2520 "${snortCfgDir}/barnyard2.conf";
2521 #
2522 # Set the 'classification_file config' directive...
2523 /bin/sed -i -e "s,^[#]*config classification_file:[ \t].*$,config classification_file: ${snortCfgDir}/classification.config," \
2524 "${snortCfgDir}/barnyard2.conf";
2525 #
2526 # Set the 'gen_file config' directive...
2527 /bin/sed -i -e "s,^[#]*config gen_file:[ \t].*$,config gen_file: ${snortCfgDir}/gen-msg.map," \
2528 "${snortCfgDir}/barnyard2.conf";
2529 #
2530 # Set the 'sid_file config' directive...
2531 /bin/sed -i -e "s,^[#]*config sid_file:[ \t].*$,config sid_file: ${snortCfgDir}/sid-msg.map," \
2532 "${snortCfgDir}/barnyard2.conf";
2533 #
2534 # Enable the 'output' directive for MySQL database in "${snortCfgDir}/barnyard2.conf"...
2535 /bin/cat >> "${snortCfgDir}/barnyard2.conf" << EOF
2536
2537# NST: Enable MySQL Snort/Barnyard2 Integration...
2538output database: alert, mysql, user=snort password=${NSTCTSNORTPASSWD} dbname=snort host=${dbHostname} port=${dbPort} sensor_name=${sensorName} detail=${alertDetail}
2539EOF
2540
2541 #
2542 # Configure the Barnyard2 systemd service for this snort instance...
2543 #
2544 # Make sure that a barnyard2 config exist...
2545 if [ ! -f "/etc/sysconfig/barnyard2" ]; then
2546 #
2547 # Create a base config if file does not exist...
2548 /bin/cat >> "/etc/sysconfig/barnyard2" << EOF
2549#
2550# Command line options for barnyard2 (barnyard2_execstart)...
2551OPTIONS=""
2552
2553#
2554# Network Interface(s) - Space separated and within double quotes...
2555INTERFACES=""
2556EOF
2557 fi
2558
2559 #
2560 # Source in the Barnyard2 systemd service conf file...
2561 source "/etc/sysconfig/barnyard2";
2562 #
2563 # Recalc the 'INTERFACES' variable...
2564 if [ -z "${INTERFACES}" ]; then
2565 INTERFACES="${interface}";
2566 else
2567 #
2568 # Add this snort sensor network interface name if not found...
2569 #
2570 # First, make sure it is not in the list already...
2571 local nint=$(for i in ${INTERFACES}; do
2572 if ! (echo ${i} | /bin/grep -q "^${interface}$";); then
2573 printf "${i} ";
2574 fi
2575 done;);
2576 #
2577 # Now add it to the end of the list...
2578 INTERFACES="$(echo ${nint};) ${interface}";
2579 fi
2580 #
2581 # Set the 'INTERFACES' var...
2582 /bin/sed -i -e 's,^[#]*INTERFACES=.*$,INTERFACES="'"${INTERFACES}"'",' \
2583 "/etc/sysconfig/barnyard2";
2584 #
2585 # Remove any previous Barnyard2 var definitions for this snort sensor interface...
2586 /bin/sed -i -e "/^# NSTBEGIN: ${interface}$/,/^# NSTEND: ${interface}$/d" \
2587 "/etc/sysconfig/barnyard2";
2588 #
2589 # Add the Barnyard2 var definitions for this snort sensor interface...
2590 /bin/cat >> "/etc/sysconfig/barnyard2" << EOF
2591# NSTBEGIN: ${interface}
2592LOGFILE_${interface}="snort.u2"
2593SNORTDIR_${interface}="/var/nst/snort"
2594CONF_${interface}="/etc/snort_${interface}/barnyard2.conf"
2595EXTRAARGS_${interface}=""
2596# NSTEND: ${interface}
2597EOF
2598
2599 return 0;
2600}
2601
2602#
2603# ### setupMySQL ### This functions sets up a MySQL database server engine for Snort...
2604setupMySQL() {
2605 pinfo;
2606 pinfo "*** Setup the MySQL Server...";
2607 if [ "${needRAMDisk}" = "true" ]; then
2608 #
2609 # use a RAM disk for the MySQL database if not already setup...
2610 setupMySQLServer="/usr/local/bin/setup_mysql -rd ${ramDevice} -rds ${ramDiskSize} -rmp ${runtimeDir}";
2611 else
2612 #
2613 # use user specified directory for the MySQL database...
2614 setupMySQLServer="/usr/local/bin/setup_mysql -rdir ${runtimeDir}";
2615 fi
2616 #
2617 # used to see a non-standard MySQL database port...
2618 setupMySQLServer="${setupMySQLServer} --dbPort ${dbPort}";
2619 if [ "${verbose_mode}" = "off" ]; then
2620 setupMySQLServer="${setupMySQLServer} &> /dev/null";
2621 else
2622 setupMySQLServer="${setupMySQLServer} -v" # be verbose...
2623 fi
2624 pinfo "${setupMySQLServer}"
2625 if ! eval ${setupMySQLServer}; then
2626 echo;
2627 echo "***ERROR*** Script \"setup_snort\" terminating: could not start a MySQL server..."
2628 echo;
2629 exit 15;
2630 fi
2631
2632 # initialize a Snort database...
2633 pinfo "*** Try to initialize the Snort MySQL databases..."
2634 if init_snort_mysql; then
2635
2636 # initialize the base Snort database tables...
2637 pinfo;
2638 pinfo "*** Initialize the base Snort MySQL database tables..."
2639 snortInit="/usr/bin/mysql -u snort -p${NSTCTSNORTPASSWD} snort < /usr/share/barnyard2/schemas/create_mysql";
2640 if [ "${verbose_mode}" = "off" ]; then
2641 snortInit="${snortInit} &> /dev/null";
2642 fi
2643 pinfo "/usr/bin/mysql -u snort -p****** snort < /usr/share/barnyard2/schemas/create_mysql";
2644 if ! eval ${snortInit}; then
2645 echo;
2646 echo "***ERROR*** Could not load base Snort database tables...";
2647 echo;
2648 exit 16;
2649 fi
2650
2651 # initialize the snort_archive database tables...
2652 pinfo;
2653 pinfo "*** Initialize the Snort archive database tables...";
2654 snortArchiveInit="/usr/bin/mysql -u snort -p${NSTCTSNORTPASSWD} snort_archive < /usr/share/barnyard2/schemas/create_mysql";
2655 if [ "${verbose_mode}" = "off" ]; then
2656 snortArchiveInit="${snortArchiveInit} &> /dev/null";
2657 fi
2658 pinfo "/usr/bin/mysql -u snort -p****** snort_archive < /usr/share/barnyard2/schemas/create_mysql";
2659 if ! eval ${snortArchiveInit}; then
2660 echo;
2661 echo "***ERROR*** Could not load Snort archive database tables...";
2662 echo;
2663 exit 18;
2664 fi
2665 fi
2666
2667 #
2668 # Add additional IDS database columns for NST processing...
2669 #
2670 # Check to add an additional column to the 'sensor' table: "ids_engine"
2671 # for snortdb2xml and IDS KML generation...
2672 pinfo;
2673 pinfo "*** Check to add the \"ids_engine\" column to the 'sensor' table for snort databases...";
2674 #
2675 # snort database check...
2676 if !(printf "show columns from sensor;" | \
2677 /usr/bin/mysql -u root -p${NSTCTMYSQLPASSWD} --disable-pager snort | \
2678 /bin/grep -q '^ids_engine'); then
2679 pinfo "*** Adding the \"ids_engine\" column to the 'sensor' table for the 'snort' database...";
2680 addColMySQL="/usr/bin/mysql -u root -p${NSTCTMYSQLPASSWD}";
2681 if [ "${verbose_mode}" = "off" ]; then
2682 addColMySQL="${addColMySQL} &> /dev/null";
2683 fi
2684 eval ${addColMySQL} << EOF
2685USE snort;
2686ALTER TABLE \`sensor\` ADD \`ids_engine\` TEXT NOT NULL AFTER \`last_cid\`;
2687QUIT
2688EOF
2689 fi
2690
2691 #
2692 # snort_archive database check...
2693 if !(printf "show columns from sensor;" | \
2694 /usr/bin/mysql -u root -p${NSTCTMYSQLPASSWD} --disable-pager snort_archive | \
2695 /bin/grep -q '^ids_engine'); then
2696 pinfo "*** Adding the \"ids_engine\" column to the 'sensor' table for the 'snort_archive' database...";
2697 addColMySQL="/usr/bin/mysql -u root -p${NSTCTMYSQLPASSWD}";
2698 if [ "${verbose_mode}" = "off" ]; then
2699 addColMySQL="${addColMySQL} &> /dev/null";
2700 fi
2701 eval ${addColMySQL} << EOF
2702USE snort_archive;
2703ALTER TABLE \`sensor\` ADD \`ids_engine\` TEXT NOT NULL AFTER \`last_cid\`;
2704QUIT
2705EOF
2706 fi
2707
2708 # test and make sure the MySQL database is setup properly for Snort...
2709 pinfo;
2710 pinfo "*** Test for proper MySQL database setup for Snort...";
2711 pinfo " List Snort database status and table entries...";
2712 pinfo " -and-";
2713 pinfo " List Snort Archive database status and table entries...";
2714 testMySQL="/usr/bin/mysql -u snort -p${NSTCTSNORTPASSWD}";
2715 if [ "${verbose_mode}" = "off" ]; then
2716 testMySQL="${testMySQL} &> /dev/null";
2717 fi
2718 eval ${testMySQL} << EOF
2719USE snort;
2720STATUS;
2721SHOW TABLES;
2722USE snort_archive;
2723STATUS;
2724SHOW TABLES;
2725QUIT
2726EOF
2727
2728 if [ $? -ne 0 ]; then
2729 echo;
2730 echo "***ERROR*** Could not display Snort database status/table information..."
2731 echo;
2732 exit 19;
2733 fi
2734
2735 return 0;
2736}
2737
2738# ### setupMySQLExtra ### This functions sets up extra servies entires in the snort database...
2739setupMySQLExtra() {
2740 pinfo;
2741 pinfo "*** Testing if extra network service table entries already exist...";
2742 # see if a MySQL database for snort is already running...
2743 if ! init_snort_mysql; then
2744 # at this point a Snort MySQL database is running, see if extra service tables already exist?
2745 if ! /usr/bin/mysql -B -u snort -p"${NSTCTSNORTPASSWD}" \
2746 -e "USE snort; SELECT * FROM services WHERE port<30 AND port>20;" &> /dev/null; then
2747 # create the extra Snort database service tables and entries...
2748 pinfo;
2749 pinfo "*** Create the extra network services Snort MySQL database tables and entries...";
2750 snortExtraTables="/bin/zcat /usr/share/${PKG}/contrib/snortdb-extra.gz | /usr/bin/mysql -u snort -p${NSTCTSNORTPASSWD} snort";
2751 if [ "${verbose_mode}" = "off" ]; then
2752 snortExtraTables="${snortExtraTables} &> /dev/null";
2753 fi
2754 pinfo "/bin/zcat /usr/share/${PKG}/contrib/snortdb-extra.gz | /usr/bin/mysql -u snort -p****** snort";
2755 if ! eval ${snortExtraTables}; then
2756 echo;
2757 echo "***ERROR*** Could not load the extra network services Snort database tables and entries...";
2758 echo;
2759 exit 17;
2760 fi
2761 fi
2762 fi
2763 # test and make sure the MySQL extra database tables are setup properly for Snort...
2764 pinfo;
2765 pinfo " List Snort database network service entries: (ports: between 20 and 30)";
2766 testMySQL="/usr/bin/mysql -u snort -p${NSTCTSNORTPASSWD}";
2767 if [ "${verbose_mode}" = "off" ]; then
2768 testMySQL="${testMySQL} &> /dev/null";
2769 fi
2770 eval ${testMySQL} << EOF
2771USE snort;
2772SELECT * FROM services WHERE port<30 AND port>20;
2773QUIT
2774EOF
2775
2776 if [ $? -ne 0 ]; then
2777 echo;
2778 echo "***ERROR*** Could not display the Snort database network service entries...";
2779 echo;
2780 exit 29;
2781 fi
2782
2783 return 0;
2784}
2785
2786
2787# ### setupWWWBASE ### This function is used to setup BASE usage with the Apache Web Server...
2788setupWWWBASE() {
2789 local TFILE="/usr/share/base-php4/contrib/nst_snort_base_conf.php.template";
2790 local CFILE="/etc/base_conf.php";
2791 local IDSUPDATEACCESS="/usr/share/snortdb2xml/cgi";
2792 local IDSUPDATEACCESSFILE="${IDSUPDATEACCESS}/htuser.nst";
2793
2794 if [ -f "${TFILE}" ]; then
2795 pinfo;
2796 pinfo "*** Create BASE config file: \"${CFILE}\"...";
2797 # insert MySQL database access passwords...
2798 /bin/sed -e 's/^\$alert_password .*$/\$alert_password = '"'${NSTCTSNORTPASSWD}'"';/' \
2799 -e 's/^\$archive_password .*$/\$archive_password = '"'${NSTCTSNORTPASSWD}'"';/' \
2800 < "${TFILE}" >| "${CFILE}";
2801 # enable the "snort_archive" database...
2802 /bin/sed -i -e 's/^\$archive_exists .*$/\$archive_exists = 1;/' "${CFILE}";
2803 # set alert database port values...
2804 /bin/sed -i -e 's/^\$alert_port .*$/\$alert_port = '"'${dbPort}'"';/' "${CFILE}";
2805 /bin/sed -i -e 's/^\$archive_port .*$/\$archive_port = '"'${dbPort}'"';/' "${CFILE}";
2806
2807 #
2808 # Try to recreate the IDS Update access file for user: 'snort'
2809 # when the ENV: 'NSTCTSNORTPASSWD' is specified...
2810 if [ -n "${NSTCTSNORTPASSWD}" ]; then
2811 if [ -d "${IDSUPDATEACCESS}" ]; then
2812 pinfo;
2813 pinfo "*** Recreate IDS update access file: \"${IDSUPDATEACCESSFILE}\"...";
2814 /usr/bin/htpasswd -bc "${IDSUPDATEACCESSFILE}" "snort" "${NSTCTSNORTPASSWD}" &> /dev/null;
2815 fi
2816 fi
2817 fi
2818
2819 # create the BASE MySQL tables...
2820 pinfo;
2821
2822 #
2823 # install BASE tables into snort database...
2824
2825 # test for BASE tables already created in "snort" database:
2826 # test for table: "base_users" exists...
2827 BASETest="/usr/bin/mysql -u snort -p${NSTCTSNORTPASSWD}";
2828 eval ${BASETest} << EOF | /bin/grep "base_users" &> /dev/null;
2829USE snort;
2830SHOW TABLES LIKE 'base_users';
2831QUIT
2832EOF
2833
2834 if [ $? -ne 0 ]; then # BASE table not found...
2835 pinfo "*** Creating BASE tables for MySQL \"snort\" database...";
2836 createBASETables="/usr/bin/mysql -u snort -p${NSTCTSNORTPASSWD} snort < /usr/share/base-php4/sql/create_base_tbls_mysql.sql";
2837 if [ "${verbose_mode}" = "off" ]; then
2838 createBASETables="${createBASETables} &> /dev/null";
2839 fi
2840 pinfo "/usr/bin/mysql -u snort -p****** snort < /usr/share/base-php4/sql/create_base_tbls_mysql.sql";
2841 if ! eval ${createBASETables}; then
2842 echo;
2843 echo "***ERROR*** Could not create BASE tables for MySQL \"snort\" database...";
2844 echo;
2845 exit 28;
2846 fi
2847 else # BASE table found...
2848 pinfo "*** BASE tables already exist for database: \"snort\", skipping...";
2849 fi
2850
2851 #
2852 # install BASE tables into snort_archive database...
2853
2854 # test for BASE tables already created in "snort_archive" database:
2855 # test for table: "base_users" exists...
2856 pinfo;
2857 BASETest="/usr/bin/mysql -u snort -p${NSTCTSNORTPASSWD}"
2858 eval ${BASETest} << EOF | /bin/grep "base_users" &> /dev/null;
2859USE snort_archive;
2860SHOW TABLES LIKE 'base_users';
2861QUIT
2862EOF
2863
2864 if [ $? -ne 0 ]; then # BASE table not found...
2865 pinfo "*** Creating BASE tables for MySQL \"snort_archive\" database...";
2866 createBASETables="/usr/bin/mysql -u snort -p${NSTCTSNORTPASSWD} snort_archive < /usr/share/base-php4/sql/create_base_tbls_mysql.sql";
2867 if [ "${verbose_mode}" = "off" ]; then
2868 createBASETables="${createBASETables} &> /dev/null";
2869 fi
2870 pinfo "/usr/bin/mysql -u snort -p****** snort_archive < /usr/share/base-php4/sql/create_base_tbls_mysql.sql";
2871 if ! eval ${createBASETables}; then
2872 echo;
2873 echo "***ERROR*** Could not create BASE tables for MySQL \"snort_archive\" database...";
2874 echo;
2875 exit 30;
2876 fi
2877 else # BASE table found...
2878 pinfo "*** BASE tables already exist for database: \"snort_archive\", skipping...";
2879 fi
2880
2881 #
2882 # restart or startup the Apache Web server if not running...
2883 if ! /bin/systemctl status nstwui.service &> /dev/null; then
2884 /bin/systemctl start nstwui.service;
2885 fi
2886
2887 return 0;
2888}
2889
2890# ### displayUserSnortInfo ### This function displays various user Snort information...
2891displayUserSnortInfo() {
2892 if [ "${collectorMode}" = "false" ]; then
2893 pinfo;
2894 pinfo "*** Snort config files: \"${snortCfgDir}\"...";
2895 if [ "${verbose_mode}" = "on" ]; then
2896 /bin/ls -al "${snortCfgDir}";
2897 fi
2898
2899 echo;
2900 echo "*** Setup Snort complete...";
2901 echo;
2902 pinfo " ... A SNORT CONFIGURATION INSTANCE - SENSOR INTERFACE: ${interface} ...";
2903 pinfo "*****************************************************************";
2904 pinfo "*****************************************************************";
2905 pinfo "*** Snort Version: ${snort_VER}";
2906 pinfo "*** DAQ Version: ${daq_VER}";
2907 pinfo "*** Barnyard2 Version: ${barnyard2_VER}";
2908 if [ "${dbHostname}" = "localhost" ]; then
2909 pinfo "*** MariaDB (MySQL) Version: ${mysql_VER}";
2910 pinfo "*** BASE Version: ${snort_utils_base_VER}";
2911 pinfo "*** ADODB Version: ${snort_utils_adodb_VER}";
2912 fi
2913 pinfo "*** Snort Runtime Directory: ${pkgDir}";
2914 pinfo "*** Snort Configuration File: ${snortCfgDir}/snort.conf";
2915 pinfo "*** Barnyard2 Configuration File: ${snortCfgDir}/barnyard2.conf";
2916 pinfo "*** Snort Rules Directory: ${pkgDir}/rules";
2917 pinfo "*** Snort Unified2 Logs Directory: ${pkgDir}/logs_${interface}";
2918 if [ "${pkgRulesFetch}" = "local" ]; then
2919 pinfo "*** Base Snort Rules Source: local (NST Distribution)";
2920 else
2921 einfo "*** Base Snort Rules Source: $(commentURLPasswd "${pkgRulesSite}")";
2922 fi
2923 for ar in "${ARS[@]}"; do
2924 einfo "*** Additional Snort Rules Signatures: $(commentURLPasswd "${ar}")";
2925 done
2926 pinfo "*** MariaDB (MySQL) Database Hostname: ${dbHostname}";
2927 pinfo "*** MariaDB (MySQL) Database Port: ${dbPort}";
2928 pinfo "*** Snort IDS Interface: ${interface}";
2929 pinfo "*** Snort IDS Sensor Name: ${sensorName}";
2930 pinfo "*** Snort Alert Event Logging Mode: ${alertDetail}";
2931 if [ -r "${snortCfgDir}/${snort_options_filename}" ]; then
2932 pinfo "*** Snort Options: $(/bin/cat ${snortCfgDir}/${snort_options_filename})";
2933 else
2934 pinfo "*** Snort Options: N/A";
2935 fi
2936 pinfo "*****************************************************************";
2937 pinfo "*****************************************************************";
2938 echo;
2939 echo "--- To run this Snort instance on network interface: \"${interface}\" ---";
2940 echo;
2941 echo "# First make sure this instance of \"snort\" is 'Enabled' to run:";
2942 echo "#";
2943 echo "# /usr/local/bin/setup_snort -startup enabled -i \"${interface}\";";
2944 echo;
2945 echo "# Next start both the \"snort\" and \"barnyard2\" systemd control"
2946 echo "# service units: \"snort.service barnyard2.service\" via systemctl:";
2947 echo;
2948 echo "# ***Note: All configured and enabled snort instances will be restarted.";
2949 echo "#";
2950 echo "# /bin/systemctl restart snort.service barnyard2.service;";
2951 else
2952 if [ "${verbose_mode}" = "on" ]; then
2953 defaultIPAddr="$(/usr/bin/getipaddr -d;)";
2954 pinfo;
2955 pinfo "****************************************************";
2956 pinfo "****************************************************";
2957 pinfo "*** A MySQL database is running on this probe at ";
2958 pinfo "*** IP:Port: ${defaultIPAddr}:${dbPort} for the collection";
2959 pinfo "*** of remote Snort security incidents. ";
2960 pinfo "****************************************************";
2961 pinfo "****************************************************";
2962 else
2963 echo;
2964 echo "*** Setup of a backend MySQL database server and BASE engine for collection";
2965 echo " of remote Snort security incidents and log events is complete...";
2966 echo;
2967 fi
2968 fi
2969 echo;
2970
2971 return 0;
2972}
2973
2974
2975# Code:
2976# =====
2977
2978# show short setup_snort usage if no command line arguments specified...
2979if [ ${#} -eq 0 ]; then
2980 echo;
2981 echo "***ERROR*** No command line arguments specified to: ${0} ...";
2982 show_short_usage;
2983 exit 1;
2984fi
2985
2986# process command line switches...
2987while test $# -gt 0; do
2988
2989 opt="$1";
2990 shift;
2991
2992 case $opt in
2993
2994 -r | --rules)
2995 error_if_switch "$1" "$opt";
2996 pkgRulesSite="$1";
2997 if [ "${pkgRulesSite}" = "local" ]; then
2998 pkgRulesFetch="local";
2999 else
3000 pkgRulesFetch="remote";
3001 fi
3002 setup_snort_process_type=1 # Default: setup a snort instance...
3003 shift;
3004 ;;
3005
3006 -ars | --additional-rules-site)
3007 error_if_switch "$1" "$opt";
3008 ARS[${ARSI}]="$1";
3009 ((ARSI++)); # increment index...
3010 shift;
3011 ;;
3012
3013 -c | --collector)
3014 collectorMode="true";
3015 setup_snort_process_type="2"; # setup a backend MySQL database server engine
3016 ;;
3017
3018 -u | --update-rules)
3019 setup_snort_process_type="3"; # update rules for more snort instances...
3020 ;;
3021
3022 -urs | --update-rules-site)
3023 error_if_switch "$1" "$opt";
3024 URS[${URSI}]="$1";
3025 ((URSI++)); # increment index...
3026 shift;
3027 ;;
3028
3029 -ncc | --no-clear-cache)
3030 clear_cache="false"; # disable clearing of cache...
3031 ;;
3032
3033 -i | --interface)
3034 error_if_switch "$1" "$opt"
3035 interface="$1";
3036 interfaceSpecified="true";
3037 shift;
3038 ;;
3039
3040 -il | --interface-list) # "-il" added for clarity...
3041 error_if_switch "$1" "$opt"
3042 interface="$1";
3043 interfaceSpecified="true";
3044 shift;
3045 ;;
3046
3047 -d | --db_hostname)
3048 error_if_switch "$1" "$opt";
3049 dbHostname="$1";
3050 shift;
3051 ;;
3052
3053 -p | --db_port)
3054 error_if_switch "$1" "$opt";
3055 dbPort="$1";
3056 shift;
3057 ;;
3058
3059 -drop | --drop_previous_database)
3060 dropPrevDb="true";
3061 ;;
3062
3063 -s | --sensor_name)
3064 error_if_switch "$1" "$opt";
3065 sensorName="$1";
3066 shift;
3067 ;;
3068
3069 -a | --alert_detail)
3070 error_if_switch "$1" "$opt";
3071 alertDetail="$1";
3072 shift;
3073 ;;
3074
3075 -rd | --ram-device)
3076 error_if_switch "$1" "$opt";
3077 ramDevice="$1";
3078 shift;
3079 ;;
3080
3081 -rds | --ram-disk-size)
3082 error_if_switch "$1" "$opt";
3083 ramDiskSize="$1";
3084 shift;
3085 ;;
3086
3087 -rmp | --ram-mount-point)
3088 error_if_switch "$1" "$opt";
3089 ramMntPt="$1";
3090 shift;
3091 ;;
3092
3093 -rdir | --runtime-directory)
3094 error_if_switch "$1" "$opt";
3095 runtimeDir="$1";
3096 shift;
3097 ;;
3098
3099 --HOME_NET)
3100 error_if_switch "$1" "$opt";
3101 home_net="$1";
3102 shift;
3103 ;;
3104
3105 --EXTERNAL_NET)
3106 error_if_switch "$1" "$opt";
3107 external_net="$1";
3108 shift;
3109 ;;
3110
3111 -x | --extra-services)
3112 mysqlExtra="true"; # install extra service entries...
3113 ;;
3114
3115 -e | --erase)
3116 eraseRuntimeDir="true";
3117 ;;
3118
3119 -disable)
3120 setup_snort_process_type="4"; # disable and kill one or more snort instances...
3121 ;;
3122
3123 -l | --list-status)
3124 setup_snort_process_type="5"; # list snort status...
3125 ;;
3126
3127 -sig | --signal)
3128 error_if_switch "$1" "$opt"
3129 signalType="$1";
3130 setup_snort_process_type="6"; # signal snort reload/dump...
3131 shift;
3132 ;;
3133
3134 -so | --snort-options)
3135 snort_options="$1";
3136 shift;
3137 ;;
3138
3139 -startup)
3140 error_if_switch "$1" "$opt"
3141 startupFlag="$1";
3142 setup_snort_process_type="7"; # snort startup flag setting...
3143 shift;
3144 ;;
3145
3146 -v | --verbose)
3147 verbose_mode="on"; # enable verbose mode...
3148 ;;
3149
3150 -h | --help)
3151 show_usage;
3152 exit 0;
3153 ;;
3154
3155 *)
3156 echo;
3157 echo "***ERROR*** Command line argument: '$opt' is not valid for this script..."
3158 show_short_usage;
3159 exit 2;
3160 esac
3161done
3162
3163#
3164# establish current Snort configuration dirs...
3165createSnortConfRuntimeRulesArrays;
3166
3167#
3168# process the selected interface list if necessary...
3169processInterfaceList;
3170
3171#
3172# if not killing a snort instance, listing snort status, or signaling snort: ...
3173if [ ${setup_snort_process_type} -le 2 ]; then
3174
3175# make sure just one interface name was selected when setting up a new snort instance...
3176 if [ ${setup_snort_process_type} -eq 1 ]; then
3177 if [ ${#SIL[@]} -gt 1 ]; then
3178 echo;
3179 echo "***ERROR*** When setting up a new Snort instance only one interface name can";
3180 echo " be used. You selected: \"-i ${interface}\"";
3181 show_short_usage;
3182 exit 53;
3183 fi
3184 snortCfgDir="/etc/snort_${SIL[0]}";
3185 fi
3186
3187# error is a snort instance for the selected interface is already running...
3188 if /bin/ps -ef | /bin/grep snort_${interface} | /bin/grep -v "grep" &> /dev/null; then
3189 echo;
3190 echo "***ERROR*** A running Snort instance for interface: \"${interface}\" already exists...";
3191 echo;
3192 echo " First use \"setup_snort -k -e -i ${interface}\" to kill the runnning Snort";
3193 echo " instance and optionally erase the existing Snort configuration.";
3194 show_short_usage;
3195 exit 54;
3196 fi
3197
3198# error if a configured snort instance already exists for the selected interface
3199# and is not scheduled for erasure...
3200 if [ -d ${snortCfgDir} -a "${eraseRuntimeDir}" = "false" ]; then
3201 echo;
3202 echo "***ERROR*** A configured Snort instance for interface: \"${interface}\" already exists...";
3203 echo;
3204 echo " Use the erase option: \"-e\" with the \"setup_snort\" script to";
3205 echo " first remove the existing Snort configuration."
3206 show_short_usage;
3207 exit 55;
3208 fi
3209
3210# calculate runtime directory...
3211 if [ -z "${runtimeDir}" ]; then
3212# set default RAM mount point dir if not already defined by user...
3213 if [ -z "${ramMntPt}" ]; then
3214 ramMntPt="/mnt/$(/bin/basename "${ramDevice}";)";
3215 fi
3216 runtimeDir="${ramMntPt}";
3217 else
3218# error if the user selected Snort runtime directory is not valid...
3219 if [ ! -d "${runtimeDir}" ]; then
3220 echo;
3221 echo "***ERROR*** Runtime Snort directory: \"${runtimeDir}\" does not exist...";
3222 echo;
3223 exit 4;
3224 fi
3225# disable creation of a RAM disk: a valid user runtime directory was issued...
3226 needRAMDisk="false"
3227 fi
3228
3229#
3230# Set variables which are rooted at runtimeDir
3231 pkgDir="${runtimeDir}/${PKG}";
3232
3233# see if collector mode was set?
3234 if [ "${collectorMode}" = "false" ]; then
3235# error if a base rule set source is not specified...
3236 if [ -z "${pkgRulesFetch}" ]; then
3237 echo;
3238 echo "***ERROR*** Base Snort rule source not set: \"-r <local> | <URL base rule source>\"..."
3239 echo "***ERROR*** -Or-"
3240 echo "***ERROR*** Need to specify Snort collector mode: \"-c\""
3241 show_short_usage;
3242 exit 6;
3243 fi
3244
3245# some input parameter error checking (alertDetail)...
3246 if [ "${alertDetail}" != "full" -a "${alertDetail}" != "fast" ]; then
3247 echo;
3248 echo "***ERROR*** Bad alert detail setting: \"${alertDetail}\"..."
3249 show_short_usage;
3250 exit 8;
3251 fi
3252
3253# default sensor name to IP Address of the default network interface if not set...
3254 if [ -z "${sensorName}" ]; then
3255 sensorName="$(/usr/bin/getipaddr -d;)";
3256 fi
3257
3258# clean up sensor name if it contains spaces: " " => "_"
3259 sensorName="${sensorName// /_}";
3260
3261 else # collector mode [-c] was set force "localhost" database hostname
3262 dbHostname="localhost";
3263 fi
3264fi
3265
3266
3267# execute the appropriate setup Snort process type...
3268case ${setup_snort_process_type} in
3269
3270 1) # setup a snort instance...
3271 if [ "${eraseRuntimeDir}" = "true" ]; then
3272 interfaceSpecified="true"
3273 eraseSnortInstance
3274 fi
3275 createRAMDisk; # see if a RAM disk is needed...
3276 setupSnortCfg; # setup a snort instance...
3277 setupBarnyard2Cfg; # setup a separate barnyard2 config for
3278 # each snort instance...
3279 # standalone Snort install -- install MySQL
3280 if [ "${dbHostname}" = "localhost" ]; then
3281 setupMySQL;
3282 # install extra snort database services entries?
3283 if [ "${mysqlExtra}" = "true" ]; then
3284 setupMySQLExtra;
3285 fi
3286 setupWWWBASE;
3287 fi
3288 displayUserSnortInfo;
3289 ;;
3290
3291 2) # setup collector mode...
3292 setupMySQL;
3293 # install extra snort database services entries?
3294 if [ "${mysqlExtra}" = "true" ]; then
3295 setupMySQLExtra;
3296 fi
3297 setupWWWBASE;
3298 displayUserSnortInfo;
3299 ;;
3300
3301 3) # update rules for one or more configured snort instances...
3302 processUpdatedSnortRules;
3303 ;;
3304
3305 4) # disable and kill snort instance(s)...
3306 disableSnortInstance;
3307 if [ "${eraseRuntimeDir}" = "true" ]; then
3308 eraseSnortInstance;
3309 fi
3310 ;;
3311
3312 5) # list snort status...
3313 listSnortStatus;
3314 ;;
3315
3316 6) # signal snort for reload/dump...
3317 if [ "${signalType}" = "reload" ]; then
3318 reloadSnort;
3319 else
3320 if [ "${signalType}" = "dump" ]; then
3321 dumpSnort;
3322 else
3323 echo;
3324 echo "***ERROR*** Need to specify the following signal types only: \"-sig <reload | dump>\"..."
3325 show_short_usage;
3326 exit 24;
3327 fi
3328 fi
3329 ;;
3330
3331 7) # set startup flag in snort conf file...
3332 if [ \( "${interfaceSpecified}" = "true" \) -a \( ${#SIL[@]} -eq 1 \) ]; then
3333 setStartupFlagSnortConf ${SIL[0]};
3334 else
3335 echo;
3336 if [ "${interfaceSpecified}" = "false" ]; then
3337 echo "***ERROR*** One interface must be specified when setting the Snort 'Startup' flag...";
3338 else
3339 echo "***ERROR*** Only one interface can be specified when setting the Snort 'Startup' flag: \"${SIL[@]}\"";
3340 fi
3341 echo;
3342 exit 36;
3343 fi
3344 ;;
3345
3346 *)
3347 echo "***ERROR*** Setup Snort process code type is not valid..."
3348 exit 9;
3349 ;;
3350
3351esac
3352
3353# terminate normally
3354exit 0;