Snort Overview
This manual is based on Writing Snort Rules by Martin Roesch and further work from Chris Green <cmg@snort.org>. It was then maintained by Brian Caswell <bmc@snort.org> and now is maintained by the Snort Team. If you have a better way to say something or ﬁnd that something in the documentation is outdated, drop us a line and we will update A it. If you would like to submit patches for this document, you can ﬁnd the latest version of the documentation in LTEX format in the Snort CVS repository at /doc/snort_manual.tex. Small documentation updates are the easiest way to help out the Snort Project.

1.1 Getting Started
Snort really isn’t very hard to use, but there are a lot of command line options to play with, and it’s not always obvious which ones go together well. This ﬁle aims to make using Snort easier for new users. Before we proceed, there are a few basic concepts you should understand about Snort. Snort can be conﬁgured to run in three modes: • Sniffer mode, which simply reads the packets off of the network and displays them for you in a continuous stream on the console (screen). • Packet Logger mode, which logs the packets to disk. • Network Intrusion Detection System (NIDS) mode, the most complex and conﬁgurable conﬁguration, which allows Snort to analyze network trafﬁc for matches against a user-deﬁned rule set and performs several actions based upon what it sees. • Inline mode, which obtains packets from iptables instead of from libpcap and then causes iptables to drop or pass packets based on Snort rules that use inline-speciﬁc rule types.

1.2 Sniffer Mode
First, let’s start with the basics. If you just want to print out the TCP/IP packet headers to the screen (i.e. sniffer mode), try this: ./snort -v This command will run Snort and just show the IP and TCP/UDP/ICMP headers, nothing else. If you want to see the application data in transit, try the following: ./snort -vd 8

1. you can read the packets back out of the ﬁle with any sniffer that supports the tcpdump binary format (such as tcpdump or Ethereal). they are logged to a directory Note that if
with a name based on the higher of the two port numbers or.3 Packet Logger Mode
OK.1) host. in the case of a tie. If you don’t./log. all of these commands are pretty cool. Once the packets have been logged to the binary ﬁle. you need to tell Snort which network is the home network: . and you want to log the packets relative to the 192. Snort can also read the packets back by using the 9
. you don’t need to run in verbose mode or specify the -d or -e switches because in binary mode the entire packet is logged.168.0 class C network.
! △NOTE both the source and destination hosts are on the home network. If you’re on a high speed network or you want to log the packets into a more compact form for later analysis. Snort will exit with an error message.)
1.0/24 This rule tells Snort that you want to print out the data link and TCP/IP headers as well as application data into the directory .168. Binary mode logs the packets in tcpdump format to a single binary ﬁle in the logging directory: ./log -h 192.168. Additionally. you should consider logging in binary mode. All you really need to do to place Snort into logger mode is to specify a logging directory at the command line using the -l switch—the -b binary logging switch merely provides a modiﬁer that tells Snort to log the packets in something other than the default output format of plain ASCII text. If you want an even more descriptive display. do this: . not just sections of it./snort -dev -l . with the directory names being based on the address of the remote (non-192. but if you want to record the packets to the disk. this assumes you have a directory named log in the current directory. When Snort runs in this mode. The last command could also be typed out as: . showing the data link layer headers.This instructs Snort to display the packet data as well as the headers./snort -dev -l ./snort -l . these switches may be divided up or smashed together in any combination./log Of course./snort -vde (As an aside. you may notice that Snort sometimes uses the address of the remote computer as the directory in which it places packets and sometimes it uses the local host address. the source address. you need to specify a logging directory and Snort will automatically know to go into packet logger mode: . which eliminates the need to tell it how to format the output directory structure. All incoming packets will be recorded into subdirectories of the log directory./snort -d -v -e and it would do the same thing. In order to log relative to the home network./log -b Note the command line changes here. If you just specify a plain -l switch. We don’t need to specify a home network any longer because binary mode logs everything into a single ﬁle. it collects every packet it sees and places it in a directory hierarchy based upon the IP address of one of the hosts in the datagram.1.

if you wanted to run a binary log ﬁle through Snort in sniffer mode to dump the packets to the screen.
1.log icmp For more info on how to use the BPF interface. it will default to /var/log/snort./log -c snort. If you don’t specify an output directory for the program. and packets can be dropped while writing to the display. alert message.168. console. 10
.0/24 -l ./snort -d -h 192. Six of these modes are accessed with the -A command line switch. This will apply the rules conﬁgured in the snort.1.4./snort -dv -r packet. The screen is a slow place to write data to. which puts it into playback mode. the -v switch should be left off the command line for the sake of speed. Writes the alert in a simple format with a timestamp. One thing to note about the last command line is that if Snort is going to be used in a long term way as an IDS. Sends “fast-style” alerts to the console (screen). read the Snort and tcpdump man pages./snort -dev -l .conf This will conﬁgure Snort to run in its most basic NIDS form. you can try something like this: . The full alert mechanism prints out the alert message in addition to the full packet headers./log -h 192. Alert modes are somewhat more complex.conf ﬁle to each packet to decide if an action based upon the rule type in the ﬁle should be taken. For example. so you can usually omit the -e switch. source and destination IPs/ports.1. Full alert mode. This is the default alert mode and will be used automatically if you do not specify a mode. as well as with the BPF interface that’s available from the command line. syslog. and none. if you only wanted to see the ICMP packets from the log ﬁle.conf is the name of your rules ﬁle. simply specify a BPF ﬁlter at the command line and Snort will only see the ICMP packets in the ﬁle: .
1. There are several other alert output modes available at the command line.log You can manipulate the data in the ﬁle in a number of ways through Snort’s packet logging and intrusion detection modes. try this: . Turns off alerting.-r switch. . For example. socket. Sends alerts to a UNIX socket that another program can listen on. as well as two logging facilities. These options are: Option -A fast -A full -A -A -A -A unsock none console cmg Description Fast alert mode.1 NIDS Mode Output Options
There are a number of ways to conﬁgure the output of Snort in NIDS mode.4 Network Intrusion Detection System Mode
To enable Network Intrusion Detection System (NIDS) mode so that you don’t record every single packet sent down the wire.168. logging packets that trigger rules speciﬁed in the snort. The default logging and alerting mechanisms are to log in decoded ASCII format and use full alerts./snort -dvr packet. It’s also not necessary to record the data link headers for most applications.0/24 -c snort.conf in plain ASCII to disk using a hierarchical directory structure (just like packet logger mode). fast. Packets from any tcpdump formatted ﬁle can be processed through Snort in any of its run modes.conf where snort. There are seven alert modes available at the command line: full. Generates “cmg style” alerts. too. cmg.

2 Understanding Standard Alert Output
When Snort generates an alert message.conf
11
.
! △NOTE
Command line logging options override any output options speciﬁed in the conﬁguration ﬁle. but still somewhat fast. as each rendition of the rule should increment this number with the rev option. This number is primarily used when writing signatures.6.0/24 -s As another example.168.conf -A fast -h 192.1 for more details on conﬁguring syslog output. The default facilities for the syslog alerting mechanism are LOG AUTHPRIV and LOG ALERT./snort -b -A fast -c snort.4. For example. you need to use uniﬁed logging and a uniﬁed log reader such as barnyard. This allows Snort to log alerts in a binary form as fast as possible while another program performs the slow actions.6. For output modes available through the conﬁguration ﬁle. please read etc/generators in the Snort source.map. For a list of preprocessor SIDs.conf -l .
1.168. To disable packet logging altogether.1. please see etc/gen-msg. See Section 2. this tells the user what component of Snort generated this alert. If you want a text ﬁle that’s easily parsable./snort -c snort. In this case. we know that this event came from the “decode” (116) component of Snort.3 High Performance Conﬁguration
If you want Snort to go fast (like keep up with a 1000 Mbps connection). For a list of GIDs. use the following command line to log to default (decoded ASCII) facility and send alerts to syslog: . use the -s switch./snort -c snort. try using binary logging with the “fast” output mechanism./log -h 192. use the -N command line switch. For example: . Rule-based SIDs are written directly into the rules with the sid option.
To send alerts to syslog. use the following command line to log to the default facility in /var/log/snort and send alerts to a fast alert ﬁle: . it will usually look like the following: [**] [116:56:1] (snort_decoder): T/TCP Detected [**] The ﬁrst number is the Generator ID. This allows debugging of conﬁguration issues quickly via the command line. The third number is the revision ID.4.Packets can be logged to their default decoded ASCII format or to a binary log ﬁle via the -b command line switch. see Section 2. If you want to conﬁgure other facilities for syslog output. 56 represents a T/TCP event.1. such as writing to a database. The second number is the Snort ID (sometimes referred to as Signature ID). use the output plugin directives in the rules ﬁles.0/24
1. This will log packets in tcpdump format and produce minimal alerts. In this case.

1.4.4 Changing Alert Order
The default way in which Snort applies its rules to packets may not be appropriate for all installations. The Pass rules are applied ﬁrst, then the Drop rules, then the Alert rules and ﬁnally, Log rules are applied.

! △NOTE

Sometimes an errant pass rule could cause alerts to not show up, in which case you can change the default ordering to allow Alert rules to be applied before Pass rules. For more information, please refer to the --alert-before-pass option.

Several command line options are available to change the order in which rule actions are taken. • --alert-before-pass option forces alert rules to take affect in favor of a pass rule. • --treat-drop-as-alert causes drop, sdrop, and reject rules and any associated alerts to be logged as alerts, rather then the normal action. This allows use of an inline policy with passive/IDS mode. • --process-all-events option causes Snort to process every event associated with a packet, while taking the actions based on the rules ordering. Without this option (default case), only the events for the ﬁrst action based on rules ordering are processed.

! △NOTE

Pass rules are special cases here, in that the event processing is terminated when a pass rule is encountered, regardless of the use of --process-all-events.

1.5 Inline Mode
Snort 2.3.0 RC1 integrated the intrusion prevention system (IPS) capability of Snort Inline into the ofﬁcial Snort project. Snort Inline obtains packets from iptables instead of libpcap and then uses new rule types to help iptables pass or drop packets based on Snort rules. In order for Snort Inline to work properly, you must download and compile the iptables code to include “make install-devel” (http://www.iptables.org). This will install the libipq library that allows Snort Inline to interface with iptables. Also, you must build and install LibNet, which is available from http://www.packetfactory. net. There are three rule types you can use when running Snort with Snort Inline: • drop - The drop rule type will tell iptables to drop the packet and log it via usual Snort means. • reject - The reject rule type will tell iptables to drop the packet, log it via usual Snort means, and send a TCP reset if the protocol is TCP or an icmp port unreachable if the protocol is UDP. • sdrop - The sdrop rule type will tell iptables to drop the packet. Nothing is logged.

! △NOTE

You can also replace sections of the packet payload when using Snort Inline. See Section 1.5.2 for more information.

When using a reject rule, there are two options you can use to send TCP resets:

12

• You can use a RAW socket (the default behavior for Snort Inline), in which case you must have an interface that has an IP address assigned to it. If there is not an interface with an IP address assigned with access to the source of the packet, the packet will be logged and the reset packet will never make it onto the network. • You can also now perform resets via a physical device when using iptables. We take the indev name from ip queue and use this as the interface on which to send resets. We no longer need an IP loaded on the bridge, and can remain pretty stealthy as the config layer2 resets in snort.conf takes a source MAC address which we substitue for the MAC of the bridge. For example: config layer2resets tells Snort Inline to use layer2 resets and uses the MAC address of the bridge as the source MAC in the packet, and: config layer2resets: 00:06:76:DD:5F:E3 will tell Snort Inline to use layer2 resets and uses the source MAC of 00:06:76:DD:5F:E3 in the reset packet. • The command-line option --disable-inline-initialization can be used to not initialize IPTables when in inline mode. It should be used with command-line option -T to test for a valid conﬁguration without requiring opening inline devices and adversely affecting trafﬁc ﬂow.

1.5.1 Snort Inline Rule Application Order
The current rule application order is: ->activation->dynamic->pass->drop->sdrop->reject->alert->log This will ensure that a drop rule has precedence over an alert or log rule.

1.5.2 Replacing Packets with Snort Inline
Additionally, Jed Haile’s content replace code allows you to modify packets before they leave the network. For example: alert tcp any any <> any 80 ( \ msg: "tcp replace"; content:"GET"; replace:"BET";) alert udp any any <> any 53 ( \ msg: "udp replace"; content: "yahoo"; replace: "xxxxx";) These rules will comb TCP port 80 trafﬁc looking for GET, and UDP port 53 trafﬁc looking for yahoo. Once they are found, they are replaced with BET and xxxxx, respectively. The only catch is that the replace must be the same length as the content.

1.5.3 Installing Snort Inline
To install Snort inline, use the following command: ./configure --enable-inline make make install

13

1.5.4 Running Snort Inline
First, you need to ensure that the ip queue module is loaded. Then, you need to send trafﬁc to Snort Inline using the QUEUE target. For example: iptables -A OUTPUT -p tcp --dport 80 -j QUEUE sends all TCP trafﬁc leaving the ﬁrewall going to port 80 to the QUEUE target. This is what sends the packet from kernel space to user space (Snort Inline). A quick way to get all outbound trafﬁc going to the QUEUE is to use the rc.ﬁrewall script created and maintained by the Honeynet Project (http://www.honeynet.org/papers/honeynet/ tools/) This script is well-documented and allows you to direct packets to Snort Inline by simply changing the QUEUE variable to yes. Finally, start Snort Inline: snort -QDc ../etc/drop.conf -l /var/log/snort You can use the following command line options: • -Q - Gets packets from iptables. • -D - Runs Snort Inline in daemon mode. The process ID is stored at /var/run/snort.pid • -c - Reads the following conﬁguration ﬁle. • -l - Logs to the following directory. Ideally, Snort Inline will be run using only its own drop.rules. If you want to use Snort for just alerting, a separate process should be running with its own rule set.

1.5.5 Using the Honeynet Snort Inline Toolkit
The Honeynet Snort Inline Toolkit is a statically compiled Snort Inline binary put together by the Honeynet Project for the Linux operating system. It comes with a set of drop.rules, the Snort Inline binary, a snort-inline rotation shell script, and a good README. It can be found at: http://www.honeynet.org/papers/honeynet/tools/

1.5.6 Troubleshooting Snort Inline
If you run Snort Inline and see something like this: Initializing Output Plugins! Reading from iptables Log directory = /var/log/snort Initializing Inline mode InlineInit: : Failed to send netlink message: Connection refused More than likely, the ip queue module is not loaded or ip queue support is not compiled into your kernel. Either recompile your kernel to support ip queue, or load the module. The ip queue module is loaded by executing: insmod ip_queue Also, if you want to ensure Snort Inline is getting packets, you can start it in the following manner: snort -Qvc <configuration file> This will display the header of every packet that Snort Inline sees. 14

3 Obfuscating IP Address Printouts
If you need to post packet logs to public mailing lists. These rule stub ﬁles are used in conjunction with the shared object rules.conf using the conﬁg option dump-dynamic-rules-path as follows: config dump-dynamic-rules-path: /tmp/sorules The path conﬁgured by command line has precedence over the one conﬁgured using dump-dynamic-rules-path.
1. This is useful if you don’t care who sees the address of the attacking host.6. The PID ﬁle will be locked so that other snort processes cannot start.log -O -h 192.
1.168. you might want to use the -O switch.1.1 Running Snort as a Daemon
If you want to run Snort as a daemon. the --pid-path command line switch causes Snort to write the PID ﬁle in the directory speciﬁed.6. the --create-pidfile switch can be used to force creation of a PID ﬁle even when not running in daemon mode.6 Miscellaneous
1.168. You can also combine the -O switch with the -h switch to only obfuscate the IP addresses of hosts on the home network. you can the add -D switch to any combination described in the previous sections. For example. Snort PID File When Snort is run as a daemon . the daemon creates a PID ﬁle in the log directory. you might need to use the –dump-dynamic-rules option.0/24 \ -l /var/log/snortlogs -c /usr/local/etc/snort.conf -s -D Relative paths are not supported due to security concerns.168. you must specify the full path to the Snort binary when you start it. In Snort 2.conf \ --dump-dynamic-rules snort. obfuscating only the addresses from the 192.2 Running in Rule Stub Creation Mode
If you need to dump the shared object rules stub to a directory. Use the --nolock-pidfile switch to not lock the PID ﬁle.0/24 class C network: .0/24 15
. The path can be relative or absolute.6.conf: config dump-dynamic-rules-path: /tmp/sorules In the above mentioned scenario the dump path is set to /tmp/sorules.1. you could use the following command to read the packets from a log ﬁle and dump them to the screen. Additionally.1./snort -d -v -r snort.conf \ --dump-dynamic-rules=/tmp This path can also be conﬁgured in the snort.6. Please notice that if you want to be able to restart Snort by sending a SIGHUP signal to the daemon. This switch obfuscates your IP addresses in packet printouts.1. for example: /usr/local/bin/snort -d -h 192. /usr/local/bin/snort -c /usr/local/etc/snort. /usr/local/bin/snort -c /usr/local/etc/snort. This is handy if you don’t want people on the mailing list to know the IP addresses involved.

Same as -r. Sorted in ascii order. is not to reset state. This can be useful for testing and debugging Snort. however.pcap /home/foo/pcaps $ snort --pcap-file=foo.
1. Each Snort instance will use the value speciﬁed to generate unique event IDs. Note that Snort will not try to determine whether the ﬁles under that directory are really pcap ﬁles or not.
--pcap-no-filter --pcap-reset --pcap-show
1. or on the same CPU but a different interface.
1. foo2.1.1 Command line arguments
Any of the below can be speciﬁed multiple times on the command line (-r included) and in addition to other Snort command line options.4 Specifying Multiple-Instance Identiﬁers
In Snort v2. Use --pcap-no-filter to delete ﬁlter for following --pcap-file or --pcap-dir arguments or speciﬁy --pcap-filter again to forget previous ﬁlter and to apply to following --pcap-file or --pcap-dir arguments. Added for completeness. the -G command line option was added that speciﬁes an instance identiﬁer for the event logs. reset snort to post-conﬁguration state before reading next pcap. Users can specify either a decimal value (-G 1) or hex value preceded by 0x (-G 0x11).pcap $ snort --pcap-single=foo.pcap.e. either on different CPUs. Print a line saying what pcap is currently being read.pcap and all ﬁles under /home/foo/pcaps. This ﬁlter will apply to any --pcap-file or --pcap-dir arguments following. This is also supported via a long option --logid. Shell style ﬁlter to apply when getting pcaps from ﬁle or directory.txt foo1. File that contains a list of pcaps to read.7 Reading Pcaps
Instead of having Snort listen on an interface. 16
. Snort will read and analyze the packets as if they came off the wire. i. The default.7. that specifying --pcap-reset and --pcap-show multiple times has the same effect as specifying them once.txt This will read foo1. Note. Can speciﬁy path to pcap or directory to recurse to get pcaps.pcap foo2. you can give it a packet capture to read. A space separated list of pcaps to read. Reset to use no ﬁlter when getting pcaps from ﬁle or directory. without this option. If reading multiple pcaps.7.pcap Read pcaps from a ﬁle $ cat foo.4. This option can be used when running multiple instances of snort.6.2 Examples
Read a single pcap $ snort -r foo. A directory to recurse to look for pcaps. Option -r <file> --pcap-single=<file> --pcap-file=<file> --pcap-list="<list>" --pcap-dir=<dir> --pcap-filter=<filter> Description Read a single pcap.

pcap”. Snort will be reset to a post-conﬁguration state.pcap" This will read foo1. 17
.cap" --pcap-dir=/home/foo/pcaps In the above. $ snort --pcap-filter="*.txt $ snort --pcap-filter="*. The addition of the second ﬁlter ”*. statistics reset. any ﬁle ending in ”. in other words.pcap.txt \ > --pcap-no-filter --pcap-dir=/home/foo/pcaps In this example.cap" --pcap-dir=/home/foo/pcaps2 In this example.pcap foo3.cap” will cause the ﬁrst ﬁlter to be forgotten and then applied to the directory /home/foo/pcaps. so all ﬁles found under /home/foo/pcaps will be included.pcap --pcap-file=foo. so only ﬁles ending in ”.txt \ > --pcap-filter="*. the ﬁrst ﬁlter ”*. etc. the ﬁrst ﬁlter will be applied to foo.txt \ > --pcap-no-filter --pcap-dir=/home/foo/pcaps \ > --pcap-filter="*.txt” (and any directories that are recursed in that ﬁle). Using ﬁlters $ cat foo.txt foo1. it will be like Snort is seeing trafﬁc for the ﬁrst time. so all ﬁles found under /home/foo/pcaps will be included. For each pcap. Resetting state $ snort --pcap-dir=/home/foo/pcaps --pcap-reset The above example will read all of the ﬁles under /home/foo/pcaps.cap” will be included from that directory.Read pcaps from a command line list $ snort --pcap-list="foo1.pcap”. but after each pcap is read.pcap.pcap /home/foo/pcaps $ snort --pcap-filter="*.pcap --pcap-file=foo.pcap --pcap-file=foo.pcap and foo3. Read pcaps under a directory $ snort --pcap-dir="/home/foo/pcaps" This will include all of the ﬁles under /home/foo/pcaps. then no ﬁlter will be applied to the ﬁles found under /home/foo/pcaps. then the ﬁlter ”*. $ snort --pcap-filter="*. then no ﬁlter will be applied to the ﬁles found under /home/foo/pcaps.pcap” will only be applied to the pcaps in the ﬁle ”foo.pcap" --pcap-dir=/home/foo/pcaps The above will only include ﬁles that match the shell pattern ”*.pcap foo2. the ﬁrst ﬁlter will be applied to foo.cap” will be applied to ﬁles found under /home/foo/pcaps2.pcap foo2.txt.pcap" --pcap-file=foo. meaning all buffers will be ﬂushed. foo2.txt. $ snort --pcap-filter="*.

Printing the pcap $ snort --pcap-dir=/home/foo/pcaps --pcap-show The above example will read all of the ﬁles under /home/foo/pcaps and will print a line indicating which pcap is currently being read.

1.8 Tunneling Protocol Support
Snort supports decoding of GRE, IP in IP and PPTP. To enable support, an extra conﬁguration option is necessary: $ ./configure --enable-gre To enable IPv6 support, one still needs to use the conﬁguration option: $ ./configure --enable-ipv6

1.8.1 Multiple Encapsulations
Snort will not decode more than one encapsulation. Scenarios such as Eth IPv4 GRE IPv4 GRE IPv4 TCP Payload or Eth IPv4 IPv6 IPv4 TCP Payload will not be handled and will generate a decoder alert.

! △NOTE PPTP, which utilizes GRE and PPP, is not currently supported on architectures that require word Decoding of
alignment such as SPARC.

18

1.9 More Information
Chapter 2 contains much information about many conﬁguration options available in the conﬁguration ﬁle. The Snort manual page and the output of snort -? or snort --help contain information that can help you get Snort running in several different modes.

! △NOTE
In many shells, a backslash (\) is needed to escape the ?, so you may have to type snort -\? instead of snort -? for a list of Snort command line options. The Snort web page (http://www.snort.org) and the Snort Users mailing list: http://marc.theaimsgroup.com/?l=snort-users at snort-users@lists.sourceforge.net provide informative announcements as well as a venue for community discussion and support. There’s a lot to Snort, so sit back with a beverage of your choosing and read the documentation and mailing list archives.

19

Chapter 2

Conﬁguring Snort
2.1 Includes
The include keyword allows other rules ﬁles to be included within the rules ﬁle indicated on the Snort command line. It works much like an #include from the C programming language, reading the contents of the named ﬁle and adding the contents in the place where the include statement appears in the ﬁle.

2.1.1 Format
include <include file path/name>

! △NOTE is no semicolon at the end of this line. Note that there
Included ﬁles will substitute any predeﬁned variable values into their own variable references. See Section 2.1.2 for more information on deﬁning and using variables in Snort rules ﬁles.

2.7.2 and 2. ipvar EXAMPLE [1.2.0/16] Port Variables and Port Lists Portlists supports the declaration and lookup of ports and the representation of lists and ranges of ports. Using ’var’ for an IP variable is still allowed for backward compatibility.0 to 2.) Logical contradictions: ipvar EXAMPLE [1.2.3.2.0.1.2.2.1 and IP from 2.1. with the exception of IPs 2.2.!1. See below for some valid examples if IP variables and IP lists. The following example list will match the IP 1.2. If IPv6 support is enabled.1.2.0.) alert tcp [1. The element ’any’ can be used to match all IPs.2.sid:2.1.2. sid:1. [1. and CIDR blocks may be negated with ’!’.x and earlier. Previously. negated IP ranges that are more general than non-negated IP ranges are not allowed. but it will be deprecated in a future release. although ’!any’ is not allowed. IP lists now OR non-negated elements and AND the result with the OR’ed negated elements.1.0/24.3]] The order of the elements in the list does not matter.0/24.2.2.2.2. as a CIDR block.1.2. Variables.1. Lists of ports must be enclosed in brackets and port ranges may be speciﬁed with a ’:’.2.2.1. each element in a list was logically OR’ed together.255. such as in: [10:50.sid:3.!1. Negation is handled differently compared with Snort versions 2.3]] alert tcp $EXAMPLE any -> any any (msg:"Example".sid:3.1.0/24] any -> any any (msg:"Example".1.) The following examples demonstrate some invalid uses of IP variables and IP lists. IP lists.![2.2.IP Variables and IP Lists IPs may be speciﬁed individually. Also.2.0/24. Also.) Different use of !any: ipvar EXAMPLE !any alert tcp $EXAMPLE any -> any any (msg:"Example".1.1. ’any’ will specify any ports. in a list. but ’!any’ is not allowed. ranges.!1.1.2. or any combination of the three.2.0/8.2. Valid port ranges are from 0 to 65535.1] Nonsensical negations: ipvar EXAMPLE [1.1.888:900]
21
.1.1.![2. IPs.2. IP variables should be speciﬁed using ’ipvar’ instead of ’var’.2.1.0. or lists may all be negated with ’!’.1. Use of !any: ipvar EXAMPLE any alert tcp !$EXAMPLE any -> any any (msg:"Example".2.

) Several invalid examples of port variables and port lists are demonstrated below: Use of !any: portvar EXAMPLE5 !any var EXAMPLE5 !any Logical contradictions: portvar EXAMPLE6 [80.) alert tcp any $PORT_EXAMPLE2 -> any any (msg:"Example". sid:1.!80] Ports out of range: portvar EXAMPLE7 [65536] Incorrect declaration and use of a port variable: var EXAMPLE8 80 alert tcp any $EXAMPLE8 -> any any (msg:"Example". You can deﬁne meta-variables using the $ operator. as described in the following table:
22
.9999:20000] (msg:"Example".Port variables should be speciﬁed using ’portvar’. sid:2. a ’var’ can still be used to declare a port variable. portvar EXAMPLE1 80 var EXAMPLE2_PORT [80:90] var PORT_EXAMPLE2 [1] portvar EXAMPLE3 any portvar EXAMPLE4 [!70:90] portvar EXAMPLE5 [80. provided the variable name either ends with ’ PORT’ or begins with ’PORT ’. For backwards compatibility. The following examples demonstrate several valid usages of both port variables and port lists. sid:4.) Variable Modiﬁers Rule variable names can be modiﬁed in several ways.100:200] alert tcp any $EXAMPLE1 -> any $EXAMPLE2_PORT (msg:"Example". These can be used with the variable modiﬁer operators ? and -. sid:3.) Port variable used as an IP: alert tcp $EXAMPLE1 any -> any any (msg:"Example".) alert tcp any 90 -> any [100:1000. sid:5.91:95. The use of ’var’ to declare a port variable will be deprecated in a future release.

but old-style variables (with the ’var’ keyword) can not be embedded inside a ’portvar’.90] Likewise. They should be renamed instead: Invalid redeﬁnition: var pvar 80 portvar pvar 90
2. Replaces with the contents of variable var or prints out the error message and exits. Replaces the contents of the variable var with “default” if var is undeﬁned.
Here is an example of advanced variable usage in action: ipvar MY_NET 192. Replaces with the contents of variable var. port variables can be deﬁned in terms of other port variables. For instance. variables can not be redeﬁned if they were previously deﬁned as a different type.3 Conﬁg
Many conﬁguration and command line options of Snort can be speciﬁed in the conﬁguration ﬁle.168.Variable Syntax var $(var) or $var $(var:-default) $(var:?message)
Description Deﬁnes a meta-variable. Format config <directive> [: <value>]
23
. Valid embedded variable: portvar pvar1 80 portvar pvar2 [$pvar1.0/24 log tcp any any -> $(MY_NET:?MY_NET is undefined!) 23 Limitations When embedding variables.90] Invalid embedded variable: var pvar1 80 portvar pvar2 [$pvar1. types can not be mixed.1.1.

Its default value is -1. Note: Alerts will still occur. If the number of hosts in the attribute table exceeds this value. Port ranges are supported. Sets the logdir (snort -l). max frag sessions <max-track>]
Specify the number of TCP reset packets to send to the source of the attack.7).config flexresp2 attempts: <num-resets>
config flexresp2 interface: <iface> config flexresp2 memcap: <bytes>
config flexresp2 rows:
<num-rows>
config flowbits size: config ignore ports: <port-list>
<num-bits> <proto>
config interface: <iface> config ipv6 frag: [bsd icmp frag alert on|off] [. an error is logged and the remainder of the hosts are ignored. Sets a Snort-wide MPLS payload type. Minimum value is 32 and the maximum is 524288 (512k). This option is only supported with a Host Attribute Table (see section 2. See Section 1. Speciﬁes ports to ignore (useful for ignoring noisy NFS trafﬁc). (Snort must be compiled with –enable-ﬂexresp2) Specify the number of rows for the hash table used to track the time of responses. Specify the protocol (TCP. Obfuscates IP Addresses (snort -O). The default is 10000. (Snort must be compiled with –enableﬂexresp2) Specify the memcap for the hash table used to track the time of responses. Sets the network interface (snort -i). (Snort must be compiled with –enable-ﬂexresp2) Specify the response interface to use. however values less than 4 will default to 4. IP. Default is on) • frag timeout <integer> (Specify amount of time in seconds to timeout ﬁrst frag in hash table) • max frag sessions <integer> (Specify the number of fragments to track in the hash table)
config layer2resets:
<mac-addr>
config logdir: <dir> config max attribute hosts:
<hosts>
config max mpls labelchain len: <num-hdrs> config min ttl: <ttl> config mpls payload type: ipv4|ipv6|ethernet config config config config no promisc nolog nopcre obfuscate
This option is only available when running in inline mode. The default MPLS payload type is ipv4 Disables promiscuous mode (snort -p). (Snort must be compiled with –enable-ﬂexresp2) Speciﬁes the maximum number of ﬂowbit tags that can be used within a rule set.5. ipv6 and ethernet are also valid options. In addition to ipv4. In Windows this can also be the interface number. The default value without this option is 4. (snort -N). Sets a limit on the maximum number of hosts to read from the attribute table. The times (hashed on a socket pair plus protocol) are used to limit sending a response to the same half of a socket pair every couple of seconds. Sets a Snort-wide limit on the number of MPLS headers a packet can have. Default is 1024 rows. Disables pcre pattern matching. UDP. Sets a Snort-wide minimum ttl to ignore all trafﬁc. Disables logging. Valid values are 0 to 20. which means that there is no limit on label chain length. Default is on) • bad ipv6 frag alert on|off (Specify whether or not to alert. or ICMP). followed by a list of ports. bad ipv6 frag alert on|off] [. frag timeout <secs>] [. Default is 1048576 bytes. The following options can be used: • bsd icmp frag alert on|off (Specify whether or not to alert.
26
.

Shows year in timestamps (snort -y). Restricts the amount of backtracking a given PCRE option. Note this option is only available if Snort was built to use time stats with --enable-timestats. Sets assurance mode for stream (stream is established). binding version must be in any ﬁle conﬁgured with config binding.5. eg: myref http://myurl. eg: pass alert log activation. A value of -1 allows for unlimited PCRE. same effect as -r <tf> option. Sets umask when running (snort -m). Sets UID to <id> (snort -u). Use conﬁg event ﬁlter instead. Also used to determine how to set up the logging directory structure for the session post detection rule option and ascii output plugin . Restricts the amount of stack used by a given PCRE option. A value of -1 allows for unlimited PCRE. Print statistics on rule performance.2 for more details. it will limit the number of nested repeats within a pattern. same effect as -P <snaplen> or --snaplen <snaplen> options. Adds a new reference system to Snort.an attempt is made to name the log directories after the IP address that is not in the reference net. A value of 0 results in no PCRE evaluation.5 on using the tag option when writing rules for more details. Changes GID to speciﬁed GID (snort -g). In addition. Set the snaplength of packet. Supply versioning information to conﬁguration ﬁles. This option is only useful if the value is less than the pcre match limit Exits after N packets (snort -n). See Section 2.before Snort has had a chance to load a previous conﬁguration. Disables banner and status reports (snort -q). For example.
27
. this option sets the maximum number of packets to be tagged regardless of the amount deﬁned by the other metric. Print statistics on preprocessor performance. The snort default value is 1500. Set global memcap in bytes for thresholding.config order:
<order>
config pcre match limit: <integer>
config pcre match limit recursion: <integer>
config pkt count: <N> config policy version: <base-version-string> [<binding-version-string>]
config profile preprocs config profile rules config quiet config read bin file: config reference:
<pcap>
<ref>
config reference net <cidr>
config set gid: <gid> set uid: <uid> config show year config snaplen: <bytes> config stateful config tagged packet limit: <max-tag>
config threshold:
memcap <bytes>
config timestats interval:
<secs>
config umask:
<umask>
Changes the order that rules are evaluated. See Section 3. up to the PCRE library compiled limit (around 10 million).5. Speciﬁes a pcap ﬁle to use (instead of reading from network). Setting this option to a value of 0 will disable the packet limit. up to the PCRE library compiled limit (around 10 million). See Section 2.7. Default is 1048576 bytes (1 megabyte). The default value when this option is not conﬁgured is 256 packets. The snort default value is 1500. Base version should be a string in all conﬁguration ﬁles including included ones. Default is 3600 (1 hour). the obfuscated net will be used if the packet contains an IP address in the reference net. A value of 0 results in no PCRE evaluation. (This is deprecated.) Set the amount of time in seconds between logging time stats.1 for more details.com/?id= For IP obfuscation. This option is used to avoid race conditions when modifying and loading a conﬁguration within a short time span . When a metric other than packets is used in a tag option in a rule.

it is possible to evade the IDS. Frag3 is intended as a replacement for the frag2 defragmentation module and was designed with the following goals: 1. Frag3 uses the sfxhash data structure and linked lists for data handling internally which allows it to have much more predictable and deterministic performance in any environment which should aid us in managing heavily fragmented environments. 28
. They allow the functionality of Snort to be extended by allowing users and programmers to drop modular plugins into Snort fairly easily. The basic idea behind target-based IDS is that we tell the IDS information about hosts on the network so that it can avoid Ptacek & Newsham style evasion attacks based on information about how an individual target IP stack operates. For more detail on this issue and how it affects IDS. Faster execution than frag2 with less complex data management. check out the famous Ptacek & Newsham paper at http://www.2 Preprocessors
Preprocessors were introduced in version 1. Preprocessors are loaded and conﬁgured using the preprocessor keyword. For an IDS this is a big problem. This is where the idea for “target-based IDS” came from. In an environment where the attacker can determine what style of IP defragmentation is being used on a particular target. Vern Paxson and Umesh Shankar did a great paper on this very topic in 2003 that detailed mapping the hosts on a network and determining how their various IP stack implementations handled the types of problems seen in IP defragmentation and TCP stream reassembly. When IP stacks are written for different operating systems. The packet can be modiﬁed or analyzed in an out-of-band manner using this mechanism. there are ambiguities in the way that the RFCs deﬁne some of the edge conditions that may occurr and when this happens different people implement certain aspects of their IP stacks differently. Splay trees are excellent data structures to use when you have some assurance of locality of reference for the data that you are handling but in high speed. Check it out at http://www. The frag2 preprocessor used splay trees extensively for managing the data structures associated with defragmenting packets.org/vern/papers/activemap-oak03.pdf. Target-based analysis is a relatively new concept in network-based intrusion detection.org/docs/ idspaper/. Frag3 was implemented to showcase and prototype a target-based module within Snort to test this idea. the attacker can try to fragment packets such that the target will put them back together in a speciﬁc manner while any passive systems trying to model the host trafﬁc have to guess which way the target OS is going to handle the overlaps and retransmits. heavily fragmented environments the nature of the splay trees worked against the system and actually hindered performance.
2. Target-based host modeling anti-evasion techniques.2. Uses verbose logging to STDOUT (snort -v). but after the packet has been decoded. but that’s a topic for another day. if the attacker has more information about the targets on a network than the IDS does. We can also present the IDS with topology information to avoid TTL-based evasions and a variety of other issues. The format of the preprocessor directive in the Snort rules ﬁle is: preprocessor <name>: <options>
2. The idea of a target-based system is to model the actual targets on the network instead of merely modeling the protocols and looking for attacks within them. Unfortunately.5 of Snort. they are usually implemented by people who read the RFCs and then write their interpretation of what the RFC outlines into code.config utc config verbose
Uses UTC instead of local time for timestamps (snort -U).icir. As I like to say. 2. Once we have this information we can start to really change the game for these complex modeling problems.1 Frag3
The frag3 preprocessor is a target-based IP defragmentation module for Snort.snort. Preprocessor code is run before the detection engine is called.

bsd. This is an optional parameter. – policy <type> . Fragments in the engine for longer than this period will be automatically dropped. This engine will only run for packets with destination addresses contained within the IP List. detect anomalies option must be conﬁgured for this option to take effect. Default is 8192.Memory cap for self preservation. Default type is bsd. and the maximum is ”255”. Available types are ﬁrst.Minimum acceptable TTL value for a fragment packet.Deﬁnes smallest fragment size (payload size) that should be considered valid. bsdright. – timeout <seconds> . Fragments smaller than or equal to this limit are considered malicious and an event is raised. if detect anomalies is also conﬁgured. detect anomalies option must be conﬁgured for this option to take effect. Default value is all. – min fragment length <number> . The default is ”0” (unlimited). linux. – memcap <bytes> . There are at least two preprocessor directives required to activate frag3. – prealloc frags <number> . Default is 1. Default is 60 seconds.Frag 3 Conﬁguration Frag3 conﬁguration is somewhat more complex than frag2. – min ttl <value> . Anyone who develops more mappings and would like to add to this list please feel free to send us an email!
29
. a global conﬁguration directive and an engine instantiation. last. This is an optional parameter. There can be an arbitrary number of engines deﬁned at startup with their own conﬁguration.Detect fragment anomalies.Alternate memory management mode.Limits the number of overlapping fragments per packet.Maximum simultaneous fragments to track.Timeout for fragments. The known mappings are as follows. the minimum is ”0”.Select a target-based defragmentation mode. – overlap limit <number> . – max frags <number> . – detect anomalies . and the maximum is ”255”. – bind to <ip list> .IP List to bind this engine to. Engine Conﬁguration • Preprocessor name: frag3 engine • Available options: NOTE: Engine conﬁguration options are space separated. but only one global conﬁguration. The Paxson Active Mapping paper introduced the terminology frag3 is using to describe policy types. Global Conﬁguration • Preprocessor name: frag3 global • Available options: NOTE: Global conﬁguration options are comma separated. Use preallocated fragment nodes (faster in some situations). The default is ”0” (unlimited). the minimum is ”0”. Default is 4MB.

[show_rebuilt_packets]. \ [memcap <number bytes>]. introduces target-based actions for handling of overlapping data and other TCP anomalies. Some of these anomalies are detected on a per-target basis.Frag 3 Alert Output Frag3 is capable of detecting eight different types of anomalies. etc. [max_tcp <number>]. Data on SYN. Target-Based Stream5. such as data on SYN packets.2 Stream5
The Stream5 preprocessor is a target-based TCP reassembly module for Snort. It is capable of tracking sessions for both TCP and UDP. Stream API Stream5 fully supports the Stream API. The methods for handling overlapping data. Anomaly Detection TCP protocol anomalies. UDP sessions are established as the result of a series of UDP packets from two end points via the same set of ports. Its event output is packet-based so it will work with all output modes of Snort.2. ICMP messages are tracked for the purposes of checking for unreachable and service unavailable messages. [max_udp <number>]. and the policies supported by Stream5 are the results of extensive research with many target operating systems. identify sessions that may be ignored (large data transfers. which effectively terminate a TCP or UDP session. \ [track_icmp <yes|no>]. data received outside the TCP window. and update the identifying information about the session (application protocol. \ [track_udp <yes|no>]. etc are conﬁgured via the detect anomalies option to the TCP conﬁguration. a few operating systems allow data in TCP SYN packets. \ [flush_on_alert]. Transport Protocols TCP sessions are identiﬁed via the classic TCP ”connection”. preprocessor stream5_global: \ [track_tcp <yes|no>]. With Stream5.
2. like Frag3. \ [prune_log_max <bytes>]
31
. while others do not. etc). Stream5 Global Conﬁguration Global settings for the Stream5 preprocessor. direction. TCP Timestamps. the rule ’ﬂow’ and ’ﬂowbits’ keywords are usable with TCP as well as UDP trafﬁc. Read the documentation in the doc/signatures directory with ﬁlenames that begin with “123-” for information on the different event types. FIN and Reset sequence numbers. other protocol normalizers/preprocessors to dynamically conﬁgure reassembly behavior as required by the application layer protocol. etc) that can later be used by rules. For example. [max_icmp <number>].

The default is set to any. [max_window <number>]. maximum is ”1052672”. [max_queued_segs <number segs>]. One default policy must be speciﬁed. The default is set to off. preprocessor stream5_tcp: \ [bind_to <ip_addr>]. Print/display packet after rebuilt (for debugging). maximum is not bounded. Track sessions for ICMP. \ [ignore_any_rules] Option bind to <ip addr> timeout <num seconds> Description IP address or network for this policy. The default is ”yes”. Memcap for TCP packet storage.
32
. Flush a TCP stream when an alert is generated on that stream. [use_static_footprint_sizes]. minimum is ”32768” (32KB). Maximum simultaneous ICMP sessions tracked. minimum is ”0” (unlimited). other than by the memcap. [detect_anomalies].Option track tcp <yes|no> max tcp <num sessions> memcap <num bytes> track udp <yes|no> max udp <num sessions> track icmp <yes|no> max icmp <num sessions> flush on alert show rebuilt packets prune log max <num bytes>
Description Track sessions for TCP. The default is ”128000”. maximum is ”1073741824” (1GB). \ [check_session_hijacking]. maximum is ”1052672”. Session timeout. The default is ”64000”. and that policy is not bound to an IP address or network. [timeout <number secs>]. minimum is ”1”. Track sessions for UDP. maximum is ”1052672”. the minimum is ”1”. [min_ttl <number>]. minimum is ”1”. [dont_reassemble_async]. \ [ports <client|server|both> <all|number [number]*>]. The default is ”1048576” (1MB). \ [dont_store_large_packets]. This can have multiple occurances. per policy that is bound to an IP address or network. \ [max_queued_bytes <bytes>]. \ [overlap_limit <number>]. Print a message when a session terminates that was consuming more than the speciﬁed number of bytes. Maximum simultaneous TCP sessions tracked. The default is ”yes”. The default is ”8388608” (8MB). minimum is ”1”. The default is ”30”. \ [require_3whs [<number secs>]]. \ [policy <policy_id>]. Backwards compatibilty. Maximum simultaneous UDP sessions tracked.
Stream5 TCP Conﬁguration Provides a means on a per IP address target to conﬁgure TCP policy. and the maximum is ”86400” (approximately 1 day). The default is set to off. The default is ”yes”. The default is ”256000”.

Use static values for determining when to build a reassembled packet to allow for repeatable tests.x and newer linux Linux 2. This check validates the hardware (MAC) address from both sides of the connect – as established on the 3-way handshake against subsequent packets received on the session.x and newer hpux HPUX 11 and newer hpux10 HPUX 10 irix IRIX 6 and newer macos MacOS 10. Alerts are generated (per ’detect anomalies’ option) for either the client or server when the MAC address for one side or the other does not match. The policy id can be one of the following: Policy Name Operating Systems. Using this option may result in missed attacks. first Favor ﬁrst overlapped segment. The default is ”0” (don’t consider existing sessions established). with a non-zero minimum of ”1024”. Windows XP. The default is ”0” (unlimited).x and newer.2 and earlier windows Windows 2000. The default is set to off. The default is set to off. A value of ”0” means unlimited. and the maximum is ”1073725440” (65535 left shift 14). and the maximum is ”86400” (approximately 1 day).3 and newer Minimum TTL. The default is set to off. This allows a grace period for existing sessions to be considered established during that interval immediately after Snort is started.4 and newer old-linux Linux 2. If an ethernet layer is not part of the protocol stack received by Snort.x and newer. bsd FresBSD 4. Windows 95/98/ME win2003 Windows 2003 Server vista Windows Vista solaris Solaris 9. last Favor ﬁrst overlapped segment. The optional number of seconds speciﬁes a startup timeout. Performance improvement to not queue large packets in reassembly buffer. the minimum is ”0”. The default is ”1”. the minimum is ”0”. Detect and alert on TCP protocol anomalies. Establish sessions only on completion of a SYN/SYN-ACK/ACK handshake. Limit the number of bytes queued for reassembly on a given TCP session to bytes. The default is set to off. Limits the number of overlapping packets per session. Maximum TCP window allowed. and a maximum of ”1073741824” (1GB).policy <policy id>
min ttl <number> overlap limit <number> max window <number>
require 3whs [<number seconds>]
detect anomalies check session hijacking
use static footprint sizes
dont store large packets
dont reassemble async max queued bytes <bytes>
The Operating System policy for the target OS. there are no checks performed. The default is set to queue packets. and the maximum is ”255”. NetBSD 2. so using a value near the maximum is discouraged. the minimum is ”1” and the maximum is ”255”. Default is ”1048576” (1MB). This option is intended to prevent a DoS against Stream5 by an attacker using an abnormally large window. Don’t queue packets for reassembly if trafﬁc has not been seen in both directions. Check for TCP session hijacking. A message is written to console/syslog when this limit is enforced. This option should not be used production environments. The default is set to off.
33
. OpenBSD 3. That is the highest possible TCP window per RFCs. the minimum is ”0”. The default is ”0” (unlimited).

and the maximum is ”86400” (approximately 1 day). and a maximum of ”1073741824” (1GB). Don’t process any -> any (ports) rules for UDP that attempt to match payload if there are no port speciﬁc rules for the src or destination port.max queued segs <num>
ports <client|server|both> <all|number(s)>
ignore any rules
Limit the number of segments queued for reassembly on a given TCP session. only those with content. a UDP rule will be ignored except when there is another port speciﬁc rule that may be applied to the trafﬁc. PCRE. derived based on an average size of 400 bytes. PCRE.
34
. but NOT to any other source or destination port. For example.
! △NOTE
With the ignore any rules option. if a UDP rule that uses any -> any ports includes either ﬂow or ﬂowbits. Since there is no target based binding.
! △NOTE
If no options are speciﬁed for a given TCP policy. [ignore_any_rules] Option timeout <num seconds> ignore any rules Description Session timeout. server. The default is ”30”. there should be only one occurance of the UDP conﬁguration. Using this does not affect rules that look at protocol headers. Don’t process any -> any (ports) rules for TCP that attempt to match payload if there are no port speciﬁc rules for the src or destination port. Rules that have ﬂow or ﬂowbits will never be ignored.
! △NOTE
With the ignore any rules option. This is a performance improvement and may result in missed attacks. A message is written to console/syslog when this limit is enforced. Rules that have ﬂow or ﬂowbits will never be ignored. or both and list of ports in which to perform reassembly. the minimum is ”1”. Specify the client. The default settings are ports client 21 23 25 42 53 80 110 111 135 136 137 139 143 445 513 514 1433 1521 2401 3306. A list of rule SIDs affected by this option are printed at Snort’s startup. This is a performance improvement and may result in missed attacks. This can appear more than once in a given conﬁg. If only a bind to option is used with no other options that TCP policy uses all of the default values. This option can be used only in default policy. Because of the potential impact of disabling a ﬂowbits rule. The default is ”off”. The default is ”2621”. with a non-zero minimum of ”2”. The default is ”off”.
Stream5 UDP Conﬁguration Conﬁguration for UDP session tracking. if a UDP rule speciﬁes destination port 53. The minimum port allowed is ”1” and the maximum allowed is ”65535”. or byte test options. the ignore any rules option is effectively pointless. that is the default TCP policy. the ’ignored’ any -> any rule will be applied to trafﬁc to/from port 53. only those with content. or byte test options. Using this does not affect rules that look at protocol headers. the ignore any rules option will be disabled in this case. A value of ”0” means unlimited. preprocessor stream5_udp: [timeout <number secs>].

all of which relate to TCP anomalies. There are no anomalies detected relating to UDP or ICMP. preprocessor stream5_global: \ max_tcp 8192. with all other trafﬁc going to the default policy of Solaris. Data sent on stream not accepting data 4. The list of SIDs is as follows: 1. Data after Reset packet 35 stream5_global: track_tcp yes stream5_tcp: bind_to 192. track_udp yes. preprocessor stream5_icmp: [timeout <number secs>] Option timeout <num seconds> Description Session timeout.Stream5 ICMP Conﬁguration Conﬁguration for ICMP session tracking. track_tcp yes. preprocessor preprocessor preprocessor preprocessor Alerts Stream5 uses generator ID 129. This example conﬁguration is the default conﬁguration in snort.0/24.conf and can be used for repeatable tests of stream reassembly in readback mode.1. It is not ICMP is currently
turned on by default. track_icmp no preprocessor stream5_tcp: \ policy first.0/24.
! △NOTE untested. in minimal code form and is NOT ready for use in production networks. Window size (after scaling) larger than policy allows 7. Data on SYN packet 3. Since there is no target based binding. The default is ”30”. SYN on established session 2. use_static_footprint_sizes preprocessor stream5_udp: \ ignore_any_rules 2. and the maximum is ”86400” (approximately 1 day). overlap adjusted size less than/equal 0 6.1. policy windows stream5_tcp: bind_to 10. policy linux stream5_tcp: policy solaris
. Limit on number of overlapping TCP packets reached 8. the minimum is ”1”.168. This conﬁguration maps two network segments to different OS policies. Bad segment.
Example Conﬁgurations 1. TCP Timestamp is outside of PAWS window 5. there should be only one occurance of the ICMP conﬁguration.1. It is capable of alerting on 8 (eight) anomalies. one for Windows and one for Linux.

developed by Sourceﬁre. this phase would not be necessary. most queries sent by the attacker will be negative (meaning that the service ports are closed). of the current portscanning techniques. Most of the port queries will be negative. This tactic helps hide the true identity of the attacker. As the attacker has no beforehand knowledge of its intended target. since most hosts have relatively few services available. Distributed portscans occur when multiple hosts query one host for open services. In the Reconnaissance phase. negative responses from hosts are rare. This phase assumes the attacking host has no prior knowledge of what protocols or services are supported by the target. This is the traditional place where a portscan takes place.2. so we track this type of scan through the scanned host. one host scans multiple ports on another host. if not all.2. an attacker determines what types of network protocols or services a host supports. otherwise. sfPortscan alerts for the following types of distributed portscans: • TCP Distributed Portscan • UDP Distributed Portscan • IP Distributed Portscan These are many→one portscans. In the nature of legitimate network communications. sfPortscan was designed to be able to detect the different types of scans Nmap can produce. sfPortscan also alerts for the following types of decoy portscans: • TCP Decoy Portscan • UDP Decoy Portscan • IP Decoy Portscan Decoy portscans are much like the Nmap portscans described above. One of the most common portscanning tools in use today is Nmap. sfPortscan will currently alert for the following types of Nmap scans: • TCP Portscan • UDP Portscan • IP Portscan These alerts are for one→one portscans.
! △NOTE
Negative queries will be distributed among scanning hosts. This is used to evade an IDS and obfuscate command and control hosts.
sfPortscan alerts for the following types of portsweeps: • TCP Portsweep • UDP Portsweep • IP Portsweep 36
. Nmap encompasses many. and rarer still are multiple negative responses within a given amount of time. Our primary objective in detecting portscans is to detect and track these negative responses. is designed to detect the ﬁrst phase in a network attack: Reconnaissance. only the attacker has a spoofed source address inter-mixed with the real scanning address. which are the traditional types of scans.3 sfPortscan
The sfPortscan module.

! △NOTE
The characteristics of a portsweep scan may not result in many negative responses. A ﬁltered alert may go off before responses from the remote hosts are received. It’s also a good indicator of whether the alert is just a very active legitimate host. You should enable the Stream preprocessor in your snort. proto <protocol> Available options: • TCP 37
. For example. as described in Section 2. Active hosts. can trigger these alerts because they can send out many connection attempts within a very small amount of time.• ICMP Portsweep These alerts are for one→many portsweeps. sfPortscan Conﬁguration Use of the Stream5 preprocessor is required for sfPortscan. Stream gives portscan direction in the case of connectionless protocols like ICMP and UDP. This usually occurs when a new exploit comes out and the attacker is looking for a speciﬁc service.conf. The parameters you can use to conﬁgure the portscan module are: 1. On TCP sweep alerts however. sfPortscan will only track open ports after the alert has been triggered. sfPortscan only generates one alert for each host pair in question during the time window (more on windows below).2. On TCP scan alerts. One host scans a single port on multiple hosts. but tags based on the orginal scan alert.2. Open port events are not individual alerts.
sfPortscan alerts on the following ﬁltered portscans and portsweeps: • TCP Filtered Portscan • UDP Filtered Portscan • IP Filtered Portscan • TCP Filtered Decoy Portscan • UDP Filtered Decoy Portscan • IP Filtered Decoy Portscan • TCP Filtered Portsweep • UDP Filtered Portsweep • IP Filtered Portsweep • ICMP Filtered Portsweep • TCP Filtered Distributed Portscan • UDP Filtered Distributed Portscan • IP Filtered Distributed Portscan “Filtered” alerts indicate that there were no network errors (ICMP unreachables or TCP RSTs) or responses on closed ports have been suppressed. sfPortscan will also display any open ports that were scanned. we will most likely not see many negative responses. such as NATs. if an attacker portsweeps a web farm for port 80.

38
. 9. logﬁle <ﬁle> This option will output portscan events to the ﬁle speciﬁed. which is why the option is off by default. The parameter is the same format as that of watch ip. The parameter is the same format as that of watch ip. • high . this can lead to false alerts. ports are speciﬁed after the IP address/CIDR using a space and can be either a single port or a range denoted by a dash. ignore scanners <ip1|ip2/cidr[ [port|port2-port3]]> Ignores the source of scan alerts.• UDP • IGMP • ip proto • all 2. which is necessary to detect ACK scans. 7. 4. This setting may false positive on active hosts (NATs. especially under heavy load with dropped packets. Optionally. DNS caches. networks. especially under heavy load with dropped packets. A ”High” setting will catch some slow scans because of the continuous monitoring. afterwhich this window is reset.“High” alerts continuously track hosts on a network using a time window to evaluate portscan statistics for that host. this ﬁle will be placed in the Snort conﬁg dir. However. This most deﬁnitely will require the user to tune sfPortscan. This can lead to false alerts.“Medium” alerts track connection counts. and so will generate ﬁltered scan alerts. However. proxies. include midstream This option will include sessions picked up in midstream by Stream5. so the user may need to deploy the use of Ignore directives to properly tune this directive. detect ack scans This option will include sessions picked up in midstream by the stream module. etc). The list is a comma separated list of IP addresses. • medium . 8. This setting is based on a static time window of 60 seconds. this setting will never trigger a Filtered Scan alert because of a lack of error responses. but is very sensitive to active hosts. If file does not contain a leading slash. 5. IPs or networks not falling into this range are ignored if this option is used. and because of the nature of error responses. scan type <scan type> Available options: • portscan • portsweep • decoy portscan • distributed portscan • all 3.“Low” alerts are only generated on error packets sent from the target host. this setting should see very few false postives. sense level <level> Available options: • low . IP address using CIDR notation. ignore scanned <ip1|ip2/cidr[ [port|port2-port3]]> Ignores the destination of scan alerts. 6. which is why the option is off by default. and speciﬁc ports on those hosts to watch. watch ip <ip1|ip2/cidr[ [port|port2-port3]]> Deﬁnes which IPs.

snort generates a pseudo-packet and uses the payload portion to store the additional portscan information of priority count. The size tends to be around 100 . port count.603881 event_ref: 2 39
. etc. one or more additional tagged packet(s) will be appended: Time: 09/08-15:07:31. The payload and payload size of the packet are equal to the length of the additional portscan information that is logged.168.603880 event_id: 2 192. and port range. connection count.3 -> 192. Log File Output Log ﬁle output is displayed in the following format.169. because open port alerts utilize the tagged packet output system. the packet looks like the IP portion of the packet that caused the portscan alert to be generated. The open port information is stored in the IP payload and contains the port that is open. so it is possible to extend favorite Snort GUIs to display portscan alerts and the additional information in the IP payload using the above packet characteristics.169.3:192. This means that if an output system that doesn’t print tagged packets is used. Open port alerts differ from the other portscan alerts. The characteristics of the packet are: Src/Dst MAC Addr == MACDAD IP Protocol == 255 IP TTL == 0 Other than that. This includes any IP options.169. then the user won’t see open port alerts.200 bytes.168. IP count.168.5 (portscan) TCP Filtered Portscan Priority Count: 0 Connection Count: 200 IP Count: 2 Scanner IP Range: 192. The sfPortscan alert output was designed to work with uniﬁed packet logging.168.Format preprocessor sfportscan: proto <protocols> \ scan_type <portscan|portsweep|decoy_portscan|distributed_portscan|all> \ sense_level <low|medium|high> \ watch_ip <IP or IP/CIDR> \ ignore_scanners <IP list> \ ignore_scanned <IP list> \ logfile <path and filename> Example preprocessor flow: stats_interval 0 hash 2 preprocessor sfportscan:\ proto { all } \ scan_type { all } \ sense_level { low } sfPortscan Alert Output Uniﬁed Output In order to get all the portscan information logged with the alert. IP range. and explained further below: Time: 09/08-15:07:31.4 Port/Proto Count: 200 Port/Proto Range: 20:47557 If there are open ports on the target.169.

3. and nfs servers. Filtered scan alerts are much more prone to false positives. The ignore scanners and ignore scanned options come into play in weeding out legitimate hosts that are very active on your network. If the host is generating portscan alerts (and is the host that is being scanned). Depending on the type of alert that the host generates. then add it to the ignore scanners option. and increments the count if the next IP is different. Whether or not a portscan was ﬁltered is determined here. add it to the ignore scanned option.169. sfPortscan will watch all network trafﬁc. Priority Count Priority Count keeps track of bad responses (resets. but be aware when ﬁrst tuning sfPortscan for these IPs. and one-to-one scans may appear as a distributed scan. 2. and Port Range to determine false positives. This is accurate for connection-based protocols. When determining false positives. Port Count. and is more of an estimate for others. For one-to-one scans. Make use of the Priority Count.5 (portscan) Open Port Open Port: 38458 1. Use the watch ip. IP Count IP Count keeps track of the last IP to contact a host. the analyst will know which to ignore it as. The watch ip option is easy to understand. sfPortscan may not generate false positives for these types of hosts. We use this count (along with IP Count) to determine the difference between one-to-one portscans and one-to-one decoys. Some of the most common examples are NAT IPs. add it to the ignore scanners list or use a lower sensitivity level. Event id/Event ref These ﬁelds are used to link an alert with the corresponding Open Port tagged packet 2. syslog servers.168. Here are some tuning tips: 1. Portsweep (one-to-many) scans display the scanned IP range. DNS cache servers. Scanned/Scanner IP Range This ﬁeld changes depending on the type of alert. Connection Count Connection Count lists how many connections are active on the hosts (src or dst). ignore scanners. Portscans (one-to-one) display the scanner IP.169.192. 5. The analyst should set this option to the list of Cidr blocks and IPs that they want to watch. Tuning sfPortscan The most important aspect in detecting portscans is tuning the detection engine for your network(s). If the host is generating portsweep events. IP Range. If the host continually generates these types of alerts. Many times this just indicates that a host was very active during the time period in question. the more bad responses have been received. 3. So be much more suspicious of ﬁltered portscans.
40
. The higher the priority count. High connection count and low priority count would indicate ﬁltered (no response received from target). and ignore scanned options. this is a low number. 4. Port Count Port Count keeps track of the last port contacted and increments this number when that changes.3 -> 192.168. Connection Count. If no watch ip is deﬁned. It’s important to correctly set these options. IP Count. 6. Most of the false positives that sfPortscan may generate are of the ﬁltered scan alert type. the alert type is very important. For active hosts this number will be high regardless. unreachables).

For portscans. lower the sensitivity level. lower the sensitivity level.2. the higher the better. Don’t alert when a single fragment record exceeds the size of one packet. indicating that the scanning host connected to few ports but on many hosts.
2. it will only process client-side trafﬁc. this ratio should be low.2. this ratio should be high and indicates that the scanned host’s ports were connected to by fewer IPs. If all else fails.4 RPC Decode
The rpc decode preprocessor normalizes RPC multiple fragmented records into a single un-fragmented record. it runs against trafﬁc on ports 111 and 32771. where statistics get printed to the speciﬁed ﬁle name. is because the priority count is included in the connection count and the above comparisons take that into consideration. The Priority Count play an important role in tuning because the higher the priority count the more likely it is a real portscan or portsweep (unless the host is ﬁrewalled). The following is a list of ratios to estimate and the associated values that indicate a legimite scan and not a false positive. Don’t alert when the sum of fragmented records exceeds one packet. Connection Count / Port Count: This ratio indicates an estimated average of connections per port. In the future. Don’t alert when there are multiple records in one packet. For portsweeps. this ratio should be high. This indicates that each connection was to a different port. but it’s also important that the portscan detection engine generate alerts that the analyst will ﬁnd informative. The low sensitivity level only generates alerts based on error responses. 4. we hope to automate much of this analysis in assigning a scope level and conﬁdence level. Snort’s real-time statistics are processed. For portscans. By default. Format preprocessor rpc_decode: \ <ports> [ alert_fragments ] \ [no_alert_multiple_requests] \ [no_alert_large_fragments] \ [no_alert_incomplete] Option alert fragments no alert multiple requests no alert large fragments no alert incomplete Description Alert on any fragmented RPC record. but for now the user must manually do this. Connection Count / IP Count: This ratio indicates an estimated average of connections per IP. For portsweeps. this ratio should be low. either “console” which prints statistics to the console window or “ﬁle” with a ﬁle name. It does this by normalizing the packet into the packet buffer. Port Count / IP Count: This ratio indicates an estimated average of ports connected to per IP. These responses indicate a portscan and the alerts generated by the low sensitivity level are highly accurate and require the least tuning. The easiest way to determine false positives is through simple ratio estimations. By default. Whenever this preprocessor is turned on. this ratio should be low. The low sensitivity level does not catch ﬁltered scans. since these are more prone to false positives.The portscan alert details are vital in determining the scope of a portscan and also the conﬁdence of the portscan. If stream5 is enabled. The reason that Priority Count is not included.
2. This includes: 41
. For portscans. it should have an output mode enabled. this ratio should be high. For portsweeps. This indicates that there were many connections to the same port.5 Performance Monitor
This preprocessor measures Snort’s real-time and theoretical maximum performance. You get the best protection the higher the sensitivity level. If none of these other tuning techniques work or the analyst doesn’t have the time for tuning.

This means that HTTP Inspect looks for HTTP ﬁelds on a packet-by-packet basis. The minimum is 4096 bytes and the maximum is 2147483648 bytes (2GB).Prints statistics at the console.Deﬁnes the maximum size of the comma-delimited ﬁle. • file . You may also use snortfile which will output into your deﬁned Snort log directory.Adjusts the number of packets to process before checking for the time sample.Prints statistics in a comma-delimited format to the ﬁle that is speciﬁed. • max file size . • console . By default.• uSeconds/Pkt (snifﬁng) • uSeconds/Pkt (combined) • KPkts/Sec (Snort) • KPkts/Sec (snifﬁng) • KPkts/Sec (combined) The following options can be used with the performance monitor: • flow .Turns on event reporting.Deﬁnes which type of drop statistics are kept by the operating system. Given a data buffer. HTTP Inspect works on both client requests and server responses. this is 10000.2. HTTP Inspect will decode the buffer. The current version of HTTP Inspect only handles stateless processing. reset is used. followed by YYYY-MM-DD. • max .Prints out statistics about the type of trafﬁc and protocol distributions that Snort is seeing.Turns on the theoretical maximum performance that Snort calculates given the processor speed and current performance. This shows the user if there is a problem with the rule set that they are running.x. it will be rolled into a new date stamped ﬁle of the format YYYY-MM-DD. This prints out statistics as to the number of signatures that were matched by the setwise pattern matcher (non-qualiﬁed events) and the number of those matches that were veriﬁed with the signature ﬂags (qualiﬁed events). Before the ﬁle exceeds this size. This option can produce large amounts of output. • pktcnt . By default.6 HTTP Inspect
HTTP Inspect is a generic HTTP decoder for user applications.Dump stats for entire life of Snort. • accumulate or reset . since many operating systems don’t keep accurate kernel statistics for multiple CPUs. The default is the same as the maximum. ﬁnd HTTP ﬁelds. This is only valid for uniprocessor machines.Represents the number of seconds between intervals. where x will be incremented each time the comma delimiated ﬁle is rolled over. and will be fooled if packets are not reassembled. • atexitonly . and normalize the ﬁelds. Not all statistics are output to this ﬁle.profile max console pktcnt 10000 preprocessor perfmonitor: \ time 300 file /var/tmp/snortstat pktcnt 10000
2. since checking the time sample reduces Snort’s performance. Both of these directives can be overridden on the command line with the -Z or --perfmon-file options. This boosts performance. • events . Examples preprocessor perfmonitor: \ time 30 events flow file stats. This works ﬁne when there is 44
. • time .

conf or be speciﬁed via a fully-qualiﬁed path to the map ﬁle. The following example gives the generic global conﬁguration format: Format preprocessor http_inspect: \ global \ iis_unicode_map <map_filename> \ codemap <integer> \ [detect_anomalous_servers] \ [proxy_alert] You can only have a single global conﬁguration. So. Global Conﬁguration The global conﬁguration deals with conﬁguration options that determine the global functioning of HTTP Inspect.
! △NOTE
Remember that this conﬁguration is for the global IIS Unicode map. In the future. detect anomalous servers This global conﬁguration option enables generic HTTP server trafﬁc inspection on non-HTTP conﬁgured ports. there are two areas of conﬁguration: global and server.
45
.snort. iis unicode map <map filename> [codemap <integer>] This is the global iis unicode map ﬁle. the codemap is usually 1252. By conﬁguring HTTP Inspect servers and enabling allow proxy use. individual servers can reference their own IIS Unicode map. Please note that if users aren’t required to conﬁgure web proxy use. but there are limitations in analyzing the protocol. HTTP Inspect has a very “rich” user conﬁguration. The iis unicode map is a required conﬁguration parameter.another module handling the reassembly. 2. Within HTTP Inspect. but for right now. this inspects all network trafﬁc. Conﬁguration 1. A tool is supplied with Snort to generate custom Unicode maps--ms unicode generator. which is available at http://www. which should allow the user to emulate any type of web server. Future versions will have a stateful processing mode which will hook into various reassembly modules. 3. you will only receive proxy use alerts for web users that aren’t using the conﬁgured proxies or are using a rogue proxy server. proxy alert This enables global alerting on HTTP server proxy usage. please only use this feature with traditional proxy environments.org/ dl/contrib/. For US servers. we want to limit this to speciﬁc networks so it’s more useful. Don’t turn this on if you don’t have a default server conﬁguration that encompasses all of the HTTP server ports that your users might access. The map ﬁle can reside in the same directory as snort.c. A Microsoft US Unicode codepoint map is provided in the Snort source etc directory by default. then you may get a lot of proxy alerts.map and should be used if no other codepoint map is available. Users can conﬁgure individual HTTP servers with a variety of options. you’ll get an error if you try otherwise. Blind ﬁrewall proxies don’t count. It is called unicode. The iis unicode map ﬁle is a Unicode codepoint map which tells HTTP Inspect which codepage to use when decoding Unicode characters. and alerts if HTTP trafﬁc is seen.

This argument speciﬁes whether the user wants the conﬁguration option to generate an HTTP Inspect alert or not. apache. Example Multiple IP Conﬁguration preprocessor http_inspect_server: \ server { 10.1 profile all ports { 80 } Conﬁguration by Multiple IP Addresses This format is very similar to “Conﬁguration by IP Address”.Example Global Conﬁguration preprocessor http_inspect: \ global iis_unicode_map unicode.1. only the alerting functionality.map 1252 Server Conﬁguration There are two types of server conﬁgurations: default and by IP address. the only difference being that speciﬁc IPs can be conﬁgured. but are not required for proper operation. The ‘yes/no’ argument does not specify whether the conﬁguration option itself is on or off.1. There is a limit of 40 IP addresses or CIDR notations per http inspect server line.2.1. HTTP normalization will still occur. Example Default Conﬁguration preprocessor http_inspect_server: \ server default profile all ports { 80 } Conﬁguration by IP Address This format is very similar to “default”. This is a great proﬁle for detecting all types of attacks.2. regardless of the HTTP server. We alert on the more serious forms of evasions. all The all proﬁle is meant to normalize the URI using most of the common tricks available.0/24 } profile all ports { 80 } Server Conﬁguration Options Important: Some conﬁguration options have an argument of ‘yes’ or ‘no’. Proﬁles allow the user to easily conﬁgure the preprocessor for a certain type of server.1 10. 1.1.3. profile all sets the conﬁguration options described in Table 2. Default This conﬁguration supplies the default server conﬁguration for any server that is not individually conﬁgured. the only difference being that multiple IPs can be speciﬁed via a space separated list. There are ﬁve proﬁles available: all. In other words. 1-A. iis5 0. and rules based on HTTP trafﬁc will still trigger. iis. and iis4 0. Most of your web servers will most likely end up using the default conﬁguration. profile <all|apache|iis|iis5 0|iis4 0> Users can conﬁgure HTTP Inspect by using pre-deﬁned HTTP server proﬁles. whether set to ‘yes’ or ’no’.
46
. Example IP Conﬁguration preprocessor http_inspect_server: \ server 10.

It is similar to server flow depth (above). For US servers. A value of -1 causes Snort to ignore all server side trafﬁc for ports deﬁned in ports. HTTPS trafﬁc is encrypted and cannot be decoded with HTTP Inspect. It primarily eliminates Snort fro inspecting larger HTTP Cookies that appear at the end of many client request Headers. Headers are usually under 300 bytes long. it’s the ANSI code page. iis unicode map <map filename> codemap <integer> The IIS Unicode map is generated by the program ms unicode generator. This increases the perfomance by inspecting only speciﬁed bytes in the post message. use the SSL preprocessor.• • • • • • • • •
client flow depth post depth no alerts inspect uri only oversize dir length normalize headers normalize cookies max header length max headers
These options must be speciﬁed after the profile option. This option signiﬁcantly increases IDS performance because we are ignoring a large part of the network trafﬁc (HTTP server response payloads). Executing this program generates a Unicode map for the system that it was run on. Most of these rules target either the HTTP header. but your mileage may vary. this is usually 1252. To ignore HTTPS trafﬁc. >]} This is how the user conﬁgures which ports to decode on the HTTP server. 3. You can select the correct code page by looking at the available code pages that the ms unicode generator outputs. you run this program on that server and use that Unicode map in this conﬁguration. server flow depth <integer> This speciﬁes the amount of server response payload to inspect. Values above 0 tell Snort the number of bytes to inspect in the ﬁrst packet of the server response. The value can be set from 0 to 65495.snort. the user needs to specify the ﬁle that contains the IIS Unicode map and also specify the Unicode map to use. which will be deprecated in a future release. Example preprocessor http_inspect_server: \ server 1.. The default value is 0. 49
. This program is located on the Snort.c.. When using this option. and has a default value of 300.1. a value of 0 causes Snort to inspect all HTTP server payloads deﬁned in ports (note that this will likely slow down IDS performance). So. 4. Inversely. client flow depth <integer> This speciﬁes the amount of raw client request payload to inspect.1 profile all ports { 80 3128 } 2. or the content that is likely to be in the ﬁrst hundred or so bytes of non-header data.1.
! △NOTE
server flow depth is the same as the old flow depth option. to get the speciﬁc Unicode mappings for an IIS web server.org web site at http://www. But the ms unicode generator program tells you which codemap to use for you server. 6. 5. A small percentage of Snort rules are targeted at this trafﬁc and a small ﬂow depth value may cause false negatives in some of these rules.org/dl/contrib/ directory. This value can be set from -1 to 1460. post depth <integer> This speciﬁes the amount of data to inspect in a client post message. ports {<port> [<port>< . However.

Bare byte encoding allows the user to emulate an IIS server and interpret non-standard encodings correctly. ASCII and UTF-8 decoding are also enabled to enforce correct decoding. iis unicode uses the default codemap.k. double decode <yes|no> The double decode option is once again IIS-speciﬁc and emulates IIS functionality. like %uxxxx. If %u encoding is enabled.a %2f = /. but this will be prone to false positives as legitimate web clients use this type of encoding. When utf 8 is enabled. How the %u encoding scheme works is as follows: the encoding scheme is started by a %u followed by 4 characters.. You should alert on %u encodings. How this works is that IIS does two passes through the request URI. ASCII encoding is also enabled to enforce correct behavior. This is not in the HTTP standard. You have to use the base36 option with the utf 8 option. ascii. because there are no legitimate clients that encode UTF-8 this way since it is non-standard. 12. The xxxx is a hex-encoded value that correlates to an IIS Unicode codepoint. An ASCII character is encoded like %u002f = /. so it is recommended that you disable HTTP Inspect alerting for this option.yk. bare byte. u encode <yes|no> This option emulates the IIS %u encoding scheme. it seems that all types of iis encoding is done: utf-8 unicode. and %u. It is normal to see ASCII encoding usage in URLs. If no iis unicode map is speciﬁed before or after this option. base36 <yes|no> This is an option to decode base36 encoded chars. so be careful. non rfc char {<byte> [<byte . ascii <yes|no> The ascii decode option tells us whether to decode encoded ASCII chars. As for alerting. this option will not work. When iis unicode is enabled. 13. and then UTF-8 is decoded in the second stage. as all non-ASCII values have to be encoded with a %. You should alert on the iis unicode option. This option is based on info from: http://www. 11.patch. When double decode is enabled. The iis unicode option handles the mapping of non-ASCII codepoints that the IIS server accepts and decodes normal UTF-8 requests. In the ﬁrst pass. When base36 is enabled. iis unicode <yes|no> The iis unicode option turns on the Unicode codepoint mapping.jp/˜ shikap/patch/spp\_http\_decode.>]} This option lets users receive an alert if certain non-RFC chars are used in a request URI. In the second pass.or. so for any Apache servers. Don’t use the %u option. the following encodings are done: ascii. To alert on UTF-8 decoding.. Please use this option with care. etc.rim. bare byte. 9. It’s ﬂexible. because we are not aware of any legitimate clients that use this encoding. because you could conﬁgure it to say. Anyway. doing decodes in each one. the default codemap is used. This value can most deﬁnitely be ASCII. Apache uses this standard. 14. We leave out utf-8 because I think how this works is that the % encoded utf-8 is decoded to the Unicode byte in the ﬁrst pass.7. For instance. 8. 10.. a user may not want to see null bytes in the request URI and we can alert on that. %u002e = .. 50
. this is really complex and adds tons of different encodings for one character. If there is no iis unicode map option speciﬁed with the server conﬁg. a. because it is seen mainly in attacks and evasion attempts. bare byte <yes|no> Bare byte encoding is an IIS trick that uses non-ASCII characters as valid values when decoding UTF-8 values. you must enable also enable utf 8 yes. you may be interested in knowing when you have a UTF-8 encoded URI. and %u. ASCII decoding is also enabled to enforce correct functioning. utf 8 <yes|no> The utf-8 decode option tells HTTP Inspect to decode standard UTF-8 Unicode sequences that are in the URI. because base36 won’t work. The alert on this decoding should be enabled. make sure you have this option turned on. This abides by the Unicode standard and only uses % encoding. %2e = . etc. So it is most likely someone trying to be covert. so ASCII is also enabled to enforce correct decoding. alert on all ‘/’ or something like that.

and is a performance enhancement if needed. no pipeline req This option turns HTTP pipeline decoding off. 22. 19. This picks up the Apache chunk encoding exploits. 18. directory <yes|no> This option normalizes directory traversals and self-referential directories. use no. but may also be false positive prone. but when this option is enabled. Alerts on this option may be interesting. 20. But you can still get an alert on this option./bar gets normalized to: /foo/bar If you want to conﬁgure an alert. iis delimiter <yes|no> This started out being IIS-speciﬁc. otherwise. Only use this option on servers that will accept URIs like this: ”get /index. but Apache takes this non-standard delimiter was well. Apache uses this.html alsjdfk alsj lj aj la jsj s\n”. This alert may give false positives.15. So a request URI of “/foo\bar” gets normalized to “/foo/bar. Since this is common.. This is again an IIS emulation. It is only inspected with the generic pattern matching. The directory: /foo/fake\_dir/.” If you want an alert when multiple slashes are seen. then conﬁgure with a yes. otherwise. The non strict option assumes the URI is between the ﬁrst and second space even if there is no valid HTTP identiﬁer after the second space.
51
./bar gets normalized to: /foo/bar The directory: /foo/. and may also alert on HTTP tunneling that uses chunk encoding. pipeline requests are not decoded and analyzed per HTTP protocol ﬁeld. multi slash <yes|no> This option normalizes multiple slashes in a row. specify yes. chunk length <non-zero positive integer> This option is an anomaly detector for abnormally large chunk sizes. enable this option. 16. apache whitespace <yes|no> This option deals with the non-RFC standard of using tab for a space delimiter. By default. since some web sites refer to ﬁles using directory traversals. pipeline requests are inspected for attacks. so something like: “foo/////////bar” get normalized to “foo/bar. non strict This option turns on non-strict URI parsing for the broken way in which Apache servers will decode a URI. specify no. iis backslash <yes|no> Normalizes backslashes to slashes. we always take this as standard since the most popular web servers accept it. so if the emulated web server is Apache. 21.” 17.

if we have the following rule set: alert tcp any any -> any 80 ( msg:"content". It is useful for normalizing Referrer URIs that may appear in the HTTP Header. then no inspection will take place. directory. This has no effect on HTTP rules in the rule set. 30. 29. you’ll catch most of the attacks. max header length <positive integer up to 65535> This option takes an integer as an argument. 27. The allow proxy use keyword is just a way to suppress unauthorized proxy use for an authorized server. not including Cookies (using the same conﬁguration parameters as the URI normalization (ie. 25. For example.23. When enabled. To enable. It is useful for normalizing data in HTTP Cookies that may be encoded. like whisker -i 4. tab uri delimiter This option turns on the use of the tab character (0x09) as a delimiter for a URI. This generates much fewer false positives than the directory option.). normalize headers This option turns on normalization for HTTP Header Fields. So if you need extra performance. For IIS. 28. 31. Apache accepts tab as a delimiter. If a url directory is larger than this argument size. IIS does not. Requests that exceed this length will cause a ”Long Header” alert. multi-slash. The inspect uri only conﬁguration turns off all forms of detection except uricontent inspection.). normalize cookies This option turns on normalization for HTTP Cookie Fields (using the same conﬁguration parameters as the URI normalization (ie.htm http/1. inspect uri only This is a performance optimization. ) and the we inspect the following URI: get /foo. etc. allow proxy use By specifying this keyword. No argument is speciﬁed. because it doesn’t alert on directory traversals that stay within the web server directory structure. The argument speciﬁes the max char directory length for URL directory. webroot <yes|no> This option generates an alert when a directory traversal traverses past the web server root directory. This alert is off by default. the user is allowing proxy use on this server. The integer is the maximum length allowed for an HTTP client request header ﬁeld. 24. specify an integer argument to max header length of 1 to 65535. multi-slash. an alert is generated. which is associated with certain web attacks. then this option does nothing. Whether this option is on or not. This means that no alert will be generated if the proxy alert global keyword has been used. and if there are none available. etc. 52
. no alerts This option turns off all alerts that are generated by the HTTP Inspect preprocessor module. a tab in the URI should be treated as any other character. Specifying a value of 0 is treated as disabling the alert. It only alerts when the directory traversals go past the web server root directory. a tab is treated as whitespace if a space character (0x20) precedes it. If the proxy alert keyword is not enabled. No argument is speciﬁed. It’s important to note that if this option is used without any uricontent rules. 26. oversize dir length <non-zero positive integer> This option takes a non-zero positive integer as an argument. directory. This should limit the alerts to IDS evasion type attacks. This is obvious since the URI is only inspected with uricontent rules. As this ﬁeld usually contains 90-95% of the web attacks. A good argument value is 300 characters. then there is nothing to inspect. content: "foo".0\r\n\r\n No alert will be generated when inspect uri only is enabled. only the URI portion of HTTP requests will be inspected for attacks. enable this optimization.

SMTP command lines can be normalized to remove extraneous spaces. RFC 2821 recommends 512 as a maximum command line length. regular mail data can be ignored for an additional performance boost.. which improves performance. ports { <port> [<port>] . Default is an empty list. }
This speciﬁes on what ports to check for SMTP data. valid cmds { <Space-delimited list of commands> } List of valid commands. inspection type <stateful | stateless> Indicate whether to operate in stateful or stateless mode. but preprocessor has this list hard-coded: { ATRN AUTH BDAT DATA DEBUG EHLO EMAL ESAM ESND ESOM ETRN EVFY EXPN } { HELO HELP IDENT MAIL NOOP QUIT RCPT RSET SAML SOML SEND ONEX QUEU } { STARTTLS TICK TIME TURN TURNME VERB VRFY X-EXPS X-LINK2STATE } { XADR XAUTH XCIR XEXCH50 XGEN XLICENSE XQUE XSTA XTRN XUSR } 54
. max header line len <int> Alert if an SMTP DATA header line is longer than this value. Normalization checks for more than one space character after a command. RFC 2821 recommends 512 as a maximum response line length.Conﬁguration SMTP has the usual conﬁguration items. this will include 25 and possibly 465. invalid cmds { <Space-delimited list of commands> } Alert if this command is sent from client side. 7. We do not alert on commands in this list. The conﬁguration options are described below: 1. cmds just checks commands listed with the normalize cmds parameter. Typically. this is relatively safe to do and can improve the performance of data inspection. 4. Absence of this option or a ”0” means never alert on response line length. 11. In addition. 10. no alerts Turn off all alerts for this preprocessor. normalize <all | none | cmds> This turns on normalization. TLS-encrypted trafﬁc can be ignored. max command line len <int> Alert if an SMTP command line is longer than this value. Default is an empty list. max response line len <int> Alert if an SMTP response line is longer than this value.. 9. such as port and inspection type. Space characters are deﬁned as space (ASCII 0x20) or tab (ASCII 0x09). alt max command line len <int> { <cmd> [<cmd>] } Overrides max command line len for speciﬁc commands. 2. 12. RFC 2821 recommends 1024 as a maximum data header line length. Absence of this option or a ”0” means never alert on data header line length. Also. all checks all commands none turns off normalization for all commands. ignore data Ignore data section of mail (except for mail headers) when processing rules. ignore tls data Ignore TLS-encrypted data when processing rules. for encrypted SMTP. 8. 3. 6. Absence of this option or a ”0” means never alert on command line length. Since so few (none in the current snort rule set) exploits are against mail data. 5.

there are four areas of conﬁguration: Global. 3.6).
! △NOTE options have an argument of yes or no. meaning it looks for information and handles reassembled data correctly. FTP Client. Conﬁguration 1. which should allow the user to emulate any type of FTP server or FTP Client. a particular session will be noted as encrypted and not inspected any further. and FTP Server. Example Global Conﬁguration preprocessor ftp_telnet: \ global inspection_type stateful encrypted_traffic no 56
. The following example gives the generic global conﬁguration format: Format preprocessor ftp_telnet: \ global \ inspection_type stateful \ encrypted_traffic yes \ check_encrypted You can only have a single global conﬁguration.
! △NOTE
When inspection type is in stateless mode. The presence of the option indicates the option itself is on. The FTP/Telnet global conﬁguration must appear before the other three areas of conﬁguration. meaning it only looks for information on a packet-bypacket basis. The default is to run FTP/Telent in stateful inspection mode. while the yes/no argument applies to the alerting functionality associated with that option. encrypted traffic <yes|no> This option enables detection and alerting on encrypted Telnet and FTP command channels. Within FTP/Telnet.FTP/Telnet has the capability to handle stateless processing. inspection type This indicates whether to operate in stateful or stateless mode. Telnet. Global Conﬁguration The global conﬁguration deals with conﬁguration options that determine the global functioning of FTP/Telnet. 2. This argument speciﬁes whether the user wants Some conﬁguration
the conﬁguration option to generate a ftptelnet alert or not. checks for encrypted trafﬁc will occur on every packet. you’ll get an error if you try otherwise. FTP/Telnet has a very “rich” user conﬁguration.2. similar to that of HTTP Inspect (See 2. whereas in stateful mode. Users can conﬁgure individual FTP servers and clients with a variety of options. check encrypted Instructs the the preprocessor to continue to check an encrypted session for a subsequent command to cease encryption.

Being that FTP uses the Telnet protocol on the control connection. certain implementations of Telnet servers will ignore the SB without a cooresponding SE. The following example gives the generic telnet conﬁguration format: Format preprocessor ftp_telnet_protocol: \ telnet \ ports { 23 } \ normalize \ ayt_attack_thresh 6 \ detect_anomalies
There should only be a single telnet conﬁguration. This is anomalous behavior which could be an evasion case. and subsequent instances will override previously set values. However. normalize This option tells the preprocessor to normalize the telnet trafﬁc by eliminating the telnet escape sequences. Telnet supports subnegotiation. It functions similarly to its predecessor.
57
. Most of your FTP servers will most likely end up using the default conﬁguration. so adding port 22 will only yield false positives. detect anomalies In order to support certain options. Default This conﬁguration supplies the default server conﬁguration for any FTP server that is not individually conﬁgured. ports {<port> [<port>< . 3.Telnet Conﬁguration The telnet conﬁguration deals with conﬁguration options that determine the functioning of the Telnet portion of the preprocessor. The detect anomalies option enables alerting on Telnet SB without the corresponding SE. SSH tunnels cannot be decoded. Rules written with ’raw’ content options will ignore the normailzed buffer that is created when this option is in use. >]} This is how the user conﬁgures which ports to decode as telnet trafﬁc. It is only applicable when the mode is stateful. it is also susceptible to this behavior. the telnet decode preprocessor. Per the Telnet RFC. subnegotiation begins with SB (subnegotiation begin) and must end with an SE (subnegotiation end). Example Telnet Conﬁguration preprocessor ftp_telnet_protocol: \ telnet ports { 23 } normalize ayt_attack_thresh 6 FTP Server Conﬁguration There are two types of FTP server conﬁgurations: default and by IP address. Typically port 23 will be included. Conﬁguration 1. 2. ayt attack thresh < number > This option causes the preprocessor to alert when the number of consecutive telnet Are You There (AYT) commands reaches the number speciﬁed... 4.

For example: ftp_cmds { XPWD XCWD XCUP XMKD XRMD } 4.1. This option speciﬁes a list of additional commands allowed by this server. 7. 3. cmd validity cmd < fmt > This option speciﬁes the valid format for parameters of a given command. Example IP speciﬁc FTP Server Conﬁguration preprocessor _telnet_protocol: \ ftp server 10. the only difference being that speciﬁc IPs can be conﬁgured. outside of the default FTP command set as speciﬁed in RFC 959. 5. For example the USER command – usernames may be no longer than 16 bytes. so the appropriate conﬁguration would be: alt_max_param_len 16 { USER } 6.. 2..Example Default FTP Server Conﬁguration preprocessor ftp_telnet_protocol: \ ftp server default ports { 21 } Refer to 60 for the list of options set in default ftp server conﬁguration.1 ports { 21 } ftp_cmds { XPWD XCWD } FTP Server Conﬁguration Options 1. chk str fmt {cmd[cmd]} This option causes a check for string format attacks in the speciﬁed commands. def max param len <number> This speciﬁes the default maximum allowed parameter length for an FTP command. this option causes the preprocessor to print the conﬁguration for each of the FTP commands for this server. fmt must be enclosed in <>’s and may contain the following:
58
. It can be used as a more speciﬁc buffer overﬂow detection. alt max param len <number> {cmd[cmd]} This speciﬁes the maximum allowed parameter length for the speciﬁed FTP command(s). >]} This is how the user conﬁgures which ports to decode as FTP command channel trafﬁc.1. ftp cmds {cmd[cmd]} The preprocessor is conﬁgured to alert when it sees an FTP command that is not allowed by the server. Conﬁguration by IP Address This format is very similar to “default”. ports {<port> [<port>< . print cmds During initialization. as well as any additional commands as needed. This may be used to allow the use of the ’X’ commands identiﬁed in RFC 775. Typically port 21 will be included. It can be used as a basic buffer overﬂow detection.

cmd_validity MDTM < [ date nnnnnnnnnnnnnn[. separated by | One of the choices enclosed within {}. Some FTP servers do not process those telnet escape sequences.org/internetdrafts/draft-ietf-ftpext-mlst-16.txt) To check validity for a server that uses the TZ format. 9. Injection of telnet escape sequences could be used as an evasion attempt on an FTP command channel.literal Parameter is a string (effectively unrestricted) Parameter must be a host/port speciﬁed. where: n Number C Character [] optional format enclosed | OR {} choice of options . # This allows additional modes. including mode Z which allows for # zip-style compression. use the following: cmd_validity MDTM < [ date nnnnnnnnnnnnnn[{+|-}n[n]] ] string > 8. | {}. Some others accept a format using YYYYMMDDHHmmss[+—]TZ format. These examples are the default checks. cmd_validity MODE < char ASBCZ > # Allow for a date in the MDTM command. ignore telnet erase cmds <yes|no> This option allows Snort to ignore telnet escape sequences for erase character (TNC EAC) and erase line (TNC EAL) when normalizing FTP command channel.ietf. + . telnet cmds <yes|no> This option turns on detection and alerting when telnet escape sequences are seen on the FTP command channel. accept a format using YYYYMMDDHHmmss[. optional value enclosed within []
Examples of the cmd validity option are shown below. While not part of an established standard. The example above is for the ﬁrst case (time format as speciﬁed in http://www. one of <chars> Parameter follows format speciﬁed.uuu]. per RFC 2428 One of choices enclosed within. certain FTP servers accept MDTM commands that set the modiﬁcation time on a ﬁle. per RFC 1639 Parameter must be an extended host port speciﬁed. cmd_validity cmd_validity cmd_validity cmd_validity cmd_validity MODE STRU ALLO TYPE PORT <char SBC> <char FRP> < int [ char R int ] > < { char AE [ char NTC ] | char I | char L [ number ] } > < host_port >
A cmd validity line can be used to override these defaults and/or add a check for other commands. 59
. per RFC 959 and others performed by the preprocessor.Value int number char <chars> date <datefmt>
string host port long host port extended host port {}. per RFC 959 Parameter must be a long host port speciﬁed. []
Description Parameter must be an integer Parameter must be an integer between 1 and 255 Parameter must be a single character. The most common among servers that do.n[n[n]]] ] string > MDTM is an off case that is worth discussing.

1.1.1 ports 20020 through 20040 – ie.1.20020 192. Some FTP clients do not process those telnet escape sequences.78.52. It can be used to deal with proxied FTP connections where the FTP data channel is different from the client. the use of PORT 192.162.1.162.168.168.20030 } 4.20040 } • Allow bounces to 192. A few examples: • Allow bounces to 192.78. 5.1. telnet cmds <yes|no> This option turns on detection and alerting when telnet escape sequences are seen on the FTP command channel.Conﬁguration by IP Address This format is very similar to “default”.168. bounce_to { 192.xx.1. the only difference being that speciﬁc IPs can be conﬁgured. It can be used as a basic buffer overﬂow detection.1.1 port 20020 and 192.1 bounce yes max_resp_len 500 FTP Client Conﬁguration Options 1. bounce_to { 192.20020. bounce_to { 192.1.1. Example IP speciﬁc FTP Client Conﬁguration preprocessor ftp_telnet_protocol: \ ftp client 10. 2.1. Injection of telnet escape sequences could be used as an evasion attempt on an FTP command channel.20020 } • Allow bounces to 192.1.1. Examples/Default Conﬁguration from snort.porthi] > When the bounce option is turned on.1.1. 3. bounce <yes|no> This option turns on detection and alerting of FTP bounce attacks. the use of PORT 192.1.[port|portlow.1 port 20020 – ie.conf preprocessor ftp_telnet: \ global \ encrypted_traffic yes \ inspection_type stateful preprocessor ftp_telnet_protocol:\ telnet \ normalize \ ayt_attack_thresh 200
61
. An FTP bounce attack occurs when the FTP PORT command is issued and the speciﬁed host does not match the host of the client.168.168.162.168.1. max resp len <number> This speciﬁes the maximum allowed response length to an FTP command accepted by the client.168.1. bounce to < CIDR.2.2 port 20030. this allows the PORT command to use the IP address (in CIDR format) and port (or inclusive port range) without generating an alert. where xx is 52 through 72 inclusive. ignore telnet erase cmds <yes|no> This option allows Snort to ignore telnet escape sequences for erase character (TNC EAC) and erase line (TNC EAL) when normalizing FTP command channel.

The SSH vulnerabilities that Snort can detect all happen at the very beginning of an SSH session. 4. Conﬁguration By default. Set CWD to allow parameter length of 200 MODE has an additional mode of Z (compressed) Check for string formats in USER & PASS commands Check MDTM commands that set modification time on the file. To detect the attacks. and the Protocol Mismatch exploit. all alerts are disabled and the preprocessor checks trafﬁc on port 22... an alert is generated. CRC 32. Both Challenge-Response Overﬂow and CRC 32 attacks occur after the key exchange. max encrypted packets < number > The number of encrypted packets that Snort will inspect before ignoring a given SSH session. and are therefore encrypted. the SSH preprocessor counts the number of bytes transmitted to the server. If those bytes exceed a predeﬁned limit within a predeﬁned number of packets. Both attacks involve sending a large payload (20kb+) to the server immediately after the authentication challenge.9 SSH
The SSH preprocessor detects the following exploits: Challenge-Response Buffer Overﬂow. Since the Challenge-Response Overﬂow only effects SSHv2 and CRC 32 only effects SSHv1. >]} This option speciﬁes which ports the SSH preprocessor should inspect trafﬁc to.# # # # #
This is consistent with the FTP rules as of 18 Sept 2004. Secure CRT. the SSH version string exchange is used to distinguish the attacks. 2.
preprocessor ftp_telnet_protocol: \ ftp server default \ def_max_param_len 100 \ alt_max_param_len 200 { CWD } \ cmd_validity MODE < char ASBCZ > \ cmd_validity MDTM < [ date nnnnnnnnnnnnnn[. The Secure CRT and protocol mismatch exploits are observable before the key exchange. 1. Snort ignores the session to increase performance.n[n[n]]] ] string > \ chk_str_fmt { USER PASS RNFR RNTO SITE MKD } \ telnet_cmds yes \ ignore_data_chan yes preprocessor ftp_telnet_protocol: \ ftp client default \ max_resp_len 256 \ bounce yes \ telnet_cmds yes
2.2. max client bytes < number > The number of unanswered bytes allowed to be transferred before alerting on Challenge-Response Overﬂow or CRC 32. Once max encrypted packets packets have been seen. The available conﬁguration options are described below. server ports {<port> [<port>< . or else Snort will ignore the trafﬁc. 3. This number must be hit before max encrypted packets packets are sent. max server version len < number >
62
.

preprocessor ssh: \ server_ports { 22 } \ max_client_bytes 19600 \ max_encrypted_packets 20 \ enable_respoverflow \ enable_ssh1crc32
2. or if a client generates server trafﬁc.The maximum number of bytes allowed in the SSH server version string before alerting on the Secure CRT server version string overﬂow.2. the rules are given reassembled DCE/RPC data to examine. enable ssh1crc32 Enables checking for the CRC 32 exploit. Example Conﬁguration from snort. enable respoverflow Enables checking for the Challenge-Response Overﬂow exploit. enable paysize Enables alerts for invalid payload sizes. enable badmsgdir Enable alerts for trafﬁc ﬂowing the wrong direction. 7. if the presumed server generates client trafﬁc. and only decodes SMB to get to the potential DCE/RPC requests carried by SMB. enable protomismatch Enables checking for the Protocol Mismatch exploit. the preprocessor will stop processing trafﬁc for a given session. the preprocessor only handles desegmentation (at SMB and TCP layers) and defragmentation of DCE/RPC. For instance. 12. If Challenge-Respone Overﬂow or CRC 32 false positive. autodetect Attempt to automatically detect SSH. The SSH preprocessor should work by default. 9. enable srvoverflow Enables checking for the Secure CRT exploit. 6. Currently. 8. try increasing the number of required client bytes with max client bytes. only segmentation using WriteAndX is currently reassembled. Other methods will be handled in future versions of the preprocessor. enable recognition Enable alerts for non-SSH trafﬁc on SSH ports. At the SMB layer. Alerts at 19600 unacknowledged bytes within 20 encrypted packets for the Challenge-Response Overﬂow/CRC32 exploits. With the preprocessor enabled.10 DCE/RPC
The dcerpc preprocessor detects and decodes SMB and DCE/RPC trafﬁc. 5. 11. Snort rules can be evaded by using both types of fragmentation.conf Looks for attacks on SSH server port 22. 10.
63
. It is primarily interested in DCE/RPC requests. After max encrypted packets is reached.

Assuming that the data is a DCE/RPC header.>] } Ports that the preprocessor monitors for SMB trafﬁc. If subsequent checks are nonsensical. If both match. • ports smb { <port> [<port> <. Default is 3000 bytes. as well as checking the NetBIOS header (which is always present for SMB) for the type ”Session Message”. two bytes are checked in the packet.. Note that DCE/RPC can run on practically any port in addition to the more common ports. in bytes. Currently. Default is 100000 kilobytes.. the preprocessor proceeds with the assumption that it is looking at DCE/RPC data. This option is not conﬁgured by default. • max frag size <number> Maximum DCE/RPC fragment size to put in defragmentation buffer..Autodetection of SMB is done by looking for ”\xFFSMB” at the start of the SMB data. • reassemble increment <number> This option speciﬁes how often the preprocessor should create a reassembled packet to send to the detection engine with the data that’s been accrued in the segmentation and fragmentation reassembly buffers. this option should not be conﬁgured as SMB segmentation provides for an easy evasion opportunity. Default is port 135. Unless you are experiencing severe performance issues. in kilobytes. This option is not conﬁgured by default. • ports dcerpc { <port> [<port> <. Conﬁguration The proprocessor has several optional conﬁguration options. one byte is checked for DCE/RPC version 5 and another for a DCE/RPC PDU type of Request. They are described below: • autodetect In addition to conﬁgured ports. This option is not conﬁgured by default. This will potentially catch an attack earlier and is useful if in inline mode. Unless you are experiencing severe performance issues. before the ﬁnal desegmentation or defragmentation of the DCE/RPC request takes place.>] } Ports that the preprocessor monitors for DCE/RPC over TCP trafﬁc. This option is not conﬁgured by default. Since the preprocessor looks at TCP reassembled packets (to avoid
64
. Autodetection of DCE/RPC is not as reliable. • memcap <number> Maximum amount of memory available to the DCE/RPC preprocessor for desegmentation and defragmentation. this option should not be conﬁgured as DCE/RPC fragmentation provides for an easy evasion opportunity. Default are ports 139 and 445. • alert memcap Alert if memcap is exceeded. • disable smb frag Do not do SMB desegmentation. it ends processing.. try to autodetect DCE/RPC sessions. • disable dcerpc frag Do not do DCE/RPC defragmentation.

Not recommended if Snort is running in passive mode as it’s not really needed. If not speciﬁed. A value of 0 will in effect disable this option as well. the default conﬁguration will look like: preprocessor dcerpc: \ ports smb { 139 445 } \ ports dcerpc { 135 } \ max_frag_size 3000 \ memcap 100000 \ reassemble_increment 0 Preprocessor Events There is currently only one alert.000 kilobytes. there is not much to do with the dcerpc preprocessor other than turn it on and let it reassemble fragmented DCE/RPC packets. Don’t do desegmentation on SMB writes. Note At the current time.000 kilobytes. which is triggered when the preprocessor has reached the memcap limit for memory allocation. Set memory cap for desegmentation/defragmentation to 200. The argument to the option speciﬁes how often the preprocessor should create a reassembled packet if there is data in the segmentation/fragmentation buffers. that in using this option. detect on DCE/RPC (or TCP) ports 135 and 2103 (overrides default). preprocessor dcerpc: \ autodetect \ disable_smb_frag \ max_frag_size 4000 In addition to defaults. Note. Snort will potentially take a performance hit. so looking at the data early will likely catch the attack before all of the exploit data has gone through. autodetect SMB and DCE/RPC sessions on non-conﬁgured ports. Truncate DCE/RPC fragment if greater than 4000 bytes. don’t do DCE/RPC defragmentation. Set memory cap for desegmentation/defragmentation to 50.TCP overlaps and segmentation evasions). 65
. the last packet of an attack using DCE/RPC segmented/fragmented evasion techniques may have already gone through before the preprocessor looks at it.) preprocessor dcerpc: \ disable_dcerpc_frag \ memcap 50000 In addition to the defaults. The alert is gid 130. Conﬁguration Examples In addition to defaults. sid 1. this option is disabled. (Since no DCE/RPC defragmentation will be done the memory cap will only apply to desegmentation. preprocessor dcerpc: \ ports dcerpc { 135 2103 } \ memcap 200000 \ reassemble_increment 1 Default Conﬁguration If no options are given to the preprocessor. Create a reassembly packet every time through the preprocessor if there is data in the desegmentation/defragmentation buffers. however.

documented below. Once the trafﬁc is determined to be encrypted. The available conﬁguration options are described below. Conﬁguration By default. ports {<port> [<port>< . such as the handshake.2. enable obsolete types Alert on Obsolete (per RFC 1035) Record Types 3. and that the trafﬁc is legitimately encrypted. all alerts are disabled and the preprocessor checks trafﬁc on port 53.12 SSL/TLS
Encrypted trafﬁc should be ignored by Snort for both performance reasons and to reduce false positives. By default. and Experimental Record Types. enable experimental types Alert on Experimental (per RFC 1035) Record Types 4. SSLPP looks for a handshake followed by encrypted trafﬁc traveling to both sides. SSL is used over port 443 as HTTPS. Therefore. Do not alert on obsolete or experimental RData record types. If one side responds with an indication that something has failed. the session is not marked as encrypted. only the SSL handshake of each connection will be inspected. Typically. the only observed response from one endpoint will be TCP ACKs.2. 66
. Check for the DNS Client RData overﬂow vulnerability. 2. Obsolete Record Types. Verifying that faultless encrypted trafﬁc is sent from both endpoints ensures two things: the last client-side handshake packet was not crafted to evade Snort. Examples/Default Conﬁguration from snort. enable rdata overflow Check for DNS Client RData TXT Overﬂow The DNS preprocessor does nothing if none of the 3 vulnerabilities it checks for are enabled. no further inspection of the data on the connection is made. the user should use the ’trustservers’ option. preprocessor dns: \ ports { 53 } \ enable_rdata_overflow
2.2.. It will not operate on TCP sessions picked up midstream. if a user knows that server-side encrypted data can be trusted to mark the session as encrypted. especially when packets may be missed..11 DNS
The DNS preprocessor decodes DNS Responses and can detect the following exploits: DNS Client RData Overﬂow. By enabling the SSLPP to inspect port 443 and enabling the noinspect encrypted option. The SSL Dynamic Preprocessor (SSLPP) decodes SSL and TLS trafﬁc and optionally determines if and when Snort should stop inspection of it. DNS looks at DNS Response trafﬁc over UDP and TCP and it requires Stream preprocessor to be enabled for TCP decoding. 1. and it will cease operation on a session if it loses state because of missing data (dropped packets).conf Looks for trafﬁc on DNS server port 53. In some cases. >]} This option speciﬁes the source ports that the DNS preprocessor should inspect trafﬁc.

2. noinspect encrypted Disable inspection on trafﬁc that is encrypted. An alert with GID 112 and SID 1 will be generated if a unicast ARP request is detected. the preprocessor inspects Ethernet addresses and the addresses in the ARP packets.. ports {<port> [<port>< .13 ARP Spoof Preprocessor
The ARP spoof preprocessor decodes ARP packets and detects ARP attacks. trustservers Disables the requirement that application (encrypted) data must be observed on both sides of the session before a session is marked encrypted. 3. The preprocessor will use this list when detecting ARP cache overwrite attacks. Specify one host IP MAC combo per line. Examples/Default Conﬁguration from snort.conf Enables the SSL preprocessor and tells it to disable inspection on encrypted trafﬁc. Format preprocessor arpspoof[: -unicast] preprocessor arpspoof_detect_host: ip mac
67
. >]} This option speciﬁes which ports SSLPP will inspect trafﬁc on. Specify a pair of IP and hardware address as the argument to arpspoof detect host.. an alert with GID 112 and SID 2 or 3 is generated. Use this option for slightly better performance if you trust that your servers are not compromised. This requires the noinspect encrypted option to be useful. SSLPP watches the following ports: • 443 HTTPS • 465 SMTPS • 563 NNTPS • 636 LDAPS • 989 FTPS • 992 TelnetS • 993 IMAPS • 994 IRCS • 995 POPS 2. Default is off. When ”-unicast” is speciﬁed as the argument of arpspoof. unicast ARP requests. By default. and inconsistent Ethernet to IP mapping. preprocessor ssl: noinspect_encrypted
2. The host with the IP address should be on the same layer 2 segment as Snort is. the preprocessor checks for unicast ARP requests.Conﬁguration 1. Alert SID 4 is used in this case. When inconsistency occurs. When no arguments are speciﬁed to arpspoof. Default is off.

the frag3 preprocessor should be enabled and conﬁgured. Read.40.2.168.2. The Ethernet address corresponding to the preceding IP. either through conﬁgured ports.40.168.14 DCE/RPC 2 Preprocessor
The main purpose of the preprocessor is to perform SMB desegmentation and DCE/RPC defragmentation to avoid rule evasion using these techniques. reduce false positives and reduce the count and complexity of DCE/RPC based rules. UDP and RPC over HTTP v.
68
. • IP defragmentation should be enabled.168.40. servers or autodetecting.1 and 192. TCP. • Stream session tracking must be enabled.40. Transaction Secondary.e. The preprocessor requires a session tracker to keep its data. preprocessor arpspoof: -unicast preprocessor arpspoof_detect_host: 192. Write and Close.2 f0:0f:00:f0:0f:01 The third example conﬁguration has unicast detection enabled.168. the dcerpc2 preprocessor will enable stream reassembly for that session if necessary. i. i. The following transports are supported for DCE/RPC: SMB.168. Read Block Raw and Read AndX. The preprosessor merely looks for Ethernet address inconsistencies. preprocessor arpspoof The next example conﬁguration does not do unicast detection but monitors ARP mapping for hosts 192.1 f0:0f:00:f0:0f:00 preprocessor arpspoof_detect_host: 192.40.1 proxy and server.
Example Conﬁguration The ﬁrst example conﬁguration does neither unicast detection nor ARP mapping monitoring. Transaction.e.1 f0:0f:00:f0:0f:00 preprocessor arpspoof_detect_host: 192.2 f0:0f:00:f0:0f:01
2. SMB desegmentation is performed for the following commands that can be used to transport DCE/RPC requests and responses: Write. preprocessor arpspoof preprocessor arpspoof_detect_host: 192. Write AndX. • Stream reassembly must be performed for TCP sessions. If it is decided that a session is SMB or DCE/RPC. Dependency Requirements For proper functioning of the preprocessor: • The dcerpc preprocessor (the initial iteration) must be disabled. New rule options have been implemented to improve performance. Write Block Raw.Option ip mac
Description IP address.40.168. stream5.

along with a valid FID can be used to make a request.0.Target Based There are enough important differences between Windows and Samba versions that a target based approach has been implemented.22 and earlier Any valid UID and TID. Windows 2000 Windows 2000 is interesting in that the ﬁrst request to a named pipe must use the same binding as that of the other Windows versions.0. Samba (all versions) Under an IPC$ tree. Samba greater than 3.e. the FID that was created using this TID becomes invalid. AndX command chaining
69
. Both the UID and TID used to open the named pipe instance must be used when writing data to the same named pipe instance.0. However. Some important differences: Named pipe instance tracking A combination of valid login handle or UID. the FID becomes invalid. Windows 2003 Windows XP Windows Vista These Windows versions require strict binding between the UID. no binding. requests after that follow the same binding as Samba 3. Accepted SMB commands Samba in particular does not recognize certain commands under an IPC$ tree. However. If the TID used to create the FID is deleted (via a tree disconnect). i. since it is necessary in making a request to the named pipe. the FID that was created using this TID becomes invalid. does not accept: Open Write And Close Read Read Block Raw Write Block Raw Windows (all versions) Accepts all of the above commands under an IPC$ tree. The binding between these is dependent on OS/software version.22 in that deleting the UID or TID used to create the named pipe instance also invalidates it. i. TID and FID used to make a request to a named pipe instance.0. It also follows Samba greater than 3.22 Any valid TID.e.22 and earlier. along with a valid FID can be used to make a request.e. i. only the UID used in opening the named pipe can be used to make a request using the FID handle to the named pipe instance. deleting either the UID or TID invalidates the FID. no more requests can be written to that named pipe instance. no more requests can be written to that named pipe instance. Samba 3. share handle or TID and ﬁle/named pipe handle or FID must be used to write data to a named pipe. Therefore. If the UID used to create the named pipe instance is deleted (via a Logoff AndX). however. if the TID used in creating the FID is deleted (via a tree disconnect).

all previous interface bindings are invalidated. What distinguishes them (when the same named pipe is being written to. all previous interface bindings are invalidated. i. Windows (all versions) Uses a combination of PID and MID to deﬁne a ”thread”. The context id ﬁeld in any other fragment can contain any value. e. Segments for each ”thread” are stored separately and written to the named pipe when all segments are received. Windows (all versions) The context id that is ultimately used for the request is contained in the ﬁrst fragment.g. having the same FID) are ﬁelds in the SMB header representing a process id (PID) and multiplex id (MID). we don’t want to keep track of data that the server won’t accept. Samba (all versions) The context id that is ultimately used for the request is contained in the last fragment. Transaction tracking The differences between a Transaction request and using one of the Write* commands to write data to a named pipe are that (1) a Transaction performs the operations of a write and a read from the named pipe. DCE/RPC Fragmented requests . only one Bind can ever be made on a session whether or not it succeeds or fails. If another Bind is made. login/logoff and tree connect/tree disconnect. multiple logins and tree connects (only one place to return handles for these). data is written to the named pipe as it is received by the server. Multliple Bind requests A Bind request is the ﬁrst request that must be made in a connection-oriented DCE/RPC session in order to specify the interface/interfaces that one wants to communicate with. Samba later than 3. These requests can also be segmented with Transaction Secondary commands. If a Bind after a successful Bind is made. Samba (all versions) Uses just the MID to deﬁne a ”thread”. Multiple Transaction requests can be made simultaneously to the same named pipe.20 Another Bind request can be made if the ﬁrst failed and no interfaces were successfully bound to. It is necessary to track this so as not to munge these requests together (which would be a potential evasion opportunity). Samba 3. Samba. is very lax and allows some nonsensical combinations.0. An MID represents different sub-processes within a process (or under a PID).0. Windows (all versions) For all of the Windows versions. the client has to explicitly send one of the Read* requests to tell the server to send the response and (2) a Transaction request is not written to the named pipe until all of the data is received (via potential Transaction Secondary requests) whereas with the Write* commands. An evasion possibility would be accepting a fragment in a request that the server won’t accept that gets sandwiched between an exploit.e. Ultimately. Any binding after that must use the Alter Context request. DCE/RPC Fragmented requests .Windows is very strict in what command combinations it allows to be chained.Context ID Each fragment in a fragmented request carries the context id of the bound interface it wants to make the request to. The PID represents the process this request is a part of. whereas in using the Write* commands.Operation number 70
. on the other hand.20 and earlier Any amount of Bind requests can be made. The context id ﬁeld in any other fragment can contain any value.

Windows (all versions) The byte order of the stub data is that which was used in the Bind request. The global preprocessor conﬁguration name is dcerpc2 and the server preprocessor conﬁguration name is dcerpc2 server.Each fragment in a fragmented request carries an operation number (opnum) which is more or less a handle to a function offered by the interface.’ event-list "memcap" | "smb" | "co" | "cl" 0-65535
Option explanations memcap 71
. The opnum ﬁeld in any other fragment can contain any value. The opnum ﬁeld in any other fragment can contain any value. cl] OFF
1024-4194303 (kilobytes) 1514-65535 pseudo-event | event | ’[’ event-list ’]’ "none" | "all" event | event ’. Conﬁguration The dcerpc2 preprocessor has a global conﬁguration and one or more server conﬁgurations. DCE/RPC Stub data byte order The byte order of the stub data is determined differently for Windows and Samba. Samba (all versions) Windows 2000 Windows 2003 Windows XP The opnum that is ultimately used for the request is contained in the last fragment. Windows Vista The opnum that is ultimately used for the request is contained in the ﬁrst fragment. Samba (all versions) The byte order of the stub data is that which is used in the request carrying the stub data. Option syntax Option memcap disable defrag max frag len events reassemble threshold
memcap max-frag-len events pseudo-event event-list event re-thresh = = = = = = =
Argument <memcap> NONE <max-frag-len> <events> <re-thresh>
Required NO NO NO NO NO
Default memcap 102400 OFF OFF events [smb. Only one global dcerpc2 conﬁguration can be speciﬁed. co. Global Conﬁguration preprocessor dcerpc2 The global dcerpc2 conﬁguration is required.

max frag len Speciﬁes the maximum fragment size that will be added to the defragmention module. Alert on events related to connection-oriented DCE/RPC processing. Defaults are smb. co Stands for connection-oriented DCE/RPC. (See Events section for an enumeration and explanation of events. Option examples
memcap 30000 max_frag_len 16840 events none events all events smb events co events [co] events [smb. If a fragment is greater than this size. cl Stands for connectionless DCE/RPC. cl] reassemble_threshold 500
Conﬁguration examples
preprocessor preprocessor preprocessor preprocessor preprocessor preprocessor dcerpc2 dcerpc2: dcerpc2: dcerpc2: dcerpc2: dcerpc2:
memcap 500000 max_frag_len 16840. it is truncated before being added to the defragmentation module. smb] reassemble_threshold 500
Default global conﬁguration
preprocessor dcerpc2: memcap 102400. Default is 100 MB. events [memcap. This option is useful in inline mode so as to potentially catch an exploit early before full defragmentation is done. smb. events [smb. alert. A value of 0 supplied as an argument to this option will. Default is to do defragmentation. co.) memcap Only one event. Run-time memory includes any memory allocated after conﬁguration. reassemble threshold Speciﬁes a minimum number of bytes in the DCE/RPC desegmentation and defragmentation buffers before creating a reassembly packet to send to the detection engine. Default is disabled. max_frag_len 14440 disable_defrag. memcap 300000. If the memcap is reached or exceeded. events [memcap. disable this option. co] events [memcap. in effect. events smb memcap 50000. co.Speciﬁes the maximum amount of run-time memory that can be allocated. smb. Default is not set. events Speciﬁes the classes of events to enable. co and cl. cl]
Server Conﬁguration 72
. Alert on events related to connectionless DCE/RPC processing. smb Alert on events related to SMB processing. cl]. disable defrag Tells the preprocessor not to do DCE/RPC defragmentation. co.

445] detect [smb [139. no autodetect http proxy ports By default. tcp] detect [smb 139. Default is to autodetect on RPC over HTTP proxy detect ports.0. detect Speciﬁes the DCE/RPC transport and server ports that should be detected on for the transport. feab:45b3:ab92:8ac4:d322:007f:e5aa:7845] policy Win2000 policy Samba-3. autodetect Speciﬁes the DCE/RPC transport and server ports that the preprocessor should attempt to autodetect on for the transport. 135 for TCP and UDP.445]] detect [smb. smb invalid shares Speciﬁes SMB shares that the preprocessor should alert on if an attempt is made to connect to them via a Tree Connect or Tree Connect AndX.168. tcp 135.445].168. Default is empty.255.0. rpc-over-http-server [593.TCP/UDP. smb max chain Speciﬁes the maximum amount of AndX command chaining that is allowed before an alert is generated.0. This option is useful if the RPC over HTTP proxy conﬁgured with the detect option is only used to proxy DCE/RPC trafﬁc.168.0.168.net Speciﬁes that this conﬁguration is an IP or net speciﬁc conﬁguration.0. Defaults are 1025-65535 for TCP. udp 135. the preprocessor will always attempt to autodetect for ports speciﬁed in the detect conﬁguration for rpc-over-http-proxy.10 net 192. Option examples
net 192.168.0/255. This is because the proxy is likely a web server and the preprocessor should not look at all web trafﬁc.0/24] net 192. Default is ”WinXP”. It would be very uncommon to see SMB on anything other than ports 139 and 445. tcp [135. The autodetect ports are only queried if no detect transport/ports match the packet. Default maximum is 3 chained commands.255.0. policy Speciﬁes the target-based policy to use when processing. Defaults are ports 139 and 445 for SMB.2103]] detect [smb [139. RPC over HTTP proxy and lastly SMB. A value of 0 disables this option.0.0/24 net [192.0/24.0 net feab:45b3:ab92:8ac4:d322:007f:e5aa:7845 net feab:45b3:ab92:8ac4:d322:007f:e5aa:7845/128 net feab:45b3::/32 net [192.168.22 detect none detect smb detect [smb] detect smb 445 detect [smb 445] detect smb [139. feab:45b3::/32] net [192. UDP and RPC over HTTP server. 593 for RPC over HTTP server and 80 for RPC over HTTP proxy.6002:6004]]
74
. Note that most dynamic DCE/RPC ports are above 1024 and ride directly over TCP or UDP. The conﬁguration will only apply to the IP addresses and nets supplied as an argument.10. RPC over HTTP server. The order in which the preprocessor will attempt to autodetect will be .

(Total data count must always be greater than or equal to current data size. Positive Response (only from server). The preprocessor will alert if the NetBIOS Session Service length ﬁeld contains a value less than the size of an SMB header. have a ﬁeld containing the total amount of data to be transmitted. If this ﬁeld is zero. Valid types are: Message. id of \xfeSMB is turned away before an eventable point is reached. If this offset puts us before data that has already been processed or after the end of payload. The preprocessor will alert if the total data count speciﬁed in the SMB command header is less than the data size speciﬁed in the SMB command header. Some commands require a minimum number of bytes after the command header. SMB commands have pretty speciﬁc word counts and if the preprocessor sees a command with a word count that doesn’t jive with that command.
3 4 5
6
7
8
9 10 11 12 13 14
15 16
17
76
. The preprocessor will alert if the format is not that which is expected for that command. Request (only from client). Retarget Response (only from server) and Keep Alive.) Some of the Core Protocol commands (from the initial SMB implementation) require that the byte count be some value greater than the data size exactly. the preprocessor will alert. the preprocessor will alert. If a command requires this and the byte count is less than the minimum required byte count for that command. The preprocessor will alert if the byte count speciﬁed in the SMB command header is less than the data size speciﬁed in the SMB command. Note that since the preprocessor does not yet support SMB2. Some commands.) The preprocessor will alert if the total amount of data sent in a transaction is greater than the total data count speciﬁed in the SMB command header. An SMB message type was speciﬁed in the header. The word count of the command header is invalid.SID 1
Description If the memory cap is reached and the preprocessor is conﬁgured to alert. the preprocessor will alert. Some SMB commands. especially the commands from the SMB Core implementation require a data format ﬁeld that speciﬁes the kind of data that will be coming next. such as Transaction. the preprocessor will alert. Many SMB commands have a ﬁeld containing an offset from the beginning of the SMB header to where the data the command is carrying starts. Some commands require a speciﬁc format for the data. Negative Response (only from server). The preprocessor will alert if the byte count minus a predetermined amount based on the SMB command is not equal to the data size.
SMB events SID 2 Description An invalid NetBIOS Session Service type was speciﬁed in the header. The preprocessor will alert if the remaining NetBIOS packet length is less than the size of the SMB command byte count speciﬁed in the command header. The SMB id does not equal \xffSMB. (The byte count must always be greater than or equal to the data size. The preprocessor will alert if the remaining NetBIOS packet length is less than the size of the SMB command data size speciﬁed in the command header. Either a request was made by the server or a response was given by the client. The preprocessor will alert if the remaining NetBIOS packet length is less than the size of the SMB command header to be decoded.

With commands that are chained after a Session Setup AndX request. however. There is. The preprocessor will alert if it sees this. This is anomalous behavior and the preprocessor will alert if it happens.) The Close command is used to close that ﬁle or named pipe. Windows does not allow this behavior. An Open AndX or Nt Create AndX command is used to open/create a ﬁle or named pipe. A Tree Connect AndX command is used to connect to a share. With AndX command chaining it is possible to chain multiple Session Setup AndX commands within the same request.
Connection-oriented DCE/RPC events SID 27 28 Description The preprocessor will alert if the connection-oriented DCE/RPC major version contained in the header is not equal to 5. The preprocessor will alert if it sees this. There should be under normal circumstances no more than a few pending Read* requests at a time and the preprocessor will alert if this number is excessive. There should be under normal circumstances no more than a few pending tree connects at a time and the preprocessor will alert if this number is excessive. however Samba does. essentially logins in and logs off in the same request and is anomalous behavior. Windows does not allow this behavior. the server responds (if the client successfully authenticates) which a user id or login handle. only one place in the SMB header to return a login handle (or Uid). so it need to be queued with the request and dequeued with the response. The server response. A Logoff AndX request is sent by the client to indicate it wants to end the session and invalidate the login handle. This is anomalous behavior and the preprocessor will alert if it happens.18
19
20 21
22
23
24
25
26
For the Tree Connect command (and not the Tree Connect AndX command). Unlike the Tree Connect AndX response. The Read* request contains the ﬁle id associated with a named pipe instance that the preprocessor will ultimately send the data to. 77
. When a Session Setup AndX request is sent to the server. The Tree Disconnect command is used to disconnect from that share. With AndX command chaining it is possible to chain multiple Tree Connect AndX commands within the same request. essentially connects to a share and disconnects from the same share in the same request and is anomalous behavior. In this case the preprocessor is concerned with the server response. The combination of a Tree Connect AndX command with a chained Tree Disconnect command. (The preprocessor is only interested in named pipes as this is where DCE/RPC requests are written to. The combination of a Session Setup AndX command with a chained Logoff AndX command. The preprocessor will alert if it sees this. the login handle returned by the server is used for the subsequent chained commands. however. There is. however Samba does. only one place in the SMB header to return a tree handle (or Tid). it issues a Read* command to the server to tell it to send a response to the data it has written. The preprocessor will alert if the number of chained commands in a single request is greater than or equal to the conﬁgured amount (default is 3). After a client is done writing data using the Write* commands. however. the preprocessor has to queue the requests up and wait for a server response to determine whether or not an IPC share was successfully connected to (which is what the preprocessor is interested in). The preprocessor will alert if the connection-oriented DCE/RPC minor version contained in the header is not equal to 0. essentially opens and closes the named pipe in the same request and is anomalous behavior. The combination of a Open AndX or Nt Create AndX command with a chained Close command. The preprocessor will alert if it sees any of the invalid SMB shares conﬁgured. does not contain this ﬁle id. there is no indication in the Tree Connect response as to whether the share is IPC or not. If multiple Read* requests are sent to the server. they are responded to in the order they were sent. It looks for a Tree Connect or Tree Connect AndX to the share. This is used by the client in subsequent requests to indicate that it has authenticated.

this number should stay the same for all fragments.
Rule Options New rule options are supported by enabling the dcerpc2 preprocessor: dce_iface dce_opnum dce_stub_data New modiﬁers to existing byte test and byte jump rule options: byte_test: dce byte_jump: dce
78
. The preprocessor will alert if the fragment length deﬁned in the header is less than the size of the header. The context id is a handle to a interface that was bound to. so this should be considered anomalous behavior. Most evasion techniques try to fragment the data as much as possible and usually each fragment comes well below the negotiated transmit size. wrapping the sequence number space produces strange behavior from the server.
Connectionless DCE/RPC events SID 40 41 42 43 Description The preprocessor will alert if the connectionless DCE/RPC major version is not equal to 4. It is anomalous behavior to attempt to change the byte order mid-session. If a request if fragmented. In testing. If a request is fragmented. The preprocessor will alert if the remaining fragment length is less than the remaining packet size. The preprocessor will alert if in a Bind or Alter Context request. there are no context items speciﬁed. The preprocessor will alert if the packet data length is less than the size of the connectionless header. The preprocessor will alert if it changes in a fragment mid-request. this number should stay the same for all fragments. The preprocessor will alert if a non-last fragment is less than the size of the negotiated maximum fragment length. The preprocessor will alert if the connectionless DCE/RPC pdu type is not a valid pdu type.29 30 31 32 33 34
35 36 37 38
39
The preprocessor will alert if the connection-oriented DCE/RPC PDU type contained in the header is not a valid PDU type. The preprocessor will alert if the sequence number uses in a request is the same or less than a previously used sequence number on the session. The preprocessor will alert if the context id changes in a fragment mid-request. The call id for a set of fragments in a fragmented request should stay the same (it is incremented for each complete request). The preprocessor will alert if in a Bind or Alter Context request. The preprocessor will alert if the opnum changes in a fragment mid-request. The preprocessor will alert if a fragment is larger than the maximum negotiated fragment length. The byte order of the request data is determined by the Bind in connection-oriented DCE/RPC for Windows. there are no transfer syntaxes to go with the requested interface. The operation number speciﬁes which function the request is calling on the bound interface.

’ "any_frag" ] uuid hexlong hexshort hexbyte operator version = = = = = = hexlong ’-’ hexshort ’-’ hexshort ’-’ 2hexbyte ’-’ 6hexbyte 4hexbyte 2hexbyte 2HEXDIGIT ’<’ | ’>’ | ’=’ | ’!’ 0-65535
Examples
dce_iface: dce_iface: dce_iface: dce_iface: 4b324fc8-1670-01d3-1278-5a47bf6ee188. by default the rule will only be evaluated for a ﬁrst fragment (or full request. will be looking at the wrong data on a fragment other than the ﬁrst. since the beginning of subsequent fragments are already offset some length from the beginning of the request. the client speciﬁes a list of interface UUIDs along with a handle (or context id) for each interface UUID that will be used during the DCE/RPC session to reference the interface.dce iface For DCE/RPC based rules it has been necessary to set ﬂow-bits based on a client bind to a service to avoid false positives. say 5 bytes into the request (maybe it’s a length ﬁeld). This tracking is required so that when a request is processed. This option requires tracking client Bind and Alter Context requests as well as server Bind Ack and Alter Context responses for connection-oriented DCE/RPC in the preprocessor.any_frag.=1. a rule can simply ask the preprocessor. A rule which is looking for data. By default it is reasonable to only evaluate if the request is a ﬁrst fragment (or full request). since subsequent fragments will contain data deeper into the DCE/RPC request. For each Bind and Alter Context request. equal to (’=’) or not equal to (’!’) the version speciﬁed. i. specify one or more service interfaces to bind to. it can. The any frag argument says to evaluate for middle and last fragments as well. Also.it either accepts or rejects the client’s wish to bind to a certain interface. This can eliminate false positives where more than one service is bound to successfully since the preprocessor can correlate the bind UUID to the context id used in the request. As an example. The preprocessor eliminates the need for two rules by normalizing the UUID. Instead of using ﬂow-bits. not a fragment) since most rules are written to start at the beginning of a request.e. Optional arguments are an interface version and operator to specify that the version be less than (’<’). the context id used in the request can be correlated with the interface UUID it is a handle for. 4b324fc8-1670-01d3-1278-5a47bf6ee188. if the any frag option is used to specify evaluating on all fragments. Many checks for data in the DCE/RPC request are only relevant if the DCE/RPC request is a ﬁrst fragment (or full request). The server response indicates which interfaces it will allow the client to make requests to .’ <operator> <version> ] [ ’.any_frag. a DCE/RPC request can be broken up into 1 or more fragments. whether or not the client has bound to a speciﬁc interface UUID and whether or not this client request is making a request to it. It is necessary for a client to bind to a service before being able to make a call to it. Each interface is represented by a UUID. A DCE/RPC request can specify whether numbers are represented as big endian or little endian. using this rule option. Also. Syntax
<uuid> [ ’. greater than (’>’).one for big endian and one for little endian.
This option is used to specify an interface UUID. The representation of the interface UUID is different depending on the endianness speciﬁed in the DCE/RPC previously requiring two rules . An interface contains a version.<2. the following Messenger interface UUID as taken off the wire from a little endian Bind request:
79
. The server will respond with the interface UUIDs it accepts as valid and will allow the client to make requests to those services. hexlong and hexshort will be speciﬁed and interpreted to be in big endian order (this is usually the default way an interface UUID will be seen and represented). a middle or the last fragment. Each interface UUID is paired with a unique index (or context id) that future requests can use to reference the service that the client is making a call to. When a client sends a bind request to the server. Flags (and a ﬁeld in the connectionless header) are set in the DCE/RPC header to indicate whether the fragment is the ﬁrst. however. However. Some versions of an interface may not be vulnerable to a certain exploit. 4b324fc8-1670-01d3-1278-5a47bf6ee188. This can be a source of false positives in fragmented DCE/RPC trafﬁc. 4b324fc8-1670-01d3-1278-5a47bf6ee188. it will specify the context id so the server knows what service the client is making a request to. When a client makes a request.

15-18. i. After is has been determined that a client has bound to a speciﬁc interface and is making a request to it (see above . Note that a defragmented DCE/RPC request will be considered a full request. This option matches if any one of the opnums speciﬁed match the opnum of the DCE/RPC request. dce opnum The opnum represents a speciﬁc function call to an interface.|f8 91 7b 5a 00 ff d0 11 a9 b2 00 c0 4f b6 e6 fc| must be written as: 5a7b91f8-ff00-11d0-a9b2-00c04fb6e6fc The same UUID taken off the wire from a big endian Bind request: |5a 7b 91 f8 ff 00 11 d0 a9 b2 00 c0 4f b6 e6 fc| must be written the same way: 5a7b91f8-ff00-11d0-a9b2-00c04fb6e6fc This option matches if the speciﬁed interface UUID matches the interface UUID (as referred to by the context id) of the DCE/RPC request and if supplied. Syntax
<opnum-list> opnum-list opnum-item opnum-range opnum = = = = opnum-item | opnum-item ’. 15. 15.18-20. This option will not match if the fragment is not a ﬁrst fragment (or full request) unless the any frag option is supplied in which case only the interface UUID and version need match.17. the remote procedure call or function call data.
80
.e. the version operation is true.
This option is used to specify an opnum (or operation number). It is likely that an exploit lies in the particular DCE/RPC function call. opnum range or list containing either or both opnum and/or opnum-range. dce stub data Since most netbios rules were doing protocol decoding only to get to the DCE/RPC stub data. Example
dce_stub_data. This reduces the number of rule option checks and the complexity of the rule. This option takes no arguments. this option will alleviate this need and place the cursor at the beginning of the DCE/RPC stub data.20-22.dce iface) usually we want to know what function call it is making to that service. The opnum of a DCE/RPC request will be matched against the opnums speciﬁed with this option.’ opnum-list opnum | opnum-range opnum ’-’ opnum 0-65535
Examples
dce_opnum: dce_opnum: dce_opnum: dce_opnum: 15.

conf that reference the rules ﬁles.3. classtype:protocol-command-decode. They also allow one to specify the rule type or action of a decoder or preprocessor event on a rule by rule basis.g. just comment it with a # or remove the rule completely from the ﬁle (commenting is recommended). if config disable decode alerts is in snort. and have the names decoder. gid: 116. \ metadata: rule-type decode . deﬁne the path to where the rules are located and uncomment the include lines in snort. just replace alert with the desired rule type.rules and preprocessor..decode for conﬁg options that control decoder events..1 Conﬁguring
The following options to conﬁgure will enable decoder and preprocessor rules: $ . See README. See doc/README. these options will take precedence over the event type of the rule. README. include $PREPROC_RULE_PATH/preprocessor. Any one of the following rule types can be used: alert log pass drop sdrop reject For example one can change: alert ( msg: "DECODE_NOT_IPV4_DGRAM".) to drop ( msg: "DECODE_NOT_IPV4_DGRAM". These ﬁles are updated as new decoder and preprocessor events are added to Snort.decode. decoder events will not be generated regardless of whether or not there are corresponding rules for the event. To enable these rules in snort. the drop cases only apply if Snort is running inline.) to drop (as well as alert on) packets where the Ethernet protocol is IPv4 but version ﬁeld in IPv4 header has a value other than 4. rev: 1. rev: 1. gid: 116. sid: 1.conf or the decoder or preprocessor rule type is drop./configure --enable-decoder-preprocessor-rules The decoder and preprocessor rules are located in the preproc rules/ directory in the top level source tree. \ metadata: rule-type decode . sid: 1.rules and preprocessor. To change the rule type or action of a decoder/preprocessor rule. A packet will be dropped if either a decoder conﬁg drop option is in snort.rules To disable any rule.
2.conf.3 Decoder and Preprocessor Rules
Decoder and preprocessor rules allow one to enable and disable decoder and preprocessor events on a rule by rule basis.rules respectively. classtype:protocol-command-decode. config enable decode drops. 82
.rules.conf. Also note that if the decoder is conﬁgured to enable drops.2. Of course.gre and the various preprocessor READMEs for descriptions of the rules in decoder. Decoder conﬁg options will still determine whether or not to generate decoder events. For example. var PREPROC_RULE_PATH /path/to/preproc_rules .rules include $PREPROC_RULE_PATH/decoder. e.

• Rate Filters You can use rate ﬁlters to change a rule action when the number or rate of events indicates a possible attack. otherwise they will be loaded.all are required except apply to.10.1 Rate Filtering
rate filter provides rate based attack prevention by allowing users to conﬁgure a new action to take for a speciﬁed time when a given rate is exceeded.
83
.
2. This can be tuned to signiﬁcantly reduce false alarms. Format Rate ﬁlters are used as standalone conﬁgurations (outside of a rule) and have the following format: rate_filter \ gen_id <gid>. • Event Filters You can use event ﬁlters to reduce the number of logged events for noisy rules.3.4 Event Processing
Snort provides a variety of mechanisms to tune event processing to suit your needs: • Detection Filters You can use detection ﬁlters to speciﬁy a threshold that must be exceeded before a rule generates an event. This option applies to rules not speciﬁed and the default behavior is to alert. \ timeout <seconds> \ [. the following conﬁg option in snort.2 Reverting to original behavior
If you have conﬁgured snort to use decoder and preprocessor rules. \ track <by_src|by_dst|by_rule>. Multiple rate ﬁlters can be deﬁned on the same rule. and the ﬁrst applicable action is taken.2. in which case they are evaluated in the order they appear in the conﬁguration ﬁle.conf.4. \ count <c>. • Event Suppression You can completely suppress the logging of unintersting events. \ new_action alert|drop|pass|log|sdrop|reject.7. apply_to <ip-list>] The options are described in the table below . seconds <s>. which is optional. sig_id <sid>.
2. you also have to remove the decoder and preprocessor rules and any reference to them from snort. This is covered in section 3.conf will make Snort revert to the old behavior: config autogenerate_preprocessor_decoder_rules Note that if you want to revert to the old behavior.

There are 3 types of event ﬁlters: • limit Alerts on the 1st m events during the time interval. source and destination means client and server respectively. the maximum number of rule matches in s seconds before the rate ﬁlter limit to is exceeded. track by rule and apply to may not be used together. sdrop and reject are conditionally compiled with GIDS. seconds 1. new action replaces rule action for t seconds. then rule action is never reverted back.4. reject. seconds 0.Option track by src | by dst | by rule
count c seconds s
new action alert | drop | pass | log | sdrop | reject timeout t
apply to <ip-list>
Description rate is tracked either by source IP address.2 Event Filtering
Event ﬁltering can be used to reduce the number of logged alerts for noisy rules by limiting the number of times a particular event is logged during a speciﬁed time interval. For example. 84
. If t is 0. for each unique destination IP address. \ track by_src. This can be tuned to signiﬁcantly reduce false alarms. 0 seconds only applies to internal rules (gen id 135) and other use will produce a fatal error by Snort. or by rule. \ new_action drop. and block further connections from that IP address for 10 seconds: rate_filter \ gen_id 135.
Examples Example 1 . the time period over which count is accrued. An event filter may be used to manage number of alerts after the rule action is enabled by rate filter.allow a maximum of 100 successful simultaneous connections from any one IP address. sig_id 1. even if the rate falls below the conﬁgured limit. restrict the conﬁguration to only to source or destination IP address (indicated by track parameter) determined by <ip-list>. \ new_action drop. track by rule and apply to may not be used together. revert to the original rule action after t seconds. Note that events are generated during the timeout period. rate filter may be used to detect if the number of connections to a speciﬁc server exceed a speciﬁc count. \ track by_src. and sdrop can be used only when snort is used in inline mode. drop. or they are aggregated at rule level. destination IP address. then ignores events for the rest of the time interval. This means the match statistics are maintained for each unique source IP address.allow a maximum of 100 connection attempts per second from any one IP address. For rules related to Stream5 sessions. timeout 10 Example 2 . \ count 100. timeout 10
2. and block further connection attempts from that IP address for 10 seconds: rate_filter \ gen_id 135. \ count 100. c must be nonzero value. sig_id 2. 0 seconds means count is a total count instead of a speciﬁc rate.

This means count is maintained for each unique source IP addresses.
track by src|by dst
count c seconds s
! △NOTE
Only one event filter may be deﬁned for a given gen id. Type both alerts once per time interval after seeing m occurrences of the event. seconds <s> threshold is an alias for event filter. If more than one event filter is applied to a speciﬁc gen id. then the ﬁlter applies to all rules. \ track <by_src|by_dst>. sig id 0 can be used to specify a ”global” threshold that applies to all rules.
event filters with sig id 0 are considered ”global” because they apply to all rules with the given gen id. the global ﬁltering test is applied. sig id 0 speciﬁes a ”global” ﬁlter because it applies to all sig ids for the given gen id. Standard ﬁltering tests are applied ﬁrst. gen id 0. or for each unique destination IP addresses. \ count <c>. rate is tracked either by source IP address.all are required. \ count <c>. sig_id <sid>. if they do not block an event from being logged. sig id.
85
. threshold is deprecated and will not be supported in future releases. c must be nonzero value. then ignores events for the rest of the time interval. (gen id 0. Type threshold alerts every m times we see this event during the time interval. sig id pair. \ type <limit|threshold|both>. then ignores any additional events during the time interval. \ type <limit|threshold|both>. s must be nonzero value. Thresholds in a rule (deprecated) will override a global event filter. • both Alerts once per time interval after seeing m occurrences of the event. \ track <by_src|by_dst>. sig id != 0 is not allowed). sig_id <sid>. Global event filters do not override what’s in a signature or a more speciﬁc stand-alone event filter. If gen id is also 0.• threshold Alerts every m times we see this event during the time interval. Format event_filter \ gen_id <gid>. type limit alerts on the 1st m events during the time interval. Option gen id <gid> sig id <sid> type limit|threshold|both Description Specify the generator ID of an associated rule. number of rule matching in s seconds that will cause event filter limit to be exceeded. seconds <s> threshold \ gen_id <gid>. then ignores any additional events during the time interval. Snort will terminate with an error while reading the conﬁguration information. Specify the signature ID of an associated rule. time period over which count is accrued. Ports or anything else are not tracked. or destination IP address. Both formats are equivalent and support the options described below .

\ suppress \ gen_id <gid>.2. This is optional. sig_id 1852: Suppress this event from this IP: suppress gen_id 1.1. SIDs. sig id 0 speciﬁes a ”global” ﬁlter because it applies to all sig ids for the given gen id. or suppressed when the causative trafﬁc is going to or coming from a speciﬁc IP or group of IP addresses. Specify the signature ID of an associated rule. ip 10. This allows a rule to be completely suppressed. Format The suppress conﬁguration has two forms: suppress \ gen_id <gid>. ip must be provided as well. gen id 0. Restrict the suppression to only source or destination IP addresses (indicated by track parameter) determined by ¡list¿. Suppression tests are performed prior to either standard or global thresholding tests.1. sig_id 1852. sig_id <sid>. sig_id <sid>. You may also combine one event filter and several suppressions to the same non-zero SID. but if present.
Examples Suppress this event completely: suppress gen_id 1.4. Suppress by source IP address or destination IP address. track by_dst.0/24
87
. You may apply multiple suppressions to a non-zero SID.1.3 Event Suppression
Event suppression stops speciﬁed events from ﬁring without removing the rule from the rule base. \ track <by_src|by_dst>. ip 10. track by_src. Suppression are standalone conﬁgurations that reference generators.54 Suppress this event to this CIDR block: suppress gen_id 1. sig id 0 can be used to specify a ”global” threshold that applies to all rules. ip must be provided as well. sig_id 1852. and IP addresses via an IP list . Suppression uses an IP list to select speciﬁc networks and users for suppression. ip <ip-list> Option gen id <gid> sig id <sid> track by src|by dst ip <list> Description Specify the generator ID of an associated rule.1. If track is provided.

max queue This determines the maximum size of the event queue. previous data in these ﬁles will be overwritten. and rules that have a longer content are ordered before rules with shorter contents. Each require only a simple config option to snort. if the event queue has a max size of 8. The method in which events are ordered does not affect rule types such as pass. When a ﬁle name is provided in profile rules or profile preprocs. We currently have two different methods: • priority . 1. alert.conf and Snort will print statistics on the worst (or all) performers on exit. The general conﬁguration of the event queue is as follows: config event_queue: [max_queue [size]] [log [size]] [order_events [TYPE]] Event Queue Conﬁguration Options There are three conﬁguration options to the conﬁguration parameter ’event queue’. • content length . such as max content length or event ordering using the event queue.Rules are ordered before decode or preprocessor alerts.5 Performance Proﬁling
Snort can provide statistics on rule and preprocessor performance. the statistics will be saved in these ﬁles.2. You can’t log more than the max event number that was speciﬁed. log. log This determines the number of events to log for a given packet or stream. The default value is 8. The default value is content length. 2. For example.4. but change event order: config event_queue: order_events priority Use the default event queue values but change the number of logged events: config event_queue: log 2
2. order events This argument determines the way that the incoming events are ordered. If the append option is not present. 88
. 3. Event Queue Conﬁguration Examples The default conﬁguration: config event_queue: max_queue 8 log 3 order_events content_length Example of a reconﬁgured event queue: config event_queue: max_queue 10 log 3 order_events content_length Use the default event queue values. only 8 events will be stored for a single packet or stream. The default value is 3. etc.4 Event Logging
Snort supports logging multiple events per packet/stream that are prioritized with different insertion methods.The highest priority (1 being the highest) events are ordered ﬁrst.

filename <filename> [append]] • <num> is the number of preprocessors to print 90
. The Microsecs (or Ticks) column is important because that is the total time spent evaluating a given rule.2 Preprocessor Proﬁling
Format config profile_preprocs: \ print [all | <num>]. By default.0 46229. sort total ticks
2.0 92458 46229. this information will be printed to the console when Snort exits.0 107822 53911.0 45027. These ﬁles will be found in the logging directory.5.0
Figure 2.Rule Profile Statistics (worst 4 rules) ========================================================== Num SID GID Rev Checks Matches Alerts === === === === ====== ======= ====== 1 2389 1 12 1 1 1 2 2178 1 17 2 0 0 3 2179 1 8 2 0 0 4 1734 1 37 2 0 0
Ticks Avg/Check ===== ========= 385698 385698. \ sort <sort_option> \ [. Quick to check. that most likely contains PCRE. High Checks and low Avg/Check is usually an any->any rule with few rule options and no content. the few options may or may not match. We are looking at moving some of these into code.0
Avg/Match Avg/Nonmatch ========= ============ 385698. But. print 4. if that rule is causing alerts.0 0. You can use the ”ﬁlename” option in snort. If ”append” is not speciﬁed. The ﬁlenames will have timestamps appended to them.0 90054 45027. A high Avg/Check is a poor performing rule.conf to specify a ﬁle where this will be written.1: Rule Proﬁling Example Output Output Snort will print a table much like the following at exit. will be high for rules that have no options) • Alerts (number of alerts generated from this rule) • CPU Ticks • Avg Ticks per Check • Avg Ticks per Match • Avg Ticks per Nonmatch Interpreting this info is the key.0 0. Conﬁguration line used to print the above table: config profile rules: The columns represent: • Number (rank) • Sig ID • Generator ID • Checks (number of times rule was evaluated after fast pattern match within portgroup or any->any rules) • Matches (number of times ALL rule options matched.0 0. a new ﬁle will be created each time Snort is run.0 53911. it makes sense to leave it alone. especially those with low SIDs.0 0.

non-instrumented code. sorted by number of checks config profile preprocs: Output Snort will print a table much like the following at exit.• <sort option> is one of: checks avg ticks total ticks • <filename> is the output ﬁlename • [append] dictates that the output will go to the same ﬁle each time (optional) Examples • Print all preprocessors. the Pct of Caller ﬁeld will not add up to 100% of the caller’s time.txt config profile preprocs. app layer header was correct. sort total_ticks The columns represent: • Number (rank) . a new ﬁle will be created each time Snort is run. • Preprocessor Name • Layer . and append to ﬁle preprocs stats. It does give a reasonable indication of how much relative time is spent within each subtask. i. The ﬁlenames will have timestamps appended to them. • Checks (number of times preprocessor decided to look at a packet. filename preprocs stats.When printing a speciﬁc number of preprocessors all subtasks info for a particular preprocessor is printed for each layer 0 preprocessor stat.txt append • Print the top 10 preprocessors. unless an exception was trapped) • CPU Ticks • Avg Ticks per Check • Percent of caller .The number is indented for each layer. sort by avg ticks. If ”append” is not speciﬁed. By default. and other factors. Conﬁguration line used to print the above table: config profile_rules: \ print 3. Layer 1 preprocessors are listed under their respective caller (and sorted similarly). this identiﬁes the percent of the caller’s ticks that is spent for this subtask. subroutines within preprocessors.conf to specify a ﬁle where this will be written. sort by avg ticks (default conﬁguration if option is turned on) config profile preprocs • Print all preprocessors. These ﬁles will be found in the logging directory. 91 print all. ports matched. sort avg ticks • Print all preprocessors.e. etc) • Exits (number of corresponding exits – just to verify code is instrumented correctly. should ALWAYS match Checks. Because of task swapping. based on highest average time config profile preprocs: print 10. this information will be printed to the console when Snort exits. sort checks
.For non layer 0 preprocessors. You can use the ”ﬁlename” option in snort.

3 Packet Performance Monitoring (PPM)
PPM provides thresholding mechanisms that can be used to provide a basic level of latency control for snort. The following sections describe conﬁguration. \ debug-pkts # Rule configuration: config ppm: max-rule-time <micro-secs>.5. \ fastpath-expensive-packets. PPM is conﬁgured as follows: # Packet configuration: config ppm: max-pkt-time <micro-secs>. \ suspend-expensive-rules. so one or both or neither may be enabled. sample output. Conﬁguration Packet Conﬁguration Options max-pkt-time <micro-secs> • enables packet latency thresholding using ’micros-secs’ as the limit. or together in just one conﬁg ppm statement. \ threshold count. Both rules and packets can be checked for latency. Packet and rule monitoring is independent. \ suspend-timeout <seconds>. It does not provide a hard and fast latency guarantee but should in effect provide a good average latency control. • default is 0 (packet latency thresholding disabled) • reasonable starting defaults: 100/250/1000 for 1G/100M/5M nets fastpath-expensive-packets • enables stopping further inspection of a packet if the max time is exceeded • default is off pkt-log • enables logging packet event if packet exceeds max-pkt-time • logging is to syslog or console depending upon snort conﬁguration • default is no logging debug-pkts • enables per packet timing stats to be printed after each packet • default is off
93
. you must build with the –enable-ppm or the –enable-sourceﬁre option to conﬁgure. \ rule-log [log] [alert] Packets and rules can be conﬁgured separately.2. \ pkt-log. as above. and some implementation details worth noting. To use PPM. The action taken upon detection of excessive latency is conﬁgurable.

94
. threshold 5 If fastpath-expensive-packets or suspend-expensive-rules is not used. A summary of this information is printed out when snort exits. Example 2: The following suspends rules and aborts packet inspection. These rules were used to generate the sample output that follows.Rule Conﬁguration Options max-rule-time <micro-secs> • enables rule latency thresholding using ’micros-secs’ as the limit. then no action is taken other than to increment the count of the number of packets that should be fastpath’d or the rules that should be suspended. • default is 0 (rule latency thresholding disabled) • reasonable starting defaults: 100/250/1000 for 1G/100M/5M nets threshold <count> • sets the number of consecutive rule time excesses before disabling a rule • default is 5 suspend-expensive-rules • enables suspending rule inspection if the max rule time is exceeded • default is off suspend-timeout <seconds> • rule suspension time in seconds • default is 60 seconds • set to zero to permanently disable expensive rules rule-log [log] [alert] • enables event logging output for rules • default is no logging • one or both of the options ’log’ and ’alert’ must be used with ’rule-log’ • the log option enables output to syslog or console depending upon snort conﬁguration Examples Example 1: The following enables packet tracking: config ppm: max-pkt-time 100 The following enables rule tracking: config ppm: max-rule-time 50.

Latency control is not enforced after each preprocessor. after the preprocessors and detection engine. giving users greater ﬂexibility in logging alerts. The format of the directives in the rules ﬁle is very similar to that of the preprocessors.1 alert syslog
This module sends alerts to the syslog facility (much like the -s command line switch). The output modules are run when the alert or logging subsystems of Snort are called. This module also allows the user to specify the logging facility and priority within the Snort rules ﬁle. Output modules are loaded at runtime by specifying the output keyword in the rules ﬁle: output <name>: <options> output alert_syslog: log_auth log_alert
2. not just the processor time the Snort application receives. • Since this implementation depends on hardware based high performance frequency counters. As with the standard logging and alerting systems. alert) are speciﬁed.6. Therefore this implementation cannot implement a precise latency guarantee with strict timing guarantees.2675 usecs
• Enforcement of packet and rule processing times is done after processing each rule.
2. output plugins send their data to /var/log/snort by default or to a user directed directory (using the -l command line switch).6 Output Modules
Output modules are new as of version 1. they are stacked and called in sequence when an event occurs. When multiple plugins of the same type (log. latency thresholding is presently only available on Intel and PPC platforms. • Time checks are made based on the total system time.6. the latency for a packet is based on the total system time. not processor usage by Snort. Available Keywords Facilities • log auth • log authpriv • log daemon 96
. Therefore. They allow Snort to be much more ﬂexible in the formatting and presentation of output to its users. Hence the reason this is considered a best effort approach.max rule time rule events avg nc-rule time Implementation Details
: 50 usecs : 0 : 0. Multiple output plugins may be speciﬁed in the Snort conﬁguration ﬁle. it is recommended that you tune your thresholding to operate optimally when your system is under load. Due to the granularity of the timing measurements any individual packet may exceed the user speciﬁed packet or rule processing time limit. • This implementation is software based and does not use an interrupt driven timing mechanism and is therefore subject to the granularity of the software based timing tests. This was a conscious design decision because when a system is loaded.

Inside the logging directory. This output method is discouraged for all but the lightest trafﬁc situations. It is a faster alerting method than full alerts because it doesn’t need to print all of the packet headers to the output ﬁle Format alert_fast: <output filename> Example output alert_fast: alert.1.3 alert full
This will print Snort alert messages with full packet headers. These ﬁles will be decoded packet dumps of the packets that triggered the alerts. <facility> <priority> <options>
2.Example output alert_syslog: 10. Format alert_unixsock Example output alert_unixsock
98
. Format alert_full: <output filename> Example output alert_full: alert.1:514.full
2.6.6.fast
2. External programs/processes can listen in on this socket and receive Snort alert and packet data in real time.1.6. This is currently an experimental interface. The creation of these ﬁles slows Snort down considerably. The alerts will be written in the default logging directory (/var/log/snort) or in the logging directory speciﬁed at the command line.4 alert unixsock
Sets up a UNIX domain socket and sends alert reports to it. a directory will be created per IP.2 alert fast
This will print Snort alerts in a quick one-line format to a speciﬁed output ﬁle.

Storage requirements .not readable requires post processing 99
.3 for example usage. see Figure 2.∼1. there is no one simple and portable way to store it in a database. The arguments to this plugin are the name of the database to be logged to and a parameter list. TCP/IP communication is used.5 log tcpdump
The log tcpdump module logs packets to a tcpdump-formatted ﬁle. This is so that data from separate Snort runs can be kept distinct. one will be generated automatically encoding . If you do not specify a name. Format log_tcpdump: <output filename> Example output log_tcpdump: snort.impossible without post processing Human readability .very good Human readability . Each has its own advantages and disadvantages: hex (default) . Without a host name.org web page. Parameters are speciﬁed with the format parameter = argument.6.Port number to connect to at the server host.Specify your own name for this Snort sensor.Represent binary data as a base64 string. This is useful for performing post-process analysis on collected trafﬁc with the vast number of tools that are available for examining tcpdump-formatted ﬁles. Note that the ﬁle name will have the UNIX timestamp in seconds appended the ﬁle name.6 database
This module from Jed Pickel sends Snort data to a variety of SQL databases. requires post processing base64 . This module only takes a single argument: the name of the output ﬁle.log
2. So i leave the encoding option to you.6.2x the size of the binary Searchability . dbname .Represent binary data as a hex string. Format database: <log | alert>. port . Storage requirements .Password used if the database demands password authentication sensor name .Database username for authentication password . <database type>.Database name user .2. More information on installing and conﬁguring this module can be found on the [91]incident. or socket ﬁlename extension for UNIX-domain connections. You can choose from the following options.Host to connect to. Blobs are not used because they are not portable across databases.Because the packet payload and option data is binary. it will connect using a local UNIX domain socket. <parameter list> The following parameters are available: host . If a non-zero-length string is speciﬁed.not readable unless you are a true geek.3x the size of the binary Searchability .

destination ip.5 for more details. dbname=snort user=snort host=localhost password=xyz Figure 2. signature. the output is in the order the formatting option is listed. Non-ASCII Data is represented as a ‘.’. and protocol) Furthermore. These are mssql.How much detailed data do you want to store? The options are: full (default) . postgresql. then data for IP and TCP options will still be represented as hex because it does not make any sense for that data to be ASCII. the plugin will be called on the log output chain.slightly larger than the binary because some characters are escaped (&. oracle. Set the type to match the database you are using.Log all details of a packet that caused an alert (including IP/TCP options and the payload) fast . destination port. log and alert. • timestamp • sig generator • sig id • sig rev • msg • proto • src • srcport
100
.>) Searchability . The following ﬁelds are logged: timestamp.
! △NOTE
The database output plugin does not have the ability to handle alerts that are generated by using the tag keyword. Storage requirements . There are two logging types available. mysql.Log only a minimum amount of data.
2. If you choose this option.very good for searching for a text string impossible if you want to search for binary human readability . but this is still the best choice for some applications.very good detail . Setting the type to alert attaches the plugin to the alert output chain within the program.<. mysql.6. You severely limit the potential of some analysis applications if you choose this option. The plugin requires 2 arguments: a full pathname to a ﬁle and the output formatting option. Setting the type to log attaches the database logging functionality to the log facility within the program.output database: \ log. The list of formatting options is below. If the formatting option is default. source port. There are ﬁve database types available in the current version of the plugin.3: Database Output Plugin Conﬁguration ascii . If you set the type to log. there is a logging method and database type that must be deﬁned. tcp flags.Represent binary data as an ASCII string. See section 3. This is the only option where you will actually lose data.7.7 csv
The csv output plugin allows alert data to be written in a format easily importable to a database. and odbc. source ip.

2. snort must be built with the –enable-aruba argument passed to .8. Format output log_null Example output log_null # like using snort -n
ruletype info { type alert output alert_fast: info. see http: //www. This is equivalent to using the -n command line option but it is able to work within a ruletype.6. see http://www.alert output log_null }
2. Format output alert_prelude: \ profile=<name of prelude profile> \ [ info=<priority number for info priority alerts>] \ [ low=<priority number for low priority alerts>] \ [ medium=<priority number for medium priority alerts>] Example output alert_prelude: profile=snort info=4 low=3 medium=2
2. For more information on Aruba Networks access control.12 alert aruba action
! △NOTE
Support to use alert aruba action is not built in by default.11 log null
Sometimes it is useful to be able to create rules that will alert to certain types of trafﬁc but will not cause packet log entries.prelude-ids. Format output alert_aruba_action: \ <controller address> <secrettype> <secret> <action>
103
. To use alert aruba action.6.org/./conﬁgure.The alert prelude output plugin is used to log to a Prelude database. For more information on Prelude.
Communicates with an Aruba Networks wireless mobility controller to change the status of authenticated users. This allows Snort to take action against users on the Aruba controller to control their network privilege levels.arubanetworks.com/. the log null plugin was introduced. In Snort 1.

7 Host Attribute Table
Starting with version 2. used to reduce the size of the ﬁle for common data elements. or the trafﬁc doesn’t have any matching service information. For rule evaluation.Blacklist the station by disabling all radio communication.2. and the host attribute section. The table is re-read during run time upon receipt of signal number 30. Snort must be conﬁgured with the –enable-targetbased ﬂag.Authentication secret conﬁgured on the Aruba mobility controller with the ”aaa xml-api client” conﬁguration command. secret .2 Attribute Table File Format
The attribute table uses an XML format and consists of two sections. a mapping section.1) and TCP Stream reassembly policies (see section 2. which is loaded at startup. Snort associates a given packet with its attribute data from the table. If the rule doesn’t have protocol metadata.2).The following parameters are required: controller address . The mapping section is optional.7. represented as a sha1 or md5 hash.1. ”md5” or ”cleartext”. and IP-Frag policy (see section 2. service information is used instead of the ports when the protocol metadata in the rule matches the service corresponding to the trafﬁc.
! △NOTE
To use a host attribute table. <SNORT_ATTRIBUTES> <ATTRIBUTE_MAP> <ENTRY> <ID>1</ID> <VALUE>Linux</VALUE> </ENTRY> <ENTRY> <ID>2</ID> 104
. action . setrole:rolename . secrettype . one of ”sha1”. if applicable. Snort has the capability to use information from an outside source to determine both the protocol for use with Snort rules.Change the user´ role to the speciﬁed rolename.Action to apply to the source IP address of the trafﬁc generating an alert. blacklist .1 Conﬁguration Format
attribute_table filename <path to file>
2. or a cleartext password. An example of the ﬁle format is shown below.
2.6 cleartext foobar setrole:quarantine_role
2.2. s Example output alert_aruba_action: \ 10.Secret type.9.3.8. This information is stored in an attribute table.7. the rule relies on the port information.Aruba mobility controller address.

conf or via command-line options. They can be loaded via directives in snort.
A DTD for veriﬁcation of the Host Attribute Table XML ﬁle is provided with the snort packages. Of the service attributes. etc). only the IP protocol (tcp. for a given host entry. etc) are used. the stream and IP frag information are both used.8.6. port.1 Format
<directive> <parameters>
106
. The application and version for a given service attribute.
2.</PROTOCOL> <APPLICATION> <ATTRIBUTE_VALUE>telnet</ATTRIBUTE_VALUE> <CONFIDENCE>50</CONFIDENCE> </APPLICATION> </SERVICE> </SERVICES> <CLIENTS> <CLIENT> <IPPROTO> <ATTRIBUTE_VALUE>tcp</ATTRIBUTE_VALUE> <CONFIDENCE>100</CONFIDENCE> </IPPROTO> <PROTOCOL> <ATTRIBUTE_ID>http</ATTRIBUTE_ID> <CONFIDENCE>91</CONFIDENCE> </PROTOCOL> <APPLICATION> <ATTRIBUTE_ID>IE Http Browser</ATTRIBUTE_ID> <CONFIDENCE>90</CONFIDENCE> <VERSION> <ATTRIBUTE_VALUE>6. and protocol (http.
! △NOTE
To disable use of dynamic modules.1. Snort must be conﬁgured with the --disable-dynamicplugin ﬂag.8 Dynamic Modules
Dynamically loadable modules were introduced with Snort 2.8. They will be used in a future release. and any client attributes are ignored. udp.0</ATTRIBUTE_VALUE> <CONFIDENCE>89</CONFIDENCE> </VERSION> </APPLICATION> </CLIENT> </CLIENTS> </HOST> </ATTRIBUTE_TABLE> </SNORT_ATTRIBUTES>
! △NOTE
With Snort 2.
2. ssh.

followed by the full or relative path to a directory of detection rules shared libraries. Or. however.
! △NOTE is not currently supported in Windows. See chapter 5 for more information on dynamic preprocessor libraries. add --disable-reload-error-restart in addition to --enable-reload to conﬁgure when compiling.1 Enabling support
To enable support for reloading a conﬁguration.3 below). add --enable-reload to conﬁgure when compiling. Note that for some preprocessors. Or. This functionality
2. A separate thread will parse and create a swappable conﬁguration object while the main Snort packet processing thread continues inspecting trafﬁc under the current conﬁguration.2 Reloading a conﬁguration
First modify your snort.9.2 Directives
Syntax dynamicpreprocessor [ file <shared library path> | directory <directory of shared libraries> ] Description Tells snort to load the dynamic preprocessor shared library (if ﬁle is used) or all dynamic preprocessor shared libraries (if directory is used). (Same effect as --dynamic-detection-lib or --dynamic-detection-lib-dir options). followed by the full or relative path to the shared library. Specify file. Specify file. See chapter 5 for more information on dynamic detection rules libraries. followed by the full or relative path to a directory of preprocessor shared libraries.9. Tells snort to load the dynamic detection rules shared library (if ﬁle is used) or all dynamic detection rules shared libraries (if directory is used). e. When a swappable conﬁguration object is ready for use. followed by the full or relative path to the shared library.g. To disable this behavior and have Snort exit instead of restart. Tells snort to load the dynamic engine shared library (if ﬁle is used) or all dynamic engine shared libraries (if directory is used). to initiate a reload.
dynamicengine [ file <shared library path> | directory <directory of shared libraries> ]
dynamicdetection [ file <shared library path> | directory <directory of shared libraries> ]
2. the main Snort packet processing thread will swap in the new conﬁguration to use and will continue processing under the new conﬁguration. Specify file. This option is enabled by default and the behavior is for Snort to restart if any nonreloadable options are added/modiﬁed/removed. specify directory. specify directory. There is also an ancillary option that determines how Snort should behave if any non-reloadable options are changed (see section 2.9 Reloading a Snort Conﬁguration
Snort now supports reloading a conﬁguration in lieu of restarting Snort in so as to provide seamless trafﬁc inspection during a conﬁguration change. specify directory. send Snort a SIGHUP signal. (Same effect as --dynamic-engine-lib or --dynamic-preprocessor-lib-dir options). existing session data will continue to use the conﬁguration under which they were created in order to continue with proper state for that session. use the new conﬁguration. Then. followed by the full or relative path to a directory of preprocessor shared libraries. 107
. Or.2.9.conf (the ﬁle passed to the -c option on the command line).8.
2. (Same effect as --dynamic-preprocessor-lib or --dynamic-preprocessor-lib-dir options). followed by the full or relative path to the shared library. See chapter 5 for more information on dynamic engine libraries. All newly created sessions will.

Those parameters are listed below the relevant conﬁg option or preprocessor. config ppm: max-rule-time <int> rule-log config profile_rules filename print sort config profile_preprocs filename print sort preprocessor dcerpc2 memcap preprocessor frag3_global max_frags memcap prealloc_frags prealloc_memcap preprocessor perfmonitor file snortfile preprocessor sfportscan memcap logfile preprocessor stream5_global memcap max_tcp max_udp max_icmp track_tcp track_udp track_icmp
2.dynamicdetection dynamicengine dynamicpreprocessor output In certain cases.1 Creating Multiple Conﬁgurations
Default conﬁguration for snort is speciﬁed using the existing -c option. only some of the parameters to a conﬁg option or preprocessor conﬁguration are not reloadable. using the following conﬁguration line: config binding: <path_to_snort. Each conﬁguration can have different preprocessor settings and detection rules. This will allow administrators to specify multiple snort conﬁguration ﬁles and bind each conﬁguration to one or more VLANs or subnets rather than running one Snort for each conﬁguration required.conf> vlan <vlanIdList> config binding: <path_to_snort. Each unique snort conﬁguration ﬁle will create a new conﬁguration instance within snort. A default conﬁguration binds multiple vlans or networks to non-default conﬁgurations.conf> net <ipList> 109
.10 Multiple Conﬁgurations
Snort now supports multiple conﬁgurations based on VLAN Id or IP subnet within a single instance of Snort.
2. VLANs/Subnets not bound to any speciﬁc conﬁguration will use the default conﬁguration.10.

A rule shares all parts of the rule options.conf .10.Refers to ip subnets. limited to: checksum_drop disable_decode_alerts disable_decode_drops disable_ipopt_alerts disable_ipopt_drops disable_tcpopt_alerts disable_tcpopt_drops disable_tcpopt_experimental_alerts disable_tcpopt_experimental_drops disable_tcpopt_obsolete_alerts disable_tcpopt_obsolete_drops disable_ttcp_alerts disable_tcpopt_ttcp_alerts disable_ttcp_drops
110
. they are included as valid in terms of conﬁguring Snort. their value applies to all other conﬁgurations. payload detection options.conf for speciﬁc conﬁguration. The following conﬁg options are speciﬁc to each conﬁguration. and post-detection options. ipList . If not deﬁned in a conﬁguration. Spaces are allowed within ranges.
! △NOTE
Vlan and Subnets can not be used in the same line. non-payload detection options. Valid vlanId is any number in 0-4095 range.2 Conﬁguration Speciﬁc Elements
Conﬁg Options Generally conﬁg options deﬁned within the default conﬁguration are global by default i. vlanIdList . including the general options. The format for ranges is two vlanId separated by a ”-”. config config config config config config config config config config config config config config Rules Rules are speciﬁc to conﬁgurations but only some parts of a rule can be customized for performance reasons.Refers to the absolute or relative path to the snort.
2.Refers to the comma seperated list of vlandIds and vlanId ranges.
! △NOTE
Even though Vlan Ids 0 and 4095 are reserved. Subnets can be CIDR blocks for IPV6 or IPv4. the default values of the option (not the default conﬁguration values) take effect.path to snort. Negative vland Ids and alphanumeric are not supported. Conﬁgurations can be applied based on either Vlans or Subnets not both.e. If a rule is not speciﬁed in a conﬁguration then the rule will never raise an event for the conﬁguration. policy_id policy_mode policy_version The following conﬁg options are speciﬁc to each conﬁguration. Parts of the rule header can be speciﬁed differently across conﬁgurations.

Source IP address and port Destination IP address and port Action A higher revision of a rule in one conﬁguration will override other revisions of the same rule in other conﬁgurations. Variables Variables deﬁned using ”var”, ”portvar” and ”ipvar” are speciﬁc to conﬁgurations. If the rules in a conﬁguration use variables, those variables must be deﬁned in that conﬁguration. Preprocessors Preprocessors conﬁgurations can be deﬁned within each vlan or subnet speciﬁc conﬁguration. Options controlling speciﬁc preprocessor memory usage, through speciﬁc limit on memory usage or number of instances, are processed only in default policy. The options control total memory usage for a preprocessor across all policies. These options are ignored in non-default policies without raising an error. A preprocessor must be conﬁgured in default conﬁguration before it can be conﬁgured in non-default conﬁguration. This is required as some mandatory preprocessor conﬁguration options are processed only in default conﬁguration. Events and Output An unique policy id can be assigned by user, to each conﬁguration using the following conﬁg line: config policy_id: <id> id - Refers to a 16-bit unsigned value. This policy id will be used to identify alerts from a speciﬁc conﬁguration in the uniﬁed2 records.

! △NOTE

If no policy id is speciﬁed, snort assigns 0 (zero) value to the conﬁguration.

Each event logged will have the vlanId from the packet if vlan headers are present otherwise 0 will be used.

111

2.10.3 How Conﬁguration is applied?
Snort assigns every incoming packet to a unique conﬁguration based on the following criteria. If VLANID is present, then the innermost VLANID is used to ﬁnd bound conﬁguration. If the bound conﬁguration is the default conﬁguration, then destination IP address is searched to the most speciﬁc subnet that is bound to a non-default conﬁguration. The packet is assigned non-default conﬁguration if found otherwise the check is repeated using source IP address. In the end, default conﬁguration is used if no other matching conﬁguration is found. For addressed based conﬁguration binding, this can lead to conﬂicts between conﬁgurations if source address is bound to one conﬁguration and destination address is bound to another. In this case, snort will use the ﬁrst conﬁguration in the order of deﬁnition, that can be applied to the packet.

112

Chapter 3

Writing Snort Rules
3.1 The Basics
Snort uses a simple, lightweight rules description language that is ﬂexible and quite powerful. There are a number of simple guidelines to remember when developing Snort rules that will help safeguard your sanity. Most Snort rules are written in a single line. This was required in versions prior to 1.8. In current versions of Snort, rules may span multiple lines by adding a backslash \ to the end of the line. Snort rules are divided into two logical sections, the rule header and the rule options. The rule header contains the rule’s action, protocol, source and destination IP addresses and netmasks, and the source and destination ports information. The rule option section contains alert messages and information on which parts of the packet should be inspected to determine if the rule action should be taken. Figure 3.1 illustrates a sample Snort rule.

The text up to the ﬁrst parenthesis is the rule header and the section enclosed in parenthesis contains the rule options. The words before the colons in the rule options section are called option keywords.

! △NOTE

Note that the rule options section is not speciﬁcally required by any rule, they are just used for the sake of making tighter deﬁnitions of packets to collect or alert on (or drop, for that matter).

All of the elements in that make up a rule must be true for the indicated rule action to be taken. When taken together, the elements can be considered to form a logical AND statement. At the same time, the various rules in a Snort rules library ﬁle can be considered to form a large logical OR statement.

3.2 Rules Headers
3.2.1 Rule Actions
The rule header contains the information that deﬁnes the who, where, and what of a packet, as well as what to do in the event that a packet with all the attributes indicated in the rule should show up. The ﬁrst item in a rule is the rule alert tcp any any -> 192.168.1.0/24 111 \ (content:"|00 01 86 a5|"; msg:"mountd access";) Figure 3.1: Sample Snort Rule 113

168.1.255. For example.log the packet 3. alert . activate. The CIDR block indicates the netmask that should be applied to the rule’s address and any incoming packets that are tested against the rule. you have additional options which include drop. etc. such as ARP. The keyword any may be used to deﬁne any address. and then send a TCP reset if the protocol is TCP or an ICMP port unreachable message if the protocol is UDP. In the future there may be more. This example will create a type that will log to just tcpdump: ruletype suspicious { type log output log_tcpdump: suspicious. IGRP. mysql. reject . The CIDR designations give us a nice short-hand way to designate large address spaces with just a few characters.remain idle until activated by an activate rule .168. RIP. log it.0/24 would signify the block of addresses from 192.168. log . and then log the packet 2.make iptables drop the packet but do not log it. pass . There are four protocols that Snort currently analyzes for suspicious behavior – TCP. Any rule that used this designation for. UDP. /16 a Class B network. There are 5 available default actions in Snort. sdrop . Snort does not have a mechanism to provide host name lookup for the IP address ﬁelds in the rules ﬁle. IPX.ignore the packet 4.2. 1. 8.make iptables drop the packet and log the packet 7. ICMP.1 to 192. You can then use the rule types as actions in Snort rules. activate . OSPF. and sdrop. The rule action tells Snort what to do when it ﬁnds a packet that matches the rule criteria. 114
. The addresses are formed by a straight numeric IP address and a CIDR[3] block. pass. GRE. A CIDR block mask of /24 indicates a Class C network. user=snort dbname=snort host=localhost }
3.make iptables drop the packet.
3. log.generate an alert using the selected alert method. alert.1. You can also deﬁne your own rule types and associate one or more output plugins with them. and /32 indicates a speciﬁc machine address.alert and then turn on another dynamic rule 5. reject.2.2 Protocols
The next ﬁeld in a rule is the protocol.3 IP Addresses
The next portion of the rule header deals with the IP address and port information for a given rule. the address/CIDR combination 192.log } This example will create a rule type that will log to syslog and a MySQL database: ruletype redalert { type alert output alert_syslog: LOG_AUTH LOG_ALERT output database: log. if you are running Snort in inline mode. drop . dynamic . In addition. say. and IP.1.action. and dynamic. the destination address would match on any address in that range. then act as a log rule 6.

1. meaning literally any port. The IP address and port numbers on the left side of the direction operator is considered to be the trafﬁc coming from the source log udp any any -> 192. how Zen. ranges. An IP list is speciﬁed by enclosing a comma separated list of IP addresses and CIDR blocks within square brackets.5.1.. The negation operator is indicated with a !.
3.) Figure 3.1. you could do something like the rule in Figure 3. the IP list may not include spaces between the addresses. which would translate to none.0/24 111 \ (content: "|00 01 86 a5|". \ msg: "external mountd access".0/24] 111 (content: "|00 01 86 a5|".0/24.
Port negation is indicated by using the negation operator !.
3.0/24 any -> 192. See Figure 3.1. Port ranges are indicated with the range operator :.3 for an example of an IP list in action. and the destination address was set to match on the 192.0/24 1:1024 log udp trafﬁc coming from any port and destination ports ranging from 1 to 1024 log tcp any any -> 192.alert tcp !192. For the time being. an easy modiﬁcation to the initial example is to make it alert on any trafﬁc that originates outside of the local net with the negation operator as shown in Figure 3.168. of the trafﬁc that the rule applies to.168. such as in Figure 3.0/24] any -> \ [192.168.1.1.1. Any ports are a wildcard value. static port deﬁnitions.2: Example IP Address Negation Rule alert tcp ![192. and by negation. the source IP address was set to match for any computer talking.1.1. including any ports. There is an operator that can be applied to IP addresses.5 The Direction Operator
The direction operator -> indicates the orientation. You may also specify lists of IP addresses.168. The range operator may be applied in a number of ways to take on different meanings. This operator tells Snort to match any IP address except the one indicated by the listed IP address.1. the negation operator.168.10. 23 for telnet.4.4: Port Range Examples 115
.168. etc. For example.1. The negation operator may be applied against any of the other rule types (except any. Static ports are indicated by a single port number.
This rule’s IP addresses indicate any tcp packet with a source IP address not originating from the internal network and a destination address on the internal network. if for some twisted reason you wanted to log everything except the X Windows ports.2.2. such as 111 for portmapper.4 Port Numbers
Port numbers may be speciﬁed in a number of ways.0/24.2.0/24 500: log tcp trafﬁc from privileged ports less than or equal to 1024 going to ports greater than or equal to 500 Figure 3..1.) Figure 3. For example.0/24 :6000 log tcp trafﬁc from any port going to ports less than or equal to 6000 log tcp any :1024 -> 192. or 80 for http. msg: "external mountd access".). or direction.168.1.3: IP Address Lists In Figure 3.10.168.0 Class C network.

\ msg: "IMAP buffer overflow!". This is handy for recording/analyzing both sides of a conversation.168.1. combining ease of use with power and ﬂexibility. so there’s value in collecting those packets for later analysis. and the address and port information on the right side of the operator is the destination host. You can now have one rule activate another when it’s action is performed for a set number of packets.168.operator.5: Example of Port Negation log tcp !192.7.) character. Activate rules are just like alerts but also tell Snort to add a rule when a speciﬁc network event occurs. If the buffer overﬂow happened and was successful. there’s a very good possibility that useful data will be contained within the next 50 (or whatever) packets going to that same service port on the network.0/24 23 Figure 3.) dynamic tcp !$HOME_NET any -> $HOME_NET 143 (activated_by: 1.6.7: Activate/Dynamic Rule Example
116
. count: 50.
Activate/dynamic rule pairs give Snort a powerful capability.) Figure 3.0/24 any <> 192.3 Rule Options
Rule options form the heart of Snort’s intrusion detection engine. except they have a *required* option ﬁeld: activates. Dynamic rules are just like log rules except are dynamically enabled when the activate rule id goes off.6 Activate/Dynamic Rules
! △NOTE
Activate and Dynamic rules are being phased out in favor of a combination of tagging (3. Rule option keywords are separated from their arguments with a colon (:) character.
3. which is indicated with a <> symbol.log tcp any any -> 192. but they have a different option ﬁeld: activated by. count. This tells Snort to consider the address/port pairs in either the source or destination orientation. Put ’em together and they look like Figure 3. \ content: "|E8C0FFFFFF|/bin".8. note that there is no <. Dynamic rules act just like log rules.1. Activate rules act just like alert rules. All Snort rule options are separated from each other using the semicolon (. These rules tell Snort to alert when it detects an IMAP buffer overﬂow and collect the next 50 packets headed for port 143 coming from outside $HOME NET headed to $HOME NET.5) and ﬂowbits (3. activates: 1. This is very useful if you want to set Snort up to perform follow on recording when a speciﬁc rule goes off. Also.0/24 !6000:6010 Figure 3.
3. such as telnet or POP3 sessions. Dynamic rules have a second required ﬁeld as well. An example of the bidirectional operator being used to record both sides of a telnet session is shown in Figure 3.6.2.168. The reason the <.1. In Snort versions before 1. the direction operator did not have proper error checking and many people used an invalid token.7.7.10).does not exist is so that rules always read consistently. There is also a bidirectional operator. activate tcp !$HOME_NET any -> $HOME_NET 143 (flags: PA.6: Snort rules using the Bidirectional Operator host.

reference:arachnids. \ flags:AP. It is a simple text string that utilizes the \ as an escape character to indicate a discrete character that might otherwise confuse Snort’s rules parser (such as the semi-colon . Make sure to also take a look at http://www.4). \
117
.4 General Rule Options
3.<id>.
3.nai.1: Supported Systems URL Preﬁx http://www.php3?id= (currently down) http://www.org/pub-bin/sigs-search.mitre. Table 3.) alert tcp any any -> any 21 (msg:"IDS287/ftp-wuftp260-venglin-linux".1 msg
The msg rule option tells the logging and alerting engine the message to print along with a packet dump or to an alert.] Examples alert tcp any any -> any 7070 (msg:"IDS411/dos-realaudio".securityfocus.<id>.4.2 reference
The reference keyword allows rules to include references to external attack identiﬁcation systems. The plugin currently supports several speciﬁc systems as well as unique URLs. [reference: <id system>. This plugin is to be used by output plugins to provide a link to additional information about the alert produced.”
3. Format msg: "<message text>".whitehats.com/vil/dispVirus.4. character).nessus.There are four major categories of rule options. \ flags:AP.com/bid/ http://cve.org/cgi-bin/cvename.snort. general These options provide information about the rule but do not have any affect during detection payload These options all look for data inside the packet payload and can be inter-related non-payload These options look for non-payload data post-detection These options are rule speciﬁc triggers that happen after a rule has “ﬁred.IDS411.cgi/ for a system that is indexing descriptions of alerts based on of the sid (See Section 3.asp?virus k= http://
System bugtraq cve nessus arachnids mcafee url
Format reference: <id system>.com/info/IDS http://vil. content:"|fff4 fffd 06|".4.org/plugins/dump. content:"|31c031db 31c9b046 cd80 31c031db|".cgi?name= http://cgi.

This information allows output plugins to identify rules easily. Format gid: <generator id>. reference:bugtraq. gid:1000001.4. sid:1000983.4) The ﬁle etc/gen-msg.)
118
.IDS287.)
3.4 sid
The sid keyword is used to uniquely identify Snort rules.3 gid
The gid keyword (generator id) is used to identify what part of Snort generates the event when a particular rule ﬁres.reference:arachnids. To avoid potential conﬂict with gids deﬁned in Snort (that for some reason aren’t noted it etc/generators).4. rev:1. it is not recommended that the gid keyword be used.000 Rules included with the Snort distribution • >1. \ reference:cve. See etc/generators in the source tree for the current generator ids in use. (See section 3.5) • <100 Reserved for future use • 100-1.000.map contains a mapping of alert messages to Snort rule IDs. sid:1.000. it will default to 1 and the rule will be part of the general rule subsystem.000 be used. Format sid: <snort rules id>.000 Used for local rules The ﬁle sid-msg. alert tcp any any -> any 80 (content:"BOB".map contains contains more information on preprocessor and decoder gids. alert tcp any any -> any 80 (content:"BOB". Note that the gid keyword is optional and if it is not speciﬁed in a rule. This information is useful when postprocessing alert to map an ID to an alert message.000. Example This example is a rule with a generator id of 1000001. This option should be used with the rev keyword. For general rule writing.4. This option should be used with the sid keyword. rev:1.4.CAN-2000-1574. (See section 3.)
3.1387. Example This example is a rule with the Snort Rule ID of 1000983. it is recommended that a value greater than 1. For example gid 1 is associated with the rules subsystem and various gids over 100 are designated for speciﬁc preprocessors and the decoder.

4. (See section 3.4.5 rev
The rev keyword is used to uniquely identify revisions of Snort rules. The ﬁle uses the following syntax: config classification: <class name>. rev:1. Format classtype: <class name>.<default priority>
These attack classiﬁcations are listed in Table 3. A priority of 1 (high) is the most severe and 3 (low) is the least severe.3. flags:A+. classtype:attempted-recon. This option should be used with the sid keyword. Revisions. \ content:"expn root".2: Snort Default Classiﬁcations Classtype attempted-admin attempted-user kickass-porn policy-violation shellcode-detect successful-admin successful-user trojan-activity unsuccessful-user web-application-attack Description Attempted Administrator Privilege Gain Attempted User Privilege Gain SCORE! Get the lotion! Potential Corporate Privacy Violation Executable code was detected Successful Administrator Privilege Gain Successful User Privilege Gain A Network Trojan was detected Unsuccessful User Privilege Gain Web Application Attack 119 Priority high high high high high high high high high high
.<class description>. along with Snort rule id’s.4) Format rev: <revision integer>.6 classtype
The classtype keyword is used to categorize a rule as detecting an attack that is part of a more general type of attack class. allow signatures and descriptions to be reﬁned and replaced with updated information. Table 3.4. Snort provides a default set of attack classes that are used by the default set of rules it provides. alert tcp any any -> any 80 (content:"BOB". Example This example is a rule with the Snort Rule Revision of 1. sid:1000983. They are currently ordered with 3 default priorities.) Attack classiﬁcations deﬁned by Snort reside in the classification.2. Example alert tcp any any -> any 25 (msg:"SMTP expn root". Deﬁning classiﬁcations for rules provides a way to better organize the event data Snort produces.)
3.config ﬁle. nocase.

Format priority: <priority integer>.config that are used by the rules it provides. A classtype rule assigns a default priority (deﬁned by the config classification option) that may be overridden with a priority rule.7 priority
The priority tag assigns a severity level to rules. \ dsize: >128. flags:A+.) alert tcp any any -> any 80 (msg:"EXPLOIT ntpdx overflow". Examples alert TCP any any -> any 80 (msg: "WEB-MISC phf attempt".conf by using the config classification option. \ content: "/cgi-bin/phf". priority:10. priority:10 ).4. Examples of each case are given below. classtype:attempted-admin.attempted-dos attempted-recon bad-unknown default-login-attempt denial-of-service misc-attack non-standard-protocol rpc-portmap-decode successful-dos successful-recon-largescale successful-recon-limited suspicious-ﬁlename-detect suspicious-login system-call-detect unusual-client-port-connection web-application-activity icmp-event misc-activity network-scan not-suspicious protocol-command-decode string-detect unknown tcp-connection
Attempted Denial of Service Attempted Information Leak Potentially Bad Trafﬁc Attempt to login by a default username and password Detection of a Denial of Service Attack Misc Attack Detection of a non-standard protocol or event Decode of an RPC Query Denial of Service Large Scale Information Leak Information Leak A suspicious ﬁlename was detected An attempted login using a suspicious username was detected A system call was detected A client was using an unusual port Access to a potentially vulnerable web application Generic ICMP event Misc activity Detection of a Network Scan Not Suspicious Trafﬁc Generic Protocol Command Decode A suspicious string was detected Unknown Trafﬁc A TCP connection was detected
medium medium medium medium medium medium medium medium medium medium medium medium medium medium medium medium low low low low low low low very low
Warnings The classtype option can only use classiﬁcations that have been deﬁned in snort.
3. Snort provides a default set of classiﬁcations in classification. 120
.

Multiple keys are separated by a comma.4: General rule option keywords Keyword msg reference gid Description The msg keyword tells the logging and alerting engine the message to print with the packet dump or alert. The gid keyword (generator id) is used to identify what part of Snort generates the event when a particular rule ﬁres. soid 3|12345. Table 3. \ metadata:engine shared.) alert tcp any any -> any 80 (msg: "Shared Library Rule Example".)
3.8 metadata
The metadata tag allows a rule writer to embed additional information about the rule. typically in a key-value format. metadata: key1 value1. the second a single metadata keyword. See Section 2. with keys separated by commas. while keys and values are separated by a space.) alert tcp any any -> any 80 (msg: "HTTP Service Rule Example". the rule is not applied (even if the ports speciﬁed in the rule match). Format The examples below show an stub rule from a shared library rule. with a key and a value.4. The reference keyword allows rules to include references to external attack identiﬁcation systems. key2 value2. otherwise.3. When the value exactly matches the service ID as speciﬁed in the table. 121
. Certain metadata keys and values have meaning to Snort and are listed in Table 3.4.
.7 for details on the Host Attribute Table. Keys other than those listed in the table are effectively ignored by Snort and can be free-form.3: Snort Metadata Keys Description Indicate a Shared Library Rule Shared Library Rule Generator and SID Target-Based Service Identiﬁer
Key engine soid service
Value Format ”shared” gid|sid ”http”
! △NOTE
The service Metadata Key is only meaningful when a Host Atttribute Table is provided.9 General Rule Quick Reference
Table 3. the rule is applied to that packet. \ metadata:engine shared.3. metadata:soid 3|12345. metadata: key1 value1. The ﬁrst uses multiple metadata keywords. Examples alert tcp any any -> any 80 (msg: "Shared Library Rule Example". \ metadata:service http.

typically in a key-value format. it can contain mixed text and binary data. the alert will be triggered on packets that do not contain this content. Note that multiple content rules can be speciﬁed in one rule. The example below shows use of mixed text and binary data in a Snort rule. and there are only 5 bytes of payload and there is no ”A” in those 5 bytes.5. The classtype keyword is used to categorize a rule as detecting an attack that is part of a more general type of attack class. If there must be 50 bytes for a valid match. modiﬁers included. Bytecode represents binary data as hexadecimal numbers and is a good shorthand method for describing complex binary data.5 Payload Detection Rule Options
3. Examples alert tcp any any -> any 139 (content:"|5c 00|P|00|I|00|P|00|E|00 5c|".) alert tcp any any -> any 80 (content:!"GET". The option data for the content keyword is somewhat complex. If the rule is preceded by a !. if using content:!"A".1 content
The content keyword is one of the more important features of Snort.
3. This is useful when writing rules that want to alert on packets that do not match a certain pattern
! △NOTE
Also note that the following characters must be escaped inside a content rule: : .)
! △NOTE
A ! modiﬁer negates the results of the entire content search.sid rev classtype priority metadata
The sid keyword is used to uniquely identify Snort rules. The binary data is generally enclosed within the pipe (|) character and represented as bytecode. Be aware that this test is case sensitive. the result will return a match. If data exactly matching the argument data string is contained anywhere within the packet’s payload. within:50. the Boyer-Moore pattern match function is called and the (rather computationally expensive) test is performed against the packet contents. It allows the user to set rules that search for speciﬁc content in the packet payload and trigger response based on that data. The metadata keyword allows a rule writer to embed additional information about the rule. This allows rules to be tailored for less false positives. Whenever a content option pattern match is performed. use isdataat as a pre-cursor to the content. The rev keyword is used to uniquely identify revisions of Snort rules. \ "
Format content: [!] "<content string>". The priority keyword assigns a severity level to rules. For example.
122
. the test is successful and the remainder of the rule option tests are performed.

and depth search rule. there must be a content in the rule before ’offset’ is speciﬁed. except it is relative to the end of the last pattern match instead of the beginning of the packet. offset. Format offset: <number>. As this keyword is a modiﬁer to the previous ’content’ keyword.{1}DEF/. there must be a content in the rule before ‘depth’ is speciﬁed. depth modiﬁes the previous ‘content’ keyword in the rule. This can be thought of as exactly the same thing as offset (See Section 3.3. content: "DEF". A depth of 5 would tell Snort to only look for the speciﬁed pattern within the ﬁrst 5 bytes of the payload. depth:20. distance:1. Format depth: <number>. Example The rule below maps to a regular expression of /ABC. Example The following example shows use of a combined content.5.)
124
. alert tcp any any -> any any (content:"ABC". offset modiﬁes the previous ’content’ keyword in the rule. As the depth keyword is a modiﬁer to the previous ‘content’ keyword. An offset of 5 would tell Snort to start looking for the speciﬁed pattern after the ﬁrst 5 bytes of the payload. Format distance: <byte count>.5.5.5.6 distance
The distance keyword allows the rule writer to specify how far into a packet Snort should ignore before starting to search for the speciﬁed pattern relative to the end of the previous pattern match.5 offset
The offset keyword allows the rule writer to specify where to start searching for a pattern within a packet. alert tcp any any -> any 80 (content: "cgi-bin/phf". offset:4.)
3.
3.5).4 depth
The depth keyword allows the rule writer to specify how far into a packet Snort should search for the speciﬁed pattern.

6) rule option.5.
3. content: "EFG". there must be a content in the rule before ’http cookie’ is speciﬁed.6). Examples This rule constrains the search for the pattern ”EFG” to the NORMALIZED body of an HTTP client request. The extracted Cookie Header ﬁeld may be NORMALIZED.1 ). It’s designed to be used in conjunction with the distance (Section 3. there must be a content in the rule before ’http client body’ is speciﬁed. Format within: <byte count>.5. per the conﬁguration of HttpInspect (see 2. Format http_cookie.5. Format http_client_body.8 http client body
The http client body keyword is a content modiﬁer that restricts the search to the NORMALIZED body of an HTTP client request.
125
. Examples This rule constrains the search of EFG to not go past 10 bytes past the ABC match. As this keyword is a modiﬁer to the previous ’content’ keyword. As this keyword is a modiﬁer to the previous ’content’ keyword. alert tcp any any -> any 80 (content:"ABC". content: "EFG".5. alert tcp any any -> any any (content:"ABC". http_client_body.3.2.7 within
The within keyword is a content modiﬁer that makes sure that at most N bytes are between pattern matches using the content keyword ( See Section 3.9 http cookie
The http cookie keyword is a content modiﬁer that restricts the search to the extracted Cookie Header ﬁeld of an HTTP client request.)
! △NOTE
The http client body modiﬁer is not allowed to be used with the rawbytes modiﬁer for the same content.5.)
3. within:10.

)
! △NOTE
The http header modiﬁer is not allowed to be used with the rawbytes modiﬁer for the same content.
126
. per the conﬁguration of HttpInspect (see 2.5. Format http_method. As this keyword is a modiﬁer to the previous ’content’ keyword.5. there must be a content in the rule before ’http method’ is speciﬁed.6). http_cookie. there must be a content in the rule before ’http header’ is speciﬁed. alert tcp any any -> any 80 (content:"ABC". The extracted Header ﬁelds may be NORMALIZED.
3.)
! △NOTE
The http cookie modiﬁer is not allowed to be used with the rawbytes or fast pattern modiﬁers for the same content. content: "EFG".2. http_header. As this keyword is a modiﬁer to the previous ’content’ keyword.Examples This rule constrains the search for the pattern ”EFG” to the extracted Cookie Header ﬁeld of an HTTP client request.10 http header
The http header keyword is a content modiﬁer that restricts the search to the extracted Header ﬁelds of an HTTP client request.
3. content: "EFG". alert tcp any any -> any 80 (content:"ABC".11 http method
The http method keyword is a content modiﬁer that restricts the search to the extracted Method from an HTTP client request. Format http_header. Examples This rule constrains the search for the pattern ”EFG” to the extracted Header ﬁelds of an HTTP client request.

http_uri. http_method. alert tcp any any -> any 80 (content:"ABC". Examples This rule causes the pattern ”EFG” to be used with the Fast Pattern Matcher.13 fast pattern
The fast pattern keyword is a content modiﬁer that sets the content within a rule to be used with the Fast Pattern Matcher. As this keyword is a modiﬁer to the previous ’content’ keyword. there must be a content in the rule before ’http uri’ is speciﬁed.)
! △NOTE modiﬁer is not allowed to be used with the rawbytes modiﬁer for the same content. It overrides the default of using the longest content within the rule. The http method
3. content: "EFG". alert tcp any any -> any 80 (content:"ABC". Using a content rule option followed by a http uri modiﬁer is the same as using a uricontent by itself (see: 3.) 127
.5. Format http_uri. there must be a content in the rule before ’fast pattern’ is speciﬁed.12 http uri
The http uri keyword is a content modiﬁer that restricts the search to the NORMALIZED request URI ﬁeld .5. content: "GET".)
! △NOTE modiﬁer is not allowed to be used with the rawbytes modiﬁer for the same content. alert tcp any any -> any 80 (content:"ABCD". Examples This rule constrains the search for the pattern ”EFG” to the NORMALIZED URI.Examples This rule constrains the search for the pattern ”GET” to the extracted Method from an HTTP client request. content: "EFG". Format fast_pattern. fast pattern may be speciﬁed at most once for each of the buffer modiﬁers (excluding the http cookie modiﬁer).5. even though it is shorter than the earlier pattern ”ABCD”.14). fast_pattern. The http uri
3. As this keyword is a modiﬁer to the previous ’content’ keyword.

nor with a content that is negated with a !. do not include directory traversals. You can write rules that look for the non-normalized content by using the content option. Format uricontent:[!]<content string>.6. (See Section 3. write the content that you want to ﬁnd in the context that the URI will be normalized.1.5..15 urilen
The urilen keyword in the Snort rule language speciﬁes the exact length..
128
. the maximum length. such as %2f or directory traversals. For example. the URI: /cgi-bin/aaaaaaaaaaaaaaaaaaaaaaaaaa/.exe?/c+ver will get normalized into: /winnt/system32/cmd.5.5.%252fp%68f? will get normalized into: /cgi-bin/phf? When writing a uricontent rule.
! △NOTE
uricontent cannot be modiﬁed by a rawbytes modiﬁer. the URI: /scripts/. the minimum length. This means that if you are writing rules that include things that are normalized.exe?/c+ver Another example. or range of URI lengths to match.2. The reason is that the things you are looking for are normalized out of the URI buffer. For example.. see the content rule options in Section 3. if Snort normalizes directory traversals.
3. This option works in conjunction with the HTTP Inspect preprocessor speciﬁed in Section 2.! △NOTE
The fast pattern modiﬁer is not allowed to be used with the http cookie modiﬁer for the same content.5.%c0%af.
3.14 uricontent
The uricontent keyword in the Snort rule language searches the NORMALIZED request URI ﬁeld. these rules will not alert.1) For a description of the parameters to this function./winnt/system32/cmd.

and 3. The post-re modiﬁers set compile time ﬂags for the regular expression.relative]. Example alert tcp any any -> any 111 (content:"PASS".org Format pcre:[!]"(/<regex>/|m<delim><regex><delim>)[ismxAEGRUBPHMCO]".
! △NOTE R and B should not be used together. See tables 3. urilen: [<. isdataat:50.5.6.7.16 isdataat
Verify that the payload has data at a speciﬁed location.) This rule looks for the string PASS exists in the packet. For more detail on what can be done via a pcre regular expression.>] <int>.8 for descriptions of each modiﬁer. The modiﬁers
129
.pcre.6.relative. Format isdataat:<int>[. within:50.5. 3. The following example will match URIs that are 5 bytes long: urilen: 5 The following example will match URIs that are shorter than 5 bytes: urilen: < 5 The following example will match URIs that are greater than 5 bytes and less than 10 bytes: urilen: 5<>10 This option works in conjunction with the HTTP Inspect preprocessor speciﬁed in Section 2.
3. then veriﬁes there is at least 50 bytes after the end of the string PASS.2. then veriﬁes that there is not a newline character within 50 bytes of the end of the PASS string. optionally looking for data relative to the end of the previous content match. check out the PCRE web site http://www.
3.Format urilen: int<>int. \ content:!"|0a|".17 pcre
The pcre keyword allows rules to be written using perl compatible regular expressions.

7: PCRE compatible modiﬁers for pcre the pattern must match only at the start of the buffer (same as ˆ ) Set $ to match only at the end of the subject string. ˆ and $ match at the beginning and ending of the string. [!]<operator>.
3. In order to use pcre to inspect all URIs.
Example This example performs a case-insensitive search for the string BLAH in the payload.<number type>. the string is treated as one big line of characters.6: Perl compatible modiﬁers for pcre case insensitive include newlines in the dot metacharacter By default.)
! △NOTE
Snort’s handling of multiple URIs with PCRE does not work as expected. Inverts the ”greediness” of the quantiﬁers so that they are not greedy by default. When m is set. ˆ and $ match immediately following or immediately before any newline in the buffer.5. Without E. whitespace data characters in the pattern are ignored except when escaped or inside a character class
A E
G
Table 3. please read Section 3.<endian>] [. <value>.18 byte test
Test a byte ﬁeld against a speciﬁc value (with operator). alert ip any any -> any any (pcre:"/BLAH/i". but become greedy if followed by ”?”.relative] [. string]. Format byte_test: <bytes to convert>.5. you must use either a content or a uricontent. Capable of testing binary values or converting representative byte strings to their binary equivalent and testing them. as well as the very start and very end of the buffer.9. <offset> [. PCRE when used without a uricontent only evaluates the ﬁrst URI.i s m
x
Table 3. For a more detailed explanation. \
130
. $ also matches immediately before the ﬁnal character if it is a newline (but not before any other newlines).

greater than • = .bitwise AND • ˆ .
! △NOTE
Snort uses the C operators for each of these operators.Process data as little endian
string number type
Data is stored in string format in packet Type of number being read: • hex . See section 2. then the operator is set to =.14 for quick reference).Process data as big endian (default) • little .less than • > .2.Converted string data is represented in octal
dce
Let the DCE/RPC 2 preprocessor determine the byte order of the value to be converted.R U P H M C B O
Table 3.equal • ! . (Similar to distance:0.1.3)
Option bytes to convert operator
Description Number of bytes to pick up from the packet Operation to perform to test the value: • < .bitwise OR
value offset relative endian
Value to test the converted value against Number of bytes into the payload to start processing Use an offset relative to last pattern match Endian type of the number being read: • big .not • & .14 for a description and examples (2.2.) Match the decoded URI buffers (Similar to uricontent and http uri) Match normalized HTTP request body (Similar to http client body) Match normalized HTTP request header (Similar to http header) Match normalized HTTP request method (Similar to http method) Match normalized HTTP request cookie (Similar to http cookie) Do not use the decoded buffers (Similar to rawbytes) Override the conﬁgured pcre match limit for this expression (See section 2. If ! is speciﬁed without an operator.
Any of the operators can also include ! to check if the operator is not true. then it would be the same as using if (data & value) { do something().8: Snort speciﬁc modiﬁers for pcre Match relative to the end of the last pattern match.}
131
.Converted string data is represented in decimal • oct .Converted string data is represented in hexadecimal • dec . If the & operator is used.

relative. 900. 20.
Example alert udp any any -> any 32770:34000 (content: "|00 01 86 B8|". sid:3441. >. Let the DCE/RPC 2 preprocessor determine the byte order of the value to be converted. align. \ flow:to_server. and looks for various malicious encodings.established. The ASN. ftpbounce. distance: 4.20 ftpbounce
The ftpbounce keyword detects FTP bounce attacks. \ msg: "statd format string buffer overflow". \ byte_jump: 4. relative. \ content: "|00 00 00 01|".Option bytes to convert offset relative multiplier <value> big little string hex dec oct align from beginning post offset <value> dce
Description Number of bytes to pick up from the packet Number of bytes into the payload to start processing Use an offset relative to last pattern match Multiply the number of calculated bytes by <value> and skip forward that number of bytes. within: 4.1 detection plugin decodes a packet or a portion of a packet. 12. Format ftpbounce. rev:1.
133
. pcre:"/ˆPORT/smi". Multiple options can be used in an ’asn1’ option and the implied logic is boolean OR.5. The preferred usage is to use a space between option and argument.21 asn1
The ASN.\ classtype:misc-attack.)
3. If an option has an argument.2.14 for a description and examples (2. the option and the argument are separated by a space or a comma.)
3.14 for quick reference).5. \ byte_test: 4. the whole option evaluates as true. nocase.2. So if any of the arguments evaluate as true. Skip forward or backwards (positive of negative value) by <value> number of bytes after the other jump options have been applied.1 options provide programmatic detection capabilities as well as some more dynamic type detection. Process data as big endian (default) Process data as little endian Data is stored in string format in packet Converted string data is represented in hexadecimal Converted string data is represented in decimal Converted string data is represented in octal Round the number of converted bytes up to the next 32-bit boundary Skip forward from the beginning of the packet payload instead of from the current position in the packet. content:"PORT". See section 2. Example alert tcp $EXTERNAL_NET any -> $HOME_NET 21 (msg:"FTP PORT bounce attempt".

This is the relative offset from the last content match or byte test/jump. but it is unknown at this time which services may be exploitable. .
oversize length <value>
absolute offset <value>
relative offset <value>
Examples alert udp any any -> any 161 (msg:"Oversize SNMP Length". the offset value. \ asn1: bitstring_overflow. .) 134
.15 and before. This is known to be an exploitable function in Microsoft. absolute offset has one argument. the offset number.)
3.Format asn1: option[ argument][. For example.1 type is greater than 500.1 sequence right after the content “foo”. then this keyword is evaluated as true. absolute_offset 0.22 cvs
The CVS detection plugin aids in the detection of: Bugtraq-10384. This keyword must have one argument which speciﬁes the length to compare against.11. Option bitstring overflow double overflow Description Detects invalid bitstring encodings that are known to be remotely exploitable.established. \ asn1: oversize_length 10000. CVE-2004-0396: ”Malformed Entry Modiﬁed and Unchanged ﬂag insertion”.
Examples alert tcp any any -> any 2401 (msg:"CVS Invalid-entry". relative_offset 0’. Compares ASN. SSH (usually port 22).1 type lengths with the supplied argument.) alert tcp any any -> any 80 (msg:"ASN1 Relative Foo". Offset values may be positive or negative. which is a way of causing a heap overﬂow (see CVE-2004-0396) and bad pointer derefenece in versions of CVS 1. So if you wanted to start decoding and ASN. content:"foo".g. e. option[ argument]] . you would specify ’content:"foo". if you wanted to decode snmp packets. relative_offset 0. relative offset has one argument. cvs:invalid-entry. Default CVS server ports are 2401 and 514 and are included in the default ports for stream reassembly. “oversize length 500”. This plugin
Format cvs:<option>. Detects a double ASCII encoding that is larger than a standard buffer. asn1: bitstring_overflow. Option invalid-entry Description Looks for an invalid Entry string. The syntax looks like.5. \ flow:to_server. This means that if an ASN. This is the absolute offset from the beginning of the packet. you would say “absolute offset 0”.
! △NOTEcannot do detection over encrypted sessions. Offset may be positive or negative.

The distance keyword allows the rule writer to specify how far into a packet Snort should ignore before starting to search for the speciﬁed pattern relative to the end of the previous pattern match.2. See the DCE/RPC 2 Preprocessor section 2.26 Payload Detection Quick Reference
Table 3.2.14 for a description and examples of using this rule option. The pcre keyword allows rules to be written using perl compatible regular expressions.14 for a description and examples of using this rule option.2.5.14. ignoring any decoding that was done by preprocessors.2. The depth keyword allows the rule writer to specify how far into a packet Snort should search for the speciﬁed pattern.5. The offset keyword allows the rule writer to specify where to start searching for a pattern within a packet.2.3. See the DCE/RPC 2 Preprocessor section 2.2.5.9: Payload detection rule option keywords Keyword content rawbytes depth offset distance Description The content keyword allows the user to set rules that search for speciﬁc content in the packet payload and trigger response based on that data. The isdataat keyword veriﬁes that the payload has data at a speciﬁed location.24 dce opnum
See the DCE/RPC 2 Preprocessor section 2.14. The asn1 detection plugin decodes a packet or a portion of a packet.25 dce stub data
See the DCE/RPC 2 Preprocessor section 2. The within keyword is a content modiﬁer that makes sure that at most N bytes are between pattern matches using the content keyword.23 dce iface
See the DCE/RPC 2 Preprocessor section 2.
3. then skip that far forward in the packet.
within uricontent isdataat pcre byte test byte jump ftpbounce asn1 cvs dce iface dce opnum dce stub data
135
.5.
3. The cvs keyword detects invalid entry strings. The ftpbounce keyword detects FTP bounce attacks. The rawbytes keyword allows rules to look at the raw packet data.14. See the DCE/RPC 2 Preprocessor section 2. The uricontent keyword in the Snort rule language searches the normalized request URI ﬁeld.14 for a description and examples of using this rule option. The byte test keyword tests a byte ﬁeld against a speciﬁc value (with operator). and looks for various malicious encodings. The byte jump keyword allows rules to read the length of a portion of data.
3.

Example This example looks for a tos value that is not 4 tos:!4. To catch all the ﬁrst fragments of an IP session.2 ttl
The ttl keyword is used to check the IP time-to-live value.6. Format tos:[!]<number>. Example This example checks for a time-to-live value that is less than 3.
3.6. Format ttl:[[<number>-]><=]<number>. ttl:3-5. Example alert ip any any -> any any \ (msg: "First Fragment".
136
. ttl:<3.1 fragoffset
The fragoffset keyword allows one to compare the IP fragment offset ﬁeld against a decimal value. you could use the fragbits keyword and look for the More fragments option in conjunction with a fragoffset of 0.3 tos
The tos keyword is used to check the IP TOS ﬁeld for a speciﬁc value.)
3.6 Non-Payload Detection Rule Options
3.6. This example checks for a time-to-live value that between 3 and 5. This option keyword was intended for use in the detection of traceroute attempts. fragbits: M. Format fragoffset:[<|>]<number>.3. fragoffset: 0.

scanners and other odd programs) set this ﬁeld speciﬁcally for various purposes. Example This example looks for the IP ID of 31337.any IP options are set The most frequently watched for IP options are strict and loose source routing which aren’t used in any widespread internet applications.
3.5 ipopts
The ipopts keyword is used to check if a speciﬁc IP option is present.IP Security esec . Format id:<number>. the value 31337 is very popular with some hackers.6.Stream identiﬁer any . id:31337.Loose Source Routing ssrr . ipopts:lsrr.Strict Source Routing satid .4 id
The id keyword is used to check the IP ID ﬁeld for a speciﬁc value.6.No Op ts .
137
.3. The following options may be checked: rr .Time Stamp sec .End of list nop .IP Extended Security lsrr . for example.Record Route eol . Format ipopts:<rr|eol|nop|ts|sec|esec|lsrr|ssrr|satid|any>. Example This example looks for the IP Option of Loose Source Routing. Some tools (exploits.

In many cases. it is useful for detecting buffer overﬂows.6.Warning Only a single ipopts keyword may be speciﬁed per rule.7 dsize
The dsize keyword is used to test the packet payload size. The following bits may be checked: M .6. Example This example looks for a dsize that is between 300 and 400 bytes.More Fragments D .Reserved Bit The following modiﬁers can be set to change the match criteria: + match on the speciﬁed bits.
3. 138
. Warning dsize will fail on stream rebuilt packets. This may be used to check for abnormally sized packets. regardless of the size of the payload. dsize:300<>400. fragbits:MD+.
3.6 fragbits
The fragbits keyword is used to check if fragmentation and reserved bits are set in the IP header.Don’t Fragment R . Example This example checks if the More Fragments bit and the Do not Fragment bit are set. Format dsize: [<>]<number>[<><number>]. plus any others * match if any of the speciﬁed bits are set ! match if the speciﬁed bits are not set Format fragbits:[+*!]<[MDR]>.

)
3.
139
. plus any others * . A rule could check for a ﬂags value of S. an option mask may be speciﬁed.match if any of the speciﬁed bits are set ! . This allows rules to only apply to clients or servers. Example This example checks if just the SYN and the FIN bits are set. The established keyword will replace the flags: A+ used in many places to show established TCP connections. The following bits may be checked: F .URG 1 .Reserved bit 2 0 . ignoring reserved bit 1 and reserved bit 2.FIN (LSB in TCP Flags byte) S .9 ﬂow
The ﬂow keyword is used in conjunction with TCP stream reassembly (see Section 2. alert tcp any any -> any any (flags:SF.RST P .<FSRPAU120>].2.Reserved bit 1 (MSB in TCP Flags byte) 2 .12. regardless of the values of the reserved bits.3.ACK U . This allows packets related to $HOME NET clients viewing web pages to be distinguished from servers running in the $HOME NET.2).8 ﬂags
The ﬂags keyword is used to check if speciﬁc TCP ﬂag bits are present.6.12 if one wishes to ﬁnd packets with just the syn bit.PSH A .SYN R .match on the speciﬁed bits.match if the speciﬁed bits are not set To handle writing rules for session initiation packets such as ECN where a SYN packet is sent with the previously reserved bits 1 and 2 set. Format flags:[!|*|+]<FSRPAU120>[.6. It allows rules to only apply to certain directions of the trafﬁc ﬂow.No TCP Flags Set The following modiﬁers can be set to change the match criteria: + .

Sets the speciﬁed state if the state is unset.10 ﬂowbits
The flowbits keyword is used in conjunction with conversation tracking from the Stream preprocessor (see Section2. It allows rules to track states across transport protocol sessions. Checks if the speciﬁed state is not set. \ flow:stateless.) alert tcp !$HOME_NET 0 -> $HOME_NET 0 (msg: "Port 0 TCP traffic". There are seven keywords associated with ﬂowbits. Option set unset toggle isset isnotset noalert Description Sets the speciﬁed state for the current ﬂow. content:"CWD incoming". as it allows rules to generically track the state of an application protocol. The ﬂowbits option is most useful for TCP sessions.2. Unsets the speciﬁed state for the current ﬂow. \ flow:from_client. otherwise unsets the state if the state is set. regardless of the rest of the detection options.) Description Trigger on server responses from A to B Trigger on client requests from A to B Trigger on client requests from A to B Trigger on server responses from A to B Trigger only on established TCP connections Trigger regardless of the state of the stream processor (useful for packets that are designed to cause machines to crash) Do not trigger on rebuilt stream packets (useful for dsize and stream5) Only trigger on rebuilt stream packets
3. 140
. Examples alert tcp any 143 -> any any (msg:"IMAP login". Cause the rule to not generate an alert. This string should be limited to any alphanumeric string including periods. Examples alert tcp !$HOME_NET any -> $HOME_NET 21 (msg:"cd incoming detected".<STATE_NAME>].(no_stream|only_stream)]. dashes. and underscores.2). Most of the options need a user-deﬁned name for the speciﬁc state that is being checked.(to_client|to_server|from_client|from_server)] [.6.
Format flowbits: [set|unset|toggle|isset|reset|noalert][. Checks if the speciﬁed state is set. nocase.Options Option to client to server from client from server established stateless no stream only stream Format flow: [(established|stateless)] [.

flowbits:isset. Format seq:<number>. ack:0. flowbits:set. Format window:[!]<number>. seq:0.)
3.6. Example This example looks for a TCP window size of 55808. content:"LIST".6.
3.
141
. Example This example looks for a TCP sequence number of 0. Example This example looks for a TCP acknowledge number of 0.) alert tcp any any -> any 143 (msg:"IMAP LIST". window:55808.11 seq
The seq keyword is used to check for a speciﬁc TCP sequence number. flowbits:noalert.logged_in.logged_in.12 ack
The ack keyword is used to check for a speciﬁc TCP acknowledge number.6.
3.content:"OK LOGIN".13 window
The window keyword is used to check for a speciﬁc TCP window size. Format ack: <number>.

14 itype
The itype keyword is used to check for a speciﬁc ICMP type value.
3. This is useful because some covert channel programs use static ICMP ﬁelds when they communicate. This particular plugin was developed to detect the stacheldraht DDoS agent. This particular plugin was developed to detect the stacheldraht DDoS agent. itype:>30. Format icode: [<|>]<number>[<><number>].15 icode
The icode keyword is used to check for a speciﬁc ICMP code value.16 icmp id
The icmp id keyword is used to check for a speciﬁc ICMP ID value. Example This example looks for an ICMP code greater than 30. Format itype:[<|>]<number>[<><number>]. 142
. code:>30.6. Example This example looks for an ICMP type greater than 30.6.6.17 icmp seq
The icmp seq keyword is used to check for a speciﬁc ICMP sequence value. This is useful because some covert channel programs use static ICMP ﬁelds when they communicate.
3. Format icmp_id:<number>.6.
3. icmp_id:0. Example This example looks for an ICMP ID of 0.3.

version. For a list of protocols that may be speciﬁed by name. Example This example looks for an ICMP Sequence of 0.
3.
3.)
3.Format icmp_seq:<number>. Warning Because of the fast pattern matching engine. Wildcards are valid for both version and procedure numbers by using ’*’.6.3.). Example The following example looks for an RPC portmap GETPORT request. icmp_seq:0.6. Format ip_proto:[!|>|<] <name or number>.*.20 sameip
The sameip keyword allows rules to check if the source ip is the same as the destination IP. [<procedure number>|*]>. Example This example looks for IGMP trafﬁc.19 ip proto
The ip proto keyword allows checks against the IP protocol header. the RPC keyword is slower than looking for the RPC values by using normal content matching. alert tcp any any -> any 111 (rpc: 100000. alert ip any any -> any any (ip_proto:igmp.
143
. and procedure numbers in SUNRPC CALL requests.6. [<version number>|*]. see /etc/protocols. Format rpc: <application number>.18 rpc
The rpc keyword is used to check for a RPC application.

less than or equal • >= .22 Non-Payload Detection Quick Reference
Table 3.not • <= .greater than or equal Example For example.6. 144
.greater than • = .less than • > . The tos keyword is used to check the IP TOS ﬁeld for a speciﬁc value.
Format stream_size:<server|client|both|either>. to look for a session that is less that 6 bytes from the client side.)
3.equal • != .6.Format sameip. The id keyword is used to check the IP ID ﬁeld for a speciﬁc value.<operator>.21 stream size
The stream size keyword allows a rule to match trafﬁc according to the number of bytes observed.6. Example This example looks for any trafﬁc where the Source IP and the Destination IP is the same.
! △NOTE
The stream size option is only available when the Stream5 preprocessor is enabled.<. as determined by the TCP sequence numbers.)
3. use: alert tcp any any -> any any (stream_size:client. alert ip any any -> any any (sameip. The ttl keyword is used to check the IP time-to-live value.10: Non-payload detection rule option keywords Keyword fragoffset ttl tos id Description The fragoffset keyword allows one to compare the IP fragment offset ﬁeld against a decimal value.<number> Where the operator is one of the following: • < .

or even web sessions is very useful. etc. ftp. The rpc keyword is used to check for a RPC application.
145
. HTTP CGI scans.
3. Format logto:"filename". The ﬂow keyword allows rules to only apply to certain directions of the trafﬁc ﬂow.
3. The icmp seq keyword is used to check for a speciﬁc ICMP sequence value. The dsize keyword is used to test the packet payload size. The window keyword is used to check for a speciﬁc TCP window size. The ﬂags keyword is used to check if speciﬁc TCP ﬂag bits are present.7 Post-Detection Rule Options
3. There are many cases where seeing what users are typing in telnet. It should be noted that this option does not work when Snort is in binary logging mode. The ack keyword is used to check for a speciﬁc TCP acknowledge number. Format session: [printable|all]. The printable keyword only prints out data that the user would normally see or be able to type. The ﬂowbits keyword allows rules to track states across transport protocol sessions.7. printable or all. The itype keyword is used to check for a speciﬁc ICMP type value.ipopts fragbits dsize flags flow flowbits seq ack window itype icode icmp id icmp seq rpc ip proto sameip
The ipopts keyword is used to check if a speciﬁc IP option is present. The seq keyword is used to check for a speciﬁc TCP sequence number.2 session
The session keyword is built to extract user data from TCP Sessions. The all keyword substitutes non-printable characters with their hexadecimal equivalents. There are two available argument keywords for the session rule option. The fragbits keyword is used to check if fragmentation and reserved bits are set in the IP header. The ip proto keyword allows checks against the IP protocol header. The sameip keyword allows rules to check if the source ip is the same as the destination IP. The icode keyword is used to check for a speciﬁc ICMP code value. This is especially handy for combining data from things like NMAP activity. The icmp id keyword is used to check for a speciﬁc ICMP ID value.7. rlogin. version. and procedure numbers in SUNRPC CALL requests.1 logto
The logto keyword tells Snort to log all packets that trigger this rule to a special output log ﬁle.

alert tcp any any -> any 1524 (flags:S.<resp_mechanism>[. Flexible Response supports the following mechanisms for attempting to close sessions: Option rst snd rst rcv rst all icmp net icmp host icmp port icmp all Description Send TCP-RST packets to the sending socket Send TCP-RST packets to the receiving socket Send TCP RST packets in both directions Send a ICMP NET UNREACH to the sender Send a ICMP HOST UNREACH to the sender Send a ICMP PORT UNREACH to the sender Send all above ICMP packets to the sender
These options can be combined to send multiple responses to the target host. this is called ﬂexible response. Be very careful when using Flexible Response.)
146
.<resp_mechanism>]]. The session keyword is best suited for post-processing binary (pcap) log ﬁles. Warnings This functionality is not built in by default. Format resp: <resp_mechanism>[. resp:rst_all.) Warnings Using the session keyword can slow Snort down considerably.Example The following example logs all printable strings in a telnet packet. Use the – –enable-ﬂexresp ﬂag to conﬁgure when building Snort to enable this functionality. It is quite easy to get Snort into an inﬁnite loop by deﬁning a rule such as: alert tcp any any -> any any (resp:rst_all.) It is easy to be fooled into interfering with normal network trafﬁc as well. In Snort.
3. Example The following example attempts to reset any TCP connection to port 1524.7. log tcp any any <> any 23 (session:printable.3 resp
The resp keyword is used to attempt to close sessions when an alert is triggered. so it should not be used in heavy load situations.

(Note that react may now be enabled independently of ﬂexresp and ﬂexresp2. \ msg: "Not for children!".Log packets in the session that set off the rule • host .6. tagged alerts will be sent to the same output plugins as the original alert. described in Section 2.napster and porn sites. type • session . msg. Currently.4 react
This keyword implements an ability for users to react to trafﬁc that matches a Snort rule. <metric>.6. proxy 8000. but it is the responsibility of the output plugin to properly handle these special alerts.168. The react keyword should be placed as the last one in the option list. The basic reaction is blocking interesting sites users want to access: New York Times. you must conﬁgure with –enable-react to build it.7. [direction]. does not properly handle tagged alerts.) Be very careful when using react. slashdot.Log packets from the host that caused the tag to activate (uses [direction] modiﬁer) count
147
.include the msg option text into the blocking visible notice • proxy <port nr> . The notice may include your own comment.htm". Causing a network trafﬁc generation loop is very easy to do with this functionality. or something really important . <react_additional_modifier>].1. react: block.3.0/24 80 (content: "bad. The React code allows Snort to actively close offending connections and send a visible notice to the browser.7. Format react: block[. the database output plugin. The following arguments (basic modiﬁers) are valid for this option: • block .5 tag
The tag keyword allow rules to log more than just the single packet that triggered the rule. Format tag: <type>.
3. <count>.close connection and send the visible notice The basic argument may be combined with the following arguments (additional modiﬁers): • msg . Tagged trafﬁc is logged to allow analysis of response codes and post-attack trafﬁc. Example alert tcp any any <> 192. additional trafﬁc involving the source and/or destination host is tagged.use the proxy port to send the visible notice Multiple additional arguments are separated by a comma.) Warnings React functionality is not built in by default. Once a rule is triggered.

src.seconds. (Note that the tagged packet limit was introduced to avoid DoS situations on high bandwidth sensors for tag rules with a high seconds or bytes counts.1 any (tag:host.Tag the host/session for <count> bytes direction .3 on how to use the tagged packet limit conﬁg option).1. See Section 3.600.1. a tagged packet limit will be used to limit the number of tagged packets regardless of whether the seconds or bytes count has been reached. alert tcp any any <> 10. tag:session.1.1.• <integer> . tag:host.1.1.1. any packets that generate an alert will not be tagged.)
3.
148
.) alert tcp 10. Units are speciﬁed in the <metric> ﬁeld.12. For example.1. The ﬂowbits option would be useful here.2.) Example This example logs the ﬁrst 10 seconds or the tagged packet limit (whichever comes ﬁrst) of any telnet session.1.conf to 0).1.6 for more information. • dst .tagged.tagged. Doing this will ensure that packets are tagged for the full amount of seconds or bytes and will not be cut off by the tagged packet limit. You can disable this packet limit for a particular rule by adding a packets metric to your tag option and setting its count to 0 (This can be done on a global scale by setting the tagged packet limit option in snort.1.only relevant if host type is used.Count is speciﬁed as a number of units.Tag packets containing the destination IP address of the packet that generated the initial event.seconds.1 any (flowbits:isnotset. • src . The default tagged packet limit value is 256 and can be modiﬁed by using a conﬁg option in your snort.) However.600.4 any -> 10.6 activates
The activates keyword allows the rule writer to specify a rule to add when a speciﬁc network event occurs. metric • packets .1 any \ (content:"TAGMYPACKETS". no packets will get tagged. since the rule will ﬁre on every packet involving 10.10.Tag the host/session for <count> packets • seconds .1. flowbits:set. it may seem that the following rule will tag the ﬁrst 600 seconds of any packet involving 10.0.7.600.Tag packets containing the source IP address of the packet that generated the initial event. alert tcp any any <> 10.seconds.1.conf ﬁle (see Section 2.1.1.src. tag:host.Tag the host/session for <count> seconds • bytes .packets.seconds. Format activates: 1.) Also note that if you have a tag option in a rule that uses a metric other than packets. Note. alert tcp any any -> any 23 (flags:s.src.

6 for more information. This means count is maintained for each unique source IP address or each unique destination IP address. At most one detection filter is permitted per rule.
3. See Section 3. Time period over which count is accrued.7 activated by
The activated by keyword allows the rule writer to dynamically enable a rule when a speciﬁc activate rule is triggered.7. See section 1.
3.6 for more information.3. See Section 3.10 detection ﬁlter
detection ﬁlter deﬁnes a rate which must be exceeded by a source or destination host before a rule can generate an event.2.
3. \ count <c>. Both the new string and the content it is to replace must have the same length. detection ﬁlter has the following format: detection_filter: \ track <by_src|by_dst>.2. seconds <s>.8 count
The count keyword must be used in combination with the activated by keyword. The value must be nonzero. Option track by src|by dst count c seconds s Description Rate is tracked either by source IP address or destination IP address.7. Format activated_by: 1.100 during one sampling period of 60 seconds.7.2.
Snort evaluates a detection filter as the last step of the detection phase. replace: <string>. C must be nonzero. after the ﬁrst 30 failed login attempts:
149
.5 for more on operating in inline mode. You can have multiple replacements within a rule. It allows the rule writer to specify how many packets to leave the rule enabled for after it is activated.1.this rule will ﬁre on every failed login attempt from 10. after evaluating all other rule options (regardless of the position of the ﬁlter within the rule source). count: 50. one per content.9 replace
The replace keyword is a feature available in inline mode which will cause Snort to replace the prior matching content with the given string. Format activated_by: 1.7. Example . The maximum number of rule matches in s seconds allowed before the detection ﬁlter limit to be exceeded.

1.8 Rule Thresholds
! △NOTE are deprecated and will not be supported in a future release.2. resp The resp keyword is used attempt to close sessions when an alert is triggered. a detection filter would normally be used in conjunction with an event filter to reduce the number of logged events. This can be done using the ‘limit’ type of threshold.drop tcp 10. These should incorporate the threshold into the rule.) Since potentially many events will be generated. It makes sense that the threshold feature is an integral part of this rule.11: Post-detection rule option keywords Keyword logto Description The logto keyword tells Snort to log all packets that trigger this rule to a special output log ﬁle.100 any > 10. tag The tag keyword allow rules to log more than just the single packet that triggered the rule. or using a standalone threshold applied to the same rule.2) as standalone conﬁgurations instead. count This keyword must be used in combination with the activated by keyword. \ content:"SSH". Available in inline mode only.to_server. replace Replace the prior matching content with the given string of the same length.11 Post-Detection Quick Reference
Table 3. nocase.
threshold can be included as part of a rule. seconds 60. There is a logical difference. offset:0. \ sid:1000001. Rule thresholds
Use detection filters (3.4. react This keyword implements an ability for users to react to trafﬁc that matches a Snort rule by closing connection and sending a notice.
3.7. or you can use standalone thresholds that reference the generator and SID they are applied to. Some rules may only make sense with a threshold. It allows the rule writer to specify how many packets to leave the rule enabled for after it is activated. flow:established. depth:4. count 30.100 22 ( \ msg:"SSH Brute Force Attempt". \ detection_filter: track by_src. activates This keyword allows the rule writer to specify a rule to add when a speciﬁc network event occurs. Format 150
. activated by This keyword allows the rule writer to dynamically enable a rule when a speciﬁc activate rule is triggered.
3.10) within rules. or event filters (2.7. For instance. session The session keyword is built to extract user data from TCP Sessions.1. There is no functional difference between adding a threshold to a rule. a rule for detecting a too many login password attempts may require more than 5 attempts. rev:1. detection filter Track by source or destination IP address and if the rule otherwise matches more than the conﬁgured rate it will ﬁre.1.

flow:to_server. established. sid:1000852. nocase.10302.txt access".
track by src|by dst
count c seconds s
Examples This rule logs the ﬁrst event of this SID every 60 seconds. \ classtype:web-application-activity. then ignores events for the rest of the time interval. Once an event is logged. seconds 60 . seconds <s>. or destination IP address. threshold: type both . threshold: type limit. sid:1000852. nothing gets logged. reference:nessus. or for each unique destination IP addresses. \ classtype:web-application-activity. seconds 60 . established.txt".10302. nocase. \ uricontent:"/robots.txt".txt access".
151
. c must be nonzero value. \ track <by_src|by_dst>. sid:1000852. time period over which count is accrued. established. count 10 . flow:to_server. \ count <c>. count 10 . So if less than 10 events occur in 60 seconds. reference:nessus.)
3. count 1 .txt access". nocase.) This rule logs every 10th event on this SID during a 60 second interval. Type threshold alerts every m times we see this event during the time interval. number of rule matching in s seconds that will cause event filter limit to be exceeded. flow:to_server. track \ by_src. a new time period starts for type=threshold. threshold: type threshold. alert tcp $external_net any -> $http_servers $http_ports \ (msg:"web-misc robots. rev:1. seconds 60 . rate is tracked either by source IP address. \ uricontent:"/robots. alert tcp $external_net any -> $http_servers $http_ports \ (msg:"web-misc robots. \ uricontent:"/robots. \ track by_dst. Option type limit|threshold|both Description type limit alerts on the 1st m events during the time interval.9 Writing Good Rules
There are some general concepts to keep in mind when developing Snort rules to maximize efﬁciency and speed. Type both alerts once per time interval after seeing m occurrences of the event. rev:1. then ignores any additional events during the time interval. rev:1. s must be nonzero value.threshold: \ type <limit|threshold|both>.txt".) This rule logs at most one event every 60 seconds if at least 10 events on this SID are ﬁred. \ classtype:web-application-activity. track \ by_dst. Ports or anything else are not tracked.10302. alert tcp $external_net any -> $http_servers $http_ports \ (msg:"web-misc robots. reference:nessus. This means count is maintained for each unique source IP addresses.

9. followed at least one space character (which includes tab).2 Catch the Vulnerability. looking for root.
3. verifying this is trafﬁc going to the server on an enstablished session. the more exact the match.) There are a few important things to note in this rule: • The rule has a ﬂow option. For example.3. the client sends: user username_here A simple rule to look for FTP root login attempts could be: alert tcp any any -> any any 21 (content:"user root". to send the username. they do not use the setwise pattern matching engine. looking for user. the rule is less vulnerable to evasion when an attacker changes the exploit slightly.
3.9.established. the rule needs more smarts than a simple string match. • The rule has a content option. a good rule will handle all of the odd things that the protocol might handle when accepting the user command. each of the following are accepted by most FTP servers: user root user root user root user root user<tab>root To handle all of the cases that the FTP server might handle. Not the Exploit
Try to write rules that target the vulnerability. Rules without content (or uricontent) slow the entire system down. The longer a content option is.1 Content Matching
The 2. FTP is a good example. • The rule has a pcre option. instead of shellcode that binds a shell.9. which is the longest. perform detection in the payload section of the packet. such as pcre and byte test.) While it may seem trivial to write a rule that looks for the username root. By writing rules for the vulnerability. instead of a speciﬁc exploit. followed by root. ignoring case. In FTP. 152
. If at all possible. most unique string in the attack. \ content:"root". try and have at least one content option if at all possible. look for a the vulnerable command with an argument that is too large. For example. A good rule that looks for root login on ftp would be: alert tcp any any -> any 21 (flow:to_server.3 Catch the Oddities of the Protocol in the Rule
Many services typically send the commands in upper case letters.0 detection engine changes the way Snort works slightly by having the ﬁrst phase be a setwise pattern match. While some detection options. pcre:"/user\s+root/i". This option is added to allow Snort’s setwise pattern match detection engine to give Snort a boost in speed.

However. Reordering the rule options so that discrete checks (such as dsize) are moved to the begining of the rule speed up Snort. For example. then the dsize option would fail. Repeat until the pattern is not found again or the opt functions all succeed. then look for the pattern again after where it was found the previous time. the recursion implementation is not very smart. it is obvious the rule looks for a packet with a single byte of 0x13. On ﬁrst read.3. the payload “aab” would fail. then check the dsize again. content:"|13|". and because of recursion. and if any of the detection options after that pattern fail.) This rule would look for “a”. a packet with 1024 bytes of 0x13 could cause 1023 too many pattern match attempts and 1023 too many dsize checks. the following rule options are not optimized: content:"|13|". Rules that are not properly written can cause Snort to waste time duplicating checks. that may not sound like a smart idea.9. immediately followed by “b”. The following rule options are discrete and should generally be placed at the begining of any rule: • dsize • flags • flow • fragbits • icmp id • icmp seq • icode • id • ipopts • ip proto • itype
153
. dsize:1. repeating until 0x13 is not found in the payload again. By looking at this rule snippit. take the following rule: alert ip any any -> any any (content:"a". within:1. even though it is obvious that the payload “aab” has “a” immediately followed by “b”. The optimized rule snipping would be: dsize:1. While recursion is important for detection.4 Optimizing Rules
The content matching portion of the detection engine has recursion to handle a few evasion cases. but it is needed. Without recursion. the content 0x13 would be found again starting after where the previous 0x13 was found. For example. A packet of 1024 bytes of 0x13 would fail immediately. Why? The content 0x13 would be found in the ﬁrst byte. once it is found. because of recursion. as the dsize check is the ﬁrst option checked and dsize is a discrete check without recursion. content:"b". because the ﬁrst ”a” is not immediately followed by “b”. The way the recursion works now is if a pattern matches.

verifier flavor (0 = auth\_null. the value we want to check. we need to make sure that our packet is a call to sadmind.length of the client machine name (0x0a = 10) 53 50 4c 4f 49 54 00 00 .unix timestamp (0x40283a10 = 1076378128 = feb 10 01:55:28 2004 gmt) . As such.00 00 00 00 ## 40 00 4d
00 00 00 00
00 00 00 00
0a 01 01 20
-
rpc program version (0x0000000a = 10) rpc procedure (0x00000001 = 1) credential flavor (1 = auth\_unix) length of auth\_unix data (0x20 = 32
the next 28 3a 10 00 00 0a 45 54 41
32 bytes are the auth\_unix data . To do that in a Snort rule. First. we need to make sure that our packet has auth unix credentials. we need to make sure that our packet is a call to the procedure 1. we want to read 4 bytes. aka none) . and turn those 4 bytes into an integer and jump that many bytes forward. depth:4. content:"|00 00 00 00|". we have decoded enough of the request to write our rule.length of verifier (0.metasploit
00 00 00 00 . Then. offset:12. 36 bytes from the beginning of the packet. offset:20. the vulnerable procedure. aka none)
The rest of the packet is the request that gets passed to procedure 1 of sadmind. turn it into a number. In english. We don’t care about the hostname. Starting at the length of the hostname. aligning on the 4 byte boundary. content:"|00 00 00 01|". If we do that. depth:4. This is where byte test is useful. However. we use: 155
.extra group ids (0) 00 00 00 00 00 00 00 00 . we are now at: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 which happens to be the exact location of the uid. we know the vulnerability is that sadmind trusts the uid coming from the client. making sure to account for the padding that RPC requires on strings. Then. and jump that many bytes forward.uid of requesting user (0) 00 00 00 00 . offset:4. offset:16. the data we have is: 00 00 00 0a 4d 45 54 41 53 50 4c 4f 49 54 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 We want to read 4 bytes. content:"|00 00 00 01|". we need to make sure that our packet is an RPC call. sadmind runs any request where the client’s uid is 0 as root. depth:4. depth:4. content:"|00 01 87 88|". but we want to skip over it and check a number value after the hostname. Then.gid of requesting user (0) 00 00 00 00 .

align. In Snort. so we should combine those patterns. we would read 4 bytes. within:4. depth:4.36. depth:4. content:"|00 01 87 88|".>. byte_test:4. Now that we have all the detection capabilities for our rule. offset:4. offset:12. 00 00 01|". depth:8. let’s put them all together.
If the sadmind service was vulnerable to a buffer overﬂow when reading the client’s hostname. depth:8.200.36. depth:4. Our full rule would be: content:"|00 00 00 00|". content:"|00 00 00 00|". offset:16.
156
. content:"|00 00 00 01|".200.align. content:"|00 00 00 00|". offset:12. content:"|00 00 00 01 00 00 00 01|". offset:4.>. depth:4. offset:12. content:"|00 00 00 00|". instead of reading the length of the hostname and jumping that many bytes forward.byte_jump:4. byte_jump:4. depth:4. content:"|00 01 87 88|". offset:20. content:"|00 00 00 01 00 byte_jump:4. we would check the length of the hostname to make sure it is not too large. turn it into a number. then we want to look for the uid of 0. depth:4. offset:16. and then make sure it is not too large (let’s say bigger than 200 bytes). starting 36 bytes into the packet. content:"|00 00 00 01|". offset:4. within:4. we do: byte_test:4. content:"|00 01 87 88|". offset:16. depth:4.align. We end up with: content:"|00 00 00 00|". within:4. To do that.
The 3rd and fourth string match are right next to each other. content:"|00 00 00 00|".36.36.36. depth:4.

1 MMAPed pcap
On Linux. this ends up being 1530 bytes per frame. the maximum size is 32768. By using PCAP FRAMES=max. According to Phil. This change speeds up Snort by limiting the number of times the packet is copied before Snort gets to perform its detection upon it.lanl. Once Snort linked against the shared memory libpcap. for a total of around 52 Mbytes of memory for the ring buffer alone. On Ethernet. The shared memory ring buffer libpcap can be downloaded from his website at http://public. Instead of the normal mechanism of copying the packets from kernel memory into userland memory. PCAP FRAMES is the size of the ring buffer. libpcap will automatically use the most frames possible.gov) is the current maintainer of the libpcap implementation of the shared memory ring buffer. by using a shared memory ring buffer.gov/cpw/.Chapter 4
Making Snort Faster
4.
157
. enabling the ring buffer is done via setting the enviornment variable PCAP FRAMES. libpcap is able to queue packets into a shared buffer that Snort is able to read directly. a modiﬁed version of libpcap is available that implements a shared memory ring buffer. Phil Woods (cpw@lanl. as this appears to be the maximum number of iovecs the kernel can handle.

int major. } DynamicPluginMeta. detection engines. A shared library can implement all three types. and processing functions. When enabled via the –enable-dynamicplugin conﬁgure option. rules. char uniqueName[MAX_NAME_LEN].
5. and rules can now be developed as dynamically loadable module to snort. or detection engine). Beware: the deﬁnitions herein may be out of date. but typically is limited to a single functionality such as a preprocessor.h as: #define MAX_NAME_LEN 1024 #define TYPE_ENGINE 0x01 #define TYPE_DETECTION 0x02 #define TYPE_PREPROCESSOR 0x04 typedef struct _DynamicPluginMeta { int type.1. check the appropriate header ﬁles for the current deﬁnitions. detection capabilities. int minor. restart. It is deﬁned in sf dynamic meta. exit. the version information. int build. and rules as a dynamic plugin to snort. The deﬁnition of each is deﬁned in the following sections.2 DynamicPreprocessorData
The DynamicPreprocessorData structure deﬁnes the interface the preprocessor uses to interact with snort itself.1. the dynamic API presents a means for loading dynamic libraries and allowing the module to utilize certain functions within the main snort code. It includes 158
.
5.1 Data Structures
A number of data structures are central to the API. char *libraryPath.
5. The remainder of this chapter will highlight the data structures and API functions used in developing preprocessors. and path to the shared library.Chapter 5
Dynamic Modules
Preprocessors. This inclues functions to register the preprocessor’s conﬁguration parsing.1 DynamicPluginMeta
The DynamicPluginMeta structure deﬁnes the type of dynamic module (preprocessor.

Additional data structures may be deﬁned to reference other protocol ﬁelds.h as: typedef struct _DynamicEngineData { int version. It is deﬁned in sf dynamic engine. RegisterBit flowbitRegister. and debugging info as well as a means to register and check ﬂowbits. errors. #ifdef HAVE_WCHAR_H DebugWideMsgFunc debugWideMsg. char *dataDumpDirectory. fatal errors. This data structure should be initialized when the preprocessor shared library is loaded.h. LogMsgFunc logMsg. Check the header ﬁle for the current deﬁnitions. } DynamicEngineData. access to the StreamAPI. DetectAsn1 asn1Detect. u_int8_t *altBuffer.4 SFSnortPacket
The SFSnortPacket structure mirrors the snort Packet structure and provides access to all of the data contained in a given packet.
159
.1. LogMsgFunc fatalMsg. CheckFlowbit flowbitCheck. It is deﬁned in sf dynamic preprocessor.1. GetPreprocRuleOptFuncs getPreprocOptFuncs.3 DynamicEngineData
The DynamicEngineData structure deﬁnes the interface a detection engine uses to interact with snort itself. RegisterRule ruleRegister.h. DebugMsgFunc debugMsg. errors. and debugging info. and it provides access to the normalized http and alternate data buffers. PCREExecFunc pcreExec. fatal errors. LogMsgFunc errMsg. and it provides access to the normalized http and alternate data buffers. PCRECompileFunc pcreCompile.
5. SetRuleData setRuleData.function to log messages. int *debugMsgLine. It also includes a location to store rule-stubs for dynamic rules that are loaded. PCREStudyFunc pcreStudy. It also includes information for setting alerts. GetRuleData getRuleData. #endif char **debugMsgFile. Check the header ﬁle for the current deﬁnition. This includes functions for logging messages. handling Inline drops. It and the data structures it incorporates are deﬁned in sf snort packet. UriInfo *uriBuffers[MAX_URIINFOS].
5.

termination. It includes a cursor adjust that happens through each iteration of the loop. It includes the number of bytes. /* reference ID (NULL if static) */ union { void *voidPtr.2 Required Functions
Each dynamic module must deﬁne a set of functions and data objects to work within this framework. u_int32_t op. struct _Rule *subRule. an offset. DynamicElement *end. } LoopInfo. /* type of this field . #define DYNAMIC_TYPE_INT_STATIC 1 #define DYNAMIC_TYPE_INT_REF 2 typedef struct _DynamicElement { char dynamicType. ﬂags specifying the buffer.
166
. specifies
The ByteExtract structure deﬁnes the information to use when extracting bytes for a DynamicElement used a in Loop evaltion. /* char *refId. /* Value of static */ int32_t *dynamicInt. u_int32_t flags. multiplier. typedef struct _ByteExtract { u_int32_t bytes. /* u_int32_t flags. typedef struct _LoopInfo { DynamicElement *start. u_int8_t initialized. a reference to a RuleInfo structure that deﬁnes the RuleOptions are to be evaluated through each iteration. /* } ByteExtract. CursorInfo *cursorAdjust. /* int32_t offset.
Number of bytes to extract */ Offset from cursor */ Multiply value by this (similar to byte jump) */ must include a CONTENT_BUF_X */ To match up with a DynamicElement refId */ Location to store the data extracted */
The DynamicElement structure is used to deﬁne the values for a looping evaluation. /* Holder */ int32_t staticInt. One of those options may be a ByteExtract. the value is ﬁlled by a related ByteExtract option that is part of the loop. It includes whether the element is static (an integer) or dynamic (extracted from a buffer in the packet) and the value.
5. and a reference to the DynamicElement. /* Pointer to value of dynamic */ } data. For a dynamic element. /* u_int32_t multiplier.
/* /* /* /* /* /* * /* /*
Starting value of FOR loop (i=start) */ Ending value of FOR loop (i OP end) */ Increment value of FOR loop (i+= increment) */ Type of comparison for loop termination */ How to move cursor each iteration of loop */ Pointer to SubRule & options to evaluate within the loop */ Loop initialized properly (safeguard) */ can be used to negate loop results. DynamicElement *increment.static or reference */ char *refId. } DynamicElement. /* void *memoryLocation.

etc). FlowBitsInfo *ﬂowbits) This function evaluates the ﬂowbits for a given packet. Value extracted is stored in ByteExtract memoryLocation paraneter. Each of the functions below returns RULE MATCH if the option matches based on the current criteria (cursor position. • int LibVersion(DynamicPluginMeta *) This function returns the metadata for the shared library.2. as speciﬁed by FlowBitsInfo. • int InitializePreprocessor(DynamicPreprocessorData *) This function initializes the data structure for use by the preprocessor into a library global variable. ContentInfo* content.2. • int ruleMatch(void *p. The sample code provided with Snort predeﬁnes those functions and deﬁnes the following APIs to be used by a dynamic rules library. – int contentMatch(void *p.5. checking for the existence of that content as delimited by ContentInfo and cursor. – int processFlowbits(void *p. u int8 t *cursor) This function extracts the bytes from a given packet. – int extractValue(void *p.1 Preprocessors
Each dynamic preprocessor library must deﬁne the following functions. the with option corresponds to depth. • int InitializeEngineLib(DynamicEngineData *) This function initializes the data structure for use by the engine. It will interact with ﬂowbits used by text-based rules. initialize it to setup content searches. These are deﬁned in the ﬁle sf dynamic preproc lib.2 Detection Engine
Each dynamic detection engine library must deﬁne the following functions. ByteExtract *byteExtract. log. With a text rule. The metadata and setup function for the preprocessor should be deﬁned sf preproc info.h. • int LibVersion(DynamicPluginMeta *) This function returns the metadata for the shared library. • int DumpRules(char *. dpd and invokes the setup function. and register ﬂowbits.Rule **) This is the function to iterate through each rule in the list and write a rule-stop to be used by snort to control the action of the rule (alert. This uses the individual functions outlined below for each of the rule options and handles repetitive content issues. as speciﬁed by ByteExtract and delimited by cursor. FlowFlags *ﬂowﬂags) This function evaluates the ﬂow for a given packet. Rule *rule) This is the function to evaluate a rule if the rule does not have its own Rule Evaluation Function.c. drop.
167
.
5. u int8 t **cursor) This function evaluates a single content for a given packet. and the distance option corresponds to offset. – int checkFlow(void *p. etc). • int RegisterRules(Rule **) This is the function to iterate through each rule in the list. Cursor position is updated and returned in *cursor. PCRE evalution data.

h. Examples are deﬁned in the ﬁle sfnort dynamic detection lib. u int32 t value. – int byteJump(void *p. • int EngineVersion(DynamicPluginMeta *) This function deﬁnes the version requirements for the corresponding detection engine library. u int8 t **cursor) This function evaluates a single pcre for a given packet. Asn1Context *asn1. u int8 t **cursor) This function is used to handled repetitive contents to save off a cursor position temporarily to be reset at later point. – int pcreMatch(void *p. u int8 t *cursor) This function validates that the cursor is within bounds of the speciﬁed buffer. CursorInfo *cursorInfo. – int preprocOptionEval(void *p. Take extra care to handle this situation and search for the matched pattern again if subsequent rule options fail to match. patterns that occur more than once may result in false negatives. Cursor position is updated and returned in *cursor. as delimited by LoopInfo and cursor.3 Rules
Each dynamic rules library must deﬁne the following functions. ByteData *byteData. – int checkValue(void *p.1 check for a given packet. • int LibVersion(DynamicPluginMeta *) This function returns the metadata for the shared library. – int checkCursor(void *p.
5. – int checkHdrOpt(void *p. as speciﬁed by HdrOptCheck. ByteData *byteData.– int setCursor(void *p. Cursor position is updated and returned in *cursor. u int8 t **cursor) This function adjusts the cursor as delimited by CursorInfo. and pcreMatch to adjust the cursor position after a successful match. u int8 t *cursor) This function evaluates an ASN. 168
. It handles bounds checking for the speciﬁed buffer and returns RULE NOMATCH if the cursor is moved out of bounds. u int8 t **cursor) This is a wrapper for extractValue() followed by setCursor(). – void revertTempCursor(u int8 t **temp cursor. Cursor position is updated and returned in *cursor.
! △NOTE
If you decide to write you own rule evaluation function. PCREInfo *pcre. CursorInfo *cursorInfo. – void setTempCursor(u int8 t **temp cursor. checking for the existence of the expression as delimited by PCREInfo and cursor. It is also used by contentMatch. u int8 t **cursor) This function iterates through the SubRule of LoopInfo. New cursor position is returned in *cursor. u int8 t *cursor) This function compares the value to the value stored in ByteData. u int8 t **cursor) This function is used to revert to a previously saved temporary cursor position. byteJump. HdrOptCheck *optData) This function evaluates the given packet’s protocol headers. PreprocessorOption *preprocOpt. – int loopEval(void *p. LoopInfo *loop. – int byteTest(void *p.2. as spepcifed by PreprocessorOption.c The metadata and setup function for the preprocessor should be deﬁned in sfsnort dynamic detection lib. This should be done for both content and PCRE options. u int8 t *cursor) This is a wrapper for extractValue() followed by checkValue(). u int8 t **cursor) This function evaluates the preprocessor deﬁned option. as delimited by Asn1Context and cursor. – int detectAsn1(void *p. ByteData *byteData.

registerPreproc("dynamic_example". • int InitializeDetection() This function registers each rule in the rules library.debugMsg(DEBUG_PLUGIN. void ExampleProcess(void *.3 Examples
This section provides a simple example of a dynamic preprocessor and a dynamic rule. DEBUG_WRAP(_dpd. • Rule *rules[] A NULL terminated list of Rule structures that this library deﬁnes. Deﬁne the Setup function to register the initialization function.c and sf dynamic preproc lib. void *).
5.c into lib sfdynamic preprocessor example. } The initialization function to parse the keywords from snort.• int DumpSkeletonRules() This functions writes out the rule-stubs for rules that are loaded.conf. deﬁned in sf preproc info. void ExampleSetup() { _dpd.c and is compiled together with sf dynamic preproc lib. void ExampleInit(unsigned char *).3. ExampleInit).h are used. #define GENERATOR_EXAMPLE 256 extern DynamicPreprocessorData _dpd. This is the metadata for this preprocessor.
169
. "Preprocessor: Example is setup\n"). This preprocessor always alerts on a Packet if the TCP port matches the one conﬁgured. register ﬂowbits.
5.
The remainder of the code is deﬁned in spp example. It should set up fast pattern-matcher content. #define #define #define #define MAJOR_VERSION 1 MINOR_VERSION 0 BUILD_VERSION 0 PREPROC_NAME "SF_Dynamic_Example_Preprocessor" ExampleSetup
#define DYNAMIC_PREPROC_SETUP extern void ExampleSetup(). etc.1 Preprocessor Example
The following is an example of a simple preprocessor.). This assumes the the ﬁles sf dynamic preproc lib.so. The sample code provided with Snort predeﬁnes those functions and uses the following data within the dynamic rules library.h.

a TCP analysis preprocessor could simply return if the packet does not have a TCP header. Packets are passed through a series of decoder routines that ﬁrst ﬁll out the packet structure for link level protocols then are further decoded for things like TCP and UDP ports. The detection engine checks each packet against the various options listed in the Snort rules ﬁles. please use the HEAD branch of cvs.2 Snort Data Flow
First.1 Submitting Patches
Patches to Snort should be sent to the snort-devel@lists. there are a lot of packet ﬂags available that can be used to mark a packet as “reassembled” or logged.sourceforge. This allows this to be easily extensible. trafﬁc is acquired from the network link via libpcap. It can do this by checking: if (p->tcph==null) return.net mailing list.2. End users don’t really need to be reading this section. If you are going to be helping out with Snort development. Patches should done with the command diff -nu snort-orig snort-new. We’ve had problems in the past of people submitting patches only to the stable branch (since they are likely writing this stuff for their own IDS purposes). Each preprocessor checks to see if this packet is something it should look at. Packets are then sent through the detection engine. It will someday contain references on how to create new detection plugins and preprocessors.h for the list of pkt * constants. this chapter is here as a place holder.
6. Check out src/decode. This is intended to help developers get a basic understanding of whats going on quickly.1 Preprocessors
For example.
6.Chapter 6
Snort Development
Currently.
174
.
6. Bugﬁxes are what goes into STABLE. Similarly. Packets are then sent through the registered set of preprocessors. Features go into HEAD. Each of the keyword options is a plugin.

look at an existing output plugin and copy it to a new item and change a few things.
175
.2 Detection Plugins
Basically.3 Output Plugins
Generally.2. Later. we’ll document what these few things are.2. new output plugins should go into the barnyard project rather than the Snort project.
6.6. We are currently cleaning house on the available output options.