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