idstools¶
idstools is a Python library for working with SNORT(R) and Suricata logs and rules.
Contents¶
Tools¶
rulecat - A Suricata rule update tool¶
Synopsis¶
idstools-rulecat
[OPTIONS]
Description¶
idstools-ruleset
aims to be a simple to use rule download and
management tool for Suricata. It can also be used for Snort when no SO
rule stub generation is required.
Options¶
-
-h
,
--help
¶
Show help.
-
-v
,
--verbose
¶
Be more verbose.
-
-t
<directory>
,
--temp-dir
=<directory>
¶ Temporary working directory (default: /var/tmp/idstools-rulecat).
This is where downloaded files will be stored.
-
--suricata
=<path>
¶ The path to the Suricata program used to determine which version of the ET pro rules to download if not explicitly set in a
--url
argument.
-
--suricata-version
<version>
¶ Set the Suricata version to a specific version instead of checking the version of Suricata on the path.
-
--force
¶
Force remote rule files to be downloaded if they otherwise wouldn’t be due to just recently downloaded, or the remote checksum matching the cached copy.
-
-o
,
--output
¶
The directory where rule individual rules files will be written to. One of
-o
or--merged
is required.
-
--merged
=<filename>
¶ Write a single file containing all rules. This can be used in addition to
--output
or instead of--output
.
-
--yaml-fragment
=<filename.yaml>
¶ Output a fragment of YAML containing the rule-files section will all downloaded rule files listed for inclusion in your suricata.yaml.
-
--url
=<url>
¶ A URL to download rules from. This option can be used multiple times.
-
--local
=<filename or directory>
¶ A path to a filename or directory of local rule files to include. May be specified multiple times and should not include files in the output path.
If the path is a directory all files ending in .rules will be loaded.
Wildcards are accepted but to avoid shell expansion the argument must be quoted, for example:
--local '/etc/suricata/custom-*.rules'
-
--sid-msg-map
=<filename>
¶ Output a v1 style sid-msg.map file.
-
--sid-msg-map-2
=<filename>
¶ Output a v2 style sid-msg.map file.
-
--disable
=<disable.conf>
¶ Specify the configuration file for disabling rules.
-
--enable
=<enable.conf>
¶ Specify the configuration file for enabling rules.
-
--modify
=<modify.conf>
¶ Specify the configuration file for rule modifications.
-
--drop
=<drop.conf>
¶ Specify the configuration file for rules to change to drop.
-
--ignore
=<filename>
¶ Filenames to ignore. This is a pattern that will be matched against the basename of a rule files.
This argument may be specified multiple times.
Default: *deleted.rules
Alternatively the group matcher may be used in the file passed to
--disable
.
-
--no-ignore
¶
Disable the –ignore option. Most useful to disable the default ignore pattern without adding others.
-
--etopen
¶
Download the ET open ruleset. This is the default if
--url
or--etpro
are not provided.If one of
etpro
or--url
is also specified, this option will at the ET open URL to the list of remote ruleset to be downloaded.
-
--etpro
=<code>
¶ Download the ET pro ruleset using the provided code.
-
-q
,
--quiet
¶
Run quietly. Only warning and error message will be displayed.
-
--dump-sample-configs
¶
Output sample configuration files for the
--disable
,--enable
,--modify
and--threshold-in
commands.
-
--threshold-in
=<threshold.conf.in>
¶ Specify the threshold.conf input template.
-
--threshold-out
=<threshold.conf>
¶ Specify the name of the processed threshold.conf to output.
-
--post-hook
=<command>
¶ A command to run after the rules have been updated; will not run if not change to the output files was made. For example:
--post-hook=sudo kill -USR2 $(cat /var/run/suricata.pid)
will tell Suricata to reload its rules.
-
-V
,
--version
¶
Display the version of idstools-rulecat.
Examples¶
Download ET Open rules for the version of Suricata found on the path, saving the rules in /etc/suricata/rules:
idstools-rulecat -o /etc/suricata/rules
Download ET Pro rules for the version of Suricata found on the path, saving the rules in /etc/suricata/rules:
idstools-rulecat --etpro XXXXXXXXXXXXXXXX -o /etc/suricata/rules
Download ET open rules plus an additional rule files and save the rules in /etc/suricata/rules:
idstools-rulecat --etopen \
--url https://sslbl.abuse.ch/blacklist/sslblacklist.rules \
-o /etc/suricata/rules
Configuration File¶
Command line arguments can be put in a file, one per line and used as a configuration file. By default, idstools-rulecat will look for a file in the current directory named rulecat.conf.
Example configuration file:
--suricata=/usr/sbin/suricata
--merged=rules/merged.rules
--disable=disable.conf
--enable=enable.conf
--modify=modify.conf
--post-hook=sudo kill -USR2 $(cat /var/run/suricata.pid)
--etpro=XXXXXXXXXXXXXXXX
--url=https://sslbl.abuse.ch/blacklist/sslblacklist.rules
If rulecat.conf is in the current directory it will be used just by
calling idstools-rulecat
with no arguments. Otherwise you can
point idstools-rulecat at a configuration with the command
idstools-rulecat @/path/to/rulecat.conf
.
Example Configuration Files¶
Example Configuration to Enable Rules (–enable)¶
# idstools-rulecat - enable.conf
# Example of enabling a rule by signature ID (gid is optional).
# 1:2019401
# 2019401
# Example of enabling a rule by regular expression.
# - All regular expression matches are case insensitive.
# re:hearbleed
# re:MS(0[7-9]|10)-\d+
Example Configuration to Enable Disable (–disable)¶
# idstools - disable.conf
# Example of disabling a rule by signature ID (gid is optional).
# 1:2019401
# 2019401
# Example of disabling a rule by regular expression.
# - All regular expression matches are case insensitive.
# re:hearbleed
# re:MS(0[7-9]|10)-\d+
Example Configuration to convert Rules to Drop (–drop)¶
# idstools-rulecat - drop.conf
#
# Rules matching specifiers in this file will be converted to drop rules.
#
# Examples:
#
# 1:2019401
# 2019401
#
# re:heartbleed
# re:MS(0[7-9]|10)-\d+
Example Configuration to modify Rules (–modify)¶
# idstools-rulecat - modify.conf
# Format: <sid> "<from>" "<to>"
# Example changing the seconds for rule 2019401 to 3600.
#2019401 "seconds \d+" "seconds 3600"
# Change all trojan-activity rules to drop. Its better to setup a
# drop.conf for this, but this does show the use of back references.
#re:classtype:trojan-activity "(alert)(.*)" "drop\\2"
# For compatibility, most Oinkmaster modifysid lines should work as
# well.
#modifysid * "^drop(.*)noalert(.*)" | "alert${1}noalert${2}"
Source¶
eve2pcap - Convert packets/payloads in eve logs to pcap¶
Convert packets in EVE logs to pcap.
eve2pcap will convert the packets or the payloads found in an eve log file to a pcap file.
Note that payload conversion requires Scapy, and will not recreate the original packets as the headers need to be built on the fly from the available information in the eve log.
Usage¶
usage: idstools-eve2pcap [-h] [-o <filename>] [--payload] [--dlt DLT]
filenames [filenames ...]
positional arguments:
filenames
optional arguments:
-h, --help show this help message and exit
-o <filename> Output filename
--payload Convert payload instead of packet
--dlt DLT
u2spewfoo - A python/idstools implementation of u2spewfoo¶
A python reimplementation of Snort’s u2spewfoo.
Usage¶
usage: idstools-u2spewfoo [-h] [filename [filename ...]]
positional arguments:
filename
optional arguments:
-h, --help show this help message and exit
u2json - A unified2 to JSON converter¶
Read unified2 log files and output records as JSON.
Contents
Usage¶
usage: idstools-u2json [-h] [-C <classification.config>] [-S <msg-msg.map>]
[-G <gen-msg.map>] [--snort-conf <snort.conf>]
[--directory <spool directory>]
[--prefix <spool file prefix>] [--bookmark <filename>]
[--follow] [--delete] [--output <filename>] [--stdout]
[--sort-keys] [--verbose] [--packet-printable]
[--packet-hex] [--extra-printable]
[filenames [filenames ...]]
positional arguments:
filenames
optional arguments:
-h, --help show this help message and exit
-C <classification.config>
path to classification config
-S <msg-msg.map> path to sid-msg.map
-G <gen-msg.map> path to gen-msg.map
--snort-conf <snort.conf>
attempt to load classifications and map files based on
the location of the snort.conf
--directory <spool directory>
spool directory (eg: /var/log/snort)
--prefix <spool file prefix>
spool filename prefix (eg: unified2.log)
--bookmark <filename>
enable bookmarking
--follow follow files/continuous mode (spool mode only)
--delete delete spool files
--output <filename> output filename (eg: /var/log/snort/alerts.json
--stdout also log to stdout if --output is a file
--sort-keys the output of dictionaries will be sorted by key
--verbose be more verbose
--packet-printable output printable packet data in addition to base64
--packet-hex output packet data as hex in addition to base64
--extra-printable output printable extra data in addition to base64
If --directory and --prefix are provided files will be read from the specified
'spool' directory. Otherwise files on the command line will be processed.
Example - View unified2 File as JSON¶
idstools-u2json /var/log/snort/unified2.log.1397575268
To resolve alert descriptions and classifications:
idstools-u2json --snort-conf /etc/snort/etc/snort.conf \
/var/log/snort/unified2.log.1397575268
The above assumes that sid-msg.map, gen-msg.map and classification.config live alongside the specified snort.conf. If they do not, the options to specify each individually may be used:
idstools-u2json -C /etc/snort/etc/classification.config \
-S /etc/snort/etc/sid-msg.map \
-G /etc/snort/etc/gen-msg.map \
/var/log/snort/unified2.log.1397575268
Example - Continuous Conversion to JSON¶
idstools-u2json --snort.conf /etc/snort/etc/snort.conf \
--directory /var/log/snort \
--prefix unified2.log \
--follow \
--bookmark \
--delete \
--output /var/log/snort/alerts.json \
The above command will operate like barnyard, reading all unified2.log files in /var/log/snort, waiting for new unified2 records when the end of the last file is reached.
Additionally the last read location will be bookmarked to avoid reading events multiple times, the unified2.log files will be deleted once converted to JSON, and JSON events will be written to /var/log/snort/alerts.json.
Configuration File¶
A configuration file is simply a file containing the command line arguments, one per line with an ‘=’ separating the name from the argument. For example, to save the arguments used in example 2 above:
--snort-conf=/etc/snort/etc/snort.conf
--directory=/var/log/snort
--prefix=unified2.log
--follow
--bookmark
--delete
--output=/var/log/snort/alerts.json
Then call idstools-u2json like:
idstools-u2json @/path/to/config-file
Addtional arguments can also be provided like:
idstools-u2json @/path/to/config-file --stdout
u2fast - Unified2 to fast style printer¶
Read unified2 log files and output events in “fast” style.
Usage¶
usage: idstools-u2fast [-h] [-C <classification.config>] [-S <msg-msg.map>]
[-G <gen-msg.map>] [--snort-conf <snort.conf>]
[--directory <spool directory>]
[--prefix <spool file prefix>] [--bookmark] [--follow]
[filenames [filenames ...]]
positional arguments:
filenames
optional arguments:
-h, --help show this help message and exit
-C <classification.config>
path to classification config
-S <msg-msg.map> path to sid-msg.map
-G <gen-msg.map> path to gen-msg.map
--snort-conf <snort.conf>
attempt to load classifications and map files based on
the location of the snort.conf
--directory <spool directory>
spool directory (eg: /var/log/snort)
--prefix <spool file prefix>
spool filename prefix (eg: unified2.log)
--bookmark enable bookmarking
--follow follow files/continuous mode (spool mode only)
Source¶
u2eve - Unified2 to Suricata eve events¶
Read unified2 log files and output events as Suricata EVE JSON (or as close as possible).
Usage¶
usage: idstools-u2eve [-h] [-C <classification.config>] [-S <msg-msg.map>]
[-G <gen-msg.map>] [--snort-conf <snort.conf>]
[--directory <spool directory>]
[--prefix <spool file prefix>] [--bookmark] [--follow]
[--delete] [-o <filename>] [--stdout]
[--packet-printable] [--packet-hex]
[filenames [filenames ...]]
positional arguments:
filenames
optional arguments:
-h, --help show this help message and exit
-C <classification.config>
path to classification config
-S <msg-msg.map> path to sid-msg.map
-G <gen-msg.map> path to gen-msg.map
--snort-conf <snort.conf>
attempt to load classifications and map files based on
the location of the snort.conf
--directory <spool directory>
spool directory (eg: /var/log/snort)
--prefix <spool file prefix>
spool filename prefix (eg: unified2.log)
--bookmark enable bookmarking
--follow follow files/continuous mode (spool mode only)
--delete delete spool files
-o <filename>, --output <filename>
output filename (eg: /var/log/snort/alerts.json
--stdout also log to stdout if --output is a file
--packet-printable add packet_printable field to events
--packet-hex add packet_hex field to events
If --directory and --prefix are provided files will be read from the specified
'spool' directory. Otherwise files on the command line will be processed.
Example - View a unified2 file as eve¶
idstools-u2eve -C path/to/classification.config \
-S /path/to/sid-msg.map \
-G /path/to/gen-msg.map merged.log.1431384519
Example - Continuous conversion to eve¶
idstools-u2eve --snort-conf /etc/snort/etc/snort.conf \
--directory /var/log/snort \
--prefix unified2.log \
--follow \
--bookmark \
--delete \
--output /var/log/snort/alerts.json \
The above command will operate like barnyard, reading all unified2.log files in /var/log/snort, waiting for new unified2 records when the end of the last file is reached.
Additionally the last read location will be bookmarked to avoid reading events multiple times, the unified2.log files will be deleted once converted to JSON, and JSON events will be written to /var/log/snort/alerts.json.
Configuration File¶
A configuration file is simply a file containing the command line arguments, one per line with an ‘=’ separating the name from the argument. For example, to save the arguments used in example 2 above:
--snort-conf=/etc/snort/etc/snort.conf
--directory=/var/log/snort
--prefix=unified2.log
--follow
--bookmark
--delete
--output=/var/log/snort/alerts.json
Then call idstools-u2eve like:
idstools-u2eve @/path/to/config-file
Addtional arguments can also be provided like:
idstools-u2eve @/path/to/config-file --stdout
Source¶
gensidmsgmap - sid-msg.map generator¶
Generate sid-msg.map files (v1 and v2) from rule archives, files and/or directories.
Usage¶
usage: ../bin/idstools-gensidmsgmap [options] <file>...
options:
-2, --v2 Output a new (v2) style sid-msg.map file.
The files passed on the command line can be a list of a filenames, a
tarball, a directory name (containing rule files) or any combination
of the above.
dumpdynamicrules - Snort SO stub generator helper¶
Dump Snort SO rule stub helper program. Can optionally repack a Snort rule tarball with the generated stubs, in place or to a new file.
Usage¶
usage: idstools-dumpdynamicrules [-h] [--snort SNORT] [--version VERSION]
[--dist DIST] [--out OUT]
[--repack [filename]] [-v]
<path>
positional arguments:
<path> SO rule directory or rule tarball
optional arguments:
-h, --help show this help message and exit
--snort SNORT path to snort
--version VERSION Snort version
--dist DIST operating system/distribution
--out OUT path to output SO stubs to
--repack [filename] repack archive with generated SO stubs
-v, --verbose log more information
Library¶
Unified2 File Reading¶
idstools provides unified2 readers for reading unified2 records.
Contents
Reader Objects¶
RecordReader¶
-
class
idstools.unified2.
RecordReader
(fileobj)[source] RecordReader reads and decodes unified2 records from a file-like object.
Parameters: fileobj – The file-like object to read from. Example:
fileobj = open("/var/log/snort/merged.log.1382627987", "rb") reader = RecordReader(fileobj): for record in reader: print(record)
-
next
()[source] Return the next record or None if EOF.
Records returned will be one of the types
Event
,Packet
,ExtraData
orUnknown
if the record is of an unknown type.
-
tell
()[source] Get the current offset in the underlying file object.
-
FileRecordReader¶
-
class
idstools.unified2.
FileRecordReader
(*files)[source] FileRecordReader reads and decodes unified2 records from one or more files supplied by filename.
Parameters: files... – One or more filenames to read records from. Example:
reader = unified2.RecordReader("unified2.log.1382627941", "unified2.log.1382627966) for record in reader: print(record)
-
next
()[source] Return the next record or None if EOF.
Records returned will be one of the types
Event
,Packet
,ExtraData
orUnknown
if the record is of an unknown type.
-
tell
()[source] Returns the current filename and offset.
-
SpoolRecordReader¶
-
class
idstools.unified2.
SpoolRecordReader
(directory, prefix, init_filename=None, init_offset=None, follow=False, rollover_hook=None)[source] SpoolRecordReader reads and decodes records from a unified2 spool directory.
Required parameters:
Parameters: - directory – Path to unified2 spool directory.
- prefix – Filename prefix for unified2 log files.
Optional parameters:
Parameters: - init_filename – Filename open on initialization.
- init_offset – Offset to seek to on initialization.
- follow – Set to true if reading should wait for the next record to become available.
- rollover_hook – Function to call on rollover of log file, the first parameter being the filename being closed, the second being the filename being opened.
Example with following and rollover deletion:
def rollover_hook(closed, opened): os.unlink(closed) reader = unified2.SpoolRecordReader("/var/log/snort", "unified2.log", rollover_hook = rollover_hook, follow = True) for record in reader: print(record)
-
next
()[source] Return the next decoded unified2 record from the spool directory.
-
tell
()[source] Return a tuple containing the filename and offset of the file currently being processed.
Record Types¶
Event¶
-
class
idstools.unified2.
Event
(event)[source] Event represents a unified2 event record with a dict-like interface. The unified2 file format specifies multiple types of event records, idstools normalizes them into a single type.
Fields:
- sensor-id
- event-id
- event-second
- event-microsecond
- signature-id
- generator-id
- signature-revision
- classification-id
- priority
- source-ip
- destination-ip
- sport-itype
- dport-icode
- protocol
- impact-flag
- impact
- blocked
- mpls-label
- vlan-id
Deprecated: Methods that return events rather than single records will also populate the fields packets and extra-data. These fields are lists of the
Packet
andExtraData
records associated with the event.
Rule Parsing¶
The idstools rule parsing can parse individual rule strings as well as multiple rules from a file or file like objects.
The Rule Object¶
The parsing functions will return one, or a list of Rule objects that present the rule as a dictionary.
-
class
idstools.rule.
Rule
(enabled=None, action=None, group=None)[source] Class representing a rule.
The Rule class is a class that also acts like a dictionary.
Dictionary fields:
- group: The group the rule belongs to, typically the filename.
- enabled: True if rule is enabled (uncommented), False is disabled (commented)
- action: The action of the rule (alert, pass, etc) as a string
- direction: The direction string of the rule.
- gid: The gid of the rule as an integer
- sid: The sid of the rule as an integer
- rev: The revision of the rule as an integer
- msg: The rule message as a string
- flowbits: List of flowbit options in the rule
- metadata: Metadata values as a list
- references: References as a list
- classtype: The classification type
- priority: The rule priority, 0 if not provided
- raw: The raw rule as read from the file or buffer
Parameters: - enabled – Optional parameter to set the enabled state of the rule
- action – Optional parameter to set the action of the rule
- group – Optional parameter to set the group (filename) of the rule
Note
Parsed rules are primarily read only, with the exception of toggling the enabled state of the rule, modification is not really supported.
Parsing¶
-
rule.
parse
(group=None) Parse a single rule for a string buffer.
Parameters: buf – A string buffer containing a single Snort-like rule Returns: An instance of of Rule
representing the parsed rule
-
rule.
parse_fileobj
(group=None) Parse multiple rules from a file like object.
Note: At this time rules must exist on one line.
Parameters: fileobj – A file like object to parse rules from. Returns: A list of Rule
instances, one for each rule parsed
-
rule.
parse_file
(group=None) Parse multiple rules from the provided filename.
Parameters: filename – Name of file to parse rules from Returns: A list of Rule
instances, one for each rule parsed
Printing¶
The string representation of the object will print the full rule respecting the enabled option of the rule.
For example:
>>> idstools.rule.parse('alert ip any any -> any any (msg:"TEST MESSAGE"; content:"uid=0|28|root|29|"; classtype:bad-unknown; sid:10000000; rev:1;)')
>>> rule = idstools.rule.parse('alert ip any any -> any any (msg:"TEST MESSAGE"; content:"uid=0|28|root|29|"; classtype:bad-unknown; sid:10000000; rev:1;)')
>>> print(rule)
alert ip any any -> any any (msg:"TEST MESSAGE"; content:"uid=0|28|root|29|"; classtype:bad-unknown; sid:10000000; rev:1;)
>>> rule["enabled"] = False
>>> print(rule)
# alert ip any any -> any any (msg:"TEST MESSAGE"; content:"uid=0|28|root|29|"; classtype:bad-unknown; sid:10000000; rev:1;)
A brief description of the rule can be printed with
idstools.rule.Rule.brief()
or a string representing the rule ID
can be printed with idstools.rule.Rule.idstr()
.
Flowbit Resolution¶
The idstools.rule.FlowbitResolver
is able to resolve the
flowbits for a set of rules presented as a dictionary.
Maps¶
The maps module provides classes for mapping IDs to information objects such as signature IDs to a signature description.
Contents
SignatureMap¶
-
class
idstools.maps.
SignatureMap
[source] SignatureMap maps signature IDs to a signature info dict.
The signature map can be build up from classification.config, gen-msg.map, and new and old-style sid-msg.map files.
The dict’s in the map will have at a minimum the following fields:
- gid (int)
- sid (int)
- msg (string)
- refs (list of strings)
Signatures loaded from a new style sid-msg.map file will also have rev, classification and priority fields.
Example:
>>> from idstools import maps >>> sigmap = maps.SignatureMap() >>> sigmap.load_generator_map(open("tests/gen-msg.map")) >>> sigmap.load_signature_map(open("tests/sid-msg-v2.map")) >>> print(sigmap.get(1, 2495)) {'classification': 'misc-attack', 'rev': 8, 'priority': 0, 'gid': 1, 'sid': 2495, 'msg': 'GPL NETBIOS SMB DCEPRC ORPCThis request flood attempt', 'ref': ['bugtraq,8811', 'cve,2003-0813', 'nessus,12206', 'url,www.microsoft.com/technet/security/bulletin/MS04-011.mspx']}
-
get
(generator_id, signature_id)[source] Get signature info by generator_id and signature_id.
Parameters: - generator_id – The generator id of the signature to lookup.
- signature_id – The signature id of the signature to lookup.
For convenience, if the generator_id is 3 and the signature is not found, a second lookup will be done using a generator_id of 1.
-
load_generator_map
(fileobj)[source] Load the generator message map (gen-msg.map) from a file-like object.
-
load_signature_map
(fileobj, defaultgid=1)[source] Load signature message map (sid-msg.map) from a file-like object.
ClassificationMap¶
-
class
idstools.maps.
ClassificationMap
(fileobj=None)[source] ClassificationMap maps classification IDs and names to a dict object describing a classification.
Parameters: fileobj – (Optional) A file like object to load classifications from on initialization. The classification dicts stored in the map have the following fields:
- name (string)
- description (string)
- priority (int)
Example:
>>> from idstools import maps >>> classmap = maps.ClassificationMap() >>> classmap.load_from_file(open("tests/classification.config")) >>> classmap.get(3) {'priority': 2, 'name': 'bad-unknown', 'description': 'Potentially Bad Traffic'} >>> classmap.get_by_name("bad-unknown") {'priority': 2, 'name': 'bad-unknown', 'description': 'Potentially Bad Traffic'}
-
get
(class_id)[source] Get a classification by ID.
Parameters: class_id – The classification ID to get. Returns: A dict describing the classification or None.
-
get_by_name
(name)[source] Get a classification by name.
Parameters: name – The name of the classification Returns: A dict describing the classification or None.
-
load_from_file
(fileobj)[source] Load classifications from a Snort style classification.config file object.
API - Auto Generated API Documentation¶
idstools¶
idstools package¶
-
class
idstools.rulecat.loghandler.
SuriColourLogHandler
(stream=None)[source]¶ Bases:
logging.StreamHandler
An alternative stream log handler that logs with Suricata inspired log colours.
-
BLUE
= '\x1b[34m'¶
-
GREEN
= '\x1b[32m'¶
-
ORANGE
= '\x1b[38;5;208m'¶
-
RED
= '\x1b[31m'¶
-
REDB
= '\x1b[1;31m'¶
-
RESET
= '\x1b[0m'¶
-
YELLOW
= '\x1b[33m'¶
-
YELLOWB
= '\x1b[1;33m'¶
-
emit
(record)[source]¶ Emit a record.
If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an ‘encoding’ attribute, it is used to determine how to do the output to the stream.
-
Dump Snort SO rule stub helper program. Can optionally repack a Snort rule tarball with the generated stubs, in place or to a new file.
Convert packets in EVE logs to pcap.
eve2pcap will convert the packets or the payloads found in an eve log file to a pcap file.
Note that payload conversion requires Scapy, and will not recreate the original packets as the headers need to be built on the fly from the available information in the eve log.
-
class
idstools.scripts.eve2pcap.
Pcap
(pcap_t)[source]¶
Generate sid-msg.map files (v1 and v2) from rule archives, files and/or directories.
-
class
idstools.scripts.rulecat.
AllRuleMatcher
[source]¶ Bases:
object
Matcher object to match all rules.
-
class
idstools.scripts.rulecat.
DropRuleFilter
(matcher)[source]¶ Bases:
object
Filter to modify an idstools rule object to a drop rule.
-
class
idstools.scripts.rulecat.
FileTracker
[source]¶ Used to check if files are modified.
Usage: Add files with add(filename) prior to modification. Test with any_modified() which will return True if any of the checksums have been modified.
-
class
idstools.scripts.rulecat.
FilenameMatcher
(filename)[source]¶ Bases:
object
Matcher object to match a rule by its filename. This is similar to a group but has no specifier prefix.
-
class
idstools.scripts.rulecat.
GroupMatcher
(pattern)[source]¶ Bases:
object
Matcher object to match an idstools rule object by its group (ie: filename).
-
class
idstools.scripts.rulecat.
IdRuleMatcher
(generatorId, signatureId)[source]¶ Bases:
object
Matcher object to match an idstools rule object by its signature ID.
-
class
idstools.scripts.rulecat.
ModifyRuleFilter
(matcher, pattern, repl)[source]¶ Bases:
object
Filter to modify an idstools rule object.
Important note: This filter does not modify the rule inplace, but instead returns a new rule object with the modification.
-
class
idstools.scripts.rulecat.
ReRuleMatcher
(pattern)[source]¶ Bases:
object
Matcher object to match an idstools rule object by regular expression.
-
class
idstools.scripts.rulecat.
ThresholdProcessor
[source]¶ -
-
patterns
= [<_sre.SRE_Pattern object>, <_sre.SRE_Pattern object>, <_sre.SRE_Pattern object>]¶
-
-
idstools.scripts.rulecat.
build_report
(prev_rulemap, rulemap)[source]¶ Build a report of changes between 2 rulemaps.
Returns a dict with the following keys that each contain a list of rules. - added - removed - modified
Read unified2 log files and output events as Suricata EVE JSON (or as close as possible).
-
class
idstools.scripts.u2eve.
EveFilter
(msgmap=None, classmap=None, packet_printable=False, packet_hex=False)[source]¶ Bases:
object
Read unified2 log files and output events in “fast” style.
Read unified2 log files and output records as JSON.
-
class
idstools.scripts.u2json.
Formatter
(msgmap=None, classmap=None, packet_printable=False, packet_hex=False, extra_printable=False)[source]¶ Bases:
object
A python reimplementation of Snort’s u2spewfoo.
Provide mappings from ID’s to descriptions.
Includes mapping classes for event ID messages and classification information.
-
class
idstools.maps.
ClassificationMap
(fileobj=None)[source]¶ Bases:
object
ClassificationMap maps classification IDs and names to a dict object describing a classification.
Parameters: fileobj – (Optional) A file like object to load classifications from on initialization. The classification dicts stored in the map have the following fields:
- name (string)
- description (string)
- priority (int)
Example:
>>> from idstools import maps >>> classmap = maps.ClassificationMap() >>> classmap.load_from_file(open("tests/classification.config")) >>> classmap.get(3) {'priority': 2, 'name': 'bad-unknown', 'description': 'Potentially Bad Traffic'} >>> classmap.get_by_name("bad-unknown") {'priority': 2, 'name': 'bad-unknown', 'description': 'Potentially Bad Traffic'}
-
get
(class_id)[source]¶ Get a classification by ID.
Parameters: class_id – The classification ID to get. Returns: A dict describing the classification or None.
-
get_by_name
(name)[source]¶ Get a classification by name.
Parameters: name – The name of the classification Returns: A dict describing the classification or None.
-
class
idstools.maps.
SignatureMap
[source]¶ Bases:
object
SignatureMap maps signature IDs to a signature info dict.
The signature map can be build up from classification.config, gen-msg.map, and new and old-style sid-msg.map files.
The dict’s in the map will have at a minimum the following fields:
- gid (int)
- sid (int)
- msg (string)
- refs (list of strings)
Signatures loaded from a new style sid-msg.map file will also have rev, classification and priority fields.
Example:
>>> from idstools import maps >>> sigmap = maps.SignatureMap() >>> sigmap.load_generator_map(open("tests/gen-msg.map")) >>> sigmap.load_signature_map(open("tests/sid-msg-v2.map")) >>> print(sigmap.get(1, 2495)) {'classification': 'misc-attack', 'rev': 8, 'priority': 0, 'gid': 1, 'sid': 2495, 'msg': 'GPL NETBIOS SMB DCEPRC ORPCThis request flood attempt', 'ref': ['bugtraq,8811', 'cve,2003-0813', 'nessus,12206', 'url,www.microsoft.com/technet/security/bulletin/MS04-011.mspx']}
-
get
(generator_id, signature_id)[source]¶ Get signature info by generator_id and signature_id.
Parameters: - generator_id – The generator id of the signature to lookup.
- signature_id – The signature id of the signature to lookup.
For convenience, if the generator_id is 3 and the signature is not found, a second lookup will be done using a generator_id of 1.
-
load_generator_map
(fileobj)[source]¶ Load the generator message map (gen-msg.map) from a file-like object.
Module for network related operations.
-
idstools.net.
get
(url, fileobj, progress_hook=None)[source]¶ Perform a GET request against a URL writing the contents into the provideded file like object.
Parameters: - url – The URL to fetch
- fileobj – The fileobj to write the content to
- progress_hook – The function to call with progress updates
Returns: Returns a tuple containing the number of bytes read and the result of the info() function from urllib2.urlopen().
Raises: Exceptions from urllib2.urlopen() and writing to the provided fileobj may occur.
Provides basic packet decoding.
Module for parsing Snort-like rules.
Parsing is done using regular expressions and the job of this module is to do its best at parsing out fields of interest from the rule rather than perform a sanity check.
The methods that parse multiple rules for a provided input (parse_file, parse_fileobj) return a list of rules instead of dict keyed by ID as its not the job of this module to detect or deal with duplicate signature IDs.
-
class
idstools.rule.
FlowbitResolver
[source]¶ Bases:
object
-
get_required_rules
(rulemap, flowbits, include_enabled=False)[source]¶ Returns a list of rules that need to be enabled in order to satisfy the list of required flowbits.
-
getters
= ['isset', 'isnotset']¶
-
setters
= ['set', 'setx', 'unset', 'toggle']¶
-
-
class
idstools.rule.
Rule
(enabled=None, action=None, group=None)[source]¶ Bases:
dict
Class representing a rule.
The Rule class is a class that also acts like a dictionary.
Dictionary fields:
- group: The group the rule belongs to, typically the filename.
- enabled: True if rule is enabled (uncommented), False is disabled (commented)
- action: The action of the rule (alert, pass, etc) as a string
- direction: The direction string of the rule.
- gid: The gid of the rule as an integer
- sid: The sid of the rule as an integer
- rev: The revision of the rule as an integer
- msg: The rule message as a string
- flowbits: List of flowbit options in the rule
- metadata: Metadata values as a list
- references: References as a list
- classtype: The classification type
- priority: The rule priority, 0 if not provided
- raw: The raw rule as read from the file or buffer
Parameters: - enabled – Optional parameter to set the enabled state of the rule
- action – Optional parameter to set the action of the rule
- group – Optional parameter to set the group (filename) of the rule
-
brief
()[source]¶ A brief description of the rule.
Returns: A brief description of the rule Return type: string
-
id
¶ The ID of the rule.
Returns: A tuple (gid, sid) representing the ID of the rule Return type: A tuple of 2 ints
-
idstr
¶ Return the gid and sid of the rule as a string formatted like: ‘[GID:SID]’
-
idstools.rule.
enable_flowbit_dependencies
(rulemap)[source]¶ Helper function to resolve flowbits, wrapping the FlowbitResolver class.
-
idstools.rule.
format_sidmsgmap_v2
(rule)[source]¶ Format a rule as a v2 sid-msg.map entry.
eg: gid || sid || rev || classification || priority || msg || ref0 || refN
-
idstools.rule.
parse
(buf, group=None)[source]¶ Parse a single rule for a string buffer.
Parameters: buf – A string buffer containing a single Snort-like rule Returns: An instance of of Rule
representing the parsed rule
-
idstools.rule.
parse_file
(filename, group=None)[source]¶ Parse multiple rules from the provided filename.
Parameters: filename – Name of file to parse rules from Returns: A list of Rule
instances, one for each rule parsed
-
class
idstools.snort.
SnortApp
(config=None, path=None, os=None, dynamic_engine_lib=None)[source]¶ Bases:
object
Snort represents the Snort application.
Parameters: - config – A dictionary configuration object. The dictionary can contain the same fields as the following parameters. Parameters take precedence over the config dictionary.
- path – The path to the Snort binary.
-
class
idstools.suricata.
SuricataVersion
(major, minor, patch, full, short, raw)¶ Bases:
tuple
-
full
¶ Alias for field number 3
-
major
¶ Alias for field number 0
-
minor
¶ Alias for field number 1
-
patch
¶ Alias for field number 2
-
raw
¶ Alias for field number 5
-
short
¶ Alias for field number 4
-
Unified2 record and event reading.
Unified2 is a file format used by the Snort and Suricata IDS engines for logging events.
For more information on the unified2 file format see:
usage: from idstools import unified2
-
class
idstools.unified2.
Aggregator
[source]¶ Bases:
object
Deprecated: Applications requiring the aggregation of packets and extra data with an event should implement their own aggregation logic.
A class implementing something like the aggregator pattern to aggregate records until an event can be built.
-
class
idstools.unified2.
Event
(event)[source]¶ Bases:
dict
Event represents a unified2 event record with a dict-like interface. The unified2 file format specifies multiple types of event records, idstools normalizes them into a single type.
Fields:
- sensor-id
- event-id
- event-second
- event-microsecond
- signature-id
- generator-id
- signature-revision
- classification-id
- priority
- source-ip
- destination-ip
- sport-itype
- dport-icode
- protocol
- impact-flag
- impact
- blocked
- mpls-label
- vlan-id
Deprecated: Methods that return events rather than single records will also populate the fields packets and extra-data. These fields are lists of the
Packet
andExtraData
records associated with the event.
-
class
idstools.unified2.
EventDecoder
(fields)[source]¶ Bases:
idstools.unified2.AbstractDecoder
Decoder for event type records.
-
class
idstools.unified2.
ExtraData
(*fields, **kwargs)[source]¶ Bases:
dict
ExtraData represents a unified2 extra-data record with a dict like interface.
Fields:
- event-type
- event-length
- sensor-id
- event-id
- event-second
- type
- data-type
- data-length
- data
-
class
idstools.unified2.
ExtraDataDecoder
(fields)[source]¶ Bases:
idstools.unified2.AbstractDecoder
Decoder for extra data type records.
-
class
idstools.unified2.
Field
(name, length, fmt=None)[source]¶ Bases:
object
A class to represent a field in a unified2 record. Used for building the decoders.
-
fmt
¶ Builds a format string for struct.unpack.
-
-
class
idstools.unified2.
FileEventReader
(*files)[source]¶ Bases:
object
Deprecated: Event readers have been deprecated due to the deprecation of the Aggregator.
FileEventReader reads records from one or more filenames and aggregates them into events.
Parameters: files... – One or more files to read events from. Example:
reader = unified2.FileEventReader("unified2.log.1382627941", "unified2.log.1382627966) for event in reader: print(event)
-
class
idstools.unified2.
FileRecordReader
(*files)[source]¶ Bases:
object
FileRecordReader reads and decodes unified2 records from one or more files supplied by filename.
Parameters: files... – One or more filenames to read records from. Example:
reader = unified2.RecordReader("unified2.log.1382627941", "unified2.log.1382627966) for record in reader: print(record)
-
class
idstools.unified2.
Packet
(*fields, **kwargs)[source]¶ Bases:
dict
Packet represents a unified2 packet record with a dict-like interface.
Fields:
- sensor-id
- event-id
- event-second
- packet-second
- packet-microsecond
- linktype
- length
- data
-
class
idstools.unified2.
PacketDecoder
(fields)[source]¶ Bases:
idstools.unified2.AbstractDecoder
Decoder for packet type records.
-
class
idstools.unified2.
RecordReader
(fileobj)[source]¶ Bases:
object
RecordReader reads and decodes unified2 records from a file-like object.
Parameters: fileobj – The file-like object to read from. Example:
fileobj = open("/var/log/snort/merged.log.1382627987", "rb") reader = RecordReader(fileobj): for record in reader: print(record)
-
class
idstools.unified2.
SpoolEventReader
(directory, prefix, follow=False, delete=False, bookmark=False)[source]¶ Bases:
object
Deprecated: Event readers have been deprecated due to the deprecation of the Aggregator.
SpoolEventReader reads records from a unified2 spool directory and aggregates them into events.
Required parameters:
Parameters: - directory – Path to unified2 spool directory.
- prefix – Filename prefix for unified2 log files.
Optional parameters:
Parameters: - follow – Set to true to follow the log files. Reading will wait until an event is available before returning.
- delete – If True, unified2 files will be deleted when reading has moved onto the next one.
- bookmark – If True, the reader will remember its location and start reading from the bookmarked location on initialization.
Example:
reader = unified2.SpoolEventReader("/var/log/snort", "unified2.log") for event in reader: print(event)
-
class
idstools.unified2.
SpoolRecordReader
(directory, prefix, init_filename=None, init_offset=None, follow=False, rollover_hook=None)[source]¶ Bases:
object
SpoolRecordReader reads and decodes records from a unified2 spool directory.
Required parameters:
Parameters: - directory – Path to unified2 spool directory.
- prefix – Filename prefix for unified2 log files.
Optional parameters:
Parameters: - init_filename – Filename open on initialization.
- init_offset – Offset to seek to on initialization.
- follow – Set to true if reading should wait for the next record to become available.
- rollover_hook – Function to call on rollover of log file, the first parameter being the filename being closed, the second being the filename being opened.
Example with following and rollover deletion:
def rollover_hook(closed, opened): os.unlink(closed) reader = unified2.SpoolRecordReader("/var/log/snort", "unified2.log", rollover_hook = rollover_hook, follow = True) for record in reader: print(record)
-
iter_next
()[source]¶ Return the next record or None if EOF.
If in follow mode and EOF, this method will sleep and and try again.
Returns: A record of type Event
,Packet
,ExtraData
orUnknown
if the record is of an unknown type.
-
class
idstools.unified2.
Unified2Bookmark
(directory=None, prefix=None, filename=None)[source]¶ Bases:
object
Class to represent a “bookmark” for unified2 spool directories.
-
class
idstools.unified2.
Unknown
(record_type, buf)[source]¶ Bases:
object
Class to represent an unknown record type.
In the unlikely case that a record is of an unknown type, an instance of Unknown will be used to hold the record type and buffer.
-
idstools.unified2.
decode_record
(record_type, buf)[source]¶ Decodes a raw record into an object representing the record.
Parameters: - record_type – The type of record.
- buf – Buffer containing the raw record.
Returns: The decoded record as a
Event
,Packet
,ExtraData
orUnknown
if the record is of an unknown type.
-
idstools.unified2.
read_record
(fileobj)[source]¶ Reads a unified2 record from the provided file object.
Parameters: fileobj – The file like object to read from. Currently this object needs to support read, seek and tell. Returns: If a complete record is read a Record
will be returned, otherwise None will be returned.If some data is read, but not enough for a whole record, the location of the file object will be reset and a
EOFError
exception will be raised.
Module for utility functions that don’t really fit anywhere else.
-
idstools.util.
format_printable
(data)[source]¶ Given a buffer, return a string with the printable characters. A ‘.’ will be used for all non-printable characters.