/
snort.inc
4350 lines (3856 loc) · 167 KB
/
snort.inc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* snort.inc
*
* part of pfSense (https://www.pfsense.org)
* Copyright (c) 2006-2022 Rubicon Communications, LLC (Netgate)
* Copyright (c) 2009-2010 Robert Zelaya
* Copyright (c) 2013-2022 Bill Meeks
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once("pfsense-utils.inc");
require_once("config.inc");
require_once("functions.inc");
require_once("service-utils.inc"); // Need this to get RCFILEPREFIX definition
require_once("pkg-utils.inc");
require_once("filter.inc");
require_once("xmlrpc_client.inc");
require("/usr/local/pkg/snort/snort_defs.inc");
// Snort GUI needs some extra PHP memory space to manipulate large rules arrays
ini_set("memory_limit", "384M");
// Explicitly declare this as global so it works through function call includes
global $g, $rebuild_rules;
/* Rebuild Rules Flag -- if "true", rebuild enforcing rules and flowbit-rules files */
$rebuild_rules = false;
function snort_is_single_addr_alias($alias) {
/***************************************************/
/* This function evaluates the passed Alias to */
/* determine if it represents a single IP address, */
/* or a network in CIDR form, and returns TRUE if */
/* the condition is met, and FALSE if not. */
/* */
/* On Entry: $alias ==> Alias to be evaluated */
/* Returns: TRUE if Alias represents a single */
/* IP address or network, and FALSE */
/* if not. */
/***************************************************/
/* If spaces in expanded Alias, it's not a single entity */
if (strpos(trim(filter_expand_alias($alias)), " ") !== false)
return false;
else
return true;
}
function snort_expand_port_range($ports, $delim = ',') {
/**************************************************/
/* This function examines the passed ports string */
/* and expands any embedded port ranges into the */
/* individual ports separated by the specified */
/* delimiter. A port range is indicated by a */
/* colon in the string. */
/* */
/* On Entry: $ports ==> string to be evaluated */
/* with {$delim} separating */
/* the port values. */
/* Returns: string with any encountered port */
/* ranges expanded and the values */
/* delimited by {$delim}. */
/**************************************************/
$value = "";
// Split the incoming string on the specified delimiter
$tmp = explode($delim, $ports);
// Look for any included port range and expand it
foreach ($tmp as $val) {
if (is_portrange($val)) {
$start = strtok($val, ":");
$end = strtok(":");
if ($end !== false) {
$val = $start . $delim;
for ($i = intval($start) + 1; $i < intval($end); $i++)
$val .= strval($i) . $delim;
$val .= $end;
}
}
$value .= $val . $delim;
}
// Remove any trailing delimiter in return value
return trim($value, $delim);
}
function snort_get_blocked_ips() {
$blocked_ips = array();
exec('/sbin/pfctl -t snort2c -T show', $blocked_ips);
$blocked_ips_array = array();
if (!empty($blocked_ips)) {
$blocked_ips_array = array();
if (is_array($blocked_ips)) {
foreach ($blocked_ips as $blocked_ip) {
if (empty($blocked_ip))
continue;
$blocked_ips_array[] = trim($blocked_ip, " \n\t");
}
}
}
return $blocked_ips_array;
}
function snort_generate_id() {
while (true) {
$snort_uuid = mt_rand(1, 65535);
foreach (config_get_path('installedpackages/snortglobal/rule', []) as $value) {
if ($value['uuid'] == $snort_uuid)
continue 2;
}
break;
}
return $snort_uuid;
}
function snort_load_suppress_sigs($snortcfg, $track_by=false) {
/**********************************************************/
/* This function loads the GEN_ID and SIG_ID for all the */
/* suppressed alert entries from the Suppression List of */
/* the passed Snort interface. The results are returned */
/* in an array with GEN_ID and SIG_ID as the primary */
/* keys. Any "track by_src" or "track by_dst" entries */
/* in the Suppression List are tacked on as additional */
/* keys in the array along with the IP address in either */
/* IPv4 or IPv6 format when $track_by is passed as true. */
/* */
/* Sample returned array: */
/* $suppress[1][2069] = "suppress" */
/* $suppress[1][2070]['by_src']['10.1.1.5'] = "suppress" */
/* $suppress[1][2070]['by_dst']['10.1.1.6'] = "suppress" */
/* */
/**********************************************************/
$suppress = array();
foreach (config_get_path('installedpackages/snortglobal/suppress/item', []) as $a_id => $alist) {
if ($alist['name'] == $snortcfg['suppresslistname']) {
if (!empty($alist['suppresspassthru'])) {
$tmplist = str_replace("\r", "", base64_decode($alist['suppresspassthru']));
$tmp = explode("\n", $tmplist);
foreach ($tmp as $line) {
// Skip any blank lines
if (trim($line, " \n") == "")
continue;
// Skip any comment lines
if (preg_match('/^\s*#/', $line))
continue;
/* See if entry suppresses GID:SID for all hosts */
if (preg_match('/\s*suppress\s*gen_id\b\s*(\d+),\s*sig_id\b\s*(\d+)\s*$/i', $line, $matches)) {
$genid = $matches[1];
$sigid = $matches[2];
if (!empty($genid) && !empty($sigid)) {
if (!is_array($suppress[$genid]))
$suppress[$genid] = array();
if (!is_array($suppress[$genid][$sigid]))
$suppress[$genid][$sigid] = array();
$suppress[$genid][$sigid] = "suppress";
}
}
/* Get "track by IP" entries if requested */
if ($track_by) {
/* See if entry suppresses only by SRC or DST IPv4 address */
if (preg_match('/\s*suppress\s*gen_id\b\s*(\d+),\s*sig_id\b\s*(\d+),\s*track\s*(by_src|by_dst),\s*ip\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s*$/i', $line, $matches)) {
$genid = $matches[1];
$sigid = $matches[2];
$whichip = trim($matches[3]);
$ip = $matches[4];
if (!empty($genid) && !empty($sigid) && !empty($whichip) && !empty($ip)) {
if (!is_array($suppress[$genid]))
$suppress[$genid] = array();
if (!is_array($suppress[$genid][$sigid]))
$suppress[$genid][$sigid] = array();
if (!is_array($suppress[$genid][$sigid][$whichip]))
$suppress[$genid][$sigid][$whichip] = array();
if (!is_array($suppress[$genid][$sigid][$whichip][$ip]))
$suppress[$genid][$sigid][$whichip][$ip] = array();
$suppress[$genid][$sigid][$whichip][$ip] = "suppress";
}
}
/* See if entry suppresses only by SRC or DST IPv6 address */
if (preg_match('/\s*suppress\s*gen_id\b\s*(\d+),\s*sig_id\b\s*(\d+),\s*track\s*(by_src|by_dst),\s*ip\s*([0-9a-f\.:]+)\s*$/i', $line, $matches)) {
$genid = $matches[1];
$sigid = $matches[2];
$whichip = trim($matches[3]);
$ip = trim($matches[4]);
if (!empty($genid) && !empty($sigid) && !empty($whichip) && !empty($ip)) {
if (!is_array($suppress[$genid]))
$suppress[$genid] = array();
if (!is_array($suppress[$genid][$sigid]))
$suppress[$genid][$sigid] = array();
if (!is_array($suppress[$genid][$sigid][$whichip]))
$suppress[$genid][$sigid][$whichip] = array();
if (!is_array($suppress[$genid][$sigid][$whichip][$ip]))
$suppress[$genid][$sigid][$whichip][$ip] = array();
$suppress[$genid][$sigid][$whichip][$ip] = "suppress";
}
}
}
}
unset($tmp);
}
break;
}
}
return $suppress;
}
/* func finds custom lists by name and type (defaults to 'whitelist') */
function snort_find_list($find_name, $type = 'whitelist') {
foreach (config_get_path("installedpackages/snortglobal/{$type}/item", []) as $value) {
if ($value['name'] == $find_name)
return $value;
}
return array();
}
/* func builds custom whitelists and the HOME_NET variable */
function snort_build_list($snortcfg, $listname = "", $whitelist = false, $externallist = false) {
/***********************************************************/
/* The default is to build a HOME_NET variable unless */
/* '$whitelist' or '$externallist is set to TRUE when */
/* calling. */
/* */
/* When '$whitelist' is TRUE, a Pass List is built. */
/* When '$externalist' is TRUE, the EXTERNAL_NET variable */
/* is built. */
/***********************************************************/
global $g, $aliastable, $filterdns;
$home_net = array();
// If passed an empty interface config array, then
// exit returning an empty list array. This is an
// unexpected condition.
if (empty($snortcfg))
return $home_net;
if (!$externallist && ($listname == 'default' || empty($listname))) {
$localnet = 'yes'; $wanip = 'yes'; $wangw = 'yes'; $wandns = 'yes'; $vips = 'yes'; $vpns = 'yes';
}
else {
$list = snort_find_list($listname);
if (empty($list))
return $list;
$localnet = $list['localnets'];
$wanip = 'yes';
$wangw = $list['wangateips'];
$wandns = $list['wandnsips'];
$vips = $list['vips'];
$vpns = $list['vpnips'];
// Process any custom IPs or aliases defined for the list.
// We allow dynamically updated aliases only for a Pass
// List. So for Pass Lists, we test for null strings from
// filter_expand_alias() and assume the passed alias is a
// FQDN or other dynamically updated alias.
if (array_get_path($list, 'address/item')) {
foreach ($list['address']['item'] as $addr) {
if (!$whitelist) {
if (is_alias($addr) && (alias_get_type($addr) == "host" || alias_get_type($addr) == "network")) {
$home_net = array_merge($home_net, explode(" ", trim(filter_expand_alias($addr))));
} elseif (is_ipaddr($addr) || is_subnet($addr)) {
$home_net[] = $addr;
}
} elseif ($whitelist) {
if (is_alias($addr) && (alias_get_type($addr) == "host" || alias_get_type($addr) == "network")) {
$tmp = trim(filter_expand_alias($addr));
if ($tmp <> "") {
$home_net = array_merge($home_net, explode(" ", $tmp));
} else {
$home_net[] = $addr;
}
} elseif (is_ipaddr($addr) || is_subnet($addr)) {
$home_net[] = $addr;
}
}
}
}
}
/* Always add loopback addresses to HOME_NET and whitelist */
if (!$externallist) {
if (!in_array("127.0.0.1", $home_net))
$home_net[] = "127.0.0.1";
if (!in_array("::1", $home_net))
$home_net[] = "::1";
}
/********************************************************************/
/* Always put the interface running Snort in HOME_NET and whitelist */
/* unless it's the WAN. WAN options are handled further down. */
/* If the user specifically chose not to include LOCAL_NETS in the */
/* WHITELIST, then do not include the Snort interface subnet in the */
/* WHITELIST. We do include the actual LAN interface IP for Snort, */
/* though, to prevent locking out the firewall itself. */
/********************************************************************/
$snortip = get_interface_ip($snortcfg['interface']);
if (($externallist && $localnet == 'yes') || (!$externallist && $whitelist && ($localnet == 'yes' || empty($localnet)))) {
if (is_ipaddr($snortip)) {
if ($snortcfg['interface'] <> "wan") {
if ($sn = get_interface_subnet($snortcfg['interface'])) {
$ip = gen_subnet($snortip, $sn) . "/{$sn}";
if (!in_array($ip, $home_net))
$home_net[] = $ip;
}
}
}
}
elseif (!$externallist && $localnet != 'yes') {
if (is_ipaddrv4($snortip)) {
if (!in_array($snortip, $home_net))
$home_net[] = $snortip;
}
}
// Grab the IPv6 address if we have one assigned
$snortip = get_interface_ipv6($snortcfg['interface']);
// Trim off the interface designation (e.g., %em1) if present
if (strpos($snortip, "%") !== FALSE)
$snortip = substr($snortip, 0, strpos($snortip, "%"));
if (($externallist && $localnet == 'yes') || ($whitelist && ($localnet == 'yes' || empty($localnet))) || (!$externallist && !$whitelist && ($localnet == 'yes' || empty($localnet)))) {
if (is_ipaddrv6($snortip)) {
if ($snortcfg['interface'] <> "wan") {
if ($sn = get_interface_subnetv6($snortcfg['interface'])) {
$ip = gen_subnetv6($snortip, $sn). "/{$sn}";
if (!in_array($ip, $home_net))
$home_net[] = $ip;
}
}
}
}
elseif (!$externallist && $localnet != 'yes') {
if (is_ipaddrv6($snortip)) {
if (!in_array($snortip, $home_net))
$home_net[] = $snortip;
}
}
// Add link-local address if user included locally-attached networks
$snortip = get_interface_linklocal($snortcfg['interface']);
if (!empty($snortip) && $localnet == 'yes') {
// Trim off the interface designation (e.g., %em1) if present
if (strpos($snortip, "%") !== FALSE)
$snortip = substr($snortip, 0, strpos($snortip, "%"));
if (!in_array($snortip, $home_net))
$home_net[] = $snortip;
}
if (($externallist && $localnet == 'yes') || ($whitelist && ($localnet == 'yes' || empty($localnet))) || (!$externallist && !$whitelist && ($localnet == 'yes' || empty($localnet)))) {
/*************************************************************************/
/* Iterate through the interface list and write out whitelist items and */
/* also compile a HOME_NET list of all the local interfaces for snort. */
/* Skip the WAN interface as we do not typically want that whole subnet */
/* whitelisted (just the i/f IP itself which was handled earlier). */
/*************************************************************************/
$int_array = get_configured_interface_list();
foreach ($int_array as $int) {
if ($int == "wan")
continue;
$subnet = get_interface_ip($int);
if (is_ipaddrv4($subnet)) {
if ($sn = get_interface_subnet($int)) {
$ip = gen_subnet($subnet, $sn) . "/{$sn}";
if (!in_array($ip, $home_net))
$home_net[] = $ip;
}
}
$subnet = get_interface_ipv6($int);
// Trim off the interface designation (e.g., %em1) if present
if (strpos($subnet, "%") !== FALSE)
$subnet = substr($subnet, 0, strpos($subnet, "%"));
if (is_ipaddrv6($subnet)) {
if ($sn = get_interface_subnetv6($int)) {
$ip = gen_subnetv6($subnet, $sn). "/{$sn}";
if (!in_array($ip, $home_net))
$home_net[] = $ip;
}
}
// Add link-local address
$snortip = get_interface_linklocal($int);
if (!empty($snortip)) {
// Trim off the interface designation (e.g., %em1) if present
if (strpos($snortip, "%") !== FALSE)
$snortip = substr($snortip, 0, strpos($snortip, "%"));
if (!in_array($snortip, $home_net))
$home_net[] = $snortip;
}
}
}
if ($wanip == 'yes') {
$ip = get_interface_ip("wan");
if (is_ipaddrv4($ip)) {
if (!in_array($ip, $home_net))
$home_net[] = $ip;
}
$ip = get_interface_ipv6("wan");
// Trim off the interface designation (e.g., %em1) if present
if (strpos($ip, "%") !== FALSE)
$ip = substr($ip, 0, strpos($ip, "%"));
if (is_ipaddrv6($ip)) {
if (!in_array($ip, $home_net))
$home_net[] = $ip;
}
// Explicitly grab the WAN Link-Local address
$snortip = get_interface_linklocal("wan");
if (!empty($snortip)) {
// Trim off the interface designation (e.g., %em1) if present
if (strpos($snortip, "%") !== FALSE)
$snortip = substr($snortip, 0, strpos($snortip, "%"));
if (!in_array($snortip, $home_net))
$home_net[] = $snortip;
}
}
if ($wangw == 'yes') {
/* Grab the default gateway if set */
$default_gw = exec("/sbin/route -n get default |grep 'gateway:' | /usr/bin/awk '{ print $2 }'");
if (is_ipaddrv4($default_gw) && !in_array($default_gw, $home_net))
$home_net[] = $default_gw;
if (is_ipaddrv6($default_gw) && !in_array($default_gw, $home_net))
$home_net[] = $default_gw;
/* Get any other interface gateway and put in $HOME_NET if not there already */
$gw = get_interface_gateway($snortcfg['interface']);
if (is_ipaddrv4($gw) && !in_array($gw, $home_net))
$home_net[] = $gw;
$gw = get_interface_gateway_v6($snortcfg['interface']);
// Trim off the interface designation (e.g., %em1) if present
if (strpos($gw, "%") !== FALSE)
$gw = substr($gw, 0, strpos($gw, "%"));
if (is_ipaddrv6($gw) && !in_array($gw, $home_net))
$home_net[] = $gw;
}
if ($wandns == 'yes') {
/* Add DNS server for WAN interface to whitelist */
$dns_servers = get_dns_servers();
foreach ($dns_servers as $dns) {
if ($dns && !in_array($dns, $home_net))
$home_net[] = $dns;
}
}
if($vips == 'yes') {
/* iterate all vips and add to whitelist */
foreach(config_get_path('virtualip/vip', []) as $vip) {
if ($vip['subnet']) {
if (!in_array("{$vip['subnet']}/{$vip['subnet_bits']}", $home_net))
$home_net[] = "{$vip['subnet']}/{$vip['subnet_bits']}";
}
}
}
// Grab a list of vpns enabled - these come back as CIDR mask networks
if ($vpns == 'yes') {
$vpns_list = snort_get_vpns_list();
if (!empty($vpns_list)) {
/* Convert the returned space-delimited string to an array */
/* and then add each VPN address to our HOME_NET array. */
$vpns = explode(" ", $vpns_list);
foreach ($vpns as $vpn)
$home_net[] = trim($vpn);
unset($vpns, $vpns_list);
}
}
// Validate the HOME_NET entries
$valresult = array();
foreach ($home_net as $vald) {
if (empty($vald) || (!is_subnet($vald) && !is_ipaddr($vald) && !is_alias($vald))) {
continue;
}
$vald = trim($vald);
if (empty($valresult[$vald])) {
$valresult[$vald] = $vald;
}
}
/* Release memory no longer required */
unset($home_net);
/* Sort the list and return it */
natsort($valresult);
return $valresult;
}
/* Checks to see if service is running by looking for PID filename matching the UUID */
function snort_is_running($uuid) {
global $g;
return isvalidpid("{$g['varrun_path']}/snort_{$uuid}.pid");
}
function snort_stop($snortcfg, $if_real) {
global $g;
$snort_uuid = $snortcfg['uuid'];
if (isvalidpid("{$g['varrun_path']}/snort_{$snort_uuid}.pid")) {
syslog(LOG_NOTICE, "[Snort] Snort STOP for " . convert_real_interface_to_friendly_descr($if_real) . "({$if_real})...");
killbypid("{$g['varrun_path']}/snort_{$snort_uuid}.pid");
// Now wait up to 10 seconds for Snort to actually stop and clear its PID file
$count = 0;
do {
if (!isvalidpid("{$g['varrun_path']}/snort_{$snort_uuid}.pid"))
break;
sleep(1);
$count++;
} while ($count < 10);
}
unlink_if_exists("{$g['varrun_path']}/snort_{$snort_uuid}.pid");
}
function snort_start($snortcfg, $if_real, $background=FALSE) {
global $g;
$snortdir = SNORTDIR;
$snortlogdir = SNORTLOGDIR;
$snort_uuid = $snortcfg['uuid'];
$snortbindir = SNORT_BINDIR;
if (config_get_path('installedpackages/snortglobal/verbose_logging') == "on")
$quiet = "";
else
$quiet = "-q --suppress-config-log";
// If Snort is already running on this interface, stop it before restarting
if (snort_is_running($snort_uuid)) {
snort_stop($snortcfg, $if_real);
}
if ($snortcfg['enable'] == 'on' && $if_real <> "" && !isvalidpid("{$g['varrun_path']}/snort_{$snort_uuid}.pid")) {
// Adjust the interface specification and DAQ type according to operating mode
if ($snortcfg['ips_mode'] == "ips_mode_inline" && $snortcfg['blockoffenders7'] == "on") {
$iface = $if_real . "^:" . $if_real;
$daq_type = "-Q --daq netmap";
}
else {
$iface = $if_real;
$daq_type = "--daq pcap --daq-mode passive --treat-drop-as-alert";
}
syslog(LOG_NOTICE, "[Snort] Snort START for " . convert_real_interface_to_friendly_descr($if_real) . "({$if_real})...");
if ($background)
mwexec_bg("{$snortbindir}snort -R _{$snort_uuid} -D {$quiet} {$daq_type} -l {$snortlogdir}/snort_{$if_real}{$snort_uuid} --pid-path {$g['varrun_path']} --nolock-pidfile --no-interface-pidfile -G {$snort_uuid} -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/snort.conf -i {$iface}");
else
mwexec("{$snortbindir}snort -R _{$snort_uuid} -D {$quiet} {$daq_type} -l {$snortlogdir}/snort_{$if_real}{$snort_uuid} --pid-path {$g['varrun_path']} --nolock-pidfile --no-interface-pidfile -G {$snort_uuid} -c {$snortdir}/snort_{$snort_uuid}_{$if_real}/snort.conf -i {$iface}");
}
}
function snort_start_all_interfaces($background=FALSE) {
/*************************************************************/
/* This function starts all configured and enabled Snort */
/* interfaces. */
/*************************************************************/
foreach (config_get_path('installedpackages/snortglobal/rule', []) as $snortcfg) {
if ($snortcfg['enable'] != 'on' || get_real_interface($snortcfg['interface']) == "")
continue;
snort_start($snortcfg, get_real_interface($snortcfg['interface']), $background);
}
}
function snort_stop_all_interfaces() {
/*************************************************************/
/* This function stops all configured Snort interfaces. */
/*************************************************************/
foreach (config_get_path('installedpackages/snortglobal/rule', []) as $snortcfg) {
snort_stop($snortcfg, get_real_interface($snortcfg['interface']));
}
}
function snort_restart_all_interfaces() {
/*************************************************************/
/* This function stops all configured Snort interfaces and */
/* restarts enabled Snort interfaces. */
/*************************************************************/
snort_stop_all_interfaces();
sleep(2);
snort_start_all_interfaces(TRUE);
}
function snort_reload_config($snortcfg, $signal="SIGHUP") {
/*************************************************************/
/* This function sends the passed SIGNAL to the Snort */
/* instance on the passed interface to cause Snort to */
/* reload and parse the running configuration without */
/* stopping packet processing. It also executes the */
/* the reload as a background process and returns control */
/* immediately to the caller. */
/* */
/* $signal = SIGHUP (default) parses and reloads config. */
/* SIGURG updates Host Attribute Table. */
/*************************************************************/
global $g;
$snortdir = SNORTDIR;
$snort_uuid = $snortcfg['uuid'];
$if_real = get_real_interface($snortcfg['interface']);
/******************************************************/
/* Only send the SIGHUP if Snort is running and we */
/* can find a valid PID for the process. */
/******************************************************/
if (isvalidpid("{$g['varrun_path']}/snort_{$snort_uuid}.pid")) {
syslog(LOG_NOTICE, "[Snort] Snort RELOAD CONFIG for " . convert_real_interface_to_friendly_descr($if_real) . "({$if_real})...");
mwexec_bg("/bin/pkill -{$signal} -F {$g['varrun_path']}/snort_{$snort_uuid}.pid");
}
}
/*
this code block is for deleting logs while keeping the newest file,
snort is linked to these files while running, do not take the easy way out
by touch and rm, snort will lose sync and not log.
*/
function snort_post_delete_logs($snort_uuid = 0) {
global $g;
foreach (config_get_path('installedpackages/snortglobal/rule', []) as $value) {
if ($value['uuid'] != $snort_uuid)
continue;
$if_real = get_real_interface($value['interface']);
$snort_log_dir = SNORTLOGDIR . "/snort_{$if_real}{$snort_uuid}";
if ($if_real != '') {
/* Clean-up rotated unified2 log files if any exist */
$filelist = glob("{$snort_log_dir}/*{$snort_uuid}_{$if_real}.u2.*");
/* Skip the most recently rotated log */
unset($filelist[count($filelist) - 1]);
foreach ($filelist as $file)
@unlink($file);
/* Clean-up packet capture files if any exist */
unlink_if_exists("{$snort_log_dir}/snort.log.*");
/* Clean-up stats file if enabled */
if ($value['perform_stat'] == 'on')
@file_put_contents("{$snort_log_dir}/{$if_real}.stats", "");
}
}
}
/* This returns size of passed directory or file in 1024-byte blocks */
function snort_Getdirsize($node) {
if(!is_readable($node))
return false;
$blah = exec( "/usr/bin/du -kdc $node" );
return substr( $blah, 0, strpos($blah, 9) );
}
function snort_cron_job_exists($crontask, $match_time=FALSE, $minute="0", $hour="*", $monthday="*", $month="*", $weekday="*", $who="root") {
/************************************************************
* This function iterates the cron[] array in the config *
* to determine if the passed $crontask entry exists. It *
* returns TRUE if the $crontask already exists, or FALSE *
* if there is no match. *
* *
* The $match_time flag, when set, causes a test of the *
* configured task execution times along with the task *
* when checking for a match. *
* *
* We use this to prevent unneccessary config writes if *
* the $crontask already exists. *
************************************************************/
global $g;
foreach(config_get_path('cron/item', []) as $item) {
if(strpos($item['command'], $crontask) !== FALSE) {
if ($match_time) {
if ($item['minute'] != $minute)
return FALSE;
if ($item['hour'] != $hour)
return FALSE;
if ($item['mday'] != $monthday)
return FALSE;
if ($item['month'] != $month)
return FALSE;
if ($item['wday'] != $weekday)
return FALSE;
if ($item['who'] != $who)
return FALSE;
}
return TRUE;
}
}
return FALSE;
}
function snort_snortloglimit_install_cron($should_install=TRUE) {
// See if simply removing existing "loglimit" job for Snort
if ($should_install == FALSE) {
if (snort_cron_job_exists("snort/snort_check_cron_misc.inc", FALSE))
install_cron_job("snort_check_cron_misc.inc", false);
return;
}
// If there are no changes in the cron job command string from the existing job, then exit.
if ($should_install && snort_cron_job_exists("/usr/local/pkg/snort/snort_check_cron_misc.inc", TRUE, "*/5"))
return;
// Else install the new or updated cron job by removing the
// existing job first, then installing the new or updated job.
install_cron_job("snort_check_cron_misc.inc", false);
install_cron_job("/usr/bin/nice -n20 /usr/local/bin/php -f /usr/local/pkg/snort/snort_check_cron_misc.inc", $should_install, "*/5");
}
function snort_rm_blocked_install_cron($should_install) {
global $g;
// See if simply removing existing "expiretable" job for Snort
if ($should_install == FALSE) {
if (snort_cron_job_exists("snort2c", FALSE))
install_cron_job("snort2c", false);
return;
}
// Grab the configured interval from our configuration
$snort_rm_blocked_info_ck = config_get_path('installedpackages/snortglobal/rm_blocked');
if ($snort_rm_blocked_info_ck == "15m_b") {
$snort_rm_blocked_min = "*/2";
$snort_rm_blocked_hr = "*";
$snort_rm_blocked_mday = "*";
$snort_rm_blocked_month = "*";
$snort_rm_blocked_wday = "*";
$snort_rm_blocked_expire = "900";
}
if ($snort_rm_blocked_info_ck == "30m_b") {
$snort_rm_blocked_min = "*/5";
$snort_rm_blocked_hr = "*";
$snort_rm_blocked_mday = "*";
$snort_rm_blocked_month = "*";
$snort_rm_blocked_wday = "*";
$snort_rm_blocked_expire = "1800";
}
if ($snort_rm_blocked_info_ck == "1h_b") {
$snort_rm_blocked_min = "*/5";
$snort_rm_blocked_hr = "*";
$snort_rm_blocked_mday = "*";
$snort_rm_blocked_month = "*";
$snort_rm_blocked_wday = "*";
$snort_rm_blocked_expire = "3600";
}
if ($snort_rm_blocked_info_ck == "3h_b") {
$snort_rm_blocked_min = "*/15";
$snort_rm_blocked_hr = "*";
$snort_rm_blocked_mday = "*";
$snort_rm_blocked_month = "*";
$snort_rm_blocked_wday = "*";
$snort_rm_blocked_expire = "10800";
}
if ($snort_rm_blocked_info_ck == "6h_b") {
$snort_rm_blocked_min = "*/30";
$snort_rm_blocked_hr = "*";
$snort_rm_blocked_mday = "*";
$snort_rm_blocked_month = "*";
$snort_rm_blocked_wday = "*";
$snort_rm_blocked_expire = "21600";
}
if ($snort_rm_blocked_info_ck == "12h_b") {
$snort_rm_blocked_min = "2";
$snort_rm_blocked_hr = "*/1";
$snort_rm_blocked_mday = "*";
$snort_rm_blocked_month = "*";
$snort_rm_blocked_wday = "*";
$snort_rm_blocked_expire = "43200";
}
if ($snort_rm_blocked_info_ck == "1d_b") {
$snort_rm_blocked_min = "2";
$snort_rm_blocked_hr = "*/2";
$snort_rm_blocked_mday = "*";
$snort_rm_blocked_month = "*";
$snort_rm_blocked_wday = "*";
$snort_rm_blocked_expire = "86400";
}
if ($snort_rm_blocked_info_ck == "4d_b") {
$snort_rm_blocked_min = "2";
$snort_rm_blocked_hr = "*/8";
$snort_rm_blocked_mday = "*";
$snort_rm_blocked_month = "*";
$snort_rm_blocked_wday = "*";
$snort_rm_blocked_expire = "345600";
}
if ($snort_rm_blocked_info_ck == "7d_b") {
$snort_rm_blocked_min = "2";
$snort_rm_blocked_hr = "*/14";
$snort_rm_blocked_mday = "*";
$snort_rm_blocked_month = "*";
$snort_rm_blocked_wday = "*";
$snort_rm_blocked_expire = "604800";
}
if ($snort_rm_blocked_info_ck == "28d_b") {
$snort_rm_blocked_min = "2";
$snort_rm_blocked_hr = "0";
$snort_rm_blocked_mday = "*/2";
$snort_rm_blocked_month = "*";
$snort_rm_blocked_wday = "*";
$snort_rm_blocked_expire = "2419200";
}
// Construct the basic cron command task
$command = "/usr/bin/nice -n20 /sbin/pfctl -q -t snort2c -T expire {$snort_rm_blocked_expire}";
// If there are no changes in the cron job command string from the existing job, then exit.
if (snort_cron_job_exists($command, TRUE, $snort_rm_blocked_min, $snort_rm_blocked_hr, $snort_rm_blocked_mday, $snort_rm_blocked_month, $snort_rm_blocked_wday, "root"))
return;
// Else install the new or updated cron job
if ($should_install) {
// Remove the existing job first, then install the new or updated job
install_cron_job("snort2c", false);
install_cron_job($command, true, $snort_rm_blocked_min, $snort_rm_blocked_hr, $snort_rm_blocked_mday, $snort_rm_blocked_month, $snort_rm_blocked_wday, "root");
}
}
/* func to install snort update */
function snort_rules_up_install_cron($should_install) {
global $g;
// If called with FALSE as argument, then we're removing
// the existing job.
if ($should_install == FALSE) {
if (snort_cron_job_exists("snort_check_for_rule_updates.php", FALSE))
install_cron_job("snort_check_for_rule_updates.php", false);
return;
}
// Grab the configured update interval from our configuration
$snort_rules_up_info_ck = config_get_path('installedpackages/snortglobal/autorulesupdate7');
/* See if a customized start time has been set for rule file updates */
if (!empty(config_get_path('installedpackages/snortglobal/rule_update_starttime')))
$snort_rules_upd_time = config_get_path('installedpackages/snortglobal/rule_update_starttime');
else
$snort_rules_upd_time = "00:" . str_pad(strval(random_int(0,59)), 2, "00", STR_PAD_LEFT);
if ($snort_rules_up_info_ck == "6h_up") {
$snort_rules_up_min = intval(substr($snort_rules_upd_time, -2));
$hour = intval(substr($snort_rules_upd_time, 0, 2));
$snort_rules_up_hr = strval($hour);
for ($i=0; $i<3; $i++) {
$hour += 6;
if ($hour > 24)
$hour -= 24;
$snort_rules_up_hr .= "," . strval($hour);
}
$snort_rules_up_mday = "*";
$snort_rules_up_month = "*";
$snort_rules_up_wday = "*";
}
if ($snort_rules_up_info_ck == "12h_up") {
$snort_rules_up_min = intval(substr($snort_rules_upd_time, -2));
$hour = intval(substr($snort_rules_upd_time, 0, 2));
$snort_rules_up_hr = strval($hour) . ",";
$hour += 12;
if ($hour > 24)
$hour -= 24;
$snort_rules_up_hr .= strval($hour);
$snort_rules_up_mday = "*";
$snort_rules_up_month = "*";
$snort_rules_up_wday = "*";
}
if ($snort_rules_up_info_ck == "1d_up") {
$snort_rules_up_min = intval(substr($snort_rules_upd_time, -2));
$snort_rules_up_hr = intval(substr($snort_rules_upd_time, 0, 2));
$snort_rules_up_mday = "*/1";
$snort_rules_up_month = "*";
$snort_rules_up_wday = "*";
}
if ($snort_rules_up_info_ck == "4d_up") {
$snort_rules_up_min = intval(substr($snort_rules_upd_time, -2));
$snort_rules_up_hr = intval(substr($snort_rules_upd_time, 0, 2));
$snort_rules_up_mday = "*/4";
$snort_rules_up_month = "*";
$snort_rules_up_wday = "*";
}
if ($snort_rules_up_info_ck == "7d_up") {
$snort_rules_up_min = intval(substr($snort_rules_upd_time, -2));
$snort_rules_up_hr = intval(substr($snort_rules_upd_time, 0, 2));
$snort_rules_up_mday = "*/7";
$snort_rules_up_month = "*";
$snort_rules_up_wday = "*";
}
if ($snort_rules_up_info_ck == "28d_up") {
$snort_rules_up_min = intval(substr($snort_rules_upd_time, -2));
$snort_rules_up_hr = intval(substr($snort_rules_upd_time, 0, 2));
$snort_rules_up_mday = "*/28";
$snort_rules_up_month = "*";
$snort_rules_up_wday = "*";
}
// Construct the basic cron command task
$command = "/usr/bin/nice -n20 /usr/local/bin/php -f /usr/local/pkg/snort/snort_check_for_rule_updates.php";
// If there are no changes in the cron job command string from the existing job, then exit
if (snort_cron_job_exists($command, TRUE, $snort_rules_up_min, $snort_rules_up_hr, $snort_rules_up_mday, $snort_rules_up_month, $snort_rules_up_wday, "root"))
return;
// Else install the new or updated cron job
if ($should_install) {
// Remove the existing job first, then install the new or updated job
install_cron_job("snort_check_for_rule_updates.php", false);
install_cron_job($command, $should_install, $snort_rules_up_min, $snort_rules_up_hr, $snort_rules_up_mday, $snort_rules_up_month, $snort_rules_up_wday, "root");
}
}
/* Only run when all ifaces needed to sync */
function sync_snort_package_config() {
global $g;
global $rebuild_rules;
$snortdir = SNORTDIR;
$rcdir = RCFILEPREFIX;
/* Create required log and db directories in /var on each sync, in case /var is in RAM. */
safe_mkdir(SNORTLOGDIR);
safe_mkdir(SNORT_IPREP_PATH);
safe_mkdir(SNORT_SID_MODS_PATH);
safe_mkdir(SNORT_APPID_ODP_PATH);
/* Iterate configured interfaces and generate a snort.conf for each */
foreach (config_get_path('installedpackages/snortglobal/rule', []) as $value) {
/* Skip configuration of any disabled instance or */
/* an instance whose assigned physical interface */
/* has been removed. */
if (($value['enable'] != 'on') || (get_real_interface($value['interface']) == ""))
continue;
/* create a snort.conf file for interface */
snort_generate_conf($value);
}
/* create snort bootup file snort.sh */
snort_create_rc();
snort_snortloglimit_install_cron(true);
/* set the snort block hosts time IMPORTANT */
snort_rm_blocked_install_cron(config_get_path('installedpackages/snortglobal/rm_blocked') != "never_b" ? true : false);
/* set the snort rules update time */
snort_rules_up_install_cron(config_get_path('installedpackages/snortglobal/autorulesupdate7') != "never_up" ? true : false);
/* Do not attempt package sync if reinstalling package or booting */
if (!$g['snort_postinstall'] && !$g['booting'])
snort_sync_on_changes();
}
function snort_build_sid_msg_map($rules_path, $sid_file) {
/*************************************************************/
/* This function reads all the rules file in the passed */
/* $rules_path variable and produces a properly formatted */
/* sid-msg.map v2 file for use by Snort. */
/* */
/* This function produces the new v2 format sid-msg.map */
/* with the field layout as follows: */
/* */
/* GID || SID || REV || CLASSTYPE || PRI || MSG || REF ... */
/* */
/* On Entry: $rules_path --> array or directory of files */
/* or a single file containing */
/* the rules to read. */
/* $sid_file --> the complete destination path */
/* and filename for the output */