]>
Commit | Line | Data |
---|---|---|
8dcebe53 SS |
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 | # # | |
fd2dccaa | 20 | # Copyright (C) 2018-2019 IPFire Team <info@ipfire.org> # |
8dcebe53 SS |
21 | # # |
22 | ############################################################################ | |
23 | ||
e55fa2f7 SS |
24 | use strict; |
25 | ||
8dcebe53 SS |
26 | package IDS; |
27 | ||
28 | require '/var/ipfire/general-functions.pl'; | |
abffcc99 | 29 | require "${General::swroot}/network-functions.pl"; |
35bc92a3 | 30 | require "${General::swroot}/suricata/ruleset-sources"; |
8dcebe53 | 31 | |
7d895608 SS |
32 | # Load perl module to deal with Archives. |
33 | use Archive::Tar; | |
34 | ||
35 | # Load perl module to deal with files and path. | |
36 | use File::Basename; | |
37 | ||
38 | # Load module to move files. | |
39 | use File::Copy; | |
40 | ||
41 | # Load module to recursely remove files and a folder. | |
42 | use File::Path qw(rmtree); | |
43 | ||
44 | # Load module to get file stats. | |
45 | use File::stat; | |
46 | ||
47 | # Load module to deal with temporary files. | |
48 | use File::Temp; | |
49 | ||
061391e7 SS |
50 | # Load module to deal with the date formats used by the HTTP protocol. |
51 | use HTTP::Date; | |
52 | ||
7d895608 SS |
53 | # Load the libwwwperl User Agent module. |
54 | use LWP::UserAgent; | |
55 | ||
56 | # Load function from posix module to format time strings. | |
57 | use POSIX qw (strftime); | |
58 | ||
59 | # Load module to talk to the kernel log daemon. | |
60 | use Sys::Syslog qw(:DEFAULT setlogsock); | |
61 | ||
02844177 | 62 | # Location where all config and settings files are stored. |
164eab66 | 63 | our $settingsdir = "${General::swroot}/suricata"; |
02844177 | 64 | |
ddaf8ae1 SS |
65 | # File where the main file for providers ruleset inclusion exists. |
66 | our $suricata_used_providers_file = "$settingsdir/suricata-used-providers.yaml"; | |
67 | ||
88eb5626 | 68 | # File for static ruleset inclusions. |
43d12991 | 69 | our $suricata_default_rulefiles_file = "$settingsdir/suricata-default-rules.yaml"; |
88eb5626 | 70 | |
b02e30fd SS |
71 | # File where the addresses of the homenet are stored. |
72 | our $homenet_file = "$settingsdir/suricata-homenet.yaml"; | |
73 | ||
30ee98e9 SS |
74 | # File where the addresses of the used DNS servers are stored. |
75 | our $dns_servers_file = "$settingsdir/suricata-dns-servers.yaml"; | |
76 | ||
e698090e SS |
77 | # File where the HTTP ports definition is stored. |
78 | our $http_ports_file = "$settingsdir/suricata-http-ports.yaml"; | |
79 | ||
15832b10 SS |
80 | # File which contains includes for provider specific rule modifications. |
81 | our $oinkmaster_provider_includes_file = "$settingsdir/oinkmaster-provider-includes.conf"; | |
82 | ||
b02e30fd SS |
83 | # File which contains wheater the rules should be changed. |
84 | our $modify_sids_file = "$settingsdir/oinkmaster-modify-sids.conf"; | |
85 | ||
86 | # File which stores the configured IPS settings. | |
87 | our $ids_settings_file = "$settingsdir/settings"; | |
88 | ||
a8d36d3e SS |
89 | # File which stores the used and configured ruleset providers. |
90 | our $providers_settings_file = "$settingsdir/providers-settings"; | |
91 | ||
b02e30fd SS |
92 | # File which stores the configured settings for whitelisted addresses. |
93 | our $ignored_file = "$settingsdir/ignored"; | |
94 | ||
788a71f5 SS |
95 | # Location where the downloaded rulesets are stored. |
96 | our $dl_rules_path = "/var/tmp"; | |
97 | ||
3983aebd | 98 | # File to store any errors, which also will be read and displayed by the wui. |
77910792 | 99 | our $storederrorfile = "/tmp/ids_storederror"; |
3983aebd | 100 | |
8076deba SS |
101 | # File to lock the WUI, while the autoupdate script runs. |
102 | our $ids_page_lock_file = "/tmp/ids_page_locked"; | |
103 | ||
298ef5ba | 104 | # Location where the rulefiles are stored. |
21cab141 | 105 | our $rulespath = "/var/lib/suricata"; |
298ef5ba | 106 | |
43d12991 SS |
107 | # Location where the default rulefils are stored. |
108 | our $default_rulespath = "/usr/share/suricata/rules"; | |
109 | ||
6983a96e SS |
110 | # Location where the addition config files are stored. |
111 | our $configspath = "/usr/share/suricata"; | |
112 | ||
23b56052 | 113 | # Location of the classification file. |
6983a96e | 114 | our $classification_file = "$configspath/classification.config"; |
23b56052 | 115 | |
8bd74e12 SS |
116 | # Location of the sid to msg mappings file. |
117 | our $sid_msg_file = "$rulespath/sid-msg.map"; | |
118 | ||
612bb2df SS |
119 | # Location to store local rules. This file will not be touched. |
120 | our $local_rules_file = "$rulespath/local.rules"; | |
121 | ||
b02e30fd SS |
122 | # File which contains the rules to whitelist addresses on suricata. |
123 | our $whitelist_file = "$rulespath/whitelist.rules"; | |
124 | ||
bce84f39 SS |
125 | # File which contains a list of all supported ruleset sources. |
126 | # (Sourcefire, Emergingthreads, etc..) | |
127 | our $rulesetsourcesfile = "$settingsdir/ruleset-sources"; | |
128 | ||
796eea21 SS |
129 | # The pidfile of the IDS. |
130 | our $idspidfile = "/var/run/suricata.pid"; | |
131 | ||
5240a809 SS |
132 | # Location of suricatactrl. |
133 | my $suricatactrl = "/usr/local/bin/suricatactrl"; | |
134 | ||
788a71f5 SS |
135 | # Prefix for each downloaded ruleset. |
136 | my $dl_rulesfile_prefix = "idsrules"; | |
137 | ||
0fbfffea SS |
138 | # Temporary directory where the rulesets will be extracted. |
139 | my $tmp_directory = "/tmp/ids_tmp"; | |
140 | ||
6c9d3eee SS |
141 | # Temporary directory where the extracted rules files will be stored. |
142 | my $tmp_rules_directory = "$tmp_directory/rules"; | |
143 | ||
144 | # Temporary directory where the extracted additional config files will be stored. | |
145 | my $tmp_conf_directory = "$tmp_directory/conf"; | |
146 | ||
5240a809 | 147 | # Array with allowed commands of suricatactrl. |
ed06bc81 SS |
148 | my @suricatactrl_cmds = ( 'start', 'stop', 'restart', 'reload', 'fix-rules-dir', 'cron' ); |
149 | ||
150 | # Array with supported cron intervals. | |
151 | my @cron_intervals = ('off', 'daily', 'weekly' ); | |
5240a809 | 152 | |
e698090e SS |
153 | # Array which contains the HTTP ports, which statically will be declared as HTTP_PORTS in the |
154 | # http_ports_file. | |
155 | my @http_ports = ('80', '81'); | |
156 | ||
88eb5626 | 157 | # Array which contains a list of rulefiles which always will be included if they exist. |
bb39fac4 SS |
158 | my @static_included_rulefiles = ('local.rules', 'whitelist.rules'); |
159 | ||
160 | # Array which contains a list of allways enabled application layer protocols. | |
161 | my @static_enabled_app_layer_protos = ('app-layer', 'decoder', 'files', 'stream'); | |
88eb5626 | 162 | |
788a71f5 SS |
163 | # Hash which allows to convert the download type (dl_type) to a file suffix. |
164 | my %dl_type_to_suffix = ( | |
165 | "archive" => ".tar.gz", | |
166 | "plain" => ".rules", | |
167 | ); | |
168 | ||
43d12991 SS |
169 | # Hash to translate an application layer protocol to the application name. |
170 | my %tr_app_layer_proto = ( | |
171 | "ikev2" => "ipsec", | |
172 | "krb5" => "kerberos", | |
173 | ); | |
174 | ||
b02e30fd SS |
175 | # |
176 | ## Function to check and create all IDS related files, if the does not exist. | |
177 | # | |
178 | sub check_and_create_filelayout() { | |
179 | # Check if the files exist and if not, create them. | |
15832b10 | 180 | unless (-f "$oinkmaster_provider_includes_file") { &create_empty_file($oinkmaster_provider_includes_file); } |
b02e30fd | 181 | unless (-f "$modify_sids_file") { &create_empty_file($modify_sids_file); } |
ddaf8ae1 | 182 | unless (-f "$suricata_used_providers_file") { &create_empty_file($suricata_used_providers_file); } |
2f62fd00 | 183 | unless (-f "$suricata_default_rulefiles_file") { &create_empty_file($suricata_default_rulefiles_file); } |
b02e30fd | 184 | unless (-f "$ids_settings_file") { &create_empty_file($ids_settings_file); } |
a8d36d3e | 185 | unless (-f "$providers_settings_file") { &create_empty_file($providers_settings_file); } |
b02e30fd SS |
186 | unless (-f "$whitelist_file" ) { &create_empty_file($whitelist_file); } |
187 | } | |
188 | ||
70cc1315 SS |
189 | # |
190 | ## Function to get a list of all available ruleset providers. | |
191 | ## | |
192 | ## They will be returned as a sorted array. | |
193 | # | |
194 | sub get_ruleset_providers() { | |
195 | my @providers; | |
196 | ||
197 | # Loop through the hash of providers. | |
198 | foreach my $provider ( keys %IDS::Ruleset::Providers ) { | |
199 | # Add the provider to the array. | |
200 | push(@providers, $provider); | |
201 | } | |
202 | ||
203 | # Sort and return the array. | |
204 | return sort(@providers); | |
205 | } | |
206 | ||
5e20d6cb SS |
207 | # |
208 | ## Function to get a list of all enabled ruleset providers. | |
209 | ## | |
210 | ## They will be returned as an array. | |
211 | # | |
212 | sub get_enabled_providers () { | |
213 | my %used_providers = (); | |
214 | ||
215 | # Array to store the enabled providers. | |
216 | my @enabled_providers = (); | |
217 | ||
218 | # Read-in the providers config file. | |
219 | &General::readhasharray("$providers_settings_file", \%used_providers); | |
220 | ||
221 | # Loop through the hash of used_providers. | |
222 | foreach my $id (keys %used_providers) { | |
223 | # Skip disabled providers. | |
224 | next unless ($used_providers{$id}[3] eq "enabled"); | |
225 | ||
226 | # Grab the provider handle. | |
227 | my $provider = "$used_providers{$id}[0]"; | |
228 | ||
229 | # Add the provider to the array of enabled providers. | |
230 | push(@enabled_providers, $provider); | |
231 | } | |
232 | ||
233 | # Return the array. | |
234 | return @enabled_providers; | |
235 | } | |
236 | ||
e0eb5bc7 SS |
237 | # |
238 | ## Function to get a hash of provider handles and their configured modes (IDS/IPS). | |
239 | # | |
240 | sub get_providers_mode () { | |
241 | my %used_providers = (); | |
242 | ||
243 | # Hash to store the providers and their configured modes. | |
244 | my %providers_mode = (); | |
245 | ||
246 | # Read-in the providers config file. | |
247 | &General::readhasharray("$providers_settings_file", \%used_providers); | |
248 | ||
249 | # Loop through the hash of used_providers. | |
250 | foreach my $id (keys %used_providers) { | |
251 | # Skip disabled providers. | |
252 | next unless ($used_providers{$id}[3] eq "enabled"); | |
253 | ||
254 | # Grab the provider handle. | |
255 | my $provider = "$used_providers{$id}[0]"; | |
256 | ||
257 | # Grab the provider mode. | |
258 | my $mode = "$used_providers{$id}[4]"; | |
259 | ||
260 | # Fall back to IDS if no mode could be obtained. | |
261 | unless($mode) { | |
262 | $mode = "IDS"; | |
263 | } | |
264 | ||
265 | # Add details to provider_modes hash. | |
266 | $providers_mode{$provider} = $mode; | |
267 | } | |
268 | ||
269 | # Return the hash. | |
270 | return %providers_mode; | |
271 | } | |
272 | ||
8dcebe53 SS |
273 | # |
274 | ## Function for checking if at least 300MB of free disk space are available | |
275 | ## on the "/var" partition. | |
276 | # | |
277 | sub checkdiskspace () { | |
278 | # Call diskfree to gather the free disk space of /var. | |
81631920 | 279 | my @df = &General::system_output("/bin/df", "-B", "M", "/var"); |
8dcebe53 SS |
280 | |
281 | # Loop through the output. | |
282 | foreach my $line (@df) { | |
283 | # Ignore header line. | |
284 | next if $line =~ m/^Filesystem/; | |
285 | ||
286 | # Search for a line with the device information. | |
287 | if ($line =~ m/dev/ ) { | |
288 | # Split the line into single pieces. | |
289 | my @values = split(' ', $line); | |
290 | my ($filesystem, $blocks, $used, $available, $used_perenctage, $mounted_on) = @values; | |
291 | ||
292 | # Check if the available disk space is more than 300MB. | |
293 | if ($available < 300) { | |
65e3aef5 SS |
294 | # Exit function and return the available disk space. |
295 | return $available; | |
8dcebe53 SS |
296 | } |
297 | } | |
298 | } | |
299 | ||
300 | # Everything okay, return nothing. | |
301 | return; | |
302 | } | |
303 | ||
eea2670b | 304 | # |
0f2c5211 | 305 | ## This function is responsible for downloading the ruleset for a given provider. |
eea2670b | 306 | ## |
0f2c5211 | 307 | ## * At first it initialize the downloader and sets an upstream proxy if configured. |
b3c2c336 | 308 | ## * The next step will be to generate the final download url, by obtaining the URL for the desired |
0f2c5211 SS |
309 | ## ruleset and add the settings for the upstream proxy. |
310 | ## * Finally the function will grab the rule file or tarball from the server. | |
311 | ## It tries to reduce the amount of download by using the "If-Modified-Since" HTTP header. | |
eea2670b | 312 | # |
e26edcc1 SS |
313 | ## Return codes: |
314 | ## | |
315 | ## * "no url" - If no download URL could be gathered for the provider. | |
316 | ## * "not modified" - In case the already stored rules file is up to date. | |
317 | ## * "incomplete download" - When the remote file size differs from the downloaded file size. | |
318 | ## * "$error" - The error message generated from the LWP::User Agent module. | |
319 | # | |
b3c2c336 SS |
320 | sub downloadruleset ($) { |
321 | my ($provider) = @_; | |
322 | ||
e71804fb SS |
323 | # The amount of download attempts before giving up and |
324 | # logging an error. | |
325 | my $max_dl_attempts = 3; | |
326 | ||
eea2670b SS |
327 | # Read proxysettings. |
328 | my %proxysettings=(); | |
329 | &General::readhash("${General::swroot}/proxy/settings", \%proxysettings); | |
330 | ||
eea2670b | 331 | # Init the download module. |
954dbdad SS |
332 | # |
333 | # Request SSL hostname verification and specify path | |
334 | # to the CA file. | |
335 | my $downloader = LWP::UserAgent->new( | |
336 | ssl_opts => { | |
337 | SSL_ca_file => '/etc/ssl/cert.pem', | |
338 | verify_hostname => 1, | |
339 | } | |
340 | ); | |
eea2670b SS |
341 | |
342 | # Set timeout to 10 seconds. | |
343 | $downloader->timeout(10); | |
344 | ||
345 | # Check if an upstream proxy is configured. | |
346 | if ($proxysettings{'UPSTREAM_PROXY'}) { | |
eea2670b SS |
347 | my $proxy_url; |
348 | ||
40407aee | 349 | $proxy_url = "http://"; |
eea2670b | 350 | |
40407aee PM |
351 | # Check if the proxy requires authentication. |
352 | if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) { | |
353 | $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@"; | |
eea2670b SS |
354 | } |
355 | ||
40407aee PM |
356 | # Add proxy server address and port. |
357 | $proxy_url .= $proxysettings{'UPSTREAM_PROXY'}; | |
358 | ||
eea2670b | 359 | # Setup proxy settings. |
6994f001 | 360 | $downloader->proxy(['http', 'https'], $proxy_url); |
eea2670b SS |
361 | } |
362 | ||
0f2c5211 SS |
363 | # Grab the download url for the provider. |
364 | my $url = $IDS::Ruleset::Providers{$provider}{'dl_url'}; | |
b3c2c336 | 365 | |
0f2c5211 SS |
366 | # Check if the provider requires a subscription. |
367 | if ($IDS::Ruleset::Providers{$provider}{'requires_subscription'} eq "True") { | |
368 | # Grab the subscription code. | |
369 | my $subscription_code = &get_subscription_code($provider); | |
b3c2c336 | 370 | |
0f2c5211 SS |
371 | # Add the subscription code to the download url. |
372 | $url =~ s/\<subscription_code\>/$subscription_code/g; | |
b3c2c336 | 373 | |
0f2c5211 | 374 | } |
f264adda | 375 | |
52a557a8 SS |
376 | # Abort and return "no url", if no url could be determined for the provider. |
377 | return "no url" unless ($url); | |
96da5803 | 378 | |
0f2c5211 SS |
379 | # Pass the requested URL to the downloader. |
380 | my $request = HTTP::Request->new(GET => $url); | |
061391e7 | 381 | |
0f2c5211 SS |
382 | # Generate temporary file name, located in "/var/tmp" and with a suffix of ".tmp". |
383 | # The downloaded file will be stored there until some sanity checks are performed. | |
384 | my $tmp = File::Temp->new( SUFFIX => ".tmp", DIR => "/var/tmp/", UNLINK => 0 ); | |
385 | my $tmpfile = $tmp->filename(); | |
061391e7 | 386 | |
0f2c5211 SS |
387 | # Call function to get the final path and filename for the downloaded file. |
388 | my $dl_rulesfile = &_get_dl_rulesfile($provider); | |
061391e7 | 389 | |
0f2c5211 SS |
390 | # Check if the rulesfile already exits, because it has been downloaded in the past. |
391 | # | |
392 | # In this case we are requesting the server if the remote file has been changed or not. | |
393 | # This will be done by sending the modification time in a special HTTP header. | |
394 | if (-f $dl_rulesfile) { | |
395 | # Call stat on the file. | |
396 | my $stat = stat($dl_rulesfile); | |
061391e7 | 397 | |
0f2c5211 SS |
398 | # Omit the mtime of the existing file. |
399 | my $mtime = $stat->mtime; | |
061391e7 | 400 | |
0f2c5211 SS |
401 | # Convert the timestamp into right format. |
402 | my $http_date = time2str($mtime); | |
96da5803 | 403 | |
0f2c5211 SS |
404 | # Add the If-Modified-Since header to the request to ask the server if the |
405 | # file has been modified. | |
406 | $request->header( 'If-Modified-Since' => "$http_date" ); | |
407 | } | |
96da5803 | 408 | |
0f2c5211 SS |
409 | my $dl_attempt = 1; |
410 | my $response; | |
155b3b56 | 411 | |
0f2c5211 SS |
412 | # Download and retry on failure. |
413 | while ($dl_attempt <= $max_dl_attempts) { | |
414 | # Perform the request and save the output into the tmpfile. | |
415 | $response = $downloader->request($request, $tmpfile); | |
061391e7 | 416 | |
0f2c5211 SS |
417 | # Check if the download was successfull. |
418 | if($response->is_success) { | |
419 | # Break loop. | |
420 | last; | |
061391e7 | 421 | |
0f2c5211 SS |
422 | # Check if the server responds with 304 (Not Modified). |
423 | } elsif ($response->code == 304) { | |
e26edcc1 SS |
424 | # Return "not modified". |
425 | return "not modified"; | |
e71804fb | 426 | |
0f2c5211 SS |
427 | # Check if we ran out of download re-tries. |
428 | } elsif ($dl_attempt eq $max_dl_attempts) { | |
429 | # Obtain error. | |
430 | my $error = $response->content; | |
e71804fb | 431 | |
e26edcc1 SS |
432 | # Return the error message from response.. |
433 | return "$error"; | |
155b3b56 | 434 | } |
96da5803 | 435 | |
0f2c5211 SS |
436 | # Remove temporary file, if one exists. |
437 | unlink("$tmpfile") if (-e "$tmpfile"); | |
de1199e2 | 438 | |
0f2c5211 SS |
439 | # Increase download attempt counter. |
440 | $dl_attempt++; | |
441 | } | |
061391e7 | 442 | |
0f2c5211 SS |
443 | # Obtain the connection headers. |
444 | my $headers = $response->headers; | |
de1199e2 | 445 | |
0f2c5211 SS |
446 | # Get the timestamp from header, when the file has been modified the |
447 | # last time. | |
448 | my $last_modified = $headers->last_modified; | |
96da5803 | 449 | |
0f2c5211 SS |
450 | # Get the remote size of the downloaded file. |
451 | my $remote_filesize = $headers->content_length; | |
25b6545a | 452 | |
0f2c5211 SS |
453 | # Perform stat on the tmpfile. |
454 | my $stat = stat($tmpfile); | |
eea2670b | 455 | |
0f2c5211 SS |
456 | # Grab the local filesize of the downloaded tarball. |
457 | my $local_filesize = $stat->size; | |
88daf7eb | 458 | |
0f2c5211 SS |
459 | # Check if both file sizes match. |
460 | if (($remote_filesize) && ($remote_filesize ne $local_filesize)) { | |
0f2c5211 SS |
461 | # Delete temporary file. |
462 | unlink("$tmpfile"); | |
96da5803 | 463 | |
0f2c5211 | 464 | # Return "1" - false. |
e26edcc1 | 465 | return "incomplete download"; |
0f2c5211 | 466 | } |
96da5803 | 467 | |
0f2c5211 SS |
468 | # Overwrite the may existing rulefile or tarball with the downloaded one. |
469 | move("$tmpfile", "$dl_rulesfile"); | |
ae226132 | 470 | |
0f2c5211 SS |
471 | # Check if we got a last-modified value from the server. |
472 | if ($last_modified) { | |
473 | # Assign the last-modified timestamp as mtime to the | |
474 | # rules file. | |
475 | utime(time(), "$last_modified", "$dl_rulesfile"); | |
96da5803 SS |
476 | } |
477 | ||
0f2c5211 SS |
478 | # Delete temporary file. |
479 | unlink("$tmpfile"); | |
480 | ||
481 | # Set correct ownership for the tarball. | |
482 | set_ownership("$dl_rulesfile"); | |
483 | ||
eea2670b SS |
484 | # If we got here, everything worked fine. Return nothing. |
485 | return; | |
486 | } | |
8dcebe53 | 487 | |
0fbfffea SS |
488 | # |
489 | ## Function to extract a given ruleset. | |
1b5aec1b SS |
490 | ## |
491 | ## In case the ruleset provider offers a plain file, it simply will | |
492 | ## be copied. | |
0fbfffea SS |
493 | # |
494 | sub extractruleset ($) { | |
495 | my ($provider) = @_; | |
496 | ||
8353e28a SS |
497 | # Disable chown functionality when uncompressing files. |
498 | $Archive::Tar::CHOWN = "0"; | |
499 | ||
0fbfffea SS |
500 | # Get full path and downloaded rulesfile for the given provider. |
501 | my $tarball = &_get_dl_rulesfile($provider); | |
502 | ||
503 | # Check if the file exists. | |
504 | unless (-f $tarball) { | |
1b5aec1b | 505 | &_log_to_syslog("Could not find ruleset file: $tarball"); |
0fbfffea SS |
506 | |
507 | # Return nothing. | |
508 | return; | |
509 | } | |
510 | ||
0fbfffea SS |
511 | # Check if the temporary directories exist, otherwise create them. |
512 | mkdir("$tmp_directory") unless (-d "$tmp_directory"); | |
6c9d3eee SS |
513 | mkdir("$tmp_rules_directory") unless (-d "$tmp_rules_directory"); |
514 | mkdir("$tmp_conf_directory") unless (-d "$tmp_conf_directory"); | |
0fbfffea | 515 | |
1b5aec1b SS |
516 | # Omit the type (dl_type) of the stored ruleset. |
517 | my $type = $IDS::Ruleset::Providers{$provider}{'dl_type'}; | |
0fbfffea | 518 | |
1b5aec1b SS |
519 | # Handle the different ruleset types. |
520 | if ($type eq "plain") { | |
521 | # Generate destination filename an full path. | |
522 | my $destination = "$tmp_rules_directory/$provider\-ruleset.rules"; | |
0fbfffea | 523 | |
1b5aec1b SS |
524 | # Copy the file into the temporary rules directory. |
525 | copy($tarball, $destination); | |
0fbfffea | 526 | |
1b5aec1b SS |
527 | } elsif ( $type eq "archive") { |
528 | # Initialize the tar module. | |
529 | my $tar = Archive::Tar->new($tarball); | |
0fbfffea | 530 | |
1b5aec1b SS |
531 | # Get the filelist inside the tarball. |
532 | my @packed_files = $tar->list_files; | |
0fbfffea | 533 | |
1b5aec1b SS |
534 | # Loop through the filelist. |
535 | foreach my $packed_file (@packed_files) { | |
536 | my $destination; | |
0fbfffea | 537 | |
1b5aec1b SS |
538 | # Splitt the packed file into chunks. |
539 | my $file = fileparse($packed_file); | |
0fbfffea | 540 | |
1b5aec1b SS |
541 | # Handle msg-id.map file. |
542 | if ("$file" eq "sid-msg.map") { | |
543 | # Set extract destination to temporary config_dir. | |
544 | $destination = "$tmp_conf_directory/$provider\-sid-msg.map"; | |
0fbfffea | 545 | |
1b5aec1b SS |
546 | # Handle classification.conf |
547 | } elsif ("$file" eq "classification.config") { | |
548 | # Set extract destination to temporary config_dir. | |
549 | $destination = "$tmp_conf_directory/$provider\-classification.config"; | |
0fbfffea | 550 | |
1b5aec1b SS |
551 | # Handle rules files. |
552 | } elsif ($file =~ m/\.rules$/) { | |
f349c960 SS |
553 | # Skip rule files which are not located in the rules directory or archive root. |
554 | next unless(($packed_file =~ /^rules\//) || ($packed_file !~ /\//)); | |
555 | ||
10beae64 SS |
556 | # Skip deleted.rules. |
557 | # | |
558 | # Mostly they have been taken out for correctness or performance reasons and therfore | |
559 | # it is not a great idea to enable any of them. | |
560 | next if($file =~ m/deleted.rules$/); | |
561 | ||
1b5aec1b | 562 | my $rulesfilename; |
0fbfffea | 563 | |
1b5aec1b SS |
564 | # Splitt the filename into chunks. |
565 | my @filename = split("-", $file); | |
0fbfffea | 566 | |
1b5aec1b SS |
567 | # Reverse the array. |
568 | @filename = reverse(@filename); | |
0fbfffea | 569 | |
1b5aec1b SS |
570 | # Get the amount of elements in the array. |
571 | my $elements = @filename; | |
0fbfffea | 572 | |
1b5aec1b SS |
573 | # Remove last element of the hash. |
574 | # It contains the vendor name, which will be replaced. | |
575 | if ($elements >= 3) { | |
576 | # Remove last element from hash. | |
577 | pop(@filename); | |
578 | } | |
579 | ||
580 | # Check if the last element of the filename does not | |
581 | # contain the providers name. | |
582 | if ($filename[-1] ne "$provider") { | |
583 | # Add provider name as last element. | |
584 | push(@filename, $provider); | |
585 | } | |
586 | ||
587 | # Reverse the array back. | |
588 | @filename = reverse(@filename); | |
589 | ||
590 | # Generate the name for the rulesfile. | |
591 | $rulesfilename = join("-", @filename); | |
592 | ||
593 | # Set extract destination to temporaray rules_dir. | |
594 | $destination = "$tmp_rules_directory/$rulesfilename"; | |
595 | } else { | |
596 | # Skip all other files. | |
597 | next; | |
598 | } | |
599 | ||
2b12a010 SS |
600 | # Check if the destination file exists. |
601 | unless(-e "$destination") { | |
602 | # Extract the file to the temporary directory. | |
603 | $tar->extract_file("$packed_file", "$destination"); | |
604 | } else { | |
2b12a010 SS |
605 | # Generate temporary file name, located in the temporary rules directory and a suffix of ".tmp". |
606 | my $tmp = File::Temp->new( SUFFIX => ".tmp", DIR => "$tmp_rules_directory", UNLINK => 0 ); | |
607 | my $tmpfile = $tmp->filename(); | |
608 | ||
609 | # Extract the file to the new temporary file name. | |
610 | $tar->extract_file("$packed_file", "$tmpfile"); | |
611 | ||
612 | # Open the the existing file. | |
613 | open(DESTFILE, ">>", "$destination") or die "Could not open $destination. $!\n"; | |
614 | open(TMPFILE, "<", "$tmpfile") or die "Could not open $tmpfile. $!\n"; | |
615 | ||
616 | # Loop through the content of the temporary file. | |
617 | while (<TMPFILE>) { | |
618 | # Append the content line by line to the destination file. | |
619 | print DESTFILE "$_"; | |
620 | } | |
621 | ||
622 | # Close the file handles. | |
623 | close(TMPFILE); | |
624 | close(DESTFILE); | |
625 | ||
626 | # Remove the temporary file. | |
627 | unlink("$tmpfile"); | |
628 | } | |
1b5aec1b | 629 | } |
0fbfffea SS |
630 | } |
631 | } | |
632 | ||
25f5cb0d | 633 | # |
b953677b SS |
634 | ## A wrapper function to call the oinkmaster script, setup the rules structues and |
635 | ## call the functions to merge the additional config files. (classification, sid-msg, etc.). | |
25f5cb0d SS |
636 | # |
637 | sub oinkmaster () { | |
330759d8 SS |
638 | # Check if the files in rulesdir have the correct permissions. |
639 | &_check_rulesdir_permissions(); | |
640 | ||
b953677b | 641 | # Cleanup the rules directory before filling it with the new rulests. |
883820bd SS |
642 | &_cleanup_rulesdir(); |
643 | ||
0130e0d1 | 644 | # Get all enabled providers. |
e31458de | 645 | my @enabled_providers = &get_enabled_providers(); |
b953677b | 646 | |
0130e0d1 SS |
647 | # Loop through the array of enabled providers. |
648 | foreach my $provider (@enabled_providers) { | |
1b5aec1b SS |
649 | # Call the extractruleset function. |
650 | &extractruleset($provider); | |
b953677b SS |
651 | } |
652 | ||
79446948 SS |
653 | # Call function to process the ruleset and do all modifications. |
654 | &process_ruleset(@enabled_providers); | |
b953677b | 655 | |
b953677b SS |
656 | # Call function to merge the classification files. |
657 | &merge_classifications(@enabled_providers); | |
658 | ||
659 | # Call function to merge the sid to message mapping files. | |
660 | &merge_sid_msg(@enabled_providers); | |
661 | ||
662 | # Cleanup temporary directory. | |
16b2d281 | 663 | &cleanup_tmp_directory(); |
25f5cb0d SS |
664 | } |
665 | ||
5a6c7bbe SS |
666 | # |
667 | ## Function to alter the ruleset. | |
668 | # | |
669 | sub process_ruleset(@) { | |
670 | my (@providers) = @_; | |
671 | ||
672 | # Hash to store the configured provider modes. | |
673 | my %providers_mode = &get_providers_mode(); | |
674 | ||
675 | # Array to store the extracted rulefile from the temporary rules directory. | |
676 | my @extracted_rulefiles; | |
677 | ||
678 | # Get names of the extracted raw rulefiles. | |
679 | opendir(DIR, $tmp_rules_directory) or die "Could not read from $tmp_rules_directory. $!\n"; | |
680 | while (my $file = readdir(DIR)) { | |
681 | # Ignore single and double dotted files. | |
682 | next if $file =~ /^\.\.?$/; | |
683 | ||
684 | # Add file to the array of extracted files. | |
685 | push(@extracted_rulefiles, $file); | |
686 | } | |
687 | ||
688 | # Close directory handle. | |
689 | closedir(DIR); | |
690 | ||
691 | # Loop through the array of providers. | |
692 | foreach my $provider (@providers) { | |
693 | # Hash to store the obtained SIDs and REV of each provider. | |
694 | my %rules = (); | |
695 | ||
696 | # Hash which holds modifications to apply to the rules. | |
697 | my %modifications = (); | |
698 | ||
699 | # Loop through the array of extraced rulefiles. | |
700 | foreach my $file (@extracted_rulefiles) { | |
701 | # Skip file if it does not belong to the current processed provider. | |
702 | next unless ($file =~ m/^$provider/); | |
703 | ||
704 | # Open the rulefile. | |
705 | open(FILE, "$tmp_rules_directory/$file") or die "Could not read $tmp_rules_directory/$file. $!\n"; | |
706 | ||
707 | # Loop through the file content. | |
708 | while (my $line = <FILE>) { | |
709 | # Skip blank lines. | |
710 | next if ($line =~ /^\s*$/); | |
711 | ||
712 | # Call function to get the sid and rev of the rule. | |
713 | my ($sid, $rev) = &_get_sid_and_rev($line); | |
714 | ||
715 | # Skip rule if a sid with a higher rev already has added to the rules hash. | |
716 | next if ($rev le $rules{$sid}); | |
717 | ||
718 | # Add the new or rule with higher rev to the hash of rules. | |
719 | $rules{$sid} = $rev; | |
720 | } | |
721 | ||
722 | # Close file handle. | |
723 | close(FILE); | |
724 | } | |
725 | ||
726 | # Get filename which contains the ruleset modifications for this provider. | |
727 | my $modification_file = &get_provider_ruleset_modifications_file($provider); | |
728 | ||
729 | # Read file which holds the modifications of the ruleset for the current provider. | |
730 | &General::readhash($modification_file, \%modifications) if (-f $modification_file); | |
731 | ||
732 | # Loop again through the array of extracted rulesfiles. | |
733 | foreach my $file (@extracted_rulefiles) { | |
734 | # Skip the file if it does not belong to the current provider. | |
735 | next unless ($file =~ m/^$provider/); | |
736 | ||
737 | # Open the rulefile for writing. | |
738 | open(RULEFILE, ">", "$rulespath/$file") or die "Could not write to file $rulespath/$file. $!\n"; | |
739 | ||
740 | # Open the rulefile for reading. | |
741 | open(TMP_RULEFILE, "$tmp_rules_directory/$file") or die "Could not read $tmp_rules_directory/$file. $!\n"; | |
742 | ||
743 | # Loop through the raw temporary rulefile. | |
744 | while (my $line = <TMP_RULEFILE>) { | |
745 | # Get the sid and rev of the rule. | |
746 | my ($sid, $rev) = &_get_sid_and_rev($line); | |
747 | ||
748 | # Check if the current rule is obsoleted by a newer one. | |
749 | # | |
750 | # In this case the rev number in the rules hash is higher than the current one. | |
751 | next if ($rev lt $rules{$sid}); | |
752 | ||
753 | # Check if the rule should be enabled or disabled. | |
754 | if ($modifications{$sid} eq "on") { | |
755 | # Drop the # at the start of the line. | |
756 | $line =~ s/^\#//; | |
757 | } elsif ($modifications{$sid} eq "off") { | |
758 | # Add a # at the start of the line to disable the rule. | |
759 | $line = "#$line" unless ($line =~ /^#/); | |
760 | } | |
761 | ||
762 | # Check if the Provider is set so IPS mode. | |
763 | if ($providers_mode{$provider} eq "IPS") { | |
764 | # Replacements for sourcefire rules. | |
765 | $line =~ s/^#\s*(?:alert|drop)(.+policy balanced-ips alert)/alert${1}/; | |
766 | $line =~ s/^#\s*(?:alert|drop)(.+policy balanced-ips drop)/drop${1}/; | |
767 | ||
768 | # Replacements for generic rules. | |
769 | $line =~ s/^(#?)\s*(?:alert|drop)/${1}drop/; | |
770 | $line =~ s/^(#?)\s*drop(.+flowbits:noalert;)/${1}alert${2}/; | |
771 | } | |
772 | ||
773 | # Write line / rule to the target rule file. | |
774 | print RULEFILE "$line"; | |
775 | } | |
776 | ||
777 | # Close filehandles. | |
778 | close(RULEFILE); | |
779 | close(TMP_RULEFILE); | |
780 | } | |
781 | } | |
782 | } | |
783 | ||
23b56052 SS |
784 | # |
785 | ## Function to merge the classifications for a given amount of providers and write them | |
786 | ## to the classifications file. | |
787 | # | |
788 | sub merge_classifications(@) { | |
789 | my @providers = @_; | |
790 | ||
791 | # Hash to store all collected classifications. | |
792 | my %classifications = (); | |
793 | ||
794 | # Loop through the given array of providers. | |
795 | foreach my $provider (@providers) { | |
796 | # Generate full path to classification file. | |
6c9d3eee | 797 | my $classification_file = "$tmp_conf_directory/$provider\-classification.config"; |
23b56052 SS |
798 | |
799 | # Skip provider if no classification file exists. | |
800 | next unless (-f "$classification_file"); | |
801 | ||
802 | # Open the classification file. | |
803 | open(CLASSIFICATION, $classification_file) or die "Could not open file $classification_file. $!\n"; | |
804 | ||
805 | # Loop through the file content. | |
806 | while(<CLASSIFICATION>) { | |
807 | # Parse the file and grab the classification details. | |
808 | if ($_ =~/.*config classification\: (.*)/) { | |
809 | # Split the grabbed details. | |
810 | my ($short_name, $short_desc, $priority) = split("\,", $1); | |
811 | ||
812 | # Check if the grabbed classification is allready known and the priority value is greater | |
813 | # than the stored one (which causes less priority in the IDS). | |
814 | if (($classifications{$short_name}) && ($classifications{$short_name}[1] >= $priority)) { | |
815 | #Change the priority value to the stricter one. | |
816 | $classifications{$short_name} = [ "$classifications{$short_name}[0]", "$priority" ]; | |
817 | } else { | |
818 | # Add the classification to the hash. | |
819 | $classifications{$short_name} = [ "$short_desc", "$priority" ]; | |
820 | } | |
821 | } | |
822 | } | |
823 | ||
824 | # Close the file. | |
825 | close(CLASSIFICATION); | |
826 | } | |
827 | ||
828 | # Open classification file for writing. | |
829 | open(FILE, ">", "$classification_file") or die "Could not write to $classification_file. $!\n"; | |
830 | ||
831 | # Print notice about autogenerated file. | |
832 | print FILE "#Autogenerated file. Any custom changes will be overwritten!\n\n"; | |
833 | ||
834 | # Sort and loop through the hash of classifications. | |
835 | foreach my $key (sort keys %classifications) { | |
836 | # Assign some nice variable names for the items. | |
837 | my $short_name = $key; | |
838 | my $short_desc = $classifications{$key}[0]; | |
839 | my $priority = $classifications{$key}[1]; | |
840 | ||
841 | # Write the classification to the file. | |
842 | print FILE "config classification: $short_name,$short_desc,$priority\n"; | |
843 | } | |
844 | ||
845 | # Close file handle. | |
846 | close(FILE); | |
847 | } | |
848 | ||
8bd74e12 SS |
849 | # |
850 | ## Function to merge the "sid to message mapping" files of various given providers. | |
851 | # | |
852 | sub merge_sid_msg (@) { | |
853 | my @providers = @_; | |
854 | ||
855 | # Hash which contains all the sid to message mappings. | |
856 | my %mappings = (); | |
857 | ||
858 | # Loop through the array of given providers. | |
859 | foreach my $provider (@providers) { | |
860 | # Generate full path and filename. | |
6c9d3eee | 861 | my $sid_msg_file = "$tmp_conf_directory/$provider\-sid-msg.map"; |
8bd74e12 SS |
862 | |
863 | # Skip provider if no sid to msg mapping file for this provider exists. | |
864 | next unless (-f $sid_msg_file); | |
865 | ||
866 | # Open the file. | |
867 | open(MAPPING, $sid_msg_file) or die "Could not open $sid_msg_file. $!\n"; | |
868 | ||
869 | # Loop through the file content. | |
870 | while (<MAPPING>) { | |
871 | # Remove newlines. | |
872 | chomp($_); | |
873 | ||
874 | # Skip lines which do not start with a number, | |
875 | next unless ($_ =~ /^\d+/); | |
876 | ||
877 | # Split line content and assign it to an array. | |
878 | my @line = split(/ \|\| /, $_); | |
879 | ||
880 | # Grab the first element (and remove it) from the line array. | |
881 | # It contains the sid. | |
882 | my $sid = shift(@line); | |
883 | ||
884 | # Store the grabbed sid and the remain array as hash value. | |
885 | # It still contains the messages, references etc. | |
886 | $mappings{$sid} = [@line]; | |
887 | } | |
888 | ||
889 | # Close file handle. | |
890 | close(MAPPING); | |
891 | } | |
892 | ||
893 | # Open mappings file for writing. | |
894 | open(FILE, ">", $sid_msg_file) or die "Could not write $sid_msg_file. $!\n"; | |
895 | ||
896 | # Write notice about autogenerated file. | |
897 | print FILE "#Autogenerated file. Any custom changes will be overwritten!\n\n"; | |
898 | ||
899 | # Loop through the hash of mappings. | |
900 | foreach my $sid ( sort keys %mappings) { | |
901 | # Grab data for the sid. | |
902 | my @data = @{$mappings{$sid}}; | |
903 | ||
904 | # Add the sid to the data array. | |
905 | unshift(@data, $sid); | |
906 | ||
907 | # Generate line. | |
908 | my $line = join(" \|\| ", @data); | |
909 | ||
910 | print FILE "$line\n"; | |
911 | ||
912 | } | |
913 | ||
914 | # Close file handle. | |
915 | close(FILE); | |
916 | } | |
917 | ||
50f348f6 SS |
918 | # |
919 | ## A very tiny function to move an extracted ruleset from the temporary directory into | |
920 | ## the rules directory. | |
921 | # | |
922 | sub move_tmp_ruleset() { | |
50f348f6 SS |
923 | # Do a directory listing of the temporary directory. |
924 | opendir DH, $tmp_rules_directory; | |
925 | ||
926 | # Loop over all files. | |
927 | while(my $file = readdir DH) { | |
928 | # Move them to the rules directory. | |
929 | move "$tmp_rules_directory/$file" , "$rulespath/$file"; | |
930 | } | |
931 | ||
932 | # Close directory handle. | |
933 | closedir DH; | |
934 | } | |
935 | ||
16b2d281 SS |
936 | # |
937 | ## Function to cleanup the temporary IDS directroy. | |
938 | # | |
939 | sub cleanup_tmp_directory () { | |
16b2d281 SS |
940 | |
941 | # Delete temporary directory and all containing files. | |
942 | rmtree([ "$tmp_directory" ]); | |
943 | } | |
944 | ||
3983aebd SS |
945 | # |
946 | ## Function to do all the logging stuff if the downloading or updating of the ruleset fails. | |
947 | # | |
948 | sub log_error ($) { | |
949 | my ($error) = @_; | |
950 | ||
951 | # Remove any newline. | |
952 | chomp($error); | |
953 | ||
eb5592c1 SS |
954 | # Call private function to log the error message to syslog. |
955 | &_log_to_syslog($error); | |
956 | ||
3983aebd SS |
957 | # Call private function to write/store the error message in the storederrorfile. |
958 | &_store_error_message($error); | |
959 | } | |
960 | ||
eb5592c1 SS |
961 | # |
962 | ## Function to log a given error message to the kernel syslog. | |
963 | # | |
964 | sub _log_to_syslog ($) { | |
965 | my ($message) = @_; | |
966 | ||
eb5592c1 SS |
967 | # The syslog function works best with an array based input, |
968 | # so generate one before passing the message details to syslog. | |
969 | my @syslog = ("ERR", "<ERROR> $message"); | |
970 | ||
971 | # Establish the connection to the syslog service. | |
972 | openlog('oinkmaster', 'cons,pid', 'user'); | |
973 | ||
974 | # Send the log message. | |
975 | syslog(@syslog); | |
976 | ||
977 | # Close the log handle. | |
978 | closelog(); | |
979 | } | |
980 | ||
3983aebd SS |
981 | # |
982 | ## Private function to write a given error message to the storederror file. | |
983 | # | |
984 | sub _store_error_message ($) { | |
985 | my ($message) = @_; | |
986 | ||
987 | # Remove any newline. | |
988 | chomp($message); | |
989 | ||
990 | # Open file for writing. | |
991 | open (ERRORFILE, ">$storederrorfile") or die "Could not write to $storederrorfile. $!\n"; | |
992 | ||
993 | # Write error to file. | |
994 | print ERRORFILE "$message\n"; | |
995 | ||
996 | # Close file. | |
997 | close (ERRORFILE); | |
3c59b1fa SS |
998 | |
999 | # Set correct ownership for the file. | |
1000 | &set_ownership("$storederrorfile"); | |
3983aebd SS |
1001 | } |
1002 | ||
788a71f5 SS |
1003 | # |
1004 | ## Private function to get the path and filename for a downloaded ruleset by a given provider. | |
1005 | # | |
1006 | sub _get_dl_rulesfile($) { | |
1007 | my ($provider) = @_; | |
1008 | ||
1009 | # Gather the download type for the given provider. | |
1010 | my $dl_type = $IDS::Ruleset::Providers{$provider}{'dl_type'}; | |
1011 | ||
1012 | # Obtain the file suffix for the download file type. | |
1013 | my $suffix = $dl_type_to_suffix{$dl_type}; | |
1014 | ||
1015 | # Check if a suffix has been found. | |
1016 | unless ($suffix) { | |
1017 | # Abort return - nothing. | |
1018 | return; | |
1019 | } | |
1020 | ||
1021 | # Generate the full filename and path for the stored rules file. | |
1022 | my $rulesfile = "$dl_rules_path/$dl_rulesfile_prefix-$provider$suffix"; | |
1023 | ||
1024 | # Return the generated filename. | |
1025 | return $rulesfile; | |
1026 | } | |
1027 | ||
e246285a SS |
1028 | # |
1029 | ## Private function to obtain the sid and rev of a rule. | |
1030 | # | |
1031 | ## Returns an array with the sid as first and the rev as second value. | |
1032 | # | |
1033 | sub _get_sid_and_rev ($) { | |
1034 | my ($line) = @_; | |
1035 | ||
1036 | my @ret; | |
1037 | ||
1038 | # Use regex to obtain the sid and rev. | |
1039 | if ($line =~ m/.*sid:\s*(.*?);.*rev:\s*(.*?);/) { | |
1040 | # Add the sid and rev to the array. | |
1041 | push(@ret, $1); | |
1042 | push(@ret, $2); | |
1043 | } | |
1044 | ||
1045 | # Return the array. | |
1046 | return @ret; | |
1047 | } | |
1048 | ||
61b92664 SS |
1049 | # |
1050 | ## Tiny function to delete the stored ruleset file or tarball for a given provider. | |
1051 | # | |
1052 | sub drop_dl_rulesfile ($) { | |
1053 | my ($provider) = @_; | |
1054 | ||
1055 | # Gather the full path and name of the stored rulesfile. | |
1056 | my $rulesfile = &_get_dl_rulesfile($provider); | |
1057 | ||
1058 | # Check if the given rulesfile exists. | |
1059 | if (-f $rulesfile) { | |
1060 | # Delete the stored rulesfile. | |
1061 | unlink($rulesfile) or die "Could not delete $rulesfile. $!\n"; | |
1062 | } | |
1063 | } | |
1064 | ||
5b9d877d SS |
1065 | # |
1066 | ## Tiny function to get/generate the full path and filename for the providers oinkmaster | |
1067 | ## modified sids file. | |
1068 | # | |
1069 | sub get_oinkmaster_provider_modified_sids_file ($) { | |
1070 | my ($provider) = @_; | |
1071 | ||
1072 | # Generate the filename. | |
1073 | my $filename = "$settingsdir/oinkmaster-$provider-modified-sids.conf"; | |
1074 | ||
1075 | # Return the filename. | |
1076 | return $filename; | |
1077 | } | |
1078 | ||
d878d9c0 SS |
1079 | # |
1080 | ## Function to directly altering the oinkmaster provider includes file. | |
1081 | ## | |
1082 | ## Requires tha acition "remove" or "add" and a provider handle. | |
1083 | # | |
1084 | sub alter_oinkmaster_provider_includes_file ($$) { | |
1085 | my ($action, $provider) = @_; | |
1086 | ||
1087 | # Call function to get the path and name for the given providers | |
1088 | # oinkmaster modified sids file. | |
1089 | my $provider_modified_sids_file = &get_oinkmaster_provider_modified_sids_file($provider); | |
1090 | ||
1091 | # Open the file for reading.. | |
1092 | open (FILE, $oinkmaster_provider_includes_file) or die "Could not read $oinkmaster_provider_includes_file. $!\n"; | |
1093 | ||
1094 | # Read-in file content. | |
1095 | my @lines = <FILE>; | |
1096 | ||
1097 | # Close file after reading. | |
1098 | close(FILE); | |
1099 | ||
1100 | # Re-open the file for writing. | |
1101 | open(FILE, ">", $oinkmaster_provider_includes_file) or die "Could not write to $oinkmaster_provider_includes_file. $!\n"; | |
1102 | ||
1103 | # Loop through the file content. | |
1104 | foreach my $line (@lines) { | |
1105 | # Remove newlines. | |
1106 | chomp($line); | |
1107 | ||
1108 | # Skip line if we found our given provider and the action should be remove. | |
1109 | next if (($line =~ /$provider/) && ($action eq "remove")); | |
1110 | ||
1111 | # Write the read-in line back to the file. | |
1112 | print FILE "$line\n"; | |
1113 | } | |
1114 | ||
1d860d89 SS |
1115 | # Check if the file exists and add the provider if requested. |
1116 | if ((-f $provider_modified_sids_file) && ($action eq "add")) { | |
d878d9c0 SS |
1117 | print FILE "include $provider_modified_sids_file\n"; |
1118 | } | |
1119 | ||
1120 | # Close file handle. | |
1121 | close(FILE); | |
1122 | } | |
1123 | ||
69b3156f SS |
1124 | # |
1125 | ## Function to read-in the given enabled or disables sids file. | |
1126 | # | |
1127 | sub read_enabled_disabled_sids_file($) { | |
1128 | my ($file) = @_; | |
1129 | ||
1130 | # Temporary hash to store the sids and their state. It will be | |
1131 | # returned at the end of this function. | |
1132 | my %temphash; | |
1133 | ||
1134 | # Open the given filename. | |
1135 | open(FILE, "$file") or die "Could not open $file. $!\n"; | |
1136 | ||
1137 | # Loop through the file. | |
1138 | while(<FILE>) { | |
1139 | # Remove newlines. | |
1140 | chomp $_; | |
1141 | ||
1142 | # Skip blank lines. | |
1143 | next if ($_ =~ /^\s*$/); | |
1144 | ||
1145 | # Skip coments. | |
1146 | next if ($_ =~ /^\#/); | |
1147 | ||
1148 | # Splitt line into sid and state part. | |
1149 | my ($state, $sid) = split(" ", $_); | |
1150 | ||
1151 | # Skip line if the sid is not numeric. | |
1152 | next unless ($sid =~ /\d+/ ); | |
1153 | ||
1154 | # Check if the sid was enabled. | |
1155 | if ($state eq "enablesid") { | |
1156 | # Add the sid and its state as enabled to the temporary hash. | |
1157 | $temphash{$sid} = "enabled"; | |
1158 | # Check if the sid was disabled. | |
1159 | } elsif ($state eq "disablesid") { | |
1160 | # Add the sid and its state as disabled to the temporary hash. | |
1161 | $temphash{$sid} = "disabled"; | |
1162 | # Invalid state - skip the current sid and state. | |
1163 | } else { | |
1164 | next; | |
1165 | } | |
1166 | } | |
1167 | ||
1168 | # Close filehandle. | |
1169 | close(FILE); | |
1170 | ||
1171 | # Return the hash. | |
1172 | return %temphash; | |
1173 | } | |
1174 | ||
796eea21 SS |
1175 | # |
1176 | ## Function to check if the IDS is running. | |
1177 | # | |
1178 | sub ids_is_running () { | |
1179 | if(-f $idspidfile) { | |
1180 | # Open PID file for reading. | |
1181 | open(PIDFILE, "$idspidfile") or die "Could not open $idspidfile. $!\n"; | |
1182 | ||
1183 | # Grab the process-id. | |
1184 | my $pid = <PIDFILE>; | |
1185 | ||
1186 | # Close filehandle. | |
1187 | close(PIDFILE); | |
1188 | ||
1189 | # Remove any newline. | |
1190 | chomp($pid); | |
1191 | ||
1192 | # Check if a directory for the process-id exists in proc. | |
1193 | if(-d "/proc/$pid") { | |
1194 | # The IDS daemon is running return the process id. | |
1195 | return $pid; | |
1196 | } | |
1197 | } | |
1198 | ||
1199 | # Return nothing - IDS is not running. | |
1200 | return; | |
1201 | } | |
1202 | ||
5240a809 SS |
1203 | # |
1204 | ## Function to call suricatactrl binary with a given command. | |
1205 | # | |
1206 | sub call_suricatactrl ($) { | |
1207 | # Get called option. | |
ed06bc81 | 1208 | my ($option, $interval) = @_; |
5240a809 SS |
1209 | |
1210 | # Loop through the array of supported commands and check if | |
1211 | # the given one is part of it. | |
1212 | foreach my $cmd (@suricatactrl_cmds) { | |
1213 | # Skip current command unless the given one has been found. | |
1214 | next unless($cmd eq $option); | |
1215 | ||
ed06bc81 SS |
1216 | # Check if the given command is "cron". |
1217 | if ($option eq "cron") { | |
1218 | # Check if an interval has been given. | |
1219 | if ($interval) { | |
1220 | # Check if the given interval is valid. | |
1221 | foreach my $element (@cron_intervals) { | |
1222 | # Skip current element until the given one has been found. | |
1223 | next unless($element eq $interval); | |
1224 | ||
1225 | # Call the suricatactrl binary and pass the "cron" command | |
1226 | # with the requrested interval. | |
81631920 | 1227 | &General::system("$suricatactrl", "$option", "$interval"); |
ed06bc81 SS |
1228 | |
1229 | # Return "1" - True. | |
1230 | return 1; | |
1231 | } | |
1232 | } | |
5240a809 | 1233 | |
ed06bc81 SS |
1234 | # If we got here, the given interval is not supported or none has been given. - Return nothing. |
1235 | return; | |
1236 | } else { | |
1237 | # Call the suricatactrl binary and pass the requrested | |
1238 | # option to it. | |
81631920 | 1239 | &General::system("$suricatactrl", "$option"); |
ed06bc81 SS |
1240 | |
1241 | # Return "1" - True. | |
1242 | return 1; | |
1243 | } | |
5240a809 SS |
1244 | } |
1245 | ||
1246 | # Command not found - return nothing. | |
1247 | return; | |
1248 | } | |
1249 | ||
308ba5e7 SS |
1250 | # |
1251 | ## Function to create a new empty file. | |
1252 | # | |
1253 | sub create_empty_file($) { | |
1254 | my ($file) = @_; | |
1255 | ||
1256 | # Check if the given file exists. | |
1257 | if(-e $file) { | |
1258 | # Do nothing to prevent from overwriting existing files. | |
1259 | return; | |
1260 | } | |
1261 | ||
1262 | # Open the file for writing. | |
1263 | open(FILE, ">$file") or die "Could not write to $file. $!\n"; | |
1264 | ||
1265 | # Close file handle. | |
1266 | close(FILE); | |
1267 | ||
1268 | # Return true. | |
1269 | return 1; | |
1270 | } | |
1271 | ||
330759d8 SS |
1272 | # |
1273 | ## Private function to check if the file permission of the rulespath are correct. | |
1274 | ## If not, call suricatactrl to fix them. | |
1275 | # | |
1276 | sub _check_rulesdir_permissions() { | |
e568796b SS |
1277 | # Check if the rulepath main directory is writable. |
1278 | unless (-W $rulespath) { | |
1279 | # If not call suricatctrl to fix it. | |
1280 | &call_suricatactrl("fix-rules-dir"); | |
1281 | } | |
1282 | ||
330759d8 SS |
1283 | # Open snort rules directory and do a directory listing. |
1284 | opendir(DIR, $rulespath) or die $!; | |
1285 | # Loop through the direcory. | |
1286 | while (my $file = readdir(DIR)) { | |
1287 | # We only want files. | |
1288 | next unless (-f "$rulespath/$file"); | |
1289 | ||
1290 | # Check if the file is writable by the user. | |
1291 | if (-W "$rulespath/$file") { | |
1292 | # Everything is okay - go on to the next file. | |
1293 | next; | |
1294 | } else { | |
1295 | # There are wrong permissions, call suricatactrl to fix it. | |
1296 | &call_suricatactrl("fix-rules-dir"); | |
1297 | } | |
1298 | } | |
1299 | } | |
1300 | ||
b59cdbee SS |
1301 | # |
1302 | ## Private function to cleanup the directory which contains | |
1303 | ## the IDS rules, before extracting and modifing the new ruleset. | |
1304 | # | |
1305 | sub _cleanup_rulesdir() { | |
8cf04a16 SS |
1306 | # Open rules directory and do a directory listing. |
1307 | opendir(DIR, $rulespath) or die $!; | |
1308 | ||
1309 | # Loop through the direcory. | |
1310 | while (my $file = readdir(DIR)) { | |
1311 | # We only want files. | |
1312 | next unless (-f "$rulespath/$file"); | |
1313 | ||
fefb5173 SS |
1314 | # Skip rules file for whitelisted hosts. |
1315 | next if ("$rulespath/$file" eq $whitelist_file); | |
1316 | ||
612bb2df SS |
1317 | # Skip rules file with local rules. |
1318 | next if ("$rulespath/$file" eq $local_rules_file); | |
1319 | ||
8cf04a16 | 1320 | # Delete the current processed file, if not, exit this function |
b59cdbee | 1321 | # and return an error message. |
1201c1e7 | 1322 | unlink("$rulespath/$file") or return "Could not delete $rulespath/$file. $!\n"; |
b59cdbee SS |
1323 | } |
1324 | ||
4ce42488 | 1325 | # Return nothing; |
b59cdbee SS |
1326 | return; |
1327 | } | |
1328 | ||
b02e30fd SS |
1329 | # |
1330 | ## Function to generate the file which contains the home net information. | |
1331 | # | |
1332 | sub generate_home_net_file() { | |
1333 | my %netsettings; | |
1334 | ||
1335 | # Read-in network settings. | |
1336 | &General::readhash("${General::swroot}/ethernet/settings", \%netsettings); | |
1337 | ||
1338 | # Get available network zones. | |
abffcc99 | 1339 | my @network_zones = &Network::get_available_network_zones(); |
b02e30fd SS |
1340 | |
1341 | # Temporary array to store network address and prefix of the configured | |
1342 | # networks. | |
1343 | my @networks; | |
1344 | ||
1345 | # Loop through the array of available network zones. | |
1346 | foreach my $zone (@network_zones) { | |
bcbc9897 SS |
1347 | # Check if the current processed zone is red. |
1348 | if($zone eq "red") { | |
1349 | # Grab the IP-address of the red interface. | |
1350 | my $red_address = &get_red_address(); | |
b02e30fd | 1351 | |
bcbc9897 SS |
1352 | # Check if an address has been obtained. |
1353 | if ($red_address) { | |
1354 | # Generate full network string. | |
1355 | my $red_network = join("/", $red_address, "32"); | |
b02e30fd | 1356 | |
bcbc9897 SS |
1357 | # Add the red network to the array of networks. |
1358 | push(@networks, $red_network); | |
1359 | } | |
23c0347a | 1360 | |
23c0347a SS |
1361 | # Check if the configured RED_TYPE is static. |
1362 | if ($netsettings{'RED_TYPE'} eq "STATIC") { | |
1363 | # Get configured and enabled aliases. | |
1364 | my @aliases = &get_aliases(); | |
1365 | ||
1366 | # Loop through the array. | |
1367 | foreach my $alias (@aliases) { | |
1368 | # Add "/32" prefix. | |
1369 | my $network = join("/", $alias, "32"); | |
1370 | ||
1371 | # Add the generated network to the array of networks. | |
1372 | push(@networks, $network); | |
1373 | } | |
1374 | } | |
bcbc9897 SS |
1375 | # Process remaining network zones. |
1376 | } else { | |
1377 | # Convert current zone name into upper case. | |
1378 | $zone = uc($zone); | |
1379 | ||
1380 | # Generate key to access the required data from the netsettings hash. | |
1381 | my $zone_netaddress = $zone . "_NETADDRESS"; | |
1382 | my $zone_netmask = $zone . "_NETMASK"; | |
1383 | ||
1384 | # Obtain the settings from the netsettings hash. | |
1385 | my $netaddress = $netsettings{$zone_netaddress}; | |
1386 | my $netmask = $netsettings{$zone_netmask}; | |
1387 | ||
1388 | # Convert the subnetmask into prefix notation. | |
1389 | my $prefix = &Network::convert_netmask2prefix($netmask); | |
1390 | ||
1391 | # Generate full network string. | |
1392 | my $network = join("/", $netaddress,$prefix); | |
1393 | ||
1394 | # Check if the network is valid. | |
1395 | if(&Network::check_subnet($network)) { | |
1396 | # Add the generated network to the array of networks. | |
1397 | push(@networks, $network); | |
1398 | } | |
23c0347a | 1399 | } |
b02e30fd SS |
1400 | } |
1401 | ||
1402 | # Format home net declaration. | |
7479c993 | 1403 | my $line = "\"[" . join(',', @networks) . "]\""; |
b02e30fd SS |
1404 | |
1405 | # Open file to store the addresses of the home net. | |
1406 | open(FILE, ">$homenet_file") or die "Could not open $homenet_file. $!\n"; | |
1407 | ||
1408 | # Print yaml header. | |
1409 | print FILE "%YAML 1.1\n"; | |
1410 | print FILE "---\n\n"; | |
1411 | ||
1412 | # Print notice about autogenerated file. | |
1413 | print FILE "#Autogenerated file. Any custom changes will be overwritten!\n"; | |
1414 | ||
1415 | # Print the generated and required HOME_NET declaration to the file. | |
1416 | print FILE "HOME_NET:\t$line\n"; | |
1417 | ||
1418 | # Close file handle. | |
1419 | close(FILE); | |
1420 | } | |
1421 | ||
30ee98e9 SS |
1422 | # |
1423 | # Function to generate and write the file which contains the configured and used DNS servers. | |
1424 | # | |
1425 | sub generate_dns_servers_file() { | |
12c49915 SS |
1426 | # Get the used DNS servers. |
1427 | my @nameservers = &General::get_nameservers(); | |
30ee98e9 | 1428 | |
7b97359b SS |
1429 | # Get network settings. |
1430 | my %netsettings; | |
1431 | &General::readhash("${General::swroot}/ethernet/settings", \%netsettings); | |
1432 | ||
30ee98e9 | 1433 | # Format dns servers declaration. |
b76118c3 | 1434 | my $line = ""; |
30ee98e9 | 1435 | |
12c49915 SS |
1436 | # Check if the system has configured nameservers. |
1437 | if (@nameservers) { | |
7b97359b SS |
1438 | # Add the GREEN address as DNS servers. |
1439 | push(@nameservers, $netsettings{'GREEN_ADDRESS'}); | |
1440 | ||
1441 | # Check if a BLUE zone exists. | |
1442 | if ($netsettings{'BLUE_ADDRESS'}) { | |
1443 | # Add the BLUE address to the array of nameservers. | |
1444 | push(@nameservers, $netsettings{'BLUE_ADDRESS'}); | |
1445 | } | |
1446 | ||
1447 | # Generate the line which will be written to the DNS servers file. | |
b76118c3 | 1448 | $line = join(",", @nameservers); |
12c49915 | 1449 | } else { |
7b97359b | 1450 | # External net simply contains (any). |
99cadb74 | 1451 | $line = "\$EXTERNAL_NET"; |
fd2dccaa | 1452 | } |
30ee98e9 | 1453 | |
30ee98e9 SS |
1454 | # Open file to store the used DNS server addresses. |
1455 | open(FILE, ">$dns_servers_file") or die "Could not open $dns_servers_file. $!\n"; | |
1456 | ||
1457 | # Print yaml header. | |
1458 | print FILE "%YAML 1.1\n"; | |
1459 | print FILE "---\n\n"; | |
1460 | ||
1461 | # Print notice about autogenerated file. | |
1462 | print FILE "#Autogenerated file. Any custom changes will be overwritten!\n"; | |
1463 | ||
1464 | # Print the generated DNS declaration to the file. | |
b76118c3 | 1465 | print FILE "DNS_SERVERS:\t\"[$line]\"\n"; |
30ee98e9 SS |
1466 | |
1467 | # Close file handle. | |
1468 | close(FILE); | |
1469 | } | |
1470 | ||
e698090e SS |
1471 | # |
1472 | # Function to generate and write the file which contains the HTTP_PORTS definition. | |
1473 | # | |
1474 | sub generate_http_ports_file() { | |
1475 | my %proxysettings; | |
1476 | ||
1477 | # Read-in proxy settings | |
1478 | &General::readhash("${General::swroot}/proxy/advanced/settings", \%proxysettings); | |
1479 | ||
1480 | # Check if the proxy is enabled. | |
1481 | if (( -e "${General::swroot}/proxy/enable") || (-e "${General::swroot}/proxy/enable_blue")) { | |
1482 | # Add the proxy port to the array of HTTP ports. | |
1483 | push(@http_ports, $proxysettings{'PROXY_PORT'}); | |
1484 | } | |
1485 | ||
1486 | # Check if the transparent mode of the proxy is enabled. | |
1487 | if ((-e "${General::swroot}/proxy/transparent") || (-e "${General::swroot}/proxy/transparent_blue")) { | |
1488 | # Add the transparent proxy port to the array of HTTP ports. | |
1489 | push(@http_ports, $proxysettings{'TRANSPARENT_PORT'}); | |
1490 | } | |
1491 | ||
1492 | # Format HTTP_PORTS declaration. | |
1493 | my $line = ""; | |
1494 | ||
1495 | # Generate line which will be written to the http ports file. | |
1496 | $line = join(",", @http_ports); | |
1497 | ||
1498 | # Open file to store the HTTP_PORTS. | |
1499 | open(FILE, ">$http_ports_file") or die "Could not open $http_ports_file. $!\n"; | |
1500 | ||
1501 | # Print yaml header. | |
1502 | print FILE "%YAML 1.1\n"; | |
1503 | print FILE "---\n\n"; | |
1504 | ||
1505 | # Print notice about autogenerated file. | |
1506 | print FILE "#Autogenerated file. Any custom changes will be overwritten!\n"; | |
1507 | ||
1508 | # Print the generated HTTP_PORTS declaration to the file. | |
1509 | print FILE "HTTP_PORTS:\t\"[$line]\"\n"; | |
1510 | ||
1511 | # Close file handle. | |
1512 | close(FILE); | |
1513 | } | |
1514 | ||
b02e30fd | 1515 | # |
ddaf8ae1 SS |
1516 | ## Function to generate and write the file for used rulefiles file for a given provider. |
1517 | ## | |
1518 | ## The function requires as first argument a provider handle, and as second an array with files. | |
b02e30fd | 1519 | # |
ddaf8ae1 SS |
1520 | sub write_used_provider_rulefiles_file($@) { |
1521 | my ($provider, @files) = @_; | |
1522 | ||
1523 | # Get the path and file for the provider specific used rulefiles file. | |
1524 | my $used_provider_rulesfile_file = &get_used_provider_rulesfile_file($provider); | |
b02e30fd SS |
1525 | |
1526 | # Open file for used rulefiles. | |
a081f203 | 1527 | open (FILE, ">", "$used_provider_rulesfile_file") or die "Could not write to $used_provider_rulesfile_file. $!\n"; |
b02e30fd SS |
1528 | |
1529 | # Write yaml header to the file. | |
1530 | print FILE "%YAML 1.1\n"; | |
1531 | print FILE "---\n\n"; | |
1532 | ||
1533 | # Write header to file. | |
1534 | print FILE "#Autogenerated file. Any custom changes will be overwritten!\n"; | |
1535 | ||
b02e30fd SS |
1536 | # Loop through the array of given files. |
1537 | foreach my $file (@files) { | |
1538 | # Check if the given filename exists and write it to the file of used rulefiles. | |
1539 | if(-f "$rulespath/$file") { | |
1540 | print FILE " - $file\n"; | |
1541 | } | |
1542 | } | |
1543 | ||
1544 | # Close file after writing. | |
1545 | close(FILE); | |
1546 | } | |
1547 | ||
ddaf8ae1 SS |
1548 | # |
1549 | ## Function to write the main file for provider rulesfiles inclusions. | |
1550 | ## | |
1551 | ## This function requires an array of provider handles. | |
1552 | # | |
1553 | sub write_main_used_rulefiles_file (@) { | |
1554 | my (@providers) = @_; | |
1555 | ||
88eb5626 | 1556 | # Call function to write the static rulefiles file. |
43d12991 | 1557 | &_write_default_rulefiles_file(); |
88eb5626 | 1558 | |
ddaf8ae1 SS |
1559 | # Open file for used rulefils inclusion. |
1560 | open (FILE, ">", "$suricata_used_providers_file") or die "Could not write to $suricata_used_providers_file. $!\n"; | |
1561 | ||
1562 | # Write yaml header to the file. | |
1563 | print FILE "%YAML 1.1\n"; | |
1564 | print FILE "---\n\n"; | |
1565 | ||
1566 | # Write header to file. | |
1567 | print FILE "#Autogenerated file. Any custom changes will be overwritten!\n"; | |
1568 | ||
1569 | # Loop through the list of given providers. | |
1570 | foreach my $provider (@providers) { | |
1571 | # Call function to get the providers used rulefiles file. | |
1572 | my $filename = &get_used_provider_rulesfile_file($provider); | |
1573 | ||
1b0e555f SS |
1574 | # Check if the file exists and write it into the used rulefiles file. |
1575 | if (-f $filename) { | |
1576 | # Print the provider to the file. | |
1577 | print FILE "include\: $filename\n"; | |
1578 | } | |
ddaf8ae1 SS |
1579 | } |
1580 | ||
ddaf8ae1 SS |
1581 | # Close the filehandle after writing. |
1582 | close(FILE); | |
1583 | } | |
1584 | ||
43d12991 SS |
1585 | sub _write_default_rulefiles_file () { |
1586 | # Get enabled application layer protocols. | |
1587 | my @enabled_app_layer_protos = &get_suricata_enabled_app_layer_protos(); | |
1588 | ||
88eb5626 | 1589 | # Open file. |
43d12991 | 1590 | open (FILE, ">", $suricata_default_rulefiles_file) or die "Could not write to $suricata_default_rulefiles_file. $!\n"; |
88eb5626 SS |
1591 | |
1592 | # Write yaml header to the file. | |
1593 | print FILE "%YAML 1.1\n"; | |
1594 | print FILE "---\n\n"; | |
1595 | ||
1596 | # Write notice about autogenerated file. | |
1597 | print FILE "#Autogenerated file. Any custom changes will be overwritten!\n"; | |
1598 | ||
1599 | # Loop through the array of static included rulesfiles. | |
1600 | foreach my $file (@static_included_rulefiles) { | |
1601 | # Check if the file exists. | |
1602 | if (-f "$rulespath/$file") { | |
1603 | # Write the rulesfile name to the file. | |
43d12991 SS |
1604 | print FILE " - $rulespath/$file\n"; |
1605 | } | |
1606 | } | |
1607 | ||
1608 | print FILE "\n#Default rules for used application layer protocols.\n"; | |
1609 | foreach my $enabled_app_layer_proto (@enabled_app_layer_protos) { | |
1610 | # Check if the current processed app layer proto needs to be translated | |
1611 | # into an application name. | |
1612 | if (exists($tr_app_layer_proto{$enabled_app_layer_proto})) { | |
43d12991 SS |
1613 | # Obtain the translated application name for this protocol. |
1614 | $enabled_app_layer_proto = $tr_app_layer_proto{$enabled_app_layer_proto}; | |
1615 | } | |
1616 | ||
1617 | # Generate filename. | |
1618 | my $rulesfile = "$default_rulespath/$enabled_app_layer_proto\.rules"; | |
1619 | ||
1620 | # Check if such a file exists. | |
1621 | if (-f "$rulesfile") { | |
1622 | # Write the rulesfile name to the file. | |
1623 | print FILE " - $rulesfile\n"; | |
1624 | } | |
1625 | ||
1626 | # Generate filename with "events" in filename. | |
1627 | $rulesfile = "$default_rulespath/$enabled_app_layer_proto\-events.rules"; | |
1628 | ||
1629 | # Check if this file exists. | |
1630 | if (-f "$rulesfile" ) { | |
1631 | # Write the rulesfile name to the file. | |
1632 | print FILE " - $rulesfile\n"; | |
88eb5626 SS |
1633 | } |
1634 | } | |
1635 | ||
1636 | # Close the file handle | |
1637 | close(FILE); | |
1638 | } | |
1639 | ||
ddaf8ae1 SS |
1640 | # |
1641 | ## Tiny function to generate the full path and name for the used_provider_rulesfile file of a given provider. | |
1642 | # | |
1643 | sub get_used_provider_rulesfile_file ($) { | |
1644 | my ($provider) = @_; | |
1645 | ||
1646 | my $filename = "$settingsdir/suricata\-$provider\-used\-rulefiles.yaml"; | |
1647 | ||
1648 | # Return the gernerated file. | |
1649 | return $filename; | |
1650 | } | |
1651 | ||
518cbdd3 SS |
1652 | # |
1653 | ## Tiny function to generate the full path and name for the file which stores the modifications of a ruleset. | |
1654 | # | |
1655 | sub get_provider_ruleset_modifications_file($) { | |
1656 | my ($provider) = @_; | |
1657 | ||
1658 | my $filename = "$settingsdir/$provider\-modifications"; | |
1659 | ||
1660 | # Return the filename. | |
1661 | return $filename; | |
1662 | } | |
1663 | ||
74cc8f5a SS |
1664 | # |
1665 | ## Function to generate and write the file for modify the ruleset. | |
1666 | # | |
81bae51f SS |
1667 | sub write_modify_sids_file() { |
1668 | # Get configured settings. | |
1669 | my %idssettings=(); | |
81bae51f | 1670 | &General::readhash("$ids_settings_file", \%idssettings); |
74cc8f5a SS |
1671 | |
1672 | # Open modify sid's file for writing. | |
2ee51088 | 1673 | open(FILE, ">$modify_sids_file") or die "Could not write to $modify_sids_file. $!\n"; |
74cc8f5a SS |
1674 | |
1675 | # Write file header. | |
1676 | print FILE "#Autogenerated file. Any custom changes will be overwritten!\n"; | |
1677 | ||
1678 | # Check if the traffic only should be monitored. | |
81bae51f | 1679 | unless($idssettings{'MONITOR_TRAFFIC_ONLY'} eq 'on') { |
a5ba473c TF |
1680 | # Suricata is in IPS mode, which means that the rule actions have to be changed |
1681 | # from 'alert' to 'drop', however not all rules should be changed. Some rules | |
1682 | # exist purely to set a flowbit which is used to convey other information, such | |
1683 | # as a specific type of file being downloaded, to other rulewhich then check for | |
1684 | # malware in that file. Rules which fall into the first category should stay as | |
1685 | # alert since not all flows of that type contain malware. | |
1686 | ||
aac869c4 SS |
1687 | # These types of rulesfiles contain meta-data which gives the action that should |
1688 | # be used when in IPS mode. Do the following: | |
1689 | # | |
1690 | # 1. Disable all rules and set the action to 'drop' | |
1691 | # 2. Set the action back to 'alert' if the rule contains 'flowbits:noalert;' | |
1692 | # This should give rules not in the policy a reasonable default if the user | |
1693 | # manually enables them. | |
1694 | # 3. Enable rules and set actions according to the meta-data strings. | |
a5ba473c | 1695 | |
aac869c4 | 1696 | my $policy = 'balanced'; # Placeholder to allow policy to be changed. |
a5ba473c TF |
1697 | |
1698 | print FILE <<END; | |
a5ba473c TF |
1699 | modifysid * "^#(?:alert|drop)(.+policy $policy-ips alert)" | "alert\${1}" |
1700 | modifysid * "^#(?:alert|drop)(.+policy $policy-ips drop)" | "drop\${1}" | |
a5ba473c TF |
1701 | modifysid * "^(#?)(?:alert|drop)" | "\${1}drop" |
1702 | modifysid * "^(#?)drop(.+flowbits:noalert;)" | "\${1}alert\${2}" | |
1703 | END | |
1704 | } | |
74cc8f5a SS |
1705 | |
1706 | # Close file handle. | |
1707 | close(FILE); | |
1708 | } | |
1709 | ||
235e3e92 SS |
1710 | # |
1711 | ## Function to get the subscription code of a configured provider. | |
1712 | # | |
1713 | sub get_subscription_code($) { | |
1714 | my ($provider) = @_; | |
1715 | ||
1716 | my %configured_providers = (); | |
1717 | ||
1718 | # Read-in providers settings file. | |
1719 | &General::readhasharray($providers_settings_file, \%configured_providers); | |
1720 | ||
1721 | # Loop through the hash of configured providers. | |
1722 | foreach my $id (keys %configured_providers) { | |
1723 | # Assign nice human-readable values to the data fields. | |
1724 | my $provider_handle = $configured_providers{$id}[0]; | |
1725 | my $subscription_code = $configured_providers{$id}[1]; | |
1726 | ||
1727 | # Check if the current processed provider is the requested one. | |
1728 | if ($provider_handle eq $provider) { | |
1729 | # Return the obtained subscription code. | |
1730 | return $subscription_code; | |
1731 | } | |
1732 | } | |
1733 | ||
1734 | # No subscription code found - return nothing. | |
1735 | return; | |
1736 | } | |
1737 | ||
f580aa8c SS |
1738 | # |
1739 | ## Function to get the ruleset date for a given provider. | |
1740 | ## | |
1741 | ## The function simply return the creation date in a human read-able format | |
1742 | ## of the stored providers rulesfile. | |
1743 | # | |
1744 | sub get_ruleset_date($) { | |
1745 | my ($provider) = @_; | |
fc685a36 | 1746 | my $date; |
c68bcbb2 | 1747 | my $mtime; |
f580aa8c | 1748 | |
f580aa8c SS |
1749 | # Get the stored rulesfile for this provider. |
1750 | my $stored_rulesfile = &_get_dl_rulesfile($provider); | |
1751 | ||
c68bcbb2 | 1752 | # Check if we got a file. |
cad087c7 | 1753 | if (-f $stored_rulesfile) { |
c68bcbb2 SS |
1754 | # Call stat on the rulestarball. |
1755 | my $stat = stat("$stored_rulesfile"); | |
f580aa8c | 1756 | |
c68bcbb2 SS |
1757 | # Get timestamp the file creation. |
1758 | $mtime = $stat->mtime; | |
1759 | } | |
f580aa8c | 1760 | |
057e8953 SS |
1761 | # Check if the timestamp has not been grabbed. |
1762 | unless ($mtime) { | |
1763 | # Return N/A for Not available. | |
1764 | return "N/A"; | |
1765 | } | |
1766 | ||
f580aa8c | 1767 | # Convert into human read-able format. |
fc685a36 SS |
1768 | $date = strftime('%Y-%m-%d %H:%M:%S', localtime($mtime)); |
1769 | ||
f580aa8c SS |
1770 | # Return the date. |
1771 | return $date; | |
1772 | } | |
1773 | ||
04a0d07c SS |
1774 | # |
1775 | ## Function to gather the version of suricata. | |
1776 | # | |
1777 | sub get_suricata_version($) { | |
1778 | my ($format) = @_; | |
1779 | ||
1780 | # Execute piped suricata command and return the version information. | |
1781 | open(SURICATA, "suricata -V |") or die "Couldn't execute program: $!"; | |
1782 | ||
1783 | # Grab and store the output of the piped program. | |
1784 | my $version_string = <SURICATA>; | |
1785 | ||
1786 | # Close pipe. | |
1787 | close(SURICATA); | |
1788 | ||
1789 | # Remove newlines. | |
1790 | chomp($version_string); | |
1791 | ||
fd2dccaa | 1792 | # Grab the version from the version string. |
04a0d07c SS |
1793 | $version_string =~ /([0-9]+([.][0-9]+)+)/; |
1794 | ||
1795 | # Splitt the version into single chunks. | |
1796 | my ($major_ver, $minor_ver, $patchlevel) = split(/\./, $1); | |
1797 | ||
1798 | # Check and return the requested version sheme. | |
1799 | if ($format eq "major") { | |
1800 | # Return the full version. | |
1801 | return "$major_ver"; | |
1802 | } elsif ($format eq "minor") { | |
1803 | # Return the major and minor part. | |
1804 | return "$major_ver.$minor_ver"; | |
1805 | } else { | |
1806 | # Return the full version string. | |
1807 | return "$major_ver.$minor_ver.$patchlevel"; | |
fd2dccaa | 1808 | } |
04a0d07c SS |
1809 | } |
1810 | ||
bb39fac4 SS |
1811 | # |
1812 | ## Function to get the enabled application layer protocols. | |
1813 | # | |
1814 | sub get_suricata_enabled_app_layer_protos() { | |
1815 | # Array to store and return the enabled app layer protos. | |
1816 | my @enabled_app_layer_protos = (); | |
1817 | ||
1818 | # Execute piped suricata command and return the list of | |
1819 | # enabled application layer protocols. | |
1820 | open(SURICATA, "suricata --list-app-layer-protos |") or die "Could not execute program: $!"; | |
1821 | ||
1822 | # Grab and store the list of enabled application layer protocols. | |
1823 | my @output = <SURICATA>; | |
1824 | ||
1825 | # Close pipe. | |
1826 | close(SURICATA); | |
1827 | ||
1828 | # Merge allways enabled static application layers protocols array. | |
1829 | @enabled_app_layer_protos = @static_enabled_app_layer_protos; | |
1830 | ||
1831 | # Loop through the array which contains the output of suricata. | |
1832 | foreach my $line (@output) { | |
1833 | # Skip header line which starts with "===". | |
1834 | next if ($line =~ /^\s*=/); | |
1835 | ||
1836 | # Skip info or warning lines. | |
1837 | next if ($line =~ /\s*--/); | |
1838 | ||
1839 | # Remove newlines. | |
1840 | chomp($line); | |
1841 | ||
1842 | # Add enabled app layer proto to the array. | |
1843 | push(@enabled_app_layer_protos, $line); | |
1844 | } | |
1845 | ||
1846 | # Sort the array. | |
1847 | @enabled_app_layer_protos = sort(@enabled_app_layer_protos); | |
1848 | ||
1849 | # Return the array. | |
1850 | return @enabled_app_layer_protos; | |
1851 | } | |
1852 | ||
9283e9b9 SS |
1853 | # |
1854 | ## Function to generate the rules file with whitelisted addresses. | |
1855 | # | |
1856 | sub generate_ignore_file() { | |
1857 | my %ignored = (); | |
1858 | ||
1859 | # SID range 1000000-1999999 Reserved for Local Use | |
1860 | # Put your custom rules in this range to avoid conflicts | |
1861 | my $sid = 1500000; | |
1862 | ||
1863 | # Read-in ignoredfile. | |
1864 | &General::readhasharray($IDS::ignored_file, \%ignored); | |
1865 | ||
1866 | # Open ignorefile for writing. | |
1867 | open(FILE, ">$IDS::whitelist_file") or die "Could not write to $IDS::whitelist_file. $!\n"; | |
1868 | ||
1869 | # Config file header. | |
1870 | print FILE "# Autogenerated file.\n"; | |
1871 | print FILE "# All user modifications will be overwritten.\n\n"; | |
1872 | ||
1873 | # Add all user defined addresses to the whitelist. | |
1874 | # | |
1875 | # Check if the hash contains any elements. | |
1876 | if (keys (%ignored)) { | |
1877 | # Loop through the entire hash and write the host/network | |
1878 | # and remark to the ignore file. | |
1879 | while ( (my $key) = each %ignored) { | |
1880 | my $address = $ignored{$key}[0]; | |
1881 | my $remark = $ignored{$key}[1]; | |
1882 | my $status = $ignored{$key}[2]; | |
1883 | ||
1884 | # Check if the status of the entry is "enabled". | |
1885 | if ($status eq "enabled") { | |
1886 | # Check if the address/network is valid. | |
1887 | if ((&General::validip($address)) || (&General::validipandmask($address))) { | |
1888 | # Write rule line to the file to pass any traffic from this IP | |
c1ccae1c | 1889 | print FILE "pass ip $address any -> any any (msg:\"pass all traffic from/to $address\"\; bypass; sid:$sid\;)\n"; |
9283e9b9 SS |
1890 | |
1891 | # Increment sid. | |
1892 | $sid++; | |
1893 | } | |
1894 | } | |
1895 | } | |
1896 | } | |
1897 | ||
1898 | close(FILE); | |
1899 | } | |
1900 | ||
1fedede6 SS |
1901 | # |
1902 | ## Function to set correct ownership for single files and directories. | |
1903 | # | |
1904 | ||
1905 | sub set_ownership($) { | |
1906 | my ($target) = @_; | |
1907 | ||
1908 | # User and group of the WUI. | |
1909 | my $uname = "nobody"; | |
1910 | my $grname = "nobody"; | |
1911 | ||
1912 | # The chown function implemented in perl requies the user and group as nummeric id's. | |
1913 | my $uid = getpwnam($uname); | |
1914 | my $gid = getgrnam($grname); | |
1915 | ||
1916 | # Check if the given target exists. | |
1917 | unless ($target) { | |
1918 | # Stop the script and print error message. | |
1919 | die "The $target does not exist. Cannot change the ownership!\n"; | |
1920 | } | |
1921 | ||
1922 | # Check weather the target is a file or directory. | |
1923 | if (-f $target) { | |
1924 | # Change ownership ot the single file. | |
1925 | chown($uid, $gid, "$target"); | |
1926 | } elsif (-d $target) { | |
1927 | # Do a directory listing. | |
1928 | opendir(DIR, $target) or die $!; | |
1929 | # Loop through the direcory. | |
1930 | while (my $file = readdir(DIR)) { | |
1931 | ||
1932 | # We only want files. | |
1933 | next unless (-f "$target/$file"); | |
1934 | ||
1935 | # Set correct ownership for the files. | |
1936 | chown($uid, $gid, "$target/$file"); | |
1937 | } | |
1938 | ||
1939 | closedir(DIR); | |
1940 | ||
1941 | # Change ownership of the directory. | |
1942 | chown($uid, $gid, "$target"); | |
1943 | } | |
1944 | } | |
77c31301 SS |
1945 | |
1946 | # | |
1947 | ## Function to read-in the aliases file and returns all configured and enabled aliases. | |
1948 | # | |
1949 | sub get_aliases() { | |
1950 | # Location of the aliases file. | |
1951 | my $aliases_file = "${General::swroot}/ethernet/aliases"; | |
1952 | ||
1953 | # Array to store the aliases. | |
1954 | my @aliases; | |
1955 | ||
1956 | # Check if the file is empty. | |
1957 | if (-z $aliases_file) { | |
1958 | # Abort nothing to do. | |
1959 | return; | |
1960 | } | |
1961 | ||
1962 | # Open the aliases file. | |
1963 | open(ALIASES, $aliases_file) or die "Could not open $aliases_file. $!\n"; | |
1964 | ||
1965 | # Loop through the file content. | |
1966 | while (my $line = <ALIASES>) { | |
1967 | # Remove newlines. | |
1968 | chomp($line); | |
1969 | ||
1970 | # Splitt line content into single chunks. | |
1971 | my ($address, $state, $remark) = split(/\,/, $line); | |
1972 | ||
1973 | # Check if the state of the current processed alias is "on". | |
1974 | if ($state eq "on") { | |
1975 | # Check if the address is valid. | |
1976 | if(&Network::check_ip_address($address)) { | |
1977 | # Add the alias to the array of aliases. | |
1978 | push(@aliases, $address); | |
1979 | } | |
1980 | } | |
1981 | } | |
1982 | ||
1983 | # Close file handle. | |
1984 | close(ALIASES); | |
1985 | ||
1986 | # Return the array. | |
1987 | return @aliases; | |
1988 | } | |
1989 | ||
de8e1e5b SS |
1990 | # |
1991 | ## Function to grab the current assigned IP-address on red. | |
1992 | # | |
1993 | sub get_red_address() { | |
1994 | # File, which contains the current IP-address of the red interface. | |
1995 | my $file = "${General::swroot}/red/local-ipaddress"; | |
1996 | ||
1997 | # Check if the file exists. | |
1998 | if (-e $file) { | |
1999 | # Open the given file. | |
2000 | open(FILE, "$file") or die "Could not open $file."; | |
2001 | ||
2002 | # Obtain the address from the first line of the file. | |
2003 | my $address = <FILE>; | |
2004 | ||
2005 | # Close filehandle | |
2006 | close(FILE); | |
2007 | ||
2008 | # Remove newlines. | |
2009 | chomp $address; | |
2010 | ||
2011 | # Check if the grabbed address is valid. | |
2012 | if (&General::validip($address)) { | |
2013 | # Return the address. | |
2014 | return $address; | |
2015 | } | |
2016 | } | |
2017 | ||
2018 | # Return nothing. | |
2019 | return; | |
2020 | } | |
77c31301 | 2021 | |
6563d449 | 2022 | # |
ddaf8ae1 | 2023 | ## Function to get the used rules files of a given provider. |
6563d449 | 2024 | # |
ddaf8ae1 SS |
2025 | sub read_used_provider_rulesfiles($) { |
2026 | my ($provider) = @_; | |
2027 | ||
6563d449 SS |
2028 | # Array to store the used rulefiles. |
2029 | my @used_rulesfiles = (); | |
2030 | ||
ddaf8ae1 SS |
2031 | # Get the used rulesefile file for the provider. |
2032 | my $rulesfile_file = &get_used_provider_rulesfile_file($provider); | |
2033 | ||
01fc880c SS |
2034 | # Check if the a used rulesfile exists for this provider. |
2035 | if (-f $rulesfile_file) { | |
6563d449 | 2036 | # Open the file or used rulefiles and read-in content. |
ddaf8ae1 | 2037 | open(FILE, $rulesfile_file) or die "Could not open $rulesfile_file. $!\n"; |
6563d449 SS |
2038 | |
2039 | while (<FILE>) { | |
2040 | # Assign the current line to a nice variable. | |
2041 | my $line = $_; | |
2042 | ||
2043 | # Remove newlines. | |
2044 | chomp($line); | |
2045 | ||
2046 | # Skip comments. | |
2047 | next if ($line =~ /\#/); | |
2048 | ||
2049 | # Skip blank lines. | |
2050 | next if ($line =~ /^\s*$/); | |
2051 | ||
2052 | # Gather the rulefile. | |
2053 | if ($line =~ /.*- (.*)/) { | |
2054 | my $rulefile = $1; | |
2055 | ||
2056 | # Add the rulefile to the array of used rulesfiles. | |
2057 | push(@used_rulesfiles, $rulefile); | |
2058 | } | |
2059 | } | |
2060 | ||
2061 | # Close the file. | |
2062 | close(FILE); | |
2063 | } | |
2064 | ||
2065 | # Return the array of used rulesfiles. | |
2066 | return @used_rulesfiles; | |
2067 | } | |
2068 | ||
8076deba SS |
2069 | # |
2070 | ## Function to write the lock file for locking the WUI, while | |
2071 | ## the autoupdate script runs. | |
2072 | # | |
2073 | sub lock_ids_page() { | |
2074 | # Call subfunction to create the file. | |
2075 | &create_empty_file($ids_page_lock_file); | |
2076 | } | |
2077 | ||
2078 | # | |
2079 | ## Function to release the lock of the WUI, again. | |
2080 | # | |
2081 | sub unlock_ids_page() { | |
2082 | # Delete lock file. | |
2083 | unlink($ids_page_lock_file); | |
2084 | } | |
2085 | ||
8dcebe53 | 2086 | 1; |