Comprehensive Guide to Implementing a Snort-based Intrusion Detection System (IDS)

Snort-based Intrusion Detection System

Building an Advanced IDS with Snort, Apache, MySQL, PHP, and ACID

Chapter 1: Introduction to Intrusion Detection Systems and Snort

In today’s enterprise environments, security is a major concern for all networks. Hackers and intruders have successfully compromised networks and websites of several big companies. Currently, there are some methods to protect network architecture and communications, such as firewalls, Virtual Private Networks (VPNs), and data encryption. Intrusion detection is a relatively new network security technology that has appeared in recent years. Using intrusion detection technology, we can identify whether someone is trying to attack your network or hosts from known types of attacks. The information collected from an intrusion detection system can be used to harden your systems and for other legitimate purposes. There are many vulnerability assessment tools available in the market, both commercial and open-source, that can assess various types of security vulnerabilities in the network.

A comprehensive security system includes several types of tools:

l Firewalls: Used to block network traffic into and out of the network. There are many commercial and open-source firewall products. The most well-known commercial firewall products are Checkpoint (http://www.checkpoint.com), Cisco (http://www.cisco.com), and Netscreen (http://www.netscreen.com). The most well-known open-source firewall is Netfilter/Iptables (http://www.netfilter.org).

l Intrusion Detection Systems (IDS): Used to detect if someone is intruding or trying to intrude into your network. The most famous IDS is Snort, which can be downloaded from http://www.snort.org.

l Vulnerability Assessment Tools: Used to find and fix security holes in the network. The information collected from these tools guides us to set appropriate firewall rules to block malicious Internet users. There are many vulnerability assessment tools available today, such as Nmap ( http://www.nmap.org/) and Nessus ( http://www.nessus.org/).

These tools can be used together to share information. Some products combine these functions into a complete system.

Snort is an open-source network intrusion detection system (NIDS) that can be obtained for free. NIDS is used to detect network traffic in an intrusion detection system (IDS). IDS also includes systems installed on specific hosts that detect attacks targeting the host’s behavior. IDS technology is still quite new, and Snort is at the forefront of IDS.

   This book starts with an introduction to intrusion detection and related concepts. You will learn how to install and manage Snort, as well as other products that work together with Snort. These products include the MySQL database (http://www.mysql.org), the ACID intrusion database analysis management tool (http://www.cert.org/kb/acid). Snort can log data (such as alerts and other log messages) into a database. MySQL is used as the database engine to store all this data. With ACID and the Apache (http://www.apache.com) Web server, we can analyze these data. The combined efforts of Snort, Apache, MySQL, and ACID allow us to log intrusion detection data to a database and then view and analyze it via a web interface.

   The structure of this book is organized so that readers can follow the subsequent chapters step-by-step to build a complete intrusion detection system. The steps to install and integrate various tools will be introduced step by step in the following chapters:

   Chapter 2 covers the basics of compiling and installing Snort. In this chapter, you will be able to establish a working IDS with the basic installation and default rules, and set up log files that record intrusion activities.

   Chapter 3 covers the knowledge about Snort rules, the composition of Snort rules, and how to create your own rules according to your system environment and needs. Creating good rules is key to building an intrusion detection system, so this chapter is very important. This chapter also covers the differences in rules between different versions of Snort.

   Chapter 4 covers input and output plugins. Plugins are compiled with Snort and used to tune the detection engine’s input and output parts. Input plugins prepare the captured data packets before the actual detection process takes place. Output plugins format the data for specific purposes, such as converting the output detection information into SNMP trap information or converting information into database information. This chapter will detail how to configure and use these plugins.

   Chapter 5 covers the collaboration between MySQL databases and Snort. The MySQL plugin allows Snort to log data into a database for subsequent analysis. In this chapter, you will learn how to create a database in MySQL, configure the database plugin, and log data into the database.

   Chapter 6 covers ACID and how to use ACID to obtain information from the database you created in Chapter 5 and display it using the Apache server. ACID is an important tool that provides rich data analysis capabilities. You can use it to obtain attack frequencies, attack types, view related resources of these attack methods, and more. ACID works with PHP scripting language, graphics display library (GD library), and PHPLOT (a tool for drawing charts) to analyze SQL data and generate charts.

   Chapter 7 mainly introduces other useful tools that can work with Snort.

   After reading this book, you will have built a complete system with multiple components, as shown in Figure 1-1.

   In the figure, you can see that Snort captures and analyzes data, and then uses the output plugin to store the data in a MySQL database. The Apache server, with the help of ACID, PHP, GD library, and PHP package, allows users connected to the server to display data through the browser. Users can apply different queries on the web page to analyze, back up, delete data, or generate charts.

   Essentially, you can install Snort, MySQL, Apache, PHP, ACID, GD library, and ACID all on one computer. However, after reading this book, you can build a more practical application like the system shown in Figure 1-2.

   In enterprises, people usually use multiple Snort detectors and place detectors behind each router or firewall. In this case, you can use a centralized database to collect information from all detectors and run the Apache Web server on this database server, as shown in Figure 1-3.

1.1 What is Intrusion Detection?

Intrusion detection refers to a set of techniques and methods used to detect suspicious activities targeting networks and hosts. Intrusion detection systems can be broadly categorized into two types: signature-based intrusion detection systems and anomaly detection systems. Intruders often have characteristics that software can detect, such as viruses. Intrusion detection systems detect packets that contain known intrusion behavior characteristics or anomalies within the IP protocol. Based on a series of signatures and rules, intrusion detection systems can detect and record suspicious activities and generate alerts. Anomaly-based intrusion detection systems typically analyze protocol anomalies in packet headers. In some cases, this method can be more effective than signature-based intrusion detection systems. Normally, intrusion detection systems capture network packets and compare them with rules or detect anomalies. Snort is essentially a rule-based IDS, but input plugins can analyze protocol header anomalies.

   Snort’s rules are stored in text files and can be modified using a text editor. Rules are grouped into categories. Rules in different categories are stored in different files. Finally, these files are referenced by a main configuration file called snort.conf. Snort reads these rules at startup and builds internal data structures or linked lists to use these rules to capture data. Identifying intrusions and capturing them with rules is a skillful task. In real-time detection, the more rules you apply, the more processing power you need. Thus, it’s important to capture as many intrusions as possible with as few rules as possible. Snort has predefined many intrusion detection rules, and you’re free to add your custom rules. You can also remove some built-in rules to prevent false alerts.

1.1.1 Some Definitions

   Before diving into intrusion detection and Snort, you need to understand some network security-related definitions, which will be repeatedly used in the subsequent chapters of this book. A basic understanding of these terms is necessary to comprehend other more complex security concepts.

1.1.1.1    IDS

An Intrusion Detection System or IDS is software, hardware, or a combination of both used to detect intrusions. Snort is an open-source IDS available to the public. The actual capability of an IDS depends on the complexity and sophistication of its components. Physical IDS is a combination of hardware and software, and many companies can provide such solutions. As mentioned earlier, IDS can use signature analysis techniques, anomaly detection techniques, or both.

   1.1.1.2 Network IDS or NIDS

   NIDS is an intrusion detection system used to capture data traversing the network medium and compare it with the signature database. Based on the match between the packets and the signature database, IDS generates alerts or logs records to files or databases. Snort is primarily used as NIDS.

1.1.1.3 Host IDS or HIDS

   Host-based Intrusion Detection Systems or HIDS are installed on a host as an agent and can analyze system and application logs to detect intrusions. Some HIDS are passive, notifying you only when certain things happen, while others are active, sniffing network communications targeting a specific host and generating real-time alerts.

1.1.1.4 Signature

   A signature is a characteristic contained in packet information. Signatures are used to detect one or more types of attacks. For example, if a packet sent to your web service contains “scripts/iisadmin,” it may indicate an intrusion attempt.

   Depending on the nature of the attack, signature data may appear in different locations within a packet. For example, you may find attack signatures in the IP packet header, transport layer header (TCP or UDP header), and/or application layer header or payload. You will learn more about attack signatures later in this book.

   Typically, IDS relies on signatures to detect intrusions. When discovering new attack signatures, some commercial IDSs require updated signature databases from vendors. In contrast, for IDSs like Snort, you can update the signature database yourself.

1.1.1.5 Alerts

   An alert is any notification of an intrusion. When IDS detects intruders, it alerts the security administrator. Alerts can be in the form of pop-up windows, terminal displays, or sending emails, among other forms. Alerts are also stored in log files or databases for security experts to review. Detailed information about alerts will be provided later in this book.

   Snort’s alerts are controlled by output plugins and can generate alerts in various forms. Snort can also send the same alert to different targets, such as sending alerts to a database while generating SNMP trap information. Some plugins can modify firewall configurations to control intruders at the firewall or router.

1.1.1.6 Logs

   Log information is usually stored in files. By default, Snort stores this information in the /var/log/snort directory, but this directory can be changed with command-lineDepending on the structure of your network, you should place IDS in one or more locations. The placement of IDS also depends on the type of intrusion you want to detect: internal, external, or both. For example, if you only want to detect external intrusions and you have a single router connected to the Internet, placing the IDS right next to the internal network interface of the router or firewall might be the best option. If you have multiple Internet entry points, you might want an IDS at each entry point. Sometimes, you might also want to detect internal threats, so placing an IDS on each network segment could be beneficial.

In many cases, you don’t need intrusion detection on all segments; you can place IDS in sensitive areas only. Knowing that more IDS means more work and maintenance costs, IDS deployment should be based on your security policy, i.e., what kind of intrusions you want to prevent. Figure 1-4 shows typical locations for placing IDS.

As you can see in Figure 1-4, you should typically place IDS behind each router and firewall. If your network includes a demilitarized zone (DMZ), you can place IDS there as well. Note that IDS alert strategies in the DMZ should not be as strict as in a private network.

1.1.3 Honeypots

A honeypot is a system that intentionally exposes known vulnerabilities to deceive hackers. When a hacker discovers a honeypot, they usually spend some time on it, during which you can log their behavior and identify the techniques they used. Once you understand these techniques, you can use the information to strengthen your real servers.

There are many ways to build and place honeypots. A honeypot should run some public services, such as Telnet (port 23), HTTP (port 80), FTP (port 21), etc. You should place the honeypot near your application servers so hackers might mistake it for a real server. For example, if your application server IP addresses are 192.168.10.21 and 192.168.10.23, you can set your honeypot’s IP address to 192.168.10.22 and configure your firewall and router to redirect some traffic to the honeypot, making the intruder think the honeypot is a real server. Consider the alert mechanism carefully to get immediate information when your honeypot is threatened. Storing logs on another machine is a good idea, so even if the hacker breaks into the honeypot, they can’t delete the logs.

When should you install a honeypot? It depends:

– If your organization has the resources to track hackers, you should establish a honeypot. Resources include both hardware and human resources. Without sufficient resources, deploying a honeypot is unnecessary.
– A honeypot is useful only if you can utilize the information it provides in some way.
– If you want to collect evidence of behavior to prosecute hackers, a honeypot can be helpful.

Ideally, a honeypot should look like a real system. You can create fake data files, fake accounts, etc., to make hackers believe it’s real and stay there long enough for you to log their activities.

You can find more information on the Honeypot Project website: http://project.honeynet.org/. There are also open-source honeypot resources at http://www.citi.umich.edu/u/provos/honeyd/. Other useful resources include:

– South Florida Honeynet Project: http://www.sfhn.net/
– Related white papers: http://www.sfhn.net/whites/howto.html

1.1.4 Security Zones and Trust Levels

Previously, networks were categorized into two major zones: secure and non-secure. Sometimes, this categorization implied that the network was either inside or outside the router or firewall. Modern networks are typically divided into multiple zones based on various security policies and trust levels. For example, a company’s finance department will have very high security and only allow limited services, with no Internet services; whereas a DMZ is open to the Internet and has a different trust level entirely.

Depending on the trust level and security policies, you should apply different intrusion detection rules and strategies to different zones. Networks with varying security requirements are physically separated. You can install an IDS with different rules in each zone to detect suspicious network activity. For instance, the network in the finance department doesn’t have a web server, so traffic directed to port 80 will be logged as an intrusion, whereas this rule doesn’t apply in the DMZ since the web server there is open to everyone.

1.2 IDS Strategy

Before installing IDS in your network, you need a strategy to detect intruders and respond accordingly. Your strategy must include a series of rules and how they are applied. An IDS strategy should include the following, and you can add more as needed:

– Who views the IDS information? IDS provides alerts about intrusions. The alert system could be as simple as a text file or integrated into network management software like HpOpenView or a database like MySQL. Someone must monitor these alerts and formulate a strategy. Intrusions can be monitored in real-time via pop-up windows or web pages. The operator must understand the alert significance and the security level of the events.
– Who manages the IDS and maintains the logs? Just like any system, IDS requires regular maintenance.
– Who handles security incidents? Without a mechanism to handle security incidents, there’s no point in installing IDS. Some situations might require involving government agencies.
– What does the incident handling process look like? The strategy should outline response mechanisms for different security levels and reporting lines.
– Routine reports should summarize the occurrences of the previous day, week, or month.
– Signature updates: Hackers continually create new attack methods. If IDS knows the attack signatures, it can detect them. Snort rules use an attack signature database for detection. Since attack signatures constantly change, you need to keep your IDS signature database updated. You can get regular updates from the Snort website or update the database yourself when a new attack method is discovered.

Documentation is essential for any project. IDS strategy should describe what kind of documentation should be created when an attack is detected. Documentation can include simple logs or comprehensive records of intrusion activity. Routine reports are also part of the documentation.

Based on your IDS strategy, you can determine how many IDS sensors and other resources your network needs, and calculate the IDS cost more accurately.

1.3 Snort Components

Snort is logically divided into several components that work together to detect specific attacks and produce output in a required format. A Snort-based IDS includes the following key components:

– Packet Decoder
– Preprocessor
– Detection Engine
– Logging and Alerting System
– Output Module

Figure 1-5 illustrates the relationship between these components. Any packet from the Internet first goes to the packet decoder and then gets forwarded to the output module, where it’s either discarded or logged and alerted.

In this section, we will briefly introduce these components. As you read through this book and set up some rules, you’ll become more familiar with these components and how they interact.

1.3.1 Packet Decoder

The packet decoder obtains packets from various network interfaces and prepares them for preprocessing or sending to the detection engine. Network interfaces may include Ethernet, SLIP, PPP, etc.

1.3.2 Preprocessor

The preprocessor is a component or plugin in Snort that arranges or modifies packets before the detection engine takes some steps to discover if they are used for an intrusion. Some preprocessors can also detect packet abnormalities and generate alerts. Preprocessors are crucial for any IDS detection engine as they analyze data based on rules. Hackers have many techniques to fool IDS. For instance, if you create a rule to detect the intrusion signature “scripts/iisadmin” in HTTP packets, if your character matching is too strict, a hacker can easily dodge you with slight variations, such as:

“scripts/./iisadmin”
“scripts/examples/../iisadmin”

Hackers might also embed 16-bit URI characters or Unicode characters within strings, which web servers process as valid characters and translate them back to “scripts/iisadmin”. If the IDS strictly matches a string, it may not detect this kind of attack. Preprocessors can rearrange characters to make IDS detection possible.

Preprocessors also reassemble packet fragments. When a large data stream is sent to a host, the data often gets fragmented. For instance, the default max packet size in Ethernet is 1500 bytes, determined by the network interface’s MTU (Maximum Transfer Unit). This means if the sent data exceeds 1500 bytes, it will be broken into multiple packets to ensure each packet size is ≤1500 bytes. The receiving system reassembles these small fragments into the original packet. An IDS also needs to reassemble packets for signature analysis. For example, half of the intrusion signature might be in one fragment and the other half in another fragment. For the detection engine to accurately analyze the signature, all fragments need to be assembled. Hackers also use malicious fragmentation to evade IDS.

Preprocessors in Snort can reassemble fragments, decode HTTP URIs, reassemble TCP streams, etc. These functions are crucial in any IDS.

1.3.3 Detection Engine

The detection engine is the most critical part of Snort, responsible for detecting whether packets contain intrusion activity. The detection engine uses Snort rules for this purpose. Rules are loaded into internal data structures or linked lists and compared against all packets. If a packet matches a rule, corresponding actions (logging or alert, etc.) are triggered; otherwise, the packet is discarded.

The detection engine is a time-sensitive component in Snort. Depending on your machine’s processing power and the number of defined rules, the detection engine takes varying amounts of time to respond to packets. In NIDS mode, if network traffic is too high, the detection engine may drop some packets due to slow response times. The detection engine’s load depends on the following factors:

– Number of rules
– Processing power of the machine running Snort
– Internal bus speed of the machine running Snort
– Network load

When designing an NIDS, you should consider all related factors.

You need to understand the detection system’s capability for parsing packets and applying rules to different parts of packets, including:

– IP header of the packet
– Transport layer header, including TCP, UDP, or other transport protocol headers, or possibly the ICMP header.
– Application layer header. This includes DNS headers, FTP headers, SNMP headers, SMTP headers, among others. You can sometimes use indirect methods like bit offsets to get application header info.
– Packet payload. This allows creating rules for the detection engine to search for specific characters in the transmitted data.

In different versions of Snort, detection engines function differently. In all versions 1.x of Snort, once the detection engine matches a packet to a rule, the process stops, and an alert or log is produced based on the rule. This means if a packet matches multiple rules, only the first rule is applied and no further matching occurs. While advantageous, this approach falls short if a low-priority rule matches first, resulting in low-priority alerts, bypassing high-priority subsequent rules. Snort version 2 improves this by matching packets to all rules and then generating alerts, ultimately choosing the highest-priority rule for alerting.

Snort version 2’s detection engine has been completely rewritten, making it significantly faster than previous versions. At the time of this writing, Snort 2.0 is yet to be released, but early tests show the new engine can be up to 18 times faster than the old one.

1.3.4 Logging and Alerting System

Based on the contents found in the package, a package can be used to record actions or generate alerts. Logs can be saved as simple text files, tcpdump format files, or other forms. By default, all log files are stored in the /var/log/snort directory. You can use the -l option in the command line to modify the location where logs and alerts are stored. More command line options will be discussed in the next chapter. These options can be used to modify the type and details of logs and alerts.

1.3.5 Output Modules

Output modules or plugins can perform different actions based on how you specify the way to save the output information generated by the logging and alert system. Essentially, these modules are used to control the format of the output information from the logging and alert system. Depending on the configuration, output modules can perform the following tasks:

l Log in the /var/log/snort/alerts file or other files
l Send SNMP traps
l Log to a database like MySQL or Oracle. More information on using MySQL will be provided later in this book
l Generate XML output
l Modify router or firewall configurations
l Send SMB messages to Windows hosts

Other tools can be used to send alerts in formats like email messages or web page browsing, which will be discussed in later chapters. Table 1-1 summarizes the components of IDS.

Table 1-1 IDS Components

Name

Description

Packet Decoder

Prepares the packet for processing

Preprocessor or Input Plugin

Analyzes protocol headers, normalizes headers, detects header anomalies, reassembles packet fragments, assembles TCP streams

Detection Engine

Matches packets against rules

Logging and Alerting System

Generates alerts and logs

Output Module

Outputs alerts and logs to the final destination

1.4 About Switches

Depending on the switch you are using, there are various ways to install the Snort machine on a switch port. Some switches, like Cisco, allow you to mirror all communications to the port where the Snort machine is connected. Such a port is often referred to as a Spanning port. The optimal position to install Snort is directly behind the router or firewall so that Snort can capture all internet data streams before they enter the switch or hub. For example, if your firewall has a T1 line connected to the Internet and is connected to the internal network via a switch, a typical connection scenario is shown in Figure 1-6.

If your switch has a Spanning port, you can connect the IDS device to the spanning port as shown in Figure 1-7, which allows the IDS to see all communications with the Internet as well as internal communications.

You can also connect the IDS to a hub between the firewall and the switch, making all incoming and outgoing communications visible to the IDS. This setup is shown in Figure 1-8.

However, note that if the IDS is set up as in Figure 1-8, it will not receive packets for internal communications, only the communications between the Internet and the internal network. This setup is useful when the internal network is trusted and anticipated attacks originate from outside.

1.5 Tracking TCP Data Streams

Snort has added a new preprocessor called Stream4, which can handle thousands of concurrent data streams. Its configuration will be discussed in Chapter 4. It can reassemble TCP data streams and conduct stateful detection. This means you can reassemble a specific TCP session and detect anomalies that exploit multiple TCP packets. You can also inspect packets flowing into or out of a particular server port.

1.6 Platforms Supported by Snort

Snort supports various hardware platforms and operating systems. Currently, Snort supports the following operating systems:

• Linux
• OpenBSD
• NetBSD
• Solaris (Sparc or i386)
• HP-UX
• AIX
• IRIX
• MacOS
• Windows

You can check the list of platforms currently supported by Snort on the Snort website at http://www.snort.org.

1.7 How to Protect the IDS Itself

A critical question is how to protect the system running IDS? If the security of the IDS itself is compromised, the alerts you receive may be false, or you may not receive alerts at all. Intruders might disable the IDS before launching a real attack. There are many ways to protect your system, ranging from general recommendations to more complex methods. Some methods are mentioned below:

l The first thing you can do is not run any services on the machine running the IDS detector. Network services are the most common way to probe the system.
l When new threats appear, vendors release corresponding patches, which is a continuous and never-ending process. Your IDS should install the latest patches available from the vendor. For example, if your Snort is running on a Windows machine, you should install all the latest security patches released by Microsoft.
l Configure your IDS machine so that it does not respond to ping (ICMP echo) requests.
l If you are running IDS on a Linux machine, use netfilter/iptables to block any unnecessary traffic. Snort will still be able to see all the packets.
l If your IDS machine is only used for intrusion detection, do not perform any other activities or set up other user accounts on it unless absolutely necessary.

Apart from these common methods, Snort can be applied in some special ways. Below are two specific techniques to prevent Snort from being attacked.

1.7.1 Running Snort on a Stealth Interface

You can run Snort on a stealth interface that only listens to incoming packets without sending any outgoing packets. For a stealth interface, use a special cable that shorts pins 1 and 2 and connects pins 3 and 6 on the host running Snort. More information on this method can be found on Snort’s FAQ page http://www.snort.org/docs/faq.html.

1.7.2 Running Snort on an Interface Without an IP Address

You can also run Snort on an interface that is not assigned an IP address. For instance, on a Linux machine, you can activate an interface without an IP address with a command like “ifconfig eth0 up”. The benefit of this approach is that since the Snort host does not have an IP address, no one can access it. You can configure an IP address on eth1 to access this detector, as shown in Figure 1-9.

In a Windows system, you can use an interface that does not bind to the TCP/IP protocol, preventing an IP address from being assigned to it. Do not forget to disable other protocols and services simultaneously. In some cases, when the interface is not configured with an IP address, you may encounter a message indicating that WinPcap (the library used for packet capture in Windows) is unavailable. If this happens, you can use the following method:

l Configure the TCP/IP protocol on the network interface you intend to use as a stealth interface, and disable all other protocols and services.
l Enable the DHCP client.
l Disable the DHCP server.

This will ensure that the network interface does not have an IP address, but the network interface can still bind to the TCP/IP protocol.

1.8 Related Resources

1. Intrusion Detection FAQ: http://www.sans.org/newlook/resources/IDFAQ/ID_FAQ.htm
2. Honeynet Project: http://project.honeynet.org/
3. Snort FAQ: http://www.snort.org/docs/faq.html
4. Honeyd Honeypot: http://www.citi.umich.edu/u/provos/honeyd/
5. WinPcap: http://winpcap.polito.it/
6. Cisco Systems: http://www.cisco.com
7. Checkpoint Site: http://www.checkpoint.com
8. Netscreen: http://www.netscreen.com
9. Netfilter: http://www.netfilter.org
10. Snort: http://www.snort.org
11. Nmap Tool: http://www.nmap.org
12. Nessus: http://www.nessus.org
13. MySQL Database: http://www.mysql.org
14. ACID: http://www.cert.org/kb/acid
15. Apache Web Server: http://www.apache.org

Chapter 2 Installing Snort and Getting Started

Snort can be installed as a standalone daemon or as a complete system that includes many other tools. If you install Snort alone, you can obtain the intrusion data in text or binary files, which can be viewed using a text editor or other tools similar to Barnyard, which will be described later in this book. In a simple installation scenario, you can also send alert information in the form of SNMP traps to network management systems such as HP OpenView or OpenNMS. Alerts can also be sent as SMB pop-up windows to Windows machines. If you install it along with other tools, you can perform more complex operations, such as sending Snort data to a database and analyzing it through a web interface. Analytical tools allow you to have a more intuitive understanding of the captured data without spending a lot of time deciphering obscure log files.

Below are some tools you can use, none have specific tasks. A comprehensive Snort system uses these tools to provide a backend database and a web user interface.

MySQL is used for Snort to log alerts. Although databases similar to Oracle can also be used, MySQL is more common in the Snort environment. In fact, Snort can use any ODBC-compatible database.

l Apache as the web server
l PHP as the interface between the web server and the MySQL database
l ACID is used as the PHP package for analyzing Snort data through a web interface
l GD library is used by ACID for generating graphical charts
l PHPLOT is used in the ACID web interface to present data as charts. For PHPLOT to work, the GD library must be configured correctly.
l ADODB is used by ACID to connect to the MySQL database.

2.1 Snort Installation Schemes

The installation method of Snort depends on the operating environment. Below are some typical installation schemes for reference, and you can choose based on your network conditions.

2.1.1 Test Installation

A simple installation only includes a Snort detector. Snort records data in text files. The log files are then reviewed by the Snort administrator. Due to the high cost of analyzing logs in actual use, this method is only suitable for testing environments. To install Snort using this method, you can get the compiled version at http://www.snort.org. For RedHat Linux, you can download the RPM package. For Windows, you can download the executable file and install it on your system.2.1.2 Installing an Application IDS with a Single Sensor

The single-sensor Snort application is suitable for small networks with only one Internet line. Place the sensor behind the router or firewall to detect intruders entering the system. If you are also interested in all Internet traffic, you can place the sensor outside the firewall.

In this setup, you can download precompiled versions from the Snort website at http://www.snort.org, or you can download the source code to compile it according to your requirements. This flexibility allows you to obtain the desired features that may not be available in the precompiled versions. The compilation steps for Snort will be discussed in detail in this chapter.

Snort can be set up to start and stop automatically during system bootup in the application installation. If you install a precompiled version on Linux, the RPM package will handle this for you. On Windows systems, you can start Snort as a service or place it in a startup group batch file. Issues related to Windows will be covered in Chapter 8. Logs can be recorded as text files or binary files and analyzed using tools like SnortSnarf, which will be discussed in detail in Chapter 6.

2.1.3 Integrating a Single Sensor with Network Management Systems

In application systems, you can configure Snort to send traps to a network management system. Many types of network management systems are used in enterprise applications, with major commercial vendors including HP, IBM, and Computer Associates.

Snort can be integrated into these network management systems using SNMP traps. After going through this chapter’s Snort compilation steps, you will understand how Snort provides SNMP capabilities. Chapter 4 will introduce more details on configuring SNMP trap targets, community names, and other relevant information.

2.1.4 Single Sensor with Database and Web Interface

A common usage of Snort is its integration with a database, which is used to log data that can be accessed later through a web interface. This typical setup consists of the following three components:

Snort sensor

Database server

Web server

Snort logs data into the database, which you can view by connecting to it with a web browser. This type of setup is depicted in Figure 1-1 in Chapter 1. All three components can also be installed on the same system, as shown in Figure 1-2 in Chapter 1.

Snort supports various types of databases like MySQL, PostgresSQL, Oracle, Microsoft SQL Server, and other ODBC-compatible databases. PHP is used to fetch data from the database and generate web pages.

This setup offers you a feature-rich IDS with a user-friendly interface that is easy to manage. To log data in the database, you must provide Snort with the database username, password, database name, and database server address. In a single sensor setup, if the database server is on the same machine as the sensor, you can use “localhost” as the hostname. You need to choose the database logging capability when compiling Snort, which will be detailed later in this chapter. The configuration of Snort with a database will be covered in Chapters 4, 5, and 6.

2.1.5 Managing Multiple Snort Sensors with a Centralized Database

In a distributed environment, you may need to install Snort sensors at multiple locations. Managing all these sensors and analyzing their collected data separately is a challenging task. In enterprise applications, there are ways to configure Snort as a distributed IDS.

One method involves connecting multiple sensors to a central database, as shown in Figure 1-3. All the data generated by the sensors is stored in this database, and a web server, like Apache, is run concurrently. Users can then view and analyze this data with a web browser.

However, be aware that this setup has some practical issues:

l All sensors must be able to access the database when starting Snort, or Snort will terminate the process.

l The database must always be accessible to the sensors; otherwise, data will be lost.

l If there is a firewall between the sensors and the database server, you need to open the appropriate ports. Sometimes, this may conflict with or violate the firewall’s security policy.

When sensors cannot directly access the database server, there are workarounds. Sensors can be configured to store files locally and periodically upload these files to the central database server using a tool like SCP. SCP is a tool that uses the SSH protocol for secure file transfers. The firewall administrator must allow communication through the SSH port. You can use Snort itself, Barnyard, or other tools to extract data from log files and insert it into the database. You can then review this data through a web interface later. The only issue with this method is that the data in the database isn’t strictly real-time. The delay depends on the frequency with which data is uploaded to the central database server using SCP. This method is depicted in Figure 2-1.

Note that the central database server must be running an SSH server to permit data uploads using SCP.

As mentioned in Chapter 1, this book’s ultimate goal is to help you install Snort and make all software packages work together. After walking through this book, you will understand how these components interact and form a complete intrusion detection system. The software discussed in this book is available for download from this book’s website at http://authors.phpktr.com/rhman/. You will also find some scripts on that site to help you install these packages easily on a new system. In fact, with some scripts mentioned in this book, you can set up a working IDS with just a few command lines if you have root access. If you are using a newer version of Snort than covered in this book, you can download the latest scripts supporting the newer version of Snort from http://www.argusnetsec.com/downloads.

This book details the installation of these components on RedHat Linux 7.3, but the process is similar for other Linux versions or platforms. For convenience, all components are installed under the /opt directory in this book. However, the installation location may vary if you use precompiled packages. When using the scripts from this book or its website, files will be installed in this directory. In this chapter, you will learn how to install Snort as a standalone product. Other components will be covered in later chapters.

You can obtain Snort in binary or source code form. For most installations, precompiled binary packages are excellent. As mentioned earlier, if you want to customize Snort features, you need to download and compile the source code version. For example, some users prefer SMB alerts, while others may consider them insecure. If you need a version of Snort that does not support SMB alerts, you will have to compile it yourself. This also applies to other features like SNMP traps, MySQL, and more. Another reason to compile Snort yourself is to understand the development code. This chapter will guide you step-by-step through installing Snort.

The basic installation process is straightforward, and Snort includes predefined rules covering most known attack patterns. However, customized installation can be more intricate.

2.2 Installing Snort

In this section, you will learn how to install precompiled Snort and how to compile and install it yourself. Installing the precompiled RPM package is very simple and requires only a few steps. However, if your Snort is in source code form, it will take some time to understand and install.

2.2.1 Installing Snort Using RPM Package

Installing Snort using the RPM package involves the following steps.

2.2.1.1 Download

Download the latest version of Snort from the Snort website (http://www.snort.org). At the time of writing this book, the latest binary version is snort-1.9.0-1snort.i386.rpm.

2.2.1.2 Install

Run the following command to install the Snort binary package:

rpm –install snort-1.9.0-1snort.i386.rpm

This command will perform the following actions:

n Create the /etc/snort directory where Snort’s rules and configuration files will be stored.

n Create the /var/log/snort directory where Snort’s log files will be stored.

n Create the /usr/share/doc/snort-1.9.0 directory to store Snort’s documentation files. This directory will contain files like FAQ, README, and others.

n Create a file called snort-plain in the /usr/sbin directory, which acts as Snort’s daemon. Create the /etc/rc.d/init.d/snortd file, which is the startup and shutdown script. On RedHat Linux, it is equivalent to /etc/init.d/snortd.

At this point, the basic installation is complete, and you can start using Snort. This Snort version does not have database support compiled in, so you can only use the log files in the /var/log/snort directory.

2.2.1.3 Starting, Stopping, and Restarting Snort

Use the following command to start Snort manually:

/etc/init.d/snortd start

This command will start the Snort daemon. Running the “ps –ef” command will show output similar to the following:

root 15999 1 0 18:31 ? 00:00:01 /usr/sbin/

snort -A fast -b -l /var/log/snort -d -D -i eth0 -c /etc/

snort/snort.conf

Note that you have to manually start Snort every time you restart the machine. You can automate this process by creating file links, which will be discussed later in this chapter.

Use the following command to stop Snort:

/etc/init.d/snortd stop

Use the following command to restart Snort:

/etc/init.d/snortd restart

2.2.2 Installing Snort from Source Code

To install Snort from source code, you first need to compile it. You can create the snort executable by following the steps outlined below. First, obtain the latest version of Snort from the Snort website (http://www.snort.org). At the time of writing this book, the latest version of Snort is 1.9.0, and the download file is named snort-1.9.0.tar.gz. Save the download in the /opt directory. Note that the version might be newer by the time you read this, and the installation procedure will be similar.

2.2.2.1 Extract

After downloading, the first step is to extract the source code using the following command:

tar zxvf snort-1.9.0.tar.gz

This will create the /opt/snort-1.9.0 directory. Make sure to download the file to the /opt directory and run the tar command from this directory. If it’s a different version of Snort, the directory name will differ to reflect the version number. After extraction, you can run the tree command to observe the directory structure created by the tar command. Below is the directory tree for /opt/snort-1.9.0:

[rootThe main contents of these directories are as follows:

The `contrib` directory primarily includes application software that is not strictly a part of Snort itself. This software includes ACID, MySQL database generation scripts, and others.

The `doc` directory contains documentation files.

The `etc` directory contains configuration files.

The `rules` directory contains predefined rule files.

All source code is contained within the `src` directory.

The `templates` directory is intended for those who are preparing to write their own plugins, which may not be relevant for most Snort users.

### 2.2.2.2 Compilation and Installation

The compilation and installation process involves the following three steps:

1. Run the `configure` script.
2. Run the `make` command.
3. Run the `make install` command.

To start the Snort compilation process, first navigate to the `/opt/snort-1.9.0` directory and run the `configure` script. If you are new to GNU software, it is worth knowing that the `configure` script is a common tool used in open-source software packages. It is utilized for setting up parameters, creating `makefile`, and detecting development tools and libraries on your system. While running the `configure` script, there are numerous command-line options available. These options determine which components are included when Snort is compiled. For instance, using these options, you can build support for SNMP, MySQL, or SMB alerts, among many other features. You can also customize the final installation location of the Snort files. Use `./configure –help` to see the available options, as shown below:

# ./configure –help

`configure’ configures this package to adapt to many kinds of systems.

Usage: ./configure [OPTION]… [VAR=VALUE]…

To assign environment variables (e.g., CC, CFLAGS…), specify them as
VAR=VALUE. See below for descriptions of some of the useful variables.

Defaults for the options are specified in brackets.

Configuration:
-h, –help display this help and exit
–help=short display options specific to this package
–help=recursive display the short help of all the included packages
-V, –version display version information and exit
-q, –quiet, –silent do not print `checking…’ messages
–cache-file=FILE cache test results in FILE [disabled]
-C, –config-cache alias for `–cache-file=config.cache’
-n, –no-create do not create output files
–srcdir=DIR find the sources in DIR [configure dir or `..’]

Installation directories:
–prefix=PREFIX install architecture-independent files in PREFIX
[/usr/local]
–exec-prefix=EPREFIX install architecture-dependent files in EPREFIX
[PREFIX]

By default, `make install’ will install all the files in
`/usr/local/bin’, `/usr/local/lib’ etc. You can specify
an installation prefix other than `/usr/local’ using `–prefix’,
for instance `–prefix=$HOME’.

For better control, use the options below.

Fine-tuning of the installation directories:
–bindir=DIR user executables [EPREFIX/bin]
–sbindir=DIR system admin executables [EPREFIX/sbin]
–libexecdir=DIR program executables [EPREFIX/libexec]
–datadir=DIR read-only architecture-independent data [PREFIX/share]
–sysconfdir=DIR read-only single-machine data [PREFIX/etc]
–sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com]
–localstatedir=DIR modifiable single-machine data [PREFIX/var]
–libdir=DIR object code libraries [EPREFIX/lib]
–includedir=DIR C header files [PREFIX/include]
–oldincludedir=DIR C header files for non-gcc [/usr/include]
–infodir=DIR info documentation [PREFIX/info]
–mandir=DIR man documentation [PREFIX/man]

Program names:
–program-prefix=PREFIX prepend PREFIX to installed program names
–program-suffix=SUFFIX append SUFFIX to installed program names
–program-transform-name=PROGRAM run sed PROGRAM on installed program names

System types:
–build=BUILD configure for building on BUILD [guessed]
–host=HOST cross-compile to build programs to run on HOST [BUILD]

Optional Features:
–disable-FEATURE do not include FEATURE (same as –enable-FEATURE=no)
–enable-FEATURE[=ARG] include FEATURE [ARG=yes]
–disable-dependency-tracking speeds up one-time builds
–enable-dependency-tracking do not reject slow dependency extractors
–enable-debug enable debugging options (for bug reports and developers only)
–enable-profile enable profiling options (developers only)
–enable-sourcefire Enable Sourcefire specific build options
–enable-perfmonitor Enable perfmonitor preprocessor
–enable-linux-smp-stats Enable statistics reporting through proc
–enable-flexresp Enable Flexible Responses on hostile connection attempts

Optional Packages:
–with-PACKAGE[=ARG] use PACKAGE [ARG=yes]
–without-PACKAGE do not use PACKAGE (same as –with-PACKAGE=no)
–with-libpcap-includes=DIR libpcap include directory
–with-libpcap-libraries=DIR libpcap library directory
–with-libnet-includes=DIR libnet include directory
–with-libnet-libraries=DIR libnet library directory
–with-mysql=DIR support for mysql
–with-odbc=DIR support for ODBC
–with-postgresql=DIR support for PostgreSQL
–with-oracle=DIR support for Oracle

Some influential environment variables:

  CC C compiler command

  CFLAGS C compiler flags

  LDFLAGS linker flags, e.g. -L if you have libraries in a

nonstandard directory

  CPPFLAGS C/C++ preprocessor flags, e.g. -I if you have

headers in a nonstandard directory

  CPP C preprocessor

Use these variables to override the choices made by `configure` or to help

it to find libraries and programs with nonstandard names/locations.

   Specified values within square brackets indicate the default values should the option not be specified. For example: the –prefix option’s second line indicates that if the –prefix option is not set, the system will choose the default value /usr/local. PREFIX specifies the directory where Snort files will be installed when you execute the “make install” command.

–prefix=PREFIX install architecture-independent files in PREFIX

[/usr/local]

A typical session to run the configure script is shown below. The output has been trimmed for brevity. Note the options enabled in the command line.

[root@conformix snort-

1.9.0
]# ./configure –prefix=/opt/snort

–enable-smbalerts –enable-flexresp –with-mysql –with-snmp

–with-openssl

loading cache ./config.cache

checking for a BSD compatible install… (cached) /usr/bin/

install -c

checking whether build environment is sane… yes

checking whether make sets ${MAKE}… (cached) yes

checking for working aclocal… found

checking for working autoconf… found

checking for working automake… found

checking for working autoheader… found

checking for working makeinfo… found

checking for gcc… (cached) gcc

checking whether the C compiler (gcc) works… yes

checking whether the C compiler (gcc) is a cross-compiler…

no

checking whether we are using GNU C… (cached) yes

checking whether gcc accepts -g… (cached) yes

checking for gcc option to accept ANSI C… (cached) none

needed

checking for ranlib… (cached) ranlib

   The output has been trimmed because the configure command generates a large amount of information. The prefix option tells the configure script where the program should ultimately be installed. The other options enable the following Snort components:

Support for MySQL database.

Support for SNMP trap messages.

Support for SMB alerts. SMB alerts are used to send pop-up alerts to Windows.

Support for Flex responses. Flex responses are used to terminate network sessions in real time. More details about Flex responses will be provided in subsequent sections. Note that your system must have libnet installed to use this option. You can download libnet from http://www.securityfocus.net. I used version 1.0.2a for the installation.

After running the configure script, you can compile and install Snort by executing the following two commands:

make

make install

These commands may take some time to complete, depending on your computer’s capabilities. Once you execute the second command, the files will be installed to the appropriate directories. Since you chose –prefix=/opt/snort when running the configure script, the make install command will install the Snort binary files to the /opt/snort directory.

    Available parameters for the configure script are listed in Table 2-1.

Table 2-1: Configure Script Parameters

Parameter

Description

–with-mysql

Build Snort with MySQL support.

–with-snmp

Build Snort with SNMP support. This option must be specified together with –with-openssl.

–with-openssl

Enable support for OpenSSL. This option is required if –with-snmp is selected.

–with-oracle

Build Snort with Oracle database support.

–with-odbc

Build Snort with ODBC support.

–enable-flexresp

Enable Flex response support in Snort, which allows terminating malicious connections. This feature is currently experimental (see the README.FLEXRESP file provided with Snort).

–enable-smbalerts

Enable SMB alerts in Snort. Note that each alert occupies user space on the client machine.

–prefix=DIR

Set the directory where Snort files will be installed.

Before executing the “make install” command, you can also run the “make check” command to ensure Snort has been built correctly.

After installation, run Snort to check if the executable works. Once the previous steps are completed, the Snort binary will be installed in the /opt/snort/bin directory. The following command will display general help information and command line options for the newly installed Snort.

If you see such information, then your Snort has been installed correctly. In the next section, you will learn how to configure and run Snort.

2.2.2.3 Tasks to perform after installation

Now that the Snort binary files are installed, there are still some tasks to complete:

1.  Create the /var/log/snort directory as the default location for Snort log files.

2.  Create a directory to store the configuration files. I created the /opt/snort/etc directory, but you can create your preferred directory.

3.  Create or copy the configuration files to the /opt/snort/etc directory.

4.  Create the /opt/snort/rules directory and copy the default rule files into it. This directory will be specified in the snort.conf file, but you can create your preferred directory.

Let’s go over these steps in detail:

First, create the /var/log/snort directory for Snort to store log files. You can use another directory, but this is commonly used. If you use any other directory, you need to specify it with the -l command line option when starting Snort.

Next, create the Snort configuration files. When Snort starts, it will read the configuration file snort.conf from the current directory or the .snortrc file from the home directory of the user running Snort. If this file resides in another directory, you can specify it with the -c command line option. Initially, you can copy the snort.conf file provided in the Snort source code to the /opt/snort/etc directory you created. Also copy the classification.config and reference.config files into it, as these files are referenced by snort.conf. Additionally, copy all files from the rules directory of the source code to the /opt/snort/rules directory. The following commands implement these steps:

mkdir /opt/snort/etc

cp /opt/snort-

1.9.0
/etc/snort.conf /opt/snort/etc

cp /opt/snort-

1.9.0
/etc/classification.config /opt/snort/etc

cp /opt/snort-

1.9.0
/etc/reference.config /opt/snort/etc

mkdir /opt/snort/rules

cp /opt/snort-

1.9.0
/rules/* /opt/snort/rules

The files with the .rules suffix in the rules directory contain various rules that are referenced by the snort.conf file. The location of these rules files is controlled by the RULE_PATH variable defined in the snort.conf file, commonly represented as follows:

var RULE_PATH ../rules

    This indicates that the rule files are located in a directory called rules. For example, if the snort.conf file is in the /opt/snort/etc directory, then all the rule files should be within the /opt/snort/rules directory. Alternatively, if the snort.conf file is located in the /var/snort directory, then the rule files must be in the /var/rules directory. You can also place the snort.conf file and all rule files in the same directory but change the RULE_PATH value in snort.conf from ../ to ./:

    var RULE_PATH ./

In the next chapter, you will learn more about Snort rules, as well as how to define your own rules.

The classification.config file includes information about Snort rule classifications. You will learn more about it in the next chapter. In the examples in this book, all Snort source code files are located in /opt/snort-

1.9.0
directory. If you are using a different version of Snort, the directory will be different.

The reference.config file lists URLs to refer to for different alert information, which will be referenced in Snort rules. You will learn more about this in the next chapter. A typical reference.config file looks like this:

# $Id: reference.config,v 1.3 2002/08/28 14:19:15 chrisgreen

Exp $

# The following defines URLs for the references found in the

rules

#

# config reference: system URL

config reference: bugtraq http://www.securityfocus.com/bid/

config reference: cve http://cve.mitre.org/cgi-bin/

cvename.cgi?name=

config reference: arachNIDS http://www.whitehats.com/info/IDS

# Note, this one needs a suffix as well…. let’s add that in a

bit.

config reference: McAfee http://vil.nai.com/vil/content/v_

config reference: nessus http://cgi.nessus.org/plugins/

dump.php?plugin_id=

config reference: url http://

Note: Both classification and reference.config files are referenced by the main configuration file snort.conf.

You can now run Snort using the following command, which will display startup information and then listen on the eth0 interface. To avoid some potential issues, this command specifies the absolute path of the snort.conf file using command line options.

[root@conformix snort]# /opt/snort/bin/snort -c /opt/snort/

etc/snort.conf

Initializing Output Plugins!

Log directory = /var/log/snort

Initializing Network Interface eth0

–== Initializing Snort ==–

Decoding Ethernet on interface eth0

Initializing Preprocessors!

Initializing Plug-ins!

Parsing Rules file /opt/snort/etc/snort.conf

+++++++++++++++++++++++++++++++++++++++++++++++++++

Initializing rule chains…

No arguments to frag2 directive, setting defaults to:

Fragment timeout: 60 seconds

Fragment memory cap: 4194304 bytes

Fragment min_ttl: 0

Fragment ttl_limit: 5

Fragment Problems: 0

Stream4 config:

Stateful inspection: ACTIVE

Session statistics: INACTIVE

Session timeout: 30 seconds

Session memory cap: 8388608 bytes

State alerts: INACTIVE

Evasion alerts: INACTIVE

Scan alerts: ACTIVE

Log Flushed Streams: INACTIVE

MinTTL: 1

TTL Limit: 5

Async Link: 0

No arguments to stream4_reassemble, setting defaults:

Reassemble client: ACTIVE

Reassemble server: INACTIVE

Reassemble ports: 21 23 25 53 80 143 110 111 513

Reassembly alerts: ACTIVE

Reassembly method: FAVOR_OLD

http_decode arguments:

Unicode decoding

IIS alternate Unicode decoding

IIS double encoding vuln

Flip backslash to slash

Include additional whitespace separators

Ports to decode http on: 80

rpc_decode arguments:

Ports to decode RPC on: 111 32771

telnet_decode arguments:

Ports to decode telnet on: 21 23 25 119

Conversation Config:

KeepStats: 0

Conv Count: 32000

Timeout : 60

Alert Odd?: 0

Allowed IP Protocols: All

Portscan2 config:

log: /var/log/snort/scan.log

scanners_max: 3200

targets_max: 5000

target_limit: 5

port_limit: 20

timeout: 60

1273 Snort rules read…

1273 Option Chains linked into 133 Chain Headers

0 Dynamic rules

+++++++++++++++++++++++++++++++++++++++++++++++++++

Rule application order: -> activation-> dynamic-> alert-> pass-

> log

–== Initialization Complete ==–

-*> Snort! <*-

Version

1.9.0
(Build 209)

By Martin Roesch ([email protected], www.snort.org)

As you can see from these output messages, Snort has started to listen on the eth0 interface. If any packets match the rules, Snort will take the corresponding action and generate alerts based on the rules. Alerts can be generated in various formats. In this basic mode, alerts will be logged to the /var/log/snort/alerts file. Later, you will see how to generate other forms of alerts and log them into databases, and you will also learn the format of Snort alert data files.

You can terminate the Snort process at any time by pressing the ctrl and c keys simultaneously. At that point, Snort will display a summary of program activity and then exit, as shown below:

==========================================================

Snort analyzed 65 out of 65 packets, dropping 0 (0.000%)

packets

Breakdown by protocol: Action Stats:

TCP: 55 (84.615%) ALERTS: 10

UDP: 10 (15.385%) LOGGED: 10

ICMP: 0 (0.000%) PASSED: 0

ARP: 0 (0.000%)

EAPOL: 0 (0.000%)

IPv6: 0 (0.000%)

IPX: 0 (0.000%)

OTHER: 0 (0.000%)

DISCARD: 0 (0.000%)

==========================================================

Wireless Stats:

Breakdown by type:

Management Packets: 0 (0.000%)

Control Packets: 0 (0.000%)

Data Packets: 0 (0.000%)

==========================================================

Fragmentation Stats:

Fragmented IP Packets: 0 (0.000%)

Fragment Trackers: 0

Rebuilt IP Packets: 0

Frag elements used: 0

Discarded (incomplete): 0

Discarded (timeout): 0

Frag2 memory faults: 0

==========================================================

TCP Stream Reassembly Stats:

TCP Packets Used: 55 (84.615%)

Stream Trackers: 1

Stream flushes: 0

Segments used: 0

Stream4 Memory Faults: 0

==========================================================

Snort received signal 2, exiting

[root@conformix snort]#

The previously mentioned method runs Snort in the foreground, causing you to lose the prompt in the terminal. To run Snort in the background, use the command-line switch -D. This way, Snort will still log alert information to /var/log/snort, and you will retain the prompt. Note that if you have installed Snort using an RPM package, you can use the “/etc/init.d/snortd start” command to run Snort in the background.

2.2.3 Snort Startup Errors

    If you compiled Snort yourself, you might encounter the following error message when starting Snort:

    [!] ERROR: Cannot get write access to logging directory “/var/

log/snort”.

(directory doesn’t exist or permissions are set incorrectly

or it is not a directory at all)

Fatal Error, Quitting..

This error occurs because you did not create the /var/log/snort directory. Run “mkdir /var/log/snort” and then restart Snort to resolve this issue.

If you see the following error message, it means that you did not correctly specify the configuration file when starting Snort.

Initializing rule chains…

ERROR: Unable to open rules file: /root/.snortrc or /root//

root/.snortrc

Fatal Error, Quitting..

Note: In the following situations, you may avoid specifying the configuration file:

1.  You start Snort in the directory where the configuration file is located.

2.  You have copied the configuration file to your home directory as .snortrc.

2.2.4 Testing Snort

    After starting Snort, you need to know if it is capturing data and logging intrusion events. If you start Snort in the foreground using the “-A console” option, you will see alert information on the terminal screen. If you start Snort in daemon mode without this command-line option, alerts will be recorded in the /var/log/snort/alert file.

    The following command will help you see some alert messages on the console or in the /var/log/snort/alert file, allowing you to verify Snort’s functionality:

ping -n -r -b 255.255.255.255 -p “7569643d
3028726f
6f
74290a
” -c3

    If you use the “-A console” command line option, you should see alerts similar to the following on the screen:

       11/19-18:51:04.560952 [**] [1:498:3] ATTACK RESPONSES id

check returned root [**] [Classification: Potentially Bad

Traffic] [Priority: 2] {ICMP} 10.100.1.105 -> 255.255.255.255

2.2.4.1 Generating Test Alerts

The following script, named snort-test.sh, is available at http://authors.phptr.com/rehman/. It performs a function similar to the above command but can be used when running Snort in daemon mode.

1 #!/bin/sh

2 #

3 ###############################################################

4 # You are free to copy and distribute this script under #

5 # GNU Public License until this part is not removed #

6 # from the script. #

7 ###############################################################

8 # HOW TO USE #

9 # #

10 # Right after installation of Snort, run this script. #

11 # It will generate alerts in the /var/log/snort/alert file similar#

12 # to the following: #

13 # #

14 # Note that Snort must be running at the time you run this #

15 # script. #

16 # #

17 # [**] [1:498:3] ATTACK RESPONSES id check returned root [**] #

18 # [Classification: Potentially Bad Traffic] [Priority: 2] #

19 # 08/31-15:56:48.188882 255.255.255.255 -> 192.168.1.111 #

20 # ICMP TTL:150 TOS:0x0 ID:0 IpLen:20 DgmLen:84 #

21 # Type:0 Code:0 ID:45596 Seq:1024 ECHO REPLY #

22 # #

23 # These alerts are displayed at the end of the script. #

24 ###############################################################

25 #

26 clear

27 echo “###############################################################”

28 echo “# Script to test Snort Installation #”

29 echo “# Written By #”

30 echo “# #”

31 echo “# Rafeeq Rehman #”

32 echo “# [email protected] #”

33 echo “# Argus Network Security Services Inc. #”

34 echo “# http://www.argusnetsec.com #”

35 echo “###############################################################”

36 echo

37

38 echo

39 echo “###############################################################”

40 echo “The script generates three alerts in the /var/log/snort/alert file”

41 echo “Each alert should start with a message like the following:”

42 echo

43 echo ” /”ATTACK RESPONSES id check returned root/” “

44 echo “###############################################################”

45 echo

46 echo “Enter the IP address of another host on this network. If you”

47 echo “don’t know any IP address, just hit the Enter key. By default”

48 echo -n “broadcast packets are used [255.255.255.255] : “

49

50 read ADDRESS

51

52 if [ -z $ADDRESS ]

53 then

54 ADDRESS=”255.255.255.255″

55 fi

56

57 echo

58 echo “Now generating alerts. If it takes more than 5 seconds, break”

59 echo “the script by pressing Ctrl-C. Probably you entered the wrong IP”

60 echo “address. Run the script again and don’t enter any IP address”

61

62 ping -i 0.3 -n -r -b $ADDRESS -p “7569643d
3028726f
6f
74290a
” -c3 2> /dev/

null > /dev/null

63

64 if [ $? -ne 0 ]

65 then

66 echo “Alert generation failed.”

67 echo “Aborting …”

68 exit 1

69 else

70 echo

71 echo “Alert generation complete”

72 echo

73 fi

74

75 sleep 2

76

77

78 echo

79 echo “################################################################”

80 echo “The last 18 lines of the /var/log/snort/alert file will be displayed now”

81 echo “If Snort is working properly, you will see the recently generated”
   This script will generate some alerts that you can see in the /var/log/snort/alert file if you run Snort in daemon mode, or on the terminal screen where you run Snort. The alerts are triggered by sending crafted ICMP echo packets with characteristics that match the following Snort rule and generate an alert.

alert ip any any -> any any (msg:”ATTACK RESPONSES id check returned root”; content:”uid=0(root)”; classtype:bad-unknown; sid:498; rev:3;)

Once the alert is generated, the script will display the last 18 lines of the /var/log/snort/alert file.

Let’s now look at various parts of the script and how it works. Lines 52 to 55 prompt the user to input the address to send the ping packets. If no address is provided, the script defaults to 255.255.255.255, sending the ping packets as a broadcast.

Line 62 crafts the ICMP packet that triggers the rule. Note here that “7569643d3028726f6f74290a” is equivalent to “uid=0(root),” and such characteristics can generate an alert.

The ‘-c3’ command line argument in the ping command means 3 packets will be sent. Both standard input and errors are redirected to /dev/null, so no output is seen on the screen. For more information on the ping command, you can check its man page using “man ping.”

Lines 64 to 73 of the script check the output of the ping command. The success or failure of the command’s execution is displayed. If the command fails, the script terminates here and does not proceed further.

If the alert is generated successfully, it will appear in the /var/log/snort/alert file. Lines 88 to 93 of the script check for the existence of this file. If not found, the script exits.

If everything is fine, line 95 displays the last 18 lines of the /var/log/snort/alert file.

Automatic Snort Launch and Alert Generation Script

If you install Snort in the /opt/snort directory, you can use the following script to automatically start and stop Snort and check its functionality. Ensure Snort is not running before executing this script since the script will start Snort itself. This script, named snort-test-auto.sh, can be found on the relevant website for this book at http://authors.phptr.com/rehman.

sh
#!/bin/sh
#
################################################################
# You are free to copy and distribute this script under
# GNU Public License until this part is not removed
# from the script.
################################################################
# HOW TO USE
#
# Right after installing Snort, run this script.
# It is assumed that the snort executable is in the
# /opt/argus/bin directory and that all rules and configuration
# files are under the /opt/argus/etc/snort directory.
# If files are in other locations, edit the following location
# of variables. If you used the installation script provided
# along with this script, the files will be automatically
# located in appropriate directories.
#
# Note that the script starts and stops Snort by itself, and
# you should ensure Snort is not running at the time
# you run this script.
#
# It will generate alerts in the /tmp/alert file similar
# to the following:
#
# [**] [1:498:3] ATTACK RESPONSES id check returned root [**]
# [Classification: Potentially Bad Traffic] [Priority: 2]
# 08/31-15:56:48.188882 255.255.255.255 -> 192.168.1.111
# ICMP TTL:150 TOS:0x0 ID:0 IpLen:20 DgmLen:84
# Type:0 Code:0 ID:45596 Seq:1024 ECHO REPLY
#
# These alerts are displayed at the end of the script.
################################################################
#

PREFIX=/opt/snort
SNORT=$PREFIX/bin/snort
SNORT_CONFIG=$PREFIX/etc/snort.conf
LOG_DIR=/tmp
ALERT_FILE=$LOG_DIR/alert
ALERT_FILE_OLD=$LOG_DIR/alert.old
ADDRESS=”255.255.255.255″

clear

echo “###############################################################”
echo “# Script to test Snort Installation #”
echo “# Written By #”
echo “# #”
echo “# Rafeeq Rehman #”
echo “# [email protected] #”
echo “# Argus Network Security Services Inc. #”
echo “# http://www.argusnetsec.com #”
echo “###############################################################”
echo

echo “###############################################################”
echo “The script generates three alerts in the /tmp/alert file”
echo “Each alert should start with a message like the following:”
echo
echo “/ATTACK RESPONSES id check returned root/”
echo “###############################################################”

if [ ! -d $LOG_DIR ]; then
echo “Creating log directory …”
mkdir $LOG_DIR
if [ $? -ne 0 ]; then
echo “Directory $LOGDIR creation failed”
echo “Aborting …”
exit 1
fi
fi

if [ -f $ALERT_FILE ]; then
mv -f $ALERT_FILE $ALERT_FILE_OLD
if [ $? -ne 0 ]; then
echo “Can’t rename old alerts file.”
echo “Aborting …”
exit 1
fi
fi
Perhaps you will notice, if the script succeeds, it will create an alert file in the /tmp directory. If you run the script correctly, you will see the following output messages:
###########################################################
# Script to test Snort Installation #
# Written By #
# #
# Rafeeq Rehman #
# [email protected] #
# Argus Network Security Services Inc. #
# http://www.argusnetsec.com #
###########################################################
###########################################################
The script generates three alerts in file /tmp/alert
Each alert should start with a message like the following:
“ATTACK RESPONSES id check returned root”
##########################################################
Starting Snort …
Now generating alerts.
Alert generation complete
Stopping Snort …
Done. Snort installation is working properly.

When you run this script, it will perform a series of tasks. First, in lines 36 to 42, it defines some variables. After defining the variables, the script will perform the following tasks:

Lines 66 to 67 are used to check if the $LOG_DIR directory exists. This directory is defined as /tmp in line 39. If this directory does not exist, the script will create it.

Lines 78 to 79 are used to check if the $ALERT_FILE exists, which is /tmp/alert. If it already exists, the script will rename it to /tmp/alert.old.

Lines 91 to 96 check if the Snort binary file exists, which in this case is /opt/snort/bin/snort. If the file does not exist, the script terminates.

Lines 98 to 103 check if the $SNORT_CONFIG file exists, which in this context is /opt/snort/etc/snort.conf. If it does not exist, the script terminates.

Lines 105 to 110 are used to ensure that the Snort binary file is executable.

Line 113 is used to start Snort.

Lines 115 to 120 check if Snort started correctly.

Line 125 is used to generate the aforementioned alerts, which will be sent to the broadcast address.

Lines 127 to 136 ensure that the alert generation process was successful.

Line 140 is used to check the last 18 lines of the alert file to ensure the alerts were generated and logged correctly.

Lines 142 to 147 handle the case where the test in line 140 fails by displaying an error message.

Line 150 is used to stop Snort.

Line 160 displays a message indicating the test process was successful.

### 2.2.5 Running Snort on Non-Default Ports
On a Linux system, Snort starts listening on the network interface eth0 by default. However, many users run Snort on machines with multiple interfaces. If you want Snort to listen on a different interface, you need to use the command-line option `-i`. The following command starts Snort to listen on the network interface eth1:

shell
snort -c /opt/snort/etc/snort.conf -i eth1

To automate starting and stopping Snort with the desired interface, you need to modify the script `/etc/init.d/snortd` so that Snort starts monitoring the port you want. Instructions for Snort’s automatic start and stop are explained in the next section.

### 2.2.6 Automatic Start and Stop of Snort
You can configure Snort to start and stop automatically with the system’s boot and shutdown processes. On UNIX-like machines, this can be done with scripts. On Linux, you can create such a script in the /etc/init.d/ directory. The startup script can be linked to the /etc/rc3.d directory, and the shutdown script can be linked to the /etc/rc2.d, /etc/rc1.d, and /etc/rc0.d directories. The script file `/etc/init.d/snortd` bundled with Snort’s RPM release looks roughly as follows:

shell
[root@conformix]# cat /etc/init.d/snortd
#!/bin/sh

# snortd Start/Stop the snort IDS daemon.

# chkconfig: 2345 40 60
# description: snort is a lightweight network intrusion
# detection tool that
# currently detects more than 1100 host and network
# vulnerabilities, portscans, backdoors, and more.

# June 10, 2000 — Dave Wreski <[email protected]>
# – initial version

# July 08, 2000 Dave Wreski <[email protected]>
# – added snort user/group
# – support for 1.6.2

# July 31, 2000 Wim Vandersmissen <[email protected]>
# – added chroot support

This example helps illustrate how to manage Snort’s automatic start and stop to ensure proper functionality within your infrastructure.# Source function library.

. /etc/rc.d/init.d/functions

# Specify your network interface here

INTERFACE=eth0

# See how we were called.

case “$1” in

start)

echo -n “Starting snort: “

cd /var/log/snort

daemon /usr/sbin/snort -A fast -b -l /var/log/snort /

-d -D -i $INTERFACE -c /etc/snort/snort.conf

touch /var/lock/subsys/snort

echo

;;

stop)

echo -n “Stopping snort: “

killproc snort

rm -f /var/lock/subsys/snort

echo

;;

restart)

$0 stop

$0 start

;;

status)

status snort

;;

*)

echo “Usage: $0 {start|stop|restart|status}”

exit 1

esac

exit 0

[root@conformix /root]#

Note that the same script is used to start and stop Snort. In a given run level, the first character of the link file name is used to determine whether the script is used to start or stop Snort. Start links begin with an S, such as the run level 3 start file /etc/rc3.d/S50snort, which actually links to the /etc/init.d/snortd file. Similarly, stop scripts start with a K, such as /etc/rc2.d/K50snort, which will stop Snort at run level 2.

Additionally, you can manually start and stop Snort with the following commands:

/etc/init.d/snortd start

/etc/init.d/snortd stop

Note that script links in the same run level directory may have different names. The link names depend on the position of Snort in the system startup and shutdown process. If you install Snort using RPM, these links will be created during the installation of the RPM package.

2.3 Running Snort on Multiple Network Interfaces

When Snort starts, it listens to network traffic on a specified interface. You can use the -I command-line option to specify the interface you want to monitor. If you want to monitor multiple network interfaces at the same time, you need to run multiple instances of Snort. For example, the following two commands are used to listen to the eth0 and eth1 interfaces on a Linux machine:

/opt/snort/bin/snort -c /opt/snort/etc/snort.conf -i eth0 -l /var/log/snort0

/opt/snort/bin/snort -c /opt/snort/etc/snort.conf -i eth1 -l /var/log/snort1

We see that these two commands use two different log directories: /var/log/snort0 and /var/log/snort1. Therefore, the two Snort processes will save their logs separately. These directories must exist before you start Snort.

If Snort, as configured in the snort.conf file, logs to a MySQL database, the logs will be recorded in the same database.

You should know that you can also use different configuration files for different Snort processes for various purposes. The primary reason is that the networks connected to your different network interfaces may differ. Another reason is to allow one Snort instance to log to a database while another logs to system logs. See Figure 2-2:

2.4 Snort Command Line Options

Snort has many command-line options, allowing you to tailor its behavior at startup based on your needs. As you saw earlier, you can run multiple Snort instances on a single system. You can display the command-line options with the “Snort -?” command. The most commonly used options are listed in Table 2-2.

Option

Description

-A

Sets alert mode. It defines the detail level of alert data. Available modes are fast, full, console, and none. The console mode outputs alerts to the screen without saving to a file. Fast mode is useful in high-speed network environments.

-b

This option logs data in tcpdump format, which is very fast for logging, and you can use tcpdump to view the data.

-c

This is the most commonly used option to specify the location of the snort.conf file. Using this option, Snort won’t look for snort.conf in the default location. For example, if snort.conf is in the /etc directory, start Snort with the command-line option “-c /etc/snort.conf”.

-D

Runs Snort in the background, commonly used in practical deployments. Avoid using this during initial testing.

-i

Specifies the network interface Snort listens to. It’s useful if you want to monitor a specific interface when you have multiple network interfaces. For instance, to monitor eth1, use the “-i eth1” option when starting Snort.

-l

Specifies the directory for logging. The default is /var/log/snort. For instance, to log all files to the /snort directory, use the command-line option “-l /snort”.

-M

This option requires a text file containing the list of Windows hosts to which you want to send messages, with one IP address per line. You can also achieve this via the snort.conf file, explained later.

-T

Useful for testing and reporting, this option helps identify configuration file errors.

In addition to the listed options, there are others less frequently used, which will be discussed in relevant sections later. Some command-line option functionalities can also be achieved via the snort.conf file.

2.5 Steps to Compile and Install Snort from Source Code

Installing Snort via RPM is very simple; you just run a command like “rpm -install “. However, as already noted, installing from source involves more steps. Below is a summary of the source code installation steps:

– Download the source code from http://www.snort.org.

– Extract the tar file with “tar zxvf “.

– Run the configure script, a typical command might be: “configure –prefix=/opt/snort –with-mysql –with-snmp –with-openssl”

– Run the make command.

– Run “make install”.

– Create the directory /var/log/snort.

– Create the directory /opt/snort/etc.

– Create the directory /opt/snort/rules.

– Copy snort.conf to the /opt/snort/etc directory.

– Copy the classification.config file to the /opt/snort/etc directory.

– Copy the reference.config file to the /opt/snort/etc directory.

– Copy all the rules files to the /opt/snort/rules directory.

– Create the snortd script and copy it to the /etc/init.d directory, and create links in /etc/rcx, where x is the run level number. This allows Snort to run at system startup.

– If you plan to use MySQL with Snort, start MySQL before starting Snort.

2.6 Snort File Locations

Snort files fall into the following categories:

– Snort binary files, i.e., executable files.

– The primary Snort configuration file, usually snort.conf.

– Other Snort configuration files like classification.config and reference.config.

– Rule files.

– Log files.

If you install Snort using an RPM package, its binaries will typically reside in the /usr/sbin directory. If compiled from source, the installation directory is specified with the –prefix option.

If you install Snort using an RPM package, the main configuration file snort.conf will be installed in the /etc/snort directory. Of course, you can place this file in any directory since you can specify its location using the command-line options when starting Snort. In this book’s examples, this file is placed in the /opt/snort/etc directory.

Other configuration files such as classification.config and reference.config are typically located in the same directory as snort.conf. You can change this directory in the snort.conf file.

Rule files are referenced in snort.conf. If you install Snort using an RPM package, the rules files are also installed in the /etc/snort directory. In this book’s examples, where installed from source, these files are placed in the /opt/snort/rules directory. You can modify these paths in the snort.conf file.

Snort log files’ locations can be specified in the snort.conf file or via command-line options. Typically, they are stored in the /var/log/snort directory. If this directory does not exist, you must create it manually. If Snort logs from different hosts, it can create directories for each host inside the /var/log/snort directory.

For example, you can change the default log file path to /snortlog in the snort.conf file as follows:

config logdir: /snortlog

You can also change the log file directory using the -l command line option when starting Snort. Chapter 3 includes a detailed discussion about the snort.conf file.

2.7 Snort’s Operating Modes

    Snort has two basic operating modes: packet sniffer mode and NIDS mode. Snort can be used as a sniffer akin to tcpdump and snoop. In sniffer mode, Snort can also log the packet information to log files. These files can subsequently be viewed with Snort or tcpdump. In this mode, Snort does not perform any intrusion detection activities. This mode has limited utility as many tools can already log packets, such as tcpdump, which is included with Linux distributions and is an efficient sniffer.

    If you use Snort in network intrusion detection (NIDS) mode, it will use rules to identify any intrusion activities.

    2.7.1 Network Sniffer Mode

    In network sniffer mode, Snort operates similarly to the commonly used tcpdump. It can capture packets on the network and display packet information on the terminal at varying levels of detail. Running Snort in this mode does not require a configuration file. The following command will display information about each packet traversing the network segment:

[root@conformix snort]# /opt/snort/bin/snort -v

Initializing Output Plugins!

Log directory = /var/log/snort

Initializing Network Interface eth0

–== Initializing Snort ==–

Decoding Ethernet on interface eth0

–== Initialization Complete ==–

-*> Snort! <*-

Version

1.9.0
(Build 209)

By Martin Roesch ([email protected], www.snort.org)

11/20-15:56:14.632067 192.168.1.100:2474 -> 192.168.1.2:22

TCP TTL:128 TOS:0x0 ID:4206 IpLen:20 DgmLen:40 DF

***A**** Seq: 0x9DAEEE

9C
Ack: 0xF

5683C

3A
Win: 0x43E0 TcpLen: 20

=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+

11/20-15:56:14.632188 192.168.1.2:22 -> 192.168.1.100:2474

TCP TTL:64 TOS:0x10 ID:57042 IpLen:20 DgmLen:200 DF

***AP*** Seq: 0xF

5683C

8A
Ack: 0x9DAEEE

9C
Win: 0x6330 TcpLen: 20

=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+

11/20-15:56:14.632519 192.168.1.2:22 -> 192.168.1.100:2474

TCP TTL:64 TOS:0x10 ID:57043 IpLen:20 DgmLen:120 DF

***AP*** Seq: 0xF5683D

2A
Ack: 0x9DAEEE

9C
Win: 0x6330 TcpLen: 20

=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+

11/20-15:56:14.633891 192.168.1.2:22 -> 192.168.1.100:2474

TCP TTL:64 TOS:0x10 ID:57044 IpLen:20 DgmLen:184 DF

***AP*** Seq: 0xF5683D

7A
Ack: 0x9DAEEE

9C
Win: 0x6330 TcpLen: 20

=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+

Snort will continuously display the information of captured packets on the screen until you terminate Snort with Ctrl-C, at which point it will display statistics.

   Now let’s analyze the information displayed by Snort in sniffer mode. Below is an example of typical output from a captured TCP packet:

11/20-15:56:14.633891 192.168.1.2:22 -> 192.168.1.100:2474

TCP TTL:64 TOS:0x10 ID:57044 IpLen:20 DgmLen:184 DF

***AP*** Seq: 0xF5683D

7A
Ack: 0x9DAEEE

9C
Win: 0x6330 TcpLen: 20

   By analyzing this output, you can obtain the following information about the packet:

n         The time and date when this packet was captured.

n         The source IP address is 192.168.1.2

n         The source port is 22.

n         The destination address is 192.168.1.100

n         The destination port is 2474

n         The transport layer protocol of this packet is TCP.

n         The TTL value in the IP header is 64.

n         The TOS value is 0x10.

n         The length of the IP header is 20.

n         The IP payload is 184 bytes.

n         The DF bit in the IP header is set (Do Not Fragment).

n         Two TCP flags are set to on.

n         The sequence number in the TCP header is 0xF5683D

7A
.

n         The acknowledgment number in the TCP header is 0xDAEEE

9C
.

n         The value of the TCP window field is 0x6330.

n         The length of the TCP header is 20.

You can use more command line options to display more information about the captured packets. The following command displays TCP, UDP, and ICMP information, as well as some application layer information. Note that this command does not display all packet information.

   [root@conformix snort]# /opt/snort/bin/snort -dv

Initializing Output Plugins!

Log directory = /var/log/snort

Initializing Network Interface eth0

–== Initializing Snort ==–

Decoding Ethernet on interface eth0

–== Initialization Complete ==–

-*> Snort! <*-

Version

1.9.0
(Build 209)

By Martin Roesch ([email protected], www.snort.org)

11/20-16:18:11.129548 192.168.1.100:2474 -> 192.168.1.2:22

TCP TTL:128 TOS:0x0 ID:4387 IpLen:20 DgmLen:40 DF

***A**** Seq: 0x9DAEF2FC Ack: 0xF5688CDA Win: 0x4190 TcpLen: 20

=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+

11/20-16:18:11.129723 192.168.1.2:22 -> 192.168.1.100:2474

TCP TTL:64 TOS:0x10 ID:57171 IpLen:20 DgmLen:120 DF

***AP*** Seq: 0xF5688D

2A
Ack: 0x9DAEF2FC Win: 0x6330 TcpLen: 20

C5 1D 81

8F
70 B7 12 0B C1 1B

8F
6D A9

8F
1D 05 ….p……m….

40 7D F9 BD 84 21 11 59 05 01 E

4 A
1 01

20 AC
92 @}…!.Y….. ..

58 50 73 8D 17 EA E2 17 AD

3A
AD 54 E2 50 80 CB XPs……:.T.P..

DA E1 40 30 7B 63 0D 79

5A
D8 51 07 93 95 2B A8 ..@0{c.yZ.Q…+.

F8 D

4 F
5 FA 76 D6 27 35 E8 6E E2 ED 41 2B 01 2D ….v.’5.n..A+.-

=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+

11/20-16:18:11.130802 192.168.1.2:22 -> 192.168.1.100:2474

TCP TTL:64 TOS:0x10 ID:57172 IpLen:20 DgmLen:120 DF

***AP*** Seq: 0xF5688D

7A
Ack: 0x9DAEF2FC Win: 0x6330 TcpLen: 20

E9

7C
09 E0 E0To display all information of packets, you can use the following command.

This command displays packet information simultaneously in ASCII and binary formats.

[root@conformix snort]# /opt/snort/bin/snort -dev

Initializing Output Plugins!
Log directory = /var/log/snort
Initializing Network Interface eth0
–== Initializing Snort ==–
Decoding Ethernet on interface eth0
–== Initialization Complete ==–

-*>< Snort! <*- Version 1.9.0 (Build 209) By Martin Roesch ([email protected], www.snort.org) 05/27-12:11:10.063820 0:D0:59:6C:9:8B -> FF:FF:FF:FF:FF:FF type:0x800

len:0xFC

192.168.1.100:138 -> 192.168.1.255:138 UDP TTL:128 TOS:0x0 ID:48572

IpLen:20 DgmLen:238

Len: 2182.7.1.1 Recording Snort Data in Text Format

You can save Snort data in text mode by using the -l option on the command line. The following command will log all Snort data to the /var/log/snort directory and display it on the terminal as well.

      snort –dev –l /var/log/snort

After executing this, you will find several subdirectories within the /var/log/snort directory, each corresponding to a host and containing various files. The subdirectory names generally mirror the IP addresses of the hosts. These files contain data from different connections and network data types. For example, a file named 2489-23 may contain TCP data, while a file named ICMP_ECHO indicates ICMP data. When you’re running the Snort sniffer, the contents logged are the same as what’s displayed on the monitor.

2.7.1.2 Recording Snort Data in Binary Format

In a high-speed network environment, logging numerous files in ASCII format can lead to excessive overhead. Snort allows recording data in tcpdump binary format for later analysis. In this mode, Snort logs all captured data as binary raw format. A typical command would be:

    snort –l /tmp –b

Snort will create files in the /tmp directory, usually named something like snort.log.1037840339. The final part of the filename depends on your system clock. Each time you run Snort in this mode, a new file is generated in the log directory. This mode is sometimes referred to as quick mode.

You can view the raw binary files generated by Snort using the -r switch to specify the filename. The following command will display all captured data in snort.log.1037840339:

snort -dev -r /tmp/snort.log.1037840339 | more

The output of this command is identical to what you see in real-time on the console. Various command-line switches can be used to display the data with different levels of detail.

You can also display specific types of data using commands. The following command will show all TCP data from the log file:

snort -dev -r /tmp/snort.log.1037840339 tcp

Displaying ICMP and UDP data follows a similar format.

You can also use tcpdump to read binary data generated by Snort. The command below will read and display the data captured by Snort:

[root@conformix snort]# tcpdump -r /tmp/snort.log.1037840514

You can control the display with different tcpdump command-line options. Use the “man tcpdump” command or refer to Appendix A for more information on tcpdump.

2.7.2 Network Intrusion Detection Mode

In intrusion detection mode, Snort doesn’t log all captured packets but compares them against defined rules. It logs or triggers alerts only when a packet matches one of these rules. If a packet doesn’t match any rule, it is quietly discarded without recording. When running Snort in intrusion detection mode, you typically specify a configuration file on the command line, which contains rules and references to other rule files. It also includes information about input and output plugins, discussed in Chapter 4. The configuration file is usually named snort.conf, which we moved along with other necessary files to /opt/snort/etc during the installation process. The following command will start Snort in Network Intrusion Detection (NID) mode:

snort -c /opt/snort/etc/snort.conf

After you run this command, Snort reads the /opt/snort/etc/snort.conf file and all referenced rule files. These files typically contain Snort rules and configuration data. Once these data are loaded, Snort constructs internal data structures and rule chains. All captured data are matched against these rules, and appropriate actions are taken based on rule requirements. If you modify the snort.conf file or any referenced file, you need to restart Snort for changes to take effect.

In IDS mode, there are additional options and switches available. For instance, you can choose to log data to a file or display it in real-time. When using Snort for long-term monitoring, the more data logged, the more disk space you’ll need. Displaying logs on the terminal also consumes processing power, so it’s crucial to consider where to run Snort. The following command will run Snort in IDS mode and log data to the /var/log/snort directory while acting as a sniffer:

snort -dev -l /var/log/snort -c /etc/snort/snort.conf

In many practical applications, you might run Snort with the -D switch to operate as a daemon, which doesn’t log to the terminal.

Typically, you will want to log Snort data to a database, which we will discuss in Chapter 5 with a focus on logging to a MySQL database.

2.8 Alerting Modes in Snort

When Snort operates in NID mode, it can generate alerts in various modes if a captured packet matches its rules. These modes can be configured through snort.conf or via the command line. In this section, I’ll explain common alerting modes using a rule that alerts when Snort detects an ICMP packet with a TTL value of 100:

       alert icmp any any -> any any (msg: “Ping with TTL=100”; ttl:100;)规则将在下一章详细讨论,对于本次讨论,你只需了解这个规则将在遇到TTL为100的ICMP包时产生一个包含“Ping with TTL=100”文字信息的告警即可。这个规则不关心包中的源地址或目的地址。我在我的Windows机器上使用以下命令发送一个TTL=100的ICMP echo包。

C:/rrehman> ping -n 1 -i 100 192.168.1.3

Pinging 192.168.1.3 with 32 bytes of data:

Reply from 192.168.1.3: bytes=32 time=3ms TTL=255

Ping statistics for 192.168.1.3:

Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),

Approximate round trip times in milli-seconds:

Minimum = 3ms, Maximum = 3ms, Average = 3ms

C:/rrehman>

命令行选项“-n 1”用来指定仅仅发送一个ICMP包。“-i 100”用来使ICMP包中的TTL值等于100。可以在ftp://ftp.isi.edu/in-notes/rfc792/rfc792.txt 或本书的附录C参考关于ICMP包头部格式的详细信息。

当运行上面的命令时,Snort将捕获这个数据包并产生一个告警。告警所纪录的信息的多少将依赖于特定的告警模式。下面我们来看在对一个包纪录时不同告警模式的差异:

2.8.1 Fast模式

Fast高静默模式将记录以下告警信息:

   时间戳

   告警消息(通过规则配置)

   源地址和目的地址

   源端口和目的端口

应当用命令行选项“-A fast”来配置fast告警模式,这种告警模式的系统开销较小。下面的命令用fast告警模式启动Snort:

   /opt/snort/bin/snort -c /opt/snort/etc/snort.conf -q -A fast

选项-q用来停止在屏幕显示初始化信息和最后的汇总统计。现在,如果产生一个告警,它将被记录到/var/log/snort/alert文件中,当然,你可以用命令行选项-l来改变它的位置。告警信息类似如下所示:

   05/28-22:16:25.126150 [**] [1:0:0] Ping with TTL=100 [**]

{ICMP} 192.168.1.100 -> 192.168.1.3

这个告警包含以下信息:

   告警产生的日期和时间。

   表示在规则中的告警消息,在这个例子中,这个消息就是:“Ping with TTL=100”。

   源地址是192.168.1.100。

   目的地址是192.168.1.3

   包的类型,在上面的例子中,包的类型是ICMP。

2.8.2 Full模式

这是默认的告警模式,除了输出告警信息之外,还有包的头部信息。我们可以用下面的命令使Snort具有full告警模式。

      /opt/snort/bin/snort -c /opt/snort/etc/snort.conf -q -A full

当Snort在这种告警模式下工作时,/var/log/snort/alert中记录的信息类似于如下:

[**] [1:0:0] Ping with TTL=100 [**]

05/28-22:14:37.766150 192.168.1.100 -> 192.168.1.3

ICMP TTL:100 TOS:0x0 ID:40172 IpLen:20 DgmLen:60

Type:8 Code:0 ID:768 Seq:20224 ECHO

正如你看到的,日志中记录了额外的信息,这些信息显示包头中的不同值,包括:

   IP包头部的TTL值。参见RFC791获取关于TTL的详细信息。

   IP包头部的TOS值,参考RFC791或本书附录A获取TOS的详细信息。

   IP头长度,显示为:IpLen:20。

   IP包总长,显示为:DgmLen:60。

   ICMP类型段,参考RFC792获取ICMP类型段的详细信息。

   ICMP代码段,参考RFC792获取ICMP代码段的详细信息。

   IP包的ID。

   序列号。

   ICMP包的类型:ECHO。

2.8.3 UNIX套接字模式

你可以用命令行选项“-A unsock”使Snort通过UNIX套接字将告警发送到其他程序。如果你想进一步处理Snort告警,这将非常有用。你可以用“man socket”命令来查看套接字的更多信息。

2.8.4 无告警模式

你可以用命令行选项“-A none”将Snort告警完全关闭。这在高速网络环境中应用统一日志时非常有用。你可以在使用统一日志时关闭普通日志选项。统一日志输出插件将在第4章中讨论。

2.8.5 将告警发送到Syslog

下面的命令允许Snort将告警发送到Syslog守护进程。Syslog是产生系统事件日志的守护进程,它将读取配置文件/etc/syslog.conf来确定日志文件的位置,这个位置通常是/var/log目录,在Linux系统中,主日志文件是/var/log/messages。用“man syslog”命令来获得更多信息,这个命令会显示syslog.conf文件的格式信息。

根据/etc/syslog.conf文件中的配置,告警将被记录到一个特定文件中。下面的命令可以使Snort将日志记录到Syslog守护进程:

/opt/snort/bin/snort -c /opt/snort/etc/snort.conf -s

在我的RedHat 7.1计算机上,使用的是默认配置,信息会被记录到/var/log/messages文件中。当你用TTL=100的ICMP产生告警时,/var/log/messages文件中将记录以下信息:

May 28 22:21:02 snort snort[1750]: [1:0:0] Ping with TTL=100

{ICMP} 192.168.1.100 -> 192.168.1.3

本书的第4章将讨论使用Syslog工具,同时,你将了解如何用输出插件记录日志到Syslog。

2.8.6 向SNMP发送告警

Snort的一个非常有用的特性是SNMP trap。你可以配置一个输出插件,将信息以SNMP trap的形式发送到网络管理系统。通过这个特性,你可以将你的入侵检测探测器整合到类似HP OpenView、OpenNMS、MRTG等集中的网管系统中。Snort配置SNMP trap的配置过程将在后面详细讨论。

2.8.7 向Windows发送告警

Snort可以以弹出窗口的形式向Windows发送告警,在Windows中,弹出窗口由Windows信使服务控制。为使弹出窗口工作,Windows必须要运行信使服务。你可以到 控制面板 服务 程序查看Window信使服务是否在运行。 服务 选项在你的管理工具菜单中,根据你的Windows版本不同,也可能在控制面板或其他位置。

在你的Unix机器上,必须要安装SAMBA客户端软件包。SAMBA是在UNIX下可以与Windows共享文件和打印机的开放源码软件包。它也可以与其它运行CIFS和SMB协议的操作系统共同工作。你可以在http://www.samba.org 取得关于SAMBA的更多信息。

Snort告警机制利用UNIX的smb客户端程序来连接Windows信使并发送告警。在使用这项服务之前,先确定SAMBA客户端是否正常工作。在RedHat系统中,SAMBA的操作依赖于配置文件/etc/samba/smb.conf,在其他Unix系统中,这个文件也许会在不同的位置。尽管SAMBA的详细讨论已超出本书范围,仍在下面列举一个SAMBA配置的样本文件。这个文件可以用来配置smb使之生效,它创建一个可以在Windows机器上看到的REHMAN工作组。

2.8.7.1 Samba配置文件样本

/etc/smba/smb.conf的样本文件如下:

[global]

workgroup = REHMAN

server string = REHMAN file server

log file = /var/log/samba/log.%m

max log size = 50

security = user

encrypt passwords = yes

socket options = TCP_NODELAY SO_RCVBUF=8192 SO_SNDBUF=8192

dns proxy = no

domain logons = no

unix password sync = no

map to guest = never

password level = 0

null passwords = no

os level = 0

preferred master = yes

domain master = yes

wins support = yes

dead time = 0

debug level = 0

load printers = yes

[homes]

comment = Home Directories

browseable = yes

writable = yes

available = yes

public = yes

only user = no

[htmldir]

comment = html stuff

path = /home/httpd/html

public = yes

writable = yes

printable = no

write list = rehman

[virtualhosting]

comment = html stuff

path = /usr/virt_web

public = yes

writable = yes

printable = no

write list = rehman

[printers]

[netlogon]

available = no

    More information about SMB alerts will be provided in later sections. Note that if you want to use this feature, you should compile Snort with the –with-sabalerts option, otherwise, Snort cannot function using SAMBA services.

2.9 Running Snort in stealth mode

    In certain situations, you may want to run Snort in stealth mode so that other hosts cannot detect the presence of the Snort machine. In other words, Snort is invisible to intruders or others. There are multiple methods to run Snort in stealth mode. One way is to operate Snort on an interface without a configured IP address. This is suitable for the following two situations:

1. An independent Snort detector with only one network adapter.

2. A Snort detector with two network adapters: one for accessing the detector on an isolated network, and the other connected to the public network running Snort in stealth mode. This method is illustrated in Figure 2-3: network interface eth1 connects to the isolated private network, while eth0 connects to the public network.

When you want to access the detector, you should go through the network interface eth1, which has an IP address. The management workstation shown in the figure can be used to connect to the detector to collect data or log information into a central database running on the local machine or other connected database servers.

    The network interface eth0 connected to the Internet does not have an IP address configured and operates in stealth mode, but it can still listen to the data traffic on this network segment.

    Before running Snort on eth0, you must activate it in the Linux system using the following command:

           ifconfig eth0 up

    This command makes the interface available without an IP address. Then, you can start Snort on this interface using the “-i eth

0
” command line option:

           snort -c /opt/snort/etc/snort.conf -i eth0 -D