]> git.ipfire.org Git - ipfire-2.x.git/blob - config/cfgroot/ids-functions.pl
ids-functions.pl: Add function to call suricatactrl binary
[ipfire-2.x.git] / config / cfgroot / ids-functions.pl
1 #!/usr/bin/perl -w
2 ############################################################################
3 # #
4 # This file is part of the IPFire Firewall. #
5 # #
6 # IPFire is free software; you can redistribute it and/or modify #
7 # it under the terms of the GNU General Public License as published by #
8 # the Free Software Foundation; either version 2 of the License, or #
9 # (at your option) any later version. #
10 # #
11 # IPFire is distributed in the hope that it will be useful, #
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
14 # GNU General Public License for more details. #
15 # #
16 # You should have received a copy of the GNU General Public License #
17 # along with IPFire; if not, write to the Free Software #
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #
19 # #
20 # Copyright (C) 2018 IPFire Team <info@ipfire.org>. #
21 # #
22 ############################################################################
23
24 package IDS;
25
26 require '/var/ipfire/general-functions.pl';
27
28 # Location where all config and settings files are stored.
29 our $settingsdir = "${General::swroot}/suricata";
30
31 # Location and name of the tarball which contains the ruleset.
32 our $rulestarball = "/var/tmp/idsrules.tar.gz";
33
34 # File to store any errors, which also will be read and displayed by the wui.
35 our $storederrorfile = "/tmp/ids_storederror";
36
37 # Location where the rulefiles are stored.
38 our $rulespath = "/etc/suricata/rules";
39
40 # File which contains a list of all supported ruleset sources.
41 # (Sourcefire, Emergingthreads, etc..)
42 our $rulesetsourcesfile = "$settingsdir/ruleset-sources";
43
44 # The pidfile of the IDS.
45 our $idspidfile = "/var/run/suricata.pid";
46
47 # Location of suricatactrl.
48 my $suricatactrl = "/usr/local/bin/suricatactrl";
49
50 # Array with allowed commands of suricatactrl.
51 my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload' );
52
53 #
54 ## Function for checking if at least 300MB of free disk space are available
55 ## on the "/var" partition.
56 #
57 sub checkdiskspace () {
58 # Call diskfree to gather the free disk space of /var.
59 my @df = `/bin/df -B M /var`;
60
61 # Loop through the output.
62 foreach my $line (@df) {
63 # Ignore header line.
64 next if $line =~ m/^Filesystem/;
65
66 # Search for a line with the device information.
67 if ($line =~ m/dev/ ) {
68 # Split the line into single pieces.
69 my @values = split(' ', $line);
70 my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values;
71
72 # Check if the available disk space is more than 300MB.
73 if ($available < 300) {
74 # Log error to syslog.
75 &_log_to_syslog("Not enough free disk space on /var. Only $available MB from 300 MB available.");
76
77 # Exit function and return "1" - False.
78 return 1;
79 }
80 }
81 }
82
83 # Everything okay, return nothing.
84 return;
85 }
86
87 #
88 ## This function is responsible for downloading the configured snort ruleset.
89 ##
90 ## * At first it obtains from the stored snortsettings which ruleset should be downloaded.
91 ## * The next step is to get the download locations for all available rulesets.
92 ## * After that, the function will check if an upstream proxy should be used and grab the settings.
93 ## * The last step will be to generate the final download url, by obtaining the URL for the desired
94 ## ruleset, add the settings for the upstream proxy and final grab the rules tarball from the server.
95 #
96 sub downloadruleset {
97 # Get snort settings.
98 my %snortsettings=();
99 &General::readhash("$settingsdir/settings", \%snortsettings);
100
101 # Get all available ruleset locations.
102 my %rulesetsources=();
103 &General::readhash($rulesetsourcesfile, \%rulesetsources);
104
105 # Read proxysettings.
106 my %proxysettings=();
107 &General::readhash("${General::swroot}/proxy/settings", \%proxysettings);
108
109 # Load required perl module to handle the download.
110 use LWP::UserAgent;
111
112 # Init the download module.
113 my $downloader = LWP::UserAgent->new;
114
115 # Set timeout to 10 seconds.
116 $downloader->timeout(10);
117
118 # Check if an upstream proxy is configured.
119 if ($proxysettings{'UPSTREAM_PROXY'}) {
120 my ($peer, $peerport) = (/^(?:[a-zA-Z ]+\:\/\/)?(?:[A-Za-z0-9\_\.\-]*?(?:\:[A-Za-z0-9\_\.\-]*?)?\@)?([a-zA-Z0-9\.\_\-]*?)(?:\:([0-9]{1,5}))?(?:\/.*?)?$/);
121 my $proxy_url;
122
123 # Check if we got a peer.
124 if ($peer) {
125 $proxy_url = "http://";
126
127 # Check if the proxy requires authentication.
128 if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) {
129 $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@";
130 }
131
132 # Add proxy server address and port.
133 $proxy_url .= "$peer\:$peerport";
134 } else {
135 # Log error message and break.
136 &_log_to_syslog("Could not proper configure the proxy server access.");
137
138 # Return "1" - false.
139 return 1;
140 }
141
142 # Setup proxy settings.
143 $downloader->proxy('http', $proxy_url);
144 }
145
146 # Grab the right url based on the configured vendor.
147 my $url = $rulesetsources{$snortsettings{'RULES'}};
148
149 # Check if the vendor requires an oinkcode and add it if needed.
150 $url =~ s/\<oinkcode\>/$snortsettings{'OINKCODE'}/g;
151
152 # Abort if no url could be determined for the vendor.
153 unless ($url) {
154 # Log error and abort.
155 &_log_to_syslog("Unable to gather a download URL for the selected ruleset.");
156 return 1;
157 }
158
159 # Pass the requested url to the downloader.
160 my $request = HTTP::Request->new(GET => $url);
161
162 # Perform the request and save the output into the "$rulestarball" file.
163 my $response = $downloader->request($request, $rulestarball);
164
165 # Check if there was any error.
166 unless ($response->is_success) {
167 # Log error message.
168 &_log_to_syslog("Unable to download the ruleset. $response->status_line");
169
170 # Return "1" - false.
171 return 1;
172 }
173
174 # If we got here, everything worked fine. Return nothing.
175 return;
176 }
177
178 #
179 ## A tiny wrapper function to call the oinkmaster script.
180 #
181 sub oinkmaster () {
182 # Load perl module to talk to the kernel syslog.
183 use Sys::Syslog qw(:DEFAULT setlogsock);
184
185 # Establish the connection to the syslog service.
186 openlog('oinkmaster', 'cons,pid', 'user');
187
188 # Call oinkmaster to generate ruleset.
189 open(OINKMASTER, "/usr/local/bin/oinkmaster.pl -v -s -u file://$rulestarball -C $settingsdir/oinkmaster.conf -o $rulespath|");
190
191 # Log output of oinkmaster to syslog.
192 while(<OINKMASTER>) {
193 # The syslog function works best with an array based input,
194 # so generate one before passing the message details to syslog.
195 my @syslog = ("INFO", "$_");
196
197 # Send the log message.
198 syslog(@syslog);
199 }
200
201 # Close the pipe to oinkmaster process.
202 close(OINKMASTER);
203
204 # Close the log handle.
205 closelog();
206 }
207
208 #
209 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
210 #
211 sub log_error ($) {
212 my ($error) = @_;
213
214 # Remove any newline.
215 chomp($error);
216
217 # Call private function to log the error message to syslog.
218 &_log_to_syslog($error);
219
220 # Call private function to write/store the error message in the storederrorfile.
221 &_store_error_message($error);
222 }
223
224 #
225 ## Function to log a given error message to the kernel syslog.
226 #
227 sub _log_to_syslog ($) {
228 my ($message) = @_;
229
230 # Load perl module to talk to the kernel syslog.
231 use Sys::Syslog qw(:DEFAULT setlogsock);
232
233 # The syslog function works best with an array based input,
234 # so generate one before passing the message details to syslog.
235 my @syslog = ("ERR", "<ERROR> $message");
236
237 # Establish the connection to the syslog service.
238 openlog('oinkmaster', 'cons,pid', 'user');
239
240 # Send the log message.
241 syslog(@syslog);
242
243 # Close the log handle.
244 closelog();
245 }
246
247 #
248 ## Private function to write a given error message to the storederror file.
249 #
250 sub _store_error_message ($) {
251 my ($message) = @_;
252
253 # Remove any newline.
254 chomp($message);
255
256 # Open file for writing.
257 open (ERRORFILE, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
258
259 # Write error to file.
260 print ERRORFILE "$message\n";
261
262 # Close file.
263 close (ERRORFILE);
264 }
265
266 #
267 ## Function to get a list of all available network zones.
268 #
269 sub get_available_network_zones () {
270 # Get netsettings.
271 my %netsettings = ();
272 &General::readhash("${General::swroot}/ethernet/settings", \%netsettings);
273
274 # Obtain the configuration type from the netsettings hash.
275 my $config_type = $netsettings{'CONFIG_TYPE'};
276
277 # Hash which contains the conversation from the config mode
278 # to the existing network interface names. They are stored like
279 # an array.
280 #
281 # Mode "0" red is a modem and green
282 # Mode "1" red is a netdev and green
283 # Mode "2" red, green and orange
284 # Mode "3" red, green and blue
285 # Mode "4" red, green, blue, orange
286 my %config_type_to_interfaces = (
287 "0" => [ "red", "green" ],
288 "1" => [ "red", "green" ],
289 "2" => [ "red", "green", "orange" ],
290 "3" => [ "red", "green", "blue" ],
291 "4" => [ "red", "green", "blue", "orange" ]
292 );
293
294 # Obtain and dereference the corresponding network interaces based on the read
295 # network config type.
296 my @network_zones = @{ $config_type_to_interfaces{$config_type} };
297
298 # Return them.
299 return @network_zones;
300 }
301
302 #
303 ## Function to check if the IDS is running.
304 #
305 sub ids_is_running () {
306 if(-f $idspidfile) {
307 # Open PID file for reading.
308 open(PIDFILE, "$idspidfile") or die "Could not open $idspidfile. $!\n";
309
310 # Grab the process-id.
311 my $pid = <PIDFILE>;
312
313 # Close filehandle.
314 close(PIDFILE);
315
316 # Remove any newline.
317 chomp($pid);
318
319 # Check if a directory for the process-id exists in proc.
320 if(-d "/proc/$pid") {
321 # The IDS daemon is running return the process id.
322 return $pid;
323 }
324 }
325
326 # Return nothing - IDS is not running.
327 return;
328 }
329
330 #
331 ## Function to call suricatactrl binary with a given command.
332 #
333 sub call_suricatactrl ($) {
334 # Get called option.
335 my ($option) = @_;
336
337 # Loop through the array of supported commands and check if
338 # the given one is part of it.
339 foreach my $cmd (@suricatactrl_cmds) {
340 # Skip current command unless the given one has been found.
341 next unless($cmd eq $option);
342
343 # Call the suricatactrl binary and pass the requrested
344 # option to it.
345 system("$suricatactrl $option &>/dev/null");
346
347 # Return "1" - True.
348 return 1;
349 }
350
351 # Command not found - return nothing.
352 return;
353 }
354
355 1;