aboutsummaryrefslogtreecommitdiffstats
path: root/epan/dissectors/packet-snort.c
blob: 6a57169d2e6ec0cfb646c6b95ed40581e964555b (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
/* packet-snort.c
 *
 * Copyright 2011, Jakub Zawadzki <darkjames-ws@darkjames.pl>
 * Copyright 2016, Martin Mathieson
 *
 * Google Summer of Code 2011 for The Honeynet Project
 * Mentors:
 *    Guillaume Arcas <guillaume.arcas (at) retiaire.org>
 *    Jeff Nathan <jeffnathan (at) gmail.com>
 *
 * Wireshark - Network traffic analyzer
 * By Gerald Combs <gerald@wireshark.org>
 * Copyright 1998 Gerald Combs
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */


/* TODO:
 * - sort out threading/channel-sync so works reliably in tshark
 *    - postponed for now, as Qt crashes if call g_main_context_iteration()
 *      at an inopportune time
 * - would be good if could set [Snort Running] in the title bar while Snort is running,
 *   but don't see how a dissector could do that.
 * - for a content match, find all protocol fields that cover same bytes and show in tree
 * - after tcp.reassembled_in fixed, offer to move alert to that frame?
 * - other use-cases as suggested in https://sharkfesteurope.wireshark.org/assets/presentations16eu/14.pptx
 */


#include "config.h"

#include <errno.h>
#include <ctype.h>

#include <epan/epan.h>
#include <epan/proto.h>
#include <epan/packet.h>
#include <epan/prefs.h>
#include <epan/expert.h>
#include <wsutil/report_err.h>
#include <epan/wmem/wmem.h>
#include <wiretap/wtap-int.h>

#include "snort-config.h"

/* Forward declarations */
void proto_register_snort(void);
void proto_reg_handoff_snort(void);


static int proto_snort = -1;

/* These are from parsing snort fast_alert output and/or looking up snort config */
static int hf_snort_raw_alert = -1;
static int hf_snort_classification = -1;
static int hf_snort_rule = -1;
static int hf_snort_msg = -1;
static int hf_snort_rev = -1;
static int hf_snort_sid = -1;
static int hf_snort_generator = -1;
static int hf_snort_priority = -1;
static int hf_snort_rule_string = -1;
static int hf_snort_rule_protocol = -1;
static int hf_snort_rule_filename = -1;
static int hf_snort_rule_line_number = -1;
static int hf_snort_rule_ip_var = -1;
static int hf_snort_rule_port_var = -1;

/* Patterns to match */
static int hf_snort_content = -1;
static int hf_snort_uricontent = -1;
static int hf_snort_pcre = -1;

/* Web links */
static int hf_snort_reference = -1;

/* General stats about the rule set */
static int hf_snort_global_stats = -1;
static int hf_snort_global_stats_rule_file_count = -1;     /* number of rules files */
static int hf_snort_global_stats_rule_count = -1;          /* number of rules in config */

static int hf_snort_global_stats_total_alerts_count = -1;
static int hf_snort_global_stats_alert_match_number = -1;

static int hf_snort_global_stats_rule_alerts_count = -1;
static int hf_snort_global_stats_rule_match_number = -1;


/* Subtrees */
static int ett_snort = -1;
static int ett_snort_rule = -1;
static int ett_snort_global_stats = -1;

/* Expert info */
static expert_field ei_snort_alert = EI_INIT;
static expert_field ei_snort_content_not_matched = EI_INIT;


/*****************************************/
/* Preferences                           */

/* Use explicit preference as want to disable this dissector by default */
static gboolean snort_enable_dissector = FALSE;

/* Where to look for alerts. */
enum alerts_source {
    FromRunningSnort,
    FromUserComments  /* see https://blog.packet-foo.com/2015/08/verifying-iocs-with-snort-and-tracewrangler/ */
};
/* By default schoose to run Snort to look for alerts */
static gint pref_snort_alerts_source = (gint)FromRunningSnort;

/* Snort binary and config file */
#ifndef _WIN32
static const char *pref_snort_binary_filename = "/usr/sbin/snort";
static const char *pref_snort_config_filename = "/etc/snort/snort.conf";
#else
/* Default locations from Snort Windows installer */
static const char *pref_snort_binary_filename = "C:\\Snort\\bin\\snort.exe";
static const char *pref_snort_config_filename = "C:\\Snort\\etc\\snort.conf";
#endif

/* Should rule stats be shown in protocol tree? */
static gboolean snort_show_rule_stats = FALSE;

/* Should alerts be added as expert info? */
static gboolean snort_show_alert_expert_info = FALSE;

#if 0
/* Should we try to attach the alert to the tcp.reassembled_in frame instead of current one? */
static gboolean snort_alert_in_reassembled_frame = FALSE;
#endif



/********************************************************/
/* Global variable with single parsed snort config      */
static SnortConfig_t *g_snort_config = NULL;


/******************************************************/
/* This is to keep track of the running Snort process */
typedef struct {
    gboolean running;
    gboolean working;

    GPid pid;
    int in, out, err;   /* fds for talking to snort process */

    GString *buf;       /* Incomplete alert output that has been read */
    wtap_dumper *pdh;   /* wiretap dumper used to deliver packets to 'in' */

    GIOChannel *channel; /* IO channel used for readimg stdout (alerts) */

    wmem_tree_t *alerts_tree;  /* Lookup from frame-number -> Alerts_t* */
} snort_session_t;

/* Global instance of the snort session */
static snort_session_t current_session;

static int snort_config_ok = TRUE;   /* N.B. Not running test at the moment... */



/*************************************************/
/* An alert.
   Created by parsing alert from snort, hopefully with more details linked from matched_rule. */
typedef struct Alert_t {
    /* Time */
    struct timeval tv;
    /* Rule */
    guint32       sid;             /* Rule identifier */
    guint32       rev;             /* Revision number of rule */
    guint32       gen;             /* Which engine generated alert (not often interesting) */
    int           prio;            /* Priority as reported in alert (not usually interesting) */

    const char *raw_alert;         /* The whole alert string as reported by snort */

    char       *msg;               /* Rule msg/description as it appears in the alert */
    char       *classification;    /* Classification type of rule */

    Rule_t     *matched_rule;      /* Link to corresponding rule from snort config */

    /* Stats for this alert among the capture file. */
    unsigned int overall_match_number;
    unsigned int rule_match_number;
} Alert_t;

/* Can have multiple alerts fire on same frame, so define this container */
typedef struct Alerts_t {
/* N.B. Snort limit appears to be 6 (at least with default config..) */
#define MAX_ALERTS_PER_FRAME 8
    Alert_t alerts[MAX_ALERTS_PER_FRAME];
    guint num_alerts;
} Alerts_t;


/* Add an alert to the map stored in current_session */
static void add_alert_to_session_tree(guint frame_number, Alert_t *alert)
{
    /* First look up tree to see if there is an existing entry */
    Alerts_t *alerts = (Alerts_t*)wmem_tree_lookup32(current_session.alerts_tree, frame_number);
    if (alerts == NULL) {
        /* Create a new entry for the table */
        alerts = (Alerts_t*)g_malloc(sizeof(Alerts_t));
        alerts->alerts[0] = *alert;
        alerts->num_alerts = 1;
        wmem_tree_insert32(current_session.alerts_tree, frame_number, alerts);
    }
    else {
        /* See if there is room in the existing Alerts_t struct for this frame */
        if (alerts->num_alerts < MAX_ALERTS_PER_FRAME) {
            alerts->alerts[alerts->num_alerts++] = *alert;
        }
    }
}


/******************************************************************/

/* Given an alert struct, look up by Snort ID (sid) and try to fill in other details to display. */
static void fill_alert_config(SnortConfig_t *snort_config, Alert_t *alert)
{
    guint global_match_number=0, rule_match_number=0;

    /* Look up rule by sid */
    alert->matched_rule = get_rule(snort_config, alert->sid);

    /* Classtype usually filled in from alert rather than rule, but missing for supsported
       comment format. */
    if (pref_snort_alerts_source == FromUserComments) {
        alert->classification = g_strdup(alert->matched_rule->classtype);
    }

    /* Inform the config/rule about the alert */
    rule_set_alert(snort_config, alert->matched_rule,
                   &global_match_number, &rule_match_number);
    /* Copy updated counts into the alert */
    alert->overall_match_number = global_match_number;
    alert->rule_match_number = rule_match_number;
}


/* Helper functions for matching expected bytes against the packet buffer.
  Case-sensitive comparison - can just memcmp().
  Case-insensitive comparison - need to look at each byte and compare uppercase version */
static gboolean content_compare_case_sensitive(const guint8* memory, const char* target, guint length)
{
    return (memcmp(memory, target, length) == 0);
}

static gboolean content_compare_case_insensitive(const guint8* memory, const char* target, guint length)
{
    for (guint n=0; n < length; n++) {
        if (g_ascii_isalpha(target[n])) {
            if (g_ascii_toupper(memory[n]) != g_ascii_toupper(target[n])) {
                return FALSE;
            }
        }
        else {
           if ((guint8)memory[n] != (guint8)target[n]) {
                return FALSE;
            }
        }
    }

    return TRUE;
}


/* Move through the bytes of the tvbuff, looking for a match against the expanded
   binary contents of this content object.
 */
static gboolean look_for_content(content_t *content, tvbuff_t *tvb, guint start_offset, guint *match_offset, guint *match_length)
{
    gint tvb_len = tvb_captured_length(tvb);

    /* Make sure content has been translated into binary string. */
    guint converted_content_length = content_convert_to_binary(content);

    /* Look for a match at each position. */
    for (guint m=start_offset; m <= (tvb_len-converted_content_length); m++) {
        const guint8 *ptr = tvb_get_ptr(tvb, m, converted_content_length);
        if (content->nocase) {
            if (content_compare_case_insensitive(ptr, content->binary_str, content->translated_length)) {
                *match_offset = m;
                *match_length = content->translated_length;
                return TRUE;
            }
        }
        else {
            if (content_compare_case_sensitive(ptr, content->binary_str, content->translated_length)) {
                *match_offset = m;
                *match_length = content->translated_length;
                return TRUE;
            }
        }
    }

    return FALSE;
}




/* Look for where the content match happens within the tvb.
 * Set out parameters match_offset and match_length */
static gboolean get_content_match(Alert_t *alert, guint content_idx,
                                  tvbuff_t *tvb, guint content_start_match,
                                  guint *match_offset, guint *match_length)
{
    content_t *content;
    Rule_t *rule = alert->matched_rule;

    /* Can't match if don't know rule */
    if (rule == NULL) {
        return FALSE;
    }

    /* Get content object. */
    content = &(rule->contents[content_idx]);

    /* Look for content match in the packet */
    return look_for_content(content, tvb, content_start_match, match_offset, match_length);
}


/* Gets called when snort process has died */
static void snort_reaper(GPid pid, gint status _U_, gpointer data)
{
    snort_session_t *session = (snort_session_t *) data;
    if (session->running && session->pid == pid) {
        session->working = session->running = FALSE;
        /* XXX, cleanup */
    } else {
        g_print("Errrrmm snort_reaper() %d != %d\n", session->pid, pid);
    }

    /* Close the snort pid (may only make a difference on Windows?) */
    g_spawn_close_pid(pid);
}

/* Parse timestamp line of output.  This is done in part to get the packet_number back out of usec field...
 *  Return valuee is the input stream moved onto the next field following the timestamp */
static const char* snort_parse_ts(const char *ts, struct timeval *tv)
{
    struct tm tm;
    unsigned int usec;

    /* Timestamp */
    memset(&tm, 0, sizeof(tm));
    tm.tm_isdst = -1;
    if (sscanf(ts, "%02d/%02d/%02d-%02d:%02d:%02d.%06u ",
               &(tm.tm_mon), &(tm.tm_mday), &(tm.tm_year), &(tm.tm_hour), &(tm.tm_min), &(tm.tm_sec), &usec) != 7) {
        return NULL;
    }
    tm.tm_mon -= 1;
    tm.tm_year += 100;

    tv->tv_sec = (long)mktime(&tm);
    tv->tv_usec = usec;

    return strchr(ts, ' ');
}

/* Parse a fast output alert string */
static gboolean snort_parse_fast_line(const char *line, Alert_t *alert)
{
    static const char stars[] = " [**] ";

    static const char classification[] = "[Classification: ";
    static const char priority[] = "[Priority: ";
    const char *tmp_msg;

    /* Look for timestamp */
    if (!(line = snort_parse_ts(line, &(alert->tv)))) {
        return FALSE;
    }

    /* [**] */
    if (!g_str_has_prefix(line+1, stars)) {
        return FALSE;
    }
    line += sizeof(stars);

    /* [%u:%u:%u] */
    if (sscanf(line, "[%u:%u:%u] ", &(alert->gen), &(alert->sid), &(alert->rev)) != 3) {
        return FALSE;
    }
    if (!(line = strchr(line, ' '))) {
        return FALSE;
    }

    /* [**] again */
    tmp_msg = line+1;
    if (!(line = strstr(line, stars))) {
        return FALSE;
    }

    /* msg */
    alert->msg = g_strndup(tmp_msg, line - tmp_msg);
    line += (sizeof(stars)-1);

    /* [Classification: Attempted Administrator Privilege Gain] [Priority: 10] */

    if (g_str_has_prefix(line, classification)) {
        /* [Classification: %s] */
        char *tmp;
        line += (sizeof(classification)-1);

        if (!(tmp = (char*)strstr(line, "] [Priority: "))) {
            return FALSE;
        }

        /* assume "] [Priority: " is not inside classification text :) */
        alert->classification = g_strndup(line, tmp - line);

        line = tmp+2;
    } else
        alert->classification = NULL;

    /* Optimized: if al->classification we already checked this in strstr() above */
    if (alert->classification || g_str_has_prefix(line, priority)) {
        /* [Priority: %d] */
        line += (sizeof(priority)-1);

        if ((sscanf(line, "%d", &(alert->prio))) != 1) {
            return FALSE;
        }

        if (!(line = strstr(line, "] "))) {
            return FALSE;
        }
    } else {
        alert->prio = -1; /* XXX */
    }

    return TRUE;
}

/**
 * snort_parse_user_comment()
 *
 * Parse line as written by TraceWranger
 * e.g. "1:2011768:4 - ET WEB_SERVER PHP tags in HTTP POST"
 */
static gboolean snort_parse_user_comment(const char *line, Alert_t *alert)
{
    /* %u:%u:%u */
    if (sscanf(line, "%u:%u:%u", &(alert->gen), &(alert->sid), &(alert->rev)) != 3) {
        return FALSE;
    }

    /* Skip separator between numbers and msg */
    if (!(line = strstr(line, " - "))) {
        return FALSE;
    }

    /* Copy to be consistent with other use of Alert_t */
    alert->msg = g_strdup(line);

    /* No need to set other fields as assume zero'd out before this call.. */
    return TRUE;
}

/* Output data has been received from snort.  Read from channel and look for whole alerts. */
static gboolean snort_fast_output(GIOChannel *source, GIOCondition condition, gpointer data)
{
    snort_session_t *session = (snort_session_t *)data;

    /* Loop here until all available input read */
    while (condition & G_IO_IN) {
        GIOStatus status;
        char _buf[1024];
        gsize len = 0;

        char *old_buf = NULL;
        char *buf = _buf;
        char *line;

        /* Try to read snort output info _buf */
        status = g_io_channel_read_chars(source, _buf, sizeof(_buf)-1, &len, NULL);
        if (status != G_IO_STATUS_NORMAL) {
            if (status == G_IO_STATUS_AGAIN) {
                /* Blocked, so unset G_IO_IN and get out of this function */
                condition = (GIOCondition)(condition & ~G_IO_IN);
                break;
            }
            /* Other conditions here could be G_IO_STATUS_ERROR, G_IO_STATUS_EOF */
            return FALSE;
        }
        /* Terminate buffer */
        buf[len] = '\0';

        /* If we previously had part of a line, append the new bit we just saw */
        if (session->buf) {
            g_string_append(session->buf, buf);
            buf = old_buf = g_string_free(session->buf, FALSE);
            session->buf = NULL;
        }

        /* Extract every complete line we find in the output */
        while ((line = strchr(buf, '\n'))) {
            /* Have a whole line, so can parse */
            Alert_t alert;

            /* Terminate received line */
            *line = '\0';

            if (snort_parse_fast_line(buf, &alert)) {
                /*******************************************************/
                /* We have an alert line.                              */
#if 0
                g_print("%ld.%lu [%u,%u,%u] %s {%s} [%d]\n",
                        alert.tv.tv_sec, alert.tv.tv_usec,
                        alert.gen, alert.sid, alert.rev,
                        alert.msg,
                        alert.classification ? alert.classification : "(null)",
                        alert.prio);
#endif

                /* Copy the raw alert string itself */
                alert.raw_alert = g_strdup(buf);

                /* See if we can get more info from the parsed config details */
                fill_alert_config(g_snort_config, &alert);

                /* Add parsed alert into session->tree */
                /* Store in tree. pfino->fd->num is hidden in usec time field. */
                add_alert_to_session_tree((guint)alert.tv.tv_usec, &alert);

            }
            else {
                g_print("snort_fast_output() line: '%s'\n", buf);
            }

            buf = line+1;
        }

        if (buf[0]) {
            /* Only had part of a line - store it */
            /* N.B. typically happens maybe once every 5-6 alerts. */
            session->buf = g_string_new(buf);
        }

        g_free(old_buf);
    }

    if (condition) {
        /* Will report errors (hung-up, or error) */

        /* g_print("snort_fast_output() cond: (h:%d,e:%d,r:%d)\n",
         *         !!(condition & G_IO_HUP), !!(condition & G_IO_ERR), condition); */
        return FALSE;
    }

    return TRUE;
}


/* Return the offset in the frame where snort should begin looking inside payload. */
static guint get_protocol_payload_start(const char *protocol, proto_tree *tree)
{
    guint value = 0;

    /* For icmp, look from start, whereas for others start after them. */
    gboolean look_after_protocol = (strcmp(protocol, "icmp") != 0);

    if (tree != NULL) {
        GPtrArray *items = proto_all_finfos(tree);
        if (items) {
            guint i;
            for (i=0; i< items->len; i++) {
                field_info *field = (field_info *)g_ptr_array_index(items,i);
                if (strcmp(field->hfinfo->abbrev, protocol) == 0) {
                    value = field->start;
                    if (look_after_protocol) {
                        value += field->length;
                    }
                    break;
                }
            }
            g_ptr_array_free(items,TRUE);
        }
    }
    return value;
}


/* Return offset that application layer traffic will begin from. */
static guint get_content_start_match(Rule_t *rule, proto_tree *tree)
{
    /* Work out where snort would start looking for data in the frame */
    return get_protocol_payload_start(rule->protocol, tree);
}

/* Show the Snort protocol tree based on the info in alert */
static void snort_show_alert(proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, Alert_t *alert)
{
    proto_tree *snort_tree = NULL;
    unsigned int n;
    proto_item *ti, *rule_ti;
    proto_tree *rule_tree;
    Rule_t *rule = alert->matched_rule;

    /* Can only find start if we have the rule and know the protocol */
    guint content_start_match = 0;
    if (rule) {
        content_start_match = get_content_start_match(rule, tree);
    }

    /* Snort output arrived and was previously stored - so add to tree */
    /* Take care not to try to highlight bytes that aren't there.. */
    proto_item *alert_ti = proto_tree_add_protocol_format(tree, proto_snort, tvb,
                                                          content_start_match >= tvb_captured_length(tvb) ? 0 : content_start_match,
                                                          content_start_match >= tvb_captured_length(tvb) ? 0 : -1,
                                                          "Snort: (msg: \"%s\" sid: %u rev: %u) [from %s]",
                                                          alert->msg, alert->sid, alert->rev,
                                                          (pref_snort_alerts_source == FromUserComments) ?
                                                              "User Comment" :
                                                              "Running Snort");
    snort_tree = proto_item_add_subtree(alert_ti, ett_snort);

    /* Show in expert info if configured to. */
    if (snort_show_alert_expert_info) {
        expert_add_info_format(pinfo, alert_ti, &ei_snort_alert, "Alert %u: \"%s\"", alert->sid, alert->msg);
    }

    /* Show the raw alert string. */
    if (rule) {
        ti = proto_tree_add_string(snort_tree, hf_snort_raw_alert, tvb, 0, 0, alert->raw_alert);
        PROTO_ITEM_SET_GENERATED(ti);
    }

    /* Rule classification */
    if (alert->classification) {
        ti = proto_tree_add_string(snort_tree, hf_snort_classification, tvb, 0, 0, alert->classification);
        PROTO_ITEM_SET_GENERATED(ti);
    }

    /* Put rule fields under a rule subtree */

    rule_ti = proto_tree_add_string_format(snort_tree, hf_snort_rule, tvb, 0, 0, "", "Rule");
    PROTO_ITEM_SET_GENERATED(rule_ti);
    rule_tree = proto_item_add_subtree(rule_ti, ett_snort_rule);

    /* msg/description */
    ti = proto_tree_add_string(rule_tree, hf_snort_msg, tvb, 0, 0, alert->msg);
    PROTO_ITEM_SET_GENERATED(ti);
    /* Snort ID */
    ti = proto_tree_add_uint(rule_tree, hf_snort_sid, tvb, 0, 0, alert->sid);
    PROTO_ITEM_SET_GENERATED(ti);
    /* Rule revision */
    ti = proto_tree_add_uint(rule_tree, hf_snort_rev, tvb, 0, 0, alert->rev);
    PROTO_ITEM_SET_GENERATED(ti);
    /* Generator seems to correspond to gid. */
    ti = proto_tree_add_uint(rule_tree, hf_snort_generator, tvb, 0, 0, alert->gen);
    PROTO_ITEM_SET_GENERATED(ti);
    /* Default priority is 2 - very few rules have a different priority... */
    ti = proto_tree_add_uint(rule_tree, hf_snort_priority, tvb, 0, 0, alert->prio);
    PROTO_ITEM_SET_GENERATED(ti);

    /* If we know the rule for this alert, show some of the rule fields */
    if (rule && rule->rule_string) {
        size_t rule_string_length = strlen(rule->rule_string);

        /* Show rule string itself. Add it as a separate data source so can read it all */
        if (rule_string_length > 60) {
            tvbuff_t *rule_string_tvb = tvb_new_child_real_data(tvb, rule->rule_string,
                                                                (guint)rule_string_length,
                                                                (guint)rule_string_length);
            add_new_data_source(pinfo, rule_string_tvb, "Rule String");
            ti = proto_tree_add_string(rule_tree, hf_snort_rule_string, rule_string_tvb, 0,
                                       (gint)rule_string_length,
                                       rule->rule_string);
        }
        else {
            ti = proto_tree_add_string(rule_tree, hf_snort_rule_string, tvb, 0, 0,
                                       rule->rule_string);
        }
        PROTO_ITEM_SET_GENERATED(ti);

        /* Protocol from rule */
        ti = proto_tree_add_string(rule_tree, hf_snort_rule_protocol, tvb, 0, 0, rule->protocol);
        PROTO_ITEM_SET_GENERATED(ti);

        /* Show file alert came from */
        ti = proto_tree_add_string(rule_tree, hf_snort_rule_filename, tvb, 0, 0, rule->file);
        PROTO_ITEM_SET_GENERATED(ti);
        /* Line number within file */
        ti = proto_tree_add_uint(rule_tree, hf_snort_rule_line_number, tvb, 0, 0, rule->line_number);
        PROTO_ITEM_SET_GENERATED(ti);

        /* Show IP vars */
        for (n=0; n < rule->relevant_vars.num_ip_vars; n++) {
            ti = proto_tree_add_none_format(rule_tree, hf_snort_rule_ip_var, tvb, 0, 0, "IP Var: ($%s -> %s)",
                                            rule->relevant_vars.ip_vars[n].name,
                                            rule->relevant_vars.ip_vars[n].value);
            PROTO_ITEM_SET_GENERATED(ti);
        }
        /* Show Port vars */
        for (n=0; n < rule->relevant_vars.num_port_vars; n++) {
            ti = proto_tree_add_none_format(rule_tree, hf_snort_rule_ip_var, tvb, 0, 0, "Port Var: ($%s -> %s)",
                                            rule->relevant_vars.port_vars[n].name,
                                            rule->relevant_vars.port_vars[n].value);
            PROTO_ITEM_SET_GENERATED(ti);
        }
    }


    /* Show summary information in rule tree root */
    proto_item_append_text(rule_ti, " %s (sid=%u, rev=%u)",
                           alert->msg, alert->sid, alert->rev);

    /* More fields retrieved from the parsed config */
    if (rule) {
        guint content_last_match_end = 0;

        /* Work out which ip and port vars are relevant */
        rule_set_relevant_vars(g_snort_config, rule);

        /* Contents */
        for (n=0; n < rule->number_contents; n++) {

            /* Search for string among tvb contents so we can highlight likely bytes. */
            unsigned int content_offset;
            gboolean match_found = FALSE;
            unsigned int converted_content_length;
            int content_hf_item;
            char *content_text_template;
            gboolean attempt_match;

            /* Choose type of content field to add */
            switch (rule->contents[n].content_type) {
                case Content:
                    content_hf_item = hf_snort_content;
                    content_text_template = "Content: \"%s\"";
                    attempt_match = TRUE;
                    break;
                case UriContent:
                    content_hf_item = hf_snort_uricontent;
                    content_text_template = "Uricontent: \"%s\"";
                    attempt_match = TRUE;
                    break;
                case Pcre:
                    content_hf_item = hf_snort_pcre;
                    content_text_template = "Pcre: \"%s\"";
                    attempt_match = FALSE;
                    break;
                default:
                    continue;
            }

            /* Will only try to look for content in packet ourselves if not
               a negated content entry (i.e. beginning with '!') */
            if (attempt_match && !rule->contents[n].negation) {
                /* Look up offset of match. N.B. would only expect to see on first content... */
                guint offset_to_add = 0;

                /* May need to add absolute offset into packet... */
                if (rule->contents[n].offset_set) {
                    offset_to_add = rule->contents[n].offset;
                }
                /* ... or a number of bytes beyond the previous content match */
                else if (rule->contents[n].distance_set) {
                    offset_to_add = (content_last_match_end-content_start_match) + rule->contents[n].distance;
                }

                /* Now actually look for match from calculated position */
                /* TODO: could take 'depth' and 'within' into account to limit extent of search,
                   but OK if just trying to verify what Snort already found. */
                match_found = get_content_match(alert, n,
                                                tvb, content_start_match+offset_to_add,
                                                &content_offset, &converted_content_length);
                if (match_found) {
                    content_last_match_end = content_offset + converted_content_length;
                }
            }


            /* Show content in tree (showing position if known) */
            ti = proto_tree_add_string_format(snort_tree, content_hf_item, tvb,
                                              (match_found) ? content_offset : 0,
                                              (match_found) ? converted_content_length : 0,
                                              rule->contents[n].str,
                                              content_text_template,
                                              rule->contents[n].str);
            if (!attempt_match) {
                /* TODO: for pcre could try to use same library used by
                   display filter 'matches' operator? */
                proto_item_append_text(ti, " (no match attempt made)");
            }

            /* Show (only as text) attributes of content field */
            if (rule->contents[n].fastpattern) {
                proto_item_append_text(ti, " (fast_pattern)");
            }
            if (rule->contents[n].nocase) {
                proto_item_append_text(ti, " (nocase)");
            }
            if (rule->contents[n].negation) {
                proto_item_append_text(ti, " (negated)");
            }
            if (rule->contents[n].offset_set) {
                proto_item_append_text(ti, " (offset=%d)", rule->contents[n].offset);
            }
            if (rule->contents[n].depth != 0) {
                proto_item_append_text(ti, " (depth=%u)", rule->contents[n].depth);
            }
            if (rule->contents[n].distance_set) {
                proto_item_append_text(ti, " (distance=%d)", rule->contents[n].distance);
            }
            if (rule->contents[n].within != 0) {
                proto_item_append_text(ti, " (within=%u)", rule->contents[n].within);
            }

            /* HTTP preprocessor modifiers */
            if (rule->contents[n].http_method != 0) {
                proto_item_append_text(ti, " (http_method)");
            }
            if (rule->contents[n].http_client_body != 0) {
                proto_item_append_text(ti, " (http_client_body)");
            }
            if (rule->contents[n].http_cookie != 0) {
                proto_item_append_text(ti, " (http_cookie)");
            }

            if (attempt_match && !rule->contents[n].negation && !match_found) {
                /* Useful for debugging, may also happen when Snort is reassembling.. */
                proto_item_append_text(ti, " - not located");
                expert_add_info_format(pinfo, ti, &ei_snort_content_not_matched,
                                       "Content   \"%s\"   not found in frame",
                                       rule->contents[n].str);
            }
        }

        /* References */
        for (n=0; n < rule->number_references; n++) {
            /* Substitute prefix and add to tree as clickable web links */
            ti = proto_tree_add_string(snort_tree, hf_snort_reference, tvb, 0, 0,
                                       expand_reference(g_snort_config, rule->references[n]));
            /* Make clickable */
            PROTO_ITEM_SET_URL(ti);
            PROTO_ITEM_SET_GENERATED(ti);
        }
    }

    /* Global rule stats if configured to. */
    if (snort_show_rule_stats) {
        unsigned int number_rule_files, number_rules, alerts_detected, this_rule_alerts_detected;
        proto_item *stats_ti;
        proto_tree *stats_tree;

        /* Create tree for these items */
        stats_ti = proto_tree_add_string_format(snort_tree, hf_snort_global_stats, tvb, 0, 0, "", "Global Stats");
        PROTO_ITEM_SET_GENERATED(rule_ti);
        stats_tree = proto_item_add_subtree(stats_ti, ett_snort_global_stats);

        /* Get overall number of rules */
        get_global_rule_stats(g_snort_config, alert->sid, &number_rule_files, &number_rules, &alerts_detected,
                              &this_rule_alerts_detected);
        ti = proto_tree_add_uint(stats_tree, hf_snort_global_stats_rule_file_count, tvb, 0, 0, number_rule_files);
        PROTO_ITEM_SET_GENERATED(ti);
        ti = proto_tree_add_uint(stats_tree, hf_snort_global_stats_rule_count, tvb, 0, 0, number_rules);
        PROTO_ITEM_SET_GENERATED(ti);

        /* Overall alert stats (total, and where this one comes in order) */
        ti = proto_tree_add_uint(stats_tree, hf_snort_global_stats_total_alerts_count, tvb, 0, 0, alerts_detected);
        PROTO_ITEM_SET_GENERATED(ti);
        ti = proto_tree_add_uint(stats_tree, hf_snort_global_stats_alert_match_number, tvb, 0, 0, alert->overall_match_number);
        PROTO_ITEM_SET_GENERATED(ti);

        if (rule) {
            /* Stats just for this rule (overall, and where this one comes in order) */
            ti = proto_tree_add_uint(stats_tree, hf_snort_global_stats_rule_alerts_count, tvb, 0, 0, this_rule_alerts_detected);
            PROTO_ITEM_SET_GENERATED(ti);
            ti = proto_tree_add_uint(stats_tree, hf_snort_global_stats_rule_match_number, tvb, 0, 0, alert->rule_match_number);
            PROTO_ITEM_SET_GENERATED(ti);

            /* Add a summary to the stats root */
            proto_item_append_text(stats_ti, " (%u rules from %u files, #%u of %u alerts seen (%u/%u for sid %u))",
                                   number_rules, number_rule_files, alert->overall_match_number, alerts_detected,
                                   alert->rule_match_number, this_rule_alerts_detected, alert->sid);
        }
        else {
            /* Add a summary to the stats root */
            proto_item_append_text(stats_ti, " (%u rules from %u files, #%u of %u alerts seen)",
                                   number_rules, number_rule_files, alert->overall_match_number, alerts_detected);
        }
    }
}

/* Look for, and return, any user comment set for this packet.
   Currently used for fetching alerts in the format TraceWrangler can write out to */
static const char *get_user_comment_string(proto_tree *tree)
{
    const char *value = NULL;

    if (tree != NULL) {
        GPtrArray *items = proto_all_finfos(tree);
        if (items) {
            guint i;

            for (i=0; i< items->len; i++) {
                field_info *field = (field_info *)g_ptr_array_index(items,i);
                if (strcmp(field->hfinfo->abbrev, "frame.comment") == 0) {
                    value = field->value.value.string;
                    break;
                }
                /* This is the only item that can come before "frame.comment", so otherwise break out */
                if (strncmp(field->hfinfo->abbrev, "pkt_comment", 11) != 0) {
                    break;
                }
            }
            g_ptr_array_free(items,TRUE);
        }
    }
    return value;
}


#if 0
/* TODO: unfortunately, the first frame in a series of frames to be reassembled has often been
 * seen to lack this field, despite being referenced in the reassmbled frame! */
static guint get_reassembled_in_frame(proto_tree *tree)
{
    guint value = 0;

    if (tree != NULL) {
        GPtrArray *items = proto_all_finfos(tree);
        if (items) {
            guint i;
            for (i=0; i< items->len; i++) {
                field_info *field = (field_info *)g_ptr_array_index(items,i);
                if (strcmp(field->hfinfo->abbrev, "tcp.reassembled_in") == 0) {
                    value = field->value.value.uinteger;
                    break;
                }
            }
            g_ptr_array_free(items,TRUE);
        }
    }
    return value;
}
#endif

/********************************************************************************/
/* Main (post-)dissector function.                                              */
static int
snort_dissector(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
{
    Alerts_t *alerts;

    /* Are we looking for alerts in user comments? */
    if (pref_snort_alerts_source == FromUserComments) {
        /* Look for user comments containing alerts */
        const char *alert_string = get_user_comment_string(tree);
        if (alert_string) {
            alerts = (Alerts_t*)wmem_tree_lookup32(current_session.alerts_tree, pinfo->num);
            if (!alerts) {
                Alert_t alert;
                memset(&alert, 0, sizeof(alert));
                if (snort_parse_user_comment(alert_string, &alert)) {
                    /* Copy the raw alert itself */
                    alert.raw_alert = g_strdup(alert_string);

                    /* See if we can get more info from the parsed config details */
                    fill_alert_config(g_snort_config, &alert);

                    /* Add parsed alert into session->tree */
                    add_alert_to_session_tree(pinfo->num, &alert);
                }
            }
        }
    }
    else {
        /* We expect alerts from Snort.  Pass frame into snort on first pass. */
        if (!pinfo->fd->flags.visited && current_session.working) {
            int write_err = 0;
            gchar *err_info;
            struct wtap_pkthdr wtp;

            /* First time, open current_session.in to write to for dumping into snort with */
            if (!current_session.pdh) {
                int open_err;

                /* Older versions of Snort don't support capture file with several encapsulations (like pcapng),
                 * so write in pcap format and hope we have just one encap.
                 * Newer versions of Snort can read pcapng now, but still write in pcap format.
                 */
                current_session.pdh = wtap_dump_fdopen(current_session.in,
                                                       WTAP_FILE_TYPE_SUBTYPE_PCAP,
                                                       pinfo->pkt_encap,
                                                       WTAP_MAX_PACKET_SIZE,
                                                       FALSE,                 /* compressed */
                                                       &open_err);
                if (!current_session.pdh) {
                    current_session.working = FALSE;
                    return 0;
                }
            }

            /* Start with all same values... */
            memcpy(&wtp, pinfo->phdr, sizeof(wtp));

            /* Copying packet details into wtp for writing */
            wtp.ts.secs = pinfo->fd->abs_ts.secs;
            wtp.ts.nsecs = pinfo->fd->abs_ts.nsecs;

            /* NB: overwriting wtp.ts.nsecs so we can see packet number back if an alert is written for this frame!!!! */
            /* TODO: does this seriously affect snort's ability to reason about time?
             * At least all packets will still be in order... */
            wtp.ts.nsecs = pinfo->fd->num * 1000;    /* XXX, max 999'999 frames */

            wtp.caplen = tvb_captured_length(tvb);
            wtp.len = tvb_reported_length(tvb);
            wtp.pkt_encap = pinfo->pkt_encap;
            if (current_session.pdh->encap != wtp.pkt_encap) {
                /* XXX, warning! convert? */
            }

            /* Dump frame into snort's stdin */
            if (!wtap_dump(current_session.pdh, &wtp, tvb_get_ptr(tvb, 0, tvb_reported_length(tvb)), &write_err, &err_info)) {
                current_session.working = FALSE;
                return 0;
            }
            wtap_dump_flush(current_session.pdh);

            /* Give the io channel a chance to deliver alerts.
               TODO: g_main_context_iteration(NULL, FALSE); causes crashes sometimes when Qt events get to execute.. */
        }
    }

    /* Now look up stored alerts for this packet number, and display if found */
    if (current_session.alerts_tree && (alerts = (Alerts_t*)wmem_tree_lookup32(current_session.alerts_tree, pinfo->fd->num))) {
        guint n;

        for (n=0; n < alerts->num_alerts; n++) {
            snort_show_alert(tree, tvb, pinfo, &(alerts->alerts[n]));
        }
    } else {
        /* XXX, here either this frame doesn't generate alerts or we haven't received data from snort (async)
         *
         *      It's problem when user want to filter tree on initial run, or is running one-pass tshark.
         */
    }

    return tvb_reported_length(tvb);
}


/*------------------------------------------------------------------*/
/* Start up Snort. */
static void snort_start(void)
{
    GIOChannel *channel;
    /* int snort_output_id; */
    const gchar *argv[] = {
        pref_snort_binary_filename, "-c", pref_snort_config_filename,
        /* read from stdin */
        "-r", "-",
        /* don't log */
        "-N",
        /* output to console and silence snort */
        "-A", "console", "-q",
        /* normalize time */
        "-y", /* -U", */
        NULL
    };

    /* Nothing to do if not enabled, but registered init function gets called anyway */
    if (!snort_enable_dissector) {
        return;
    }

    /* Create tree mapping packet_number -> Alerts_t*.  It will get recreated when packet list is reloaded */
    current_session.alerts_tree = wmem_tree_new_autoreset(wmem_epan_scope(), wmem_file_scope());

    /* Create afresh the config object by parsing the same file that snort uses */
    if (g_snort_config) {
        delete_config(&g_snort_config);
    }
    create_config(&g_snort_config, pref_snort_config_filename);

    /* Don't run Snort if not configured to */
    if (pref_snort_alerts_source == FromUserComments) {
        return;
    }

    if (current_session.running) {
        return;
    }
    current_session.running = TRUE;

    /* Reset global stats */
    reset_global_rule_stats(g_snort_config);

    /* Need to test that we can run snort --version and that config can be parsed... */
    /* Does nothing at present */
    if (!snort_config_ok) {
        current_session.running = FALSE;
        /* Can carry on without snort... */
        return;
    }

    /* Create snort process and set up pipes */
    if (!g_spawn_async_with_pipes(NULL,          /* working_directory */
                                  (char **)argv,
                                  NULL,          /* envp */
                                  (GSpawnFlags)( G_SPAWN_DO_NOT_REAP_CHILD), /* Leave out G_SPAWN_SEARCH_PATH */
                                  NULL,                   /* child setup - not supported in Windows, so we can't use it */
                                  NULL,                   /* user-data */
                                  &current_session.pid,   /* PID */
                                  &current_session.in,    /* stdin */
                                  &current_session.out,   /* stdout */
                                  &current_session.err,   /* stderr */
                                  NULL))                  /* error */
    {
        current_session.running = FALSE;
        current_session.working = FALSE;
        return;
    }

    /* Setup handler for when process goes away */
    g_child_watch_add(current_session.pid, snort_reaper, &current_session);

    /******************************************************************/
    /* Create channel to get notified of snort alert output on stdout */

    /* Create channel itself */
    channel = g_io_channel_unix_new(current_session.out);
    current_session.channel = channel;

    /* NULL encoding supports binary or whatever the application outputs */
    g_io_channel_set_encoding(channel, NULL, NULL);
    /* Don't buffer the channel (settable because encoding set to NULL). */
    g_io_channel_set_buffered(channel, FALSE);
    /* Set flags */
    /* TODO: could set to be blocking and get sync that way? */
    g_io_channel_set_flags(channel, G_IO_FLAG_NONBLOCK, NULL);
    /* Try setting a large buffer here. */
    g_io_channel_set_buffer_size(channel, 256000);

    current_session.buf = NULL;

    /* Set callback for receiving data from the channel */
    g_io_add_watch_full(channel,
                        G_PRIORITY_HIGH,
                        (GIOCondition)(G_IO_IN|G_IO_ERR|G_IO_HUP),
                        snort_fast_output,  /* Callback upon data being written by snort */
                        &current_session,   /* User data */
                        NULL);              /* Destroy notification callback */

    current_session.working = TRUE;
}

/* This is the cleanup routine registered with register_postseq_cleanup_routine() */
static void snort_cleanup(void)
{
    /* Only close if we think its running */
    if (!current_session.running) {
        return;
    }

    /* Close dumper writing into snort's stdin.  This will cause snort to exit! */
    if (current_session.pdh) {
        int write_err;
        if (!wtap_dump_close(current_session.pdh, &write_err)) {

        }
        current_session.pdh = NULL;
    }
}

static void snort_file_cleanup(void)
{
    if (g_snort_config) {
        delete_config(&g_snort_config);
    }
}

void
proto_reg_handoff_snort(void)
{
    /* N.B. snort self-test here deleted, as I was struggling to get it to
     * work as a non-root user (couldn't read stdin)
     * TODO: could run snort just to get the version number and check the config file is readable?
     * TODO: could make snort config parsing less forgiving and use that as a test? */

    /* Our own preference for turning off completely.  Don't want to run at all unless turned on */
    proto_set_decoding(proto_snort, snort_enable_dissector);
}

void
proto_register_snort(void)
{
    static hf_register_info hf[] = {
        { &hf_snort_sid,
            { "Rule SID", "snort.sid", FT_UINT32, BASE_DEC, NULL, 0x00,
            "Snort Rule identifier", HFILL }},
        { &hf_snort_raw_alert,
            { "Raw Alert", "snort.raw-alert", FT_STRING, BASE_NONE, NULL, 0x00,
            "Full text of Snort alert", HFILL }},
        { &hf_snort_rule,
            { "Rule", "snort.rule", FT_STRING, BASE_NONE, NULL, 0x00,
            "Entire Snort rule string", HFILL }},
        { &hf_snort_msg,
            { "Alert Message", "snort.msg", FT_STRINGZ, BASE_NONE, NULL, 0x00,
            "Description of what the rule detects", HFILL }},
        { &hf_snort_classification,
            { "Alert Classification", "snort.class", FT_STRINGZ, BASE_NONE, NULL, 0x00,
            NULL, HFILL }},
        { &hf_snort_priority,
            { "Alert Priority", "snort.priority", FT_UINT32, BASE_DEC, NULL, 0x00,
            NULL, HFILL }},
        { &hf_snort_generator,
            { "Rule Generator", "snort.generator", FT_UINT32, BASE_DEC, NULL, 0x00,
            NULL, HFILL }},
        { &hf_snort_rev,
            { "Rule Revision", "snort.rev", FT_UINT32, BASE_DEC, NULL, 0x00,
            NULL, HFILL }},
        { &hf_snort_rule_string,
            { "Rule String", "snort.rule-string", FT_STRINGZ, BASE_NONE, NULL, 0x00,
            "Full text of Snort rule", HFILL }},
        { &hf_snort_rule_protocol,
            { "Protocol", "snort.protocol", FT_STRINGZ, BASE_NONE, NULL, 0x00,
            "Protocol name as given in the rule", HFILL }},
        { &hf_snort_rule_filename,
            { "Rule Filename", "snort.rule-filename", FT_STRINGZ, BASE_NONE, NULL, 0x00,
            "Rules file where Snort rule was parsed from", HFILL }},
        { &hf_snort_rule_line_number,
            { "Line number within rules file where rule was parsed from", "snort.rule-line-number", FT_UINT32, BASE_DEC, NULL, 0x00,
            NULL, HFILL }},
        { &hf_snort_rule_ip_var,
            { "IP variable", "snort.rule-ip-var", FT_NONE, BASE_NONE, NULL, 0x00,
            "IP variable used in rule", HFILL }},
        { &hf_snort_rule_port_var,
            { "Port variable used in rule", "snort.rule-port-var", FT_NONE, BASE_NONE, NULL, 0x00,
            NULL, HFILL }},
        { &hf_snort_content,
            { "Content", "snort.content", FT_STRINGZ, BASE_NONE, NULL, 0x00,
            "Snort content field", HFILL }},
        { &hf_snort_uricontent,
            { "URI Content", "snort.uricontent", FT_STRINGZ, BASE_NONE, NULL, 0x00,
            "Snort URI content field", HFILL }},
        { &hf_snort_pcre,
            { "PCRE", "snort.pcre", FT_STRINGZ, BASE_NONE, NULL, 0x00,
            "Perl Compatible Regular Expression", HFILL }},
        { &hf_snort_reference,
            { "Reference", "snort.reference", FT_STRINGZ, BASE_NONE, NULL, 0x00,
            "Web reference provided as part of rule", HFILL }},

        /* Global stats */
        { &hf_snort_global_stats,
            { "Global Stats", "snort.global-stats", FT_STRING, BASE_NONE, NULL, 0x00,
            "Global statistics for rules and alerts", HFILL }},
        { &hf_snort_global_stats_rule_file_count,
            { "Number of rule files", "snort.global-stats.rule-file-count", FT_UINT32, BASE_DEC, NULL, 0x00,
            "Total number of rules files found in Snort config", HFILL }},
        { &hf_snort_global_stats_rule_count,
            { "Number of rules", "snort.global-stats.rule-count", FT_UINT32, BASE_DEC, NULL, 0x00,
            "Total number of rules found in Snort config", HFILL }},
        { &hf_snort_global_stats_total_alerts_count,
            { "Number of alerts detected", "snort.global-stats.total-alerts", FT_UINT32, BASE_DEC, NULL, 0x00,
            "Total number of alerts detected in this capture", HFILL }},
        { &hf_snort_global_stats_alert_match_number,
            { "Match number", "snort.global-stats.match-number", FT_UINT32, BASE_DEC, NULL, 0x00,
            "Number of match for this alert among all alerts", HFILL }},

        { &hf_snort_global_stats_rule_alerts_count,
            { "Number of alerts for this rule", "snort.global-stats.rule.match-number", FT_UINT32, BASE_DEC, NULL, 0x00,
            "Number of alerts detected for this rule", HFILL }},
        { &hf_snort_global_stats_rule_match_number,
            { "Match number for this rule", "snort.global-stats.rule.match-number", FT_UINT32, BASE_DEC, NULL, 0x00,
            "Number of match for this alert among those for this rule", HFILL }}
    };
    static gint *ett[] = {
        &ett_snort,
        &ett_snort_rule,
        &ett_snort_global_stats
    };

    static const enum_val_t alerts_source_vals[] = {
        {"from-running-snort",      "From running Snort",     FromRunningSnort},
        {"from-user-comments",      "From user comments",     FromUserComments},
        {NULL, NULL, -1}
    };

    static ei_register_info ei[] = {
        { &ei_snort_alert, { "snort.alert.expert", PI_SECURITY, PI_WARN, "Snort alert detected", EXPFILL }},
        { &ei_snort_content_not_matched, { "snort.content.not-matched", PI_PROTOCOL, PI_NOTE, "Failed to find content field of alert in frame", EXPFILL }},
    };

    expert_module_t* expert_snort;


    dissector_handle_t snort_handle;
    module_t *snort_module;

    proto_snort = proto_register_protocol("Snort Alerts", "Snort", "snort");

    proto_register_field_array(proto_snort, hf, array_length(hf));
    proto_register_subtree_array(ett, array_length(ett));

    /* Expert info */
    expert_snort = expert_register_protocol(proto_snort);
    expert_register_field_array(expert_snort, ei, array_length(ei));

    snort_module = prefs_register_protocol(proto_snort, proto_reg_handoff_snort);

    prefs_register_bool_preference(snort_module, "enable_snort_dissector",
                                   "Enable the snort dissector",
                                   "Whether or not the snort post-dissector should run.",
                                   &snort_enable_dissector);

    prefs_register_enum_preference(snort_module, "alerts_source",
        "Source of Snort alerts",
        "Set whether dissector should run Snort itself or use user packet comments",
        &pref_snort_alerts_source, alerts_source_vals, FALSE);

    prefs_register_filename_preference(snort_module, "binary",
                                       "Snort binary",
                                       "The name of the snort binary file to run",
                                       &pref_snort_binary_filename);
    prefs_register_filename_preference(snort_module, "config",
                                       "Configuration filename",
                                       "The name of the file containing the snort IDS configuration.  Typically snort.conf",
                                       &pref_snort_config_filename);

    prefs_register_bool_preference(snort_module, "show_rule_set_stats",
                                   "Show rule stats in protocol tree",
                                   "Whether or not information about the rule set and detected alerts should "
                                   "be shown in the tree of every snort PDU tree",
                                   &snort_show_rule_stats);
    prefs_register_bool_preference(snort_module, "show_alert_expert_info",
                                   "Show alerts in expert info",
                                   "Whether or not expert info should be used to highlight fired alerts",
                                   &snort_show_alert_expert_info);
#if 0
    prefs_register_bool_preference(snort_module, "show_alert_in_reassembled_frame",
                                   "Try to show alerts in reassembled frame",
                                   "Attempt to show alert in reassembled frame where possible",
                                   &snort_alert_in_reassembled_frame);
#endif


    snort_handle = create_dissector_handle(snort_dissector, proto_snort);

    register_init_routine(snort_start);
    register_postdissector(snort_handle);

    /* Callback to make sure we cleanup dumper being used to deliver packets to snort (this will tsnort). */
    register_postseq_cleanup_routine(snort_cleanup);
    /* Callback to allow us to delete snort config */
    register_cleanup_routine(snort_file_cleanup);
}

/*
 * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
 *
 * Local variables:
 * c-basic-offset: 4
 * tab-width: 8
 * indent-tabs-mode: nil
 * End:
 *
 * vi: set shiftwidth=4 tabstop=8 expandtab:
 * :indentSize=4:tabSize=8:noTabs=true:
 */