]> git.ipfire.org Git - ipfire-2.x.git/blob - config/cfgroot/ids-functions.pl
28f08182aff999190c9ceef9fda83db730753a76
[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', 'fix-rules-dir' );
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 # Obtain error.
168 my $error = $response->content;
169
170 # Log error message.
171 &_log_to_syslog("Unable to download the ruleset. \($error\)");
172
173 # Return "1" - false.
174 return 1;
175 }
176
177 # If we got here, everything worked fine. Return nothing.
178 return;
179 }
180
181 #
182 ## A tiny wrapper function to call the oinkmaster script.
183 #
184 sub oinkmaster () {
185 # Check if the files in rulesdir have the correct permissions.
186 &_check_rulesdir_permissions();
187
188 # Load perl module to talk to the kernel syslog.
189 use Sys::Syslog qw(:DEFAULT setlogsock);
190
191 # Establish the connection to the syslog service.
192 openlog('oinkmaster', 'cons,pid', 'user');
193
194 # Call oinkmaster to generate ruleset.
195 open(OINKMASTER, "/usr/local/bin/oinkmaster.pl -v -s -u file://$rulestarball -C $settingsdir/oinkmaster.conf -o $rulespath|") or die "Could not execute oinkmaster $!\n";
196
197 # Log output of oinkmaster to syslog.
198 while(<OINKMASTER>) {
199 # The syslog function works best with an array based input,
200 # so generate one before passing the message details to syslog.
201 my @syslog = ("INFO", "$_");
202
203 # Send the log message.
204 syslog(@syslog);
205 }
206
207 # Close the pipe to oinkmaster process.
208 close(OINKMASTER);
209
210 # Close the log handle.
211 closelog();
212 }
213
214 #
215 ## Function to do all the logging stuff if the downloading or updating of the ruleset fails.
216 #
217 sub log_error ($) {
218 my ($error) = @_;
219
220 # Remove any newline.
221 chomp($error);
222
223 # Call private function to log the error message to syslog.
224 &_log_to_syslog($error);
225
226 # Call private function to write/store the error message in the storederrorfile.
227 &_store_error_message($error);
228 }
229
230 #
231 ## Function to log a given error message to the kernel syslog.
232 #
233 sub _log_to_syslog ($) {
234 my ($message) = @_;
235
236 # Load perl module to talk to the kernel syslog.
237 use Sys::Syslog qw(:DEFAULT setlogsock);
238
239 # The syslog function works best with an array based input,
240 # so generate one before passing the message details to syslog.
241 my @syslog = ("ERR", "<ERROR> $message");
242
243 # Establish the connection to the syslog service.
244 openlog('oinkmaster', 'cons,pid', 'user');
245
246 # Send the log message.
247 syslog(@syslog);
248
249 # Close the log handle.
250 closelog();
251 }
252
253 #
254 ## Private function to write a given error message to the storederror file.
255 #
256 sub _store_error_message ($) {
257 my ($message) = @_;
258
259 # Remove any newline.
260 chomp($message);
261
262 # Open file for writing.
263 open (ERRORFILE, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n";
264
265 # Write error to file.
266 print ERRORFILE "$message\n";
267
268 # Close file.
269 close (ERRORFILE);
270 }
271
272 #
273 ## Function to get a list of all available network zones.
274 #
275 sub get_available_network_zones () {
276 # Get netsettings.
277 my %netsettings = ();
278 &General::readhash("${General::swroot}/ethernet/settings", \%netsettings);
279
280 # Obtain the configuration type from the netsettings hash.
281 my $config_type = $netsettings{'CONFIG_TYPE'};
282
283 # Hash which contains the conversation from the config mode
284 # to the existing network interface names. They are stored like
285 # an array.
286 #
287 # Mode "0" red is a modem and green
288 # Mode "1" red is a netdev and green
289 # Mode "2" red, green and orange
290 # Mode "3" red, green and blue
291 # Mode "4" red, green, blue, orange
292 my %config_type_to_interfaces = (
293 "0" => [ "red", "green" ],
294 "1" => [ "red", "green" ],
295 "2" => [ "red", "green", "orange" ],
296 "3" => [ "red", "green", "blue" ],
297 "4" => [ "red", "green", "blue", "orange" ]
298 );
299
300 # Obtain and dereference the corresponding network interaces based on the read
301 # network config type.
302 my @network_zones = @{ $config_type_to_interfaces{$config_type} };
303
304 # Return them.
305 return @network_zones;
306 }
307
308 #
309 ## Function to check if the IDS is running.
310 #
311 sub ids_is_running () {
312 if(-f $idspidfile) {
313 # Open PID file for reading.
314 open(PIDFILE, "$idspidfile") or die "Could not open $idspidfile. $!\n";
315
316 # Grab the process-id.
317 my $pid = <PIDFILE>;
318
319 # Close filehandle.
320 close(PIDFILE);
321
322 # Remove any newline.
323 chomp($pid);
324
325 # Check if a directory for the process-id exists in proc.
326 if(-d "/proc/$pid") {
327 # The IDS daemon is running return the process id.
328 return $pid;
329 }
330 }
331
332 # Return nothing - IDS is not running.
333 return;
334 }
335
336 #
337 ## Function to call suricatactrl binary with a given command.
338 #
339 sub call_suricatactrl ($) {
340 # Get called option.
341 my ($option) = @_;
342
343 # Loop through the array of supported commands and check if
344 # the given one is part of it.
345 foreach my $cmd (@suricatactrl_cmds) {
346 # Skip current command unless the given one has been found.
347 next unless($cmd eq $option);
348
349 # Call the suricatactrl binary and pass the requrested
350 # option to it.
351 system("$suricatactrl $option &>/dev/null");
352
353 # Return "1" - True.
354 return 1;
355 }
356
357 # Command not found - return nothing.
358 return;
359 }
360
361 #
362 ## Function to create a new empty file.
363 #
364 sub create_empty_file($) {
365 my ($file) = @_;
366
367 # Check if the given file exists.
368 if(-e $file) {
369 # Do nothing to prevent from overwriting existing files.
370 return;
371 }
372
373 # Open the file for writing.
374 open(FILE, ">$file") or die "Could not write to $file. $!\n";
375
376 # Close file handle.
377 close(FILE);
378
379 # Return true.
380 return 1;
381 }
382
383 #
384 ## Private function to check if the file permission of the rulespath are correct.
385 ## If not, call suricatactrl to fix them.
386 #
387 sub _check_rulesdir_permissions() {
388 # Check if the rulepath main directory is writable.
389 unless (-W $rulespath) {
390 # If not call suricatctrl to fix it.
391 &call_suricatactrl("fix-rules-dir");
392 }
393
394 # Open snort rules directory and do a directory listing.
395 opendir(DIR, $rulespath) or die $!;
396 # Loop through the direcory.
397 while (my $file = readdir(DIR)) {
398 # We only want files.
399 next unless (-f "$rulespath/$file");
400
401 # Check if the file is writable by the user.
402 if (-W "$rulespath/$file") {
403 # Everything is okay - go on to the next file.
404 next;
405 } else {
406 # There are wrong permissions, call suricatactrl to fix it.
407 &call_suricatactrl("fix-rules-dir");
408 }
409 }
410 }
411
412 1;