Monday, November 24, 2014

Ho to Install HA-Proxy + Stunnel on Linux Machine

Install HA-Proxy + Stunnel on Linux Machine

Prerequisites:

yum install perl-5*
yum install make wget gcc-* pcre-static pcre-deve

openssl
wget http://www.openssl.org/source/openssl-1.0.1g.tar.gz
tar zxvf openssl-1.0.1g.tar.gz
cd openssl-1.0.1g
make clean
./config shared --prefix=/usr --openssldir=/usr/local/openssl
make && make test
make install

Download HA-Proxy source package:
wget www.haproxy.org/download/1.5/src/haproxy-1.5.8.tar.gz

tar -zxvf haproxy-1.5.8.tar.gz
cd haproxy-1.5.8
make TARGET=linux26 USE_STATIC_PCRE=1 USE_LINUX_TPROXY=1
cp haproxy /usr/sbin/haproxy
cp examples/haproxy.cfg /etc/haproxy.cfg

vi /etc/haproxy.cfg
--------------------------------------------------------------------
global
        daemon
        maxconn 500000
        stats socket    /tmp/haproxy
        log 127.0.0.1 local0 debug

    defaults
        log     global
        mode http
        timeout connect 3600s
        timeout client 3600s
        timeout server 3600s
        #option keepalive
        option http-server-close
        option forwardfor
        maxconn 500000
        option  httplog
        #balance roundrobin
        #balance source
        retries 3
        option redispatch
        #stats enable
        #stats auth statsadmin:fAzaceg7Dr
####

 listen httpfarm
        bind 192.168.30.7:80
        mode http
        option httpchk HEAD  /this.txt HTTP/1.1\r\nHost:\ apply.pebc.ca
        cookie SERVERID insert nocache indirect maxidle 4h maxlife 4h
        balance roundrobin
        server web1 192.168.30.4 cookie A check inter 20000 maxconn 500000
        server web2 192.168.30.6 cookie B check inter 20000  maxconn 500000
        option abortonclose
        option httpclose
        timeout check 10
#
   listen httpsfarm
        bind 192.168.30.7:81 accept-proxy
        mode http
        option httpchk  HEAD /this.txt HTTP/1.1\r\nHost:\ www.pebc.com
        cookie SERVERID insert nocache indirect maxidle 4h maxlife 4h
        balance roundrobin
        server web1 192.168.30.4:80 cookie A check inter 20000 maxconn 500000
        server web2 192.168.30.6:80 cookie B check inter 20000  maxconn 500000
        #option forwardfor except 10.212.238.80
        option abortonclose
        option httpclose
        option forwardfor
        reqadd X-Forwarded-Proto:\ https
        #acl hostname hdr_beg(host) -i pebc.
        #acl is_ssl src 10.212.238.80
#       #redirect prefix http://apply.pebc.com if hostname
##      #use_backend purehttp if hostname
##
    listen stats 1192.168.30.7:8765
        mode http
        stats uri /
        stats enable
        stats auth statsadmin:fAzaceg7Dr
        maxconn 500000
--------------------------------------------------------

/usr/sbin/haproxy -f /etc/haproxy.cfg
ps -aux | grep haproxy

http://192.168.30.7:8765/

wget https://www.stunnel.org/downloads/stunnel-5.07.tar.gz
tar -zxvf stunnel-5.07.tar.gz
cd stunnel-5.07
./configure
make
make install

mkdir /etc/stunnel
cp /usr/local/etc/stunnel/stunnel.conf-sample /etc/stunnel/stunnel.conf

vi /etc/stunnel/stunnel.conf
----------------------------------------------------------------
#
chroot = /usr/local/var/lib/stunnel/
protocol = proxy

;CApath==/cert
;cert=/usr/local/var/lib/stunnel/cert/all.pem
;key=/var2/SSL/apply.pebc.ca.key
setuid=nobody
setgid=nobody

; PID is created inside the chroot jail
pid = /stunnel.pid

; Debugging stuff (may useful for troubleshooting)
debug = 7
output = /stunnel.log

options = NO_SSLv2

socket=l:TCP_NODELAY=1
socket=r:TCP_NODELAY=1

[https]
cert=/var/SSL/apply.pebc.ca.crt
key=/var/SSL/apply.pebc.ca.key
;
;key=/var/SSL/www.pebc.ca.key
;CApath=/usr/local/var/lib/stunnel/cert
;CApath=/var/SSL/GEO
;cafile=/var/SSL/www.pebc-intermediate.crt
;cert=/var/SSL/geochainfile.crt
;cafile=/var/SSL/geochainfile.crt
accept  = 192.168.30.7:443
connect = 192.168.30.7:81
;xforwardedfor = yes
TIMEOUTclose = 0
;
-----------------------------------------------------------------


useradd stunnel

vi /etc/init.d/stunnel
-------------------------------------------------------------------
#! /bin/sh -e
### BEGIN INIT INFO
# Provides:          stunnel
# Required-Start:    $local_fs $remote_fs
# Required-Stop:     $local_fs $remote_fs
# Should-Start:      $syslog
# Should-Stop:       $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start or stop stunnel 4.x (SSL tunnel for network daemons)
### END INIT INFO

DEFAULTPIDFILE="/var/run/stunnel.pid"
DAEMON=/usr/local/bin/stunnel
NAME=stunnel
DESC="SSL tunnels"
FILES="/etc/stunnel/*.conf"
OPTIONS=""
ENABLED=1

get_pids() {
   local file=$1
   if test -f $file; then
     CHROOT=`grep "^chroot" $file|sed "s;.*= *;;"`
     PIDFILE=`grep "^pid" $file|sed "s;.*= *;;"`
     if [ "$PIDFILE" = "" ]; then
       PIDFILE=$DEFAULTPIDFILE
     fi
     if test -f $CHROOT/$PIDFILE; then
       cat $CHROOT/$PIDFILE
     fi
   fi
}

startdaemons() {
  if ! [ -d /var/run/stunnel ]; then
    rm -rf /var/run/stunnel
    install -d -o stunnel -g stunnel /var/run/stunnel
  fi
  for file in $FILES; do
    if test -f $file; then
      ARGS="$file $OPTIONS"
PROCLIST=`get_pids $file`
      if [ "$PROCLIST" ] && kill -s 0 $PROCLIST 2>/dev/null; then
        echo -n "[Already running: $file] "
      elif $DAEMON $ARGS; then
        echo -n "[Started: $file] "
      else
        echo "[Failed: $file]"
        echo "You should check that you have specified the pid= in you configuration file"
        exit 1
      fi
    fi
  done;
}

killdaemons()
{
  SIGNAL=${1:-TERM}
  for file in $FILES; do
    PROCLIST=`get_pids $file`
    if [ "$PROCLIST" ] && kill -s 0 $PROCLIST 2>/dev/null; then
       kill -s $SIGNAL $PROCLIST
       echo -n "[stopped: $file] "
    fi
  done
}

if [ "x$OPTIONS" != "x" ]; then
  OPTIONS="-- $OPTIONS"
fi

test -f /etc/default/stunnel && . /etc/default/stunnel
if [ "$ENABLED" = "0" ] ; then
  echo "$DESC disabled, see /etc/default/stunnel"
  exit 0
fi

test -x $DAEMON || exit 0

set -e

case "$1" in
  start)
        echo -n "Starting $DESC: "
        startdaemons
        echo "$NAME."
        ;;
  stop)
        echo -n "Stopping $DESC: "
        killdaemons
        echo "$NAME."
        ;;
  reopen-logs)
        echo -n "Reopening log files $DESC: "
        killdaemons USR1
        echo "$NAME."
        ;;
  force-reload|reload)
        echo -n "Reloading configuration $DESC: "
        killdaemons HUP
        echo "$NAME."
        ;;
  restart)
        echo -n "Restarting $DESC: "
        killdaemons
        sleep 5
        startdaemons
        echo "$NAME."
        ;;
  *)
        N=/etc/init.d/$NAME
        echo "Usage: $N {start|stop|reload|reopen-logs|restart}" >&2
        exit 1
        ;;
esac

exit 0
-------------------------------------------------------------

chmod +x /etc/init.d/stunnel

service stunnel start

To start HA-Proxy:
/usr/sbin/haproxy -f /etc/haproxy.cfg -p /var/run/haproxy.pid

ps -aux | grep haproxy

service stunnel restart

to create haproxy logs:
vi /etc/rsyslog.conf
#proxy logging
local0.*                                                /var/log/haproxy.log

service rsyslog restart

check haproxy stats on http://localhost:8765





Wednesday, October 15, 2014

How to install OSSEC and configuring (host based intrusion detection)

OSSEC is a full platform to monitor and control your systems. It mixes together all the aspects of HIDS (host-based intrusion detection), log monitoring and SIM/SIEM together in a simple, powerful and open source solution.

File Integrity checking
There is one thing in common to any attack to your networks and computers: they change your systems in some way. The goal of file integrity checking (or FIM – file integrity monitoring) is to detect these changes and alert you when they happen. It can be an attack, or a misuse by an employee or even a typo by an admin, any file, directory or registry change will be alerted to you.

Log Monitoring
Your operating system wants to speak to you, but do you know how to listen? Every operating system, application, and device on your network generate logs (events) to let you know what is happening. OSSEC collects, analyzes and correlates these logs to let you know if something wrong is going on (attack, misuse, errors, etc). Do you want to know when an application is installed on your client box? Or when someone changes a rule in your firewall? By monitoring your logs, OSSEC will let you know of that.

Rootkit detection
Criminals (also known as hackers) want to hide their actions, but using rootkit detection you can be notified when they (or trojans, viruses, etc) change your system in this way.

Active response
Take immediate and automatic responses when something happens. Why wait for hours when you can alert your admin and block an attack right way?

Working:
OSSEC is composed of multiple pieces. It has a central manager monitoring everything and receiving information from agents, syslog, databases and from agentless devices.

Manager
The manager is the central piece of the OSSEC deployment. It stores the file integrity checking databases, the logs, events and system auditing entries. All the rules, decoders and major configuration options are stored centrally in the manager, making easy to administer even a large number of agents.

Agents
The agent is a small program installed on the systems you desire to monitor. It will collect information on real time and forward to the manager for analysis and correlation. It has a very small memory and CPU footprint by default, not affecting with the system’s usage.
Agent security: It runs with a low privilege user (created during the installation) and inside a chroot jail isolated from the system. Most of the agent configuration is pushed from the manager, with just some of them are stored locally on each agent. In case these local options are changed, the manager will receive the information and will generate an alert.

Agentless
For systems that you can’t install an agent, OSSEC allows you to perform file integrity monitoring on them without the agent installed. It can be very useful to monitor firewalls, routers and even Unix systems where you are not allowed to install the agent.

Untitled



INSTALLATION:
Download ossec-hids-2.x.tar.gz from https://github.com/ossec/ossec-hids/archive/2.8.2.tar.gz
#tar xzvf ossec-hids-2.x.tar.gz
#cd ossec-hids-2.x.tar.gz
#./install.sh



1

For English type : en
What kind of installation do you want (server,agent,local.hybrid): server
Choose wghere to install the OSSEC-HIDS [/var/ossec]: /var/ossec
Do you want email notification: y
what’s your email address: sam@sam.com
what’s your SMTP server ip/add: mail.sam.com
Do you want to run the integrity check daemon: y
Do you want to run the rootkit detection engine: y
Do you want to enable active response: y
Do you want to enable remote syslog (port 514 udp): y
2


#/var/ossec/bin/ossec-control start
#cd /var/www/html
#wget http://www.ossec.net/files/ui/ossec-wui-0.3.tar.gz
#tar zxvf ossec-wui-*.tar.gz
#rm -f ossec-wui-*.tar.gz
#mv ossec-wui-* ossec-wui
#mkdir /var/www/html/ossec-wui/tmp
#chown -R apache:apache /var/www/html/ossec-wui
#add apache user to ossec group
#usermod -G ossec apache
#/var/ossec/bin/ossec-control start

5

Configure apache to run at startup and start it
#chkconfig httpd on
#service httpd start
That’s it. Ossec server installation completed.now I can can browse to http://localhost/ossec-wui. The default user and password are: ossec/ossec.


7

Installing ossec agent (client in linux system)
Download ossec-hids-2.7.tar.gz from http://www.ossec.net/main/downloads
#tar xzvf ossec-hids-2.7.tar.gz
#cd ossec-hids-2.7.tar.gz
#./install.sh

For English type : en
What kind of installation do you want (server,agent,local.hybrid): agent
Choose where to install the OSSEC-agent [/var/ossec]: /var/ossec
What’s the ip address of OSSEC-HIDS server: 192.168.31.1
Do you want to run the integrity check daemon: y
Do you want to run the rootkit detection engine: y
Do you want to enable active response: y
Do you want to enable remote syslog (port 514 udp): y

8

On the OSSEC server run manage_agents tool to add a new client
#/var/ossec/bin/manage_agents
Choose A to add an agent: A
provide a name for your new agent: arthar2
provide the IP of your new agent: 192.168.31.150
Provide an OSSEC ID for your new agent: 001
Confirm adding it?: y
Choose E to extract key for an agent: E
Provide the ID of the new agent: 001
Copy the agent key information
press ENTER to return to the main manu
Choose Q to quit

10
11

On the OSSEC client run manage_agent tool to configure the new client
 
#/var/ossec/bin/manage_client
Choose I to Import key from the server: I
Paster the the already copied agent ket: paste
confirm adding it: y
Press Enter to return to the main manu
Choose Q to Quit

12

Start OSSEC
#/var/ossec/bin/ossec-control start
That’s it. OSSEC client installation completed. Now i can browse to http://localhost/ossec and see messages from my new OSSEC client.

14


Installing ossec agent (client in windows system)
Download OSSEC windows agent from http://www.ossec.net/main/downloads

Run the downloaded exe file
A. Welcome to OSSEC HIDS Windows Agent v2.6 Setup Wizard – Click Next
B. License Agreement – Read the license agreement and if you agree click on I agree
C. Choose Components – If you are not running IIS, click to remove the mark on “Scan and monitor IIS 

logs” and click Next
D. Choose Install Location – Click Install
E. Completing the OSSEC HIDS Windows Agent v2.6 Setup Wizard – check that “Run OSSEC Agent 

Manager” is marked and click Finish
On the OSSEC server run manage_agents tool to add a new client
#/var/ossec/bin/manage_agents
Choose A to add an agent: A
provide a name for your new agent: arthar
provide the IP of your new agent: 192.168.31.2
Provide an OSSEC ID for your new agent: 002
Confirm adding it?: y
Choose E to extract key for an agent: E
Provide the ID of the new agent: 002
Copy the agent key information
press ENTER to return to the main manu
Choose Q -> Enter to quit

z zz

On the OSSEC windows client run manage_agent tool if it’s not already running and configure your new client installation
A. Start -> All Programs -> OSSEC -> Manage Agents
B. OSSEC Agent Manager – Fill my 192.168.31.1, and the “Authentication Key” that was copied from the server. Click save
C. Confirm Importing Key – Click OK
D. OSSEC Agent Manager – Click on Manage -> Start OSSEC
E. Close OSSEC Agent Manager
That’s it. OSSEC client installation completed. Now i can browse to http://localhost/ossec and see messages from my new OSSEC client.


zzz 


  zzzz

Wednesday, October 1, 2014

How to writing snort rules - Part III

Continuing with the posts about Snort Snort installation (part II), now we have a complete installation and web interface to monitor our network alerts. One of the most important things when you maintain an IDS like Snort in a network, is the include of new rules to alert of possible attacks, behaviors of Malware or simply the needed of control a part of our traffic for some reasons. The rules of Snort are very flexible and has a lot of possibilities of configuration, logically in this post I’ll do a short introduction to write basic rules explaining the components of a rule and some options that can be useful.

Anatomy of a rule
A Snort rule, basically is composed by the header (information about the traffic) and the options (contains some action to do on the packet).
  • Headers is composed by:
Action Protocol Source IP Source Port Direction Operator Destination IP Destination Port (Options)
Action: Refers what snort will do when a packet match with the rule. Possible actions:
– alert: Generates an alert and register the packet.
– log: register the packet.
– pass: ignore the packet.
– activate: make an alert and next run other dynamic rule.
– dynamic: Remain inactive until an activate rule active them. Then will run as log action.
Protocol: We can use TCP, UDP, ICMP and IP protocols.
We can use the next syntax to refer an IP address or Port number:
– “!” : exclude the IP address or Port number for the rule.
– “172.16.0.0/16″: refers all the device from this network.
– “any”: refers any IP address or Port number.
– “:” : Refers a range of ports number.
– variables: We can use the variables declared in snort.conf like HOME_NET and EXTERNAL_NET.
Direction Operator: indicates the orientation of the packet for the apply of the rule. The possible operators:
– “->”: Indicates the source IP and port before the operator and after the destination.
– “<>”: Used to refer bidirectional traffic, Snort consider the pair IP and port numbers as source or destination.

Some examples of header rules
alert tcp any any -> 172.16.0.0/16 1:1023 : This rule will match with the attempts for tcp connection from any source to all the hosts in the network 172.16.0.0 to a port range from 1 to 1023.
log udp 10.0.0.0/8 :1024 -> 192.168.1.0/24 100: : Log all the UDP traffic from the network 10.0.0.0 with source port less than 1024 and destination for the network 192.168.1.0 with destination port greater than 100.
log tcp 192.168.1.0/24 any <> 192.168.1.1 22 : Log all the SSH requests from the network 192.168.1.0 to the host 192.168.1.1 and the SSH request from this host.
  • Options: Contains the messages and information necessary for the decision of the alert. The different options are separated with the caracter “;”. Exists 4 main categories of options:
Meta-data: Provides some information about the rule. Posible metadata options can be:
– msg: Indicates a string message to print when the rule is matched.
– sid: identification for a single snort rule.
– rev: Used with the option id for reference a revision number for a rule.
– classtype: Defines the classification of a rule and is defined in the file configuration classification.config and is classified by a priority.
Payload: Refers to the “useful” data from the interior of a packet, usually is known the body of the data excluding the data overhead like the packet headers. Some possible options:
– content: This option allows a rule to search specific content in useful data of a packet. The pattern to search can be in text format or in binary mode written between the character pipe “|”, representing binary numbers like hexadecimal format.
– rawbytes: Allows a rule search in the packet data without any decodification from the preprocessor.
– depth: indicates the number of bytes that Snort will search on the payload.
Non-payload: Looks data in other parts of the packet different of the body data. Some options:
– dsize: Indicates the payload size in bytes.
– id: Is used to revise the ID field on the packet header. Some exploits or scanners specify this field.
– flags: Used to check if specific TCP flag bit is enabled, some useful flags are S (SYN), A (ACK), F (Finish).
Post-detection: This option is a trigger for a rule when this is activate.
Some Examples of Snort Rules
  • Detecting when root user is trying to send an email:

alert tcp any any ->; 192.168.1.0/24 25 (sid:1002345;rev:2;msg: "root users attempts to send an email"; content: "mail from: root";classtype:suspicious-login;)

  • Identifying the source of icmp traffic of a windows host:
– First of all I had to capture a icmp packet with tcpdump to see what’s the signature for a ping packet of a Windows host, and this is the capture that I received of data in Hexadecimal format:





alert icmp any any ->; 192.168.1.0/24 any (sid:1002356;msg:"Hey!! A windows Host is pinging me!";itype:8;content:"|6566 6768 696a 6b6c 6d6e 6f70 7172 7374 7576 7761 6263 6465 6667 6869|";nocase;depth:32;classtype:icmp-event;)

  • Registering all access to the url /admin on the web server 192.168.1.250:

alert tcp any any ->; 192.168.1.250 80 (sid:1002354;rev:2;msg:"Warning!!, A host is trying to access /admin"; uricontent:"/admin";classtype:web-application-activity;)

  • Alert all SMTP traffic that contains a file virus.exe attached:

alert tcp any any ->; 192.168.1.0/24 25 (sid:1002311; rev:3; msg:"Warning!! The virus.exe is included in one mail!!"; content:"filename="virus.exe"";classtype:suspicious-filename-detect;)
 


 

To add our rules in needed to include the new file in snort.conf file and restart snortd:


# vi /etc/snort/snort.conf
include $RULE_PATH/test.rule

# /etc/init.d/snortd restart

How to install Snort with BASE & barnyard2 - Part II

Continuing with the last post Snort installation part I now I’ll explain how to install BASE and barnyard2. BASE (Basic Analysis and Security Engine) provides a web front-end to query and analyze the alerts coming from Snort. The alerts will send to a MySQL database, this feature is provided by barnyard2. Barnyard2 is an output system for Snort, it reads the binary logs from snort using the unified2 format and then it will resend the information of this logs to a database backend, for this We’ll configure Snort to output alerts to this format.

Install BASE dependencies





# yum install -y mysql-server mysql-devel php-mysql php-adodb php-pear php-gd httpd
# pear channel-update pear.php.net
# pear install Numbers_Roman

Preparing MySQL environment
– Initializing mysql and configuring to start the daemon at boot time:


# service mysql start
# chkconfig --levels 235 mysql on
– Preparing the new database for snort:

# mysql -u root -p



<pre>mysql> create database snort;
mysql> grant select,insert,update,delete,create on snort.* to snort@localhost;
mysql> set password for snort@localhost=PASSWORD('snortpassword');

Setup snort to log out in unified2 format

# vi /etc/snort/snort.conf

output unified2: filename snort.u2, limit 128
Installing barnyard2










# tar -xzvf barnyard2-1.9.tar.gz
# cd barnyard2-1.9
# ./configure --with-mysql
# make && make install
# cp etc/barnyard2.conf /etc/snort/
# mysql -u snort -psnortpassword snort < schemas/create_mysql
# touch /etc/snort/barnyard2.waldo
# chmod 777 /etc/snort/barnyard2.waldo
# chown snort:snort /etc/snort/barnyard2.waldo
– Edit barnyard2 configuration:

# vi /etc/snort/barnyard2.conf







config reference_file: /etc/snort/reference.config
config classification_file: /etc/snort/classification.config
config gen_file: /etc/snort/rules/gen-msg.map
config sid_file: /etc/snort/rules/sid-msg.map
input unified2
config hostname: localhost
config interface: eth0
config alert_with_interface_name
output database: log, mysql, user=snort password=snortpassword dbname=snort host=localhost
Adapting our init script to work with barnyard2

# vi /etc/init.d/snortd

BARNYARD2=/usr/local/bin/barnyard2
start()
{
[ -x $SNORTD ] || exit 5
echo -n $"Starting $prog: "
daemon --pidfile=$PID_FILE $SNORTD $LINK_LAYER $NO_PACKET_LOG $DUMP_APP -D $PRINT_INTERFACE $INTERFACE -u $USER -g $GROUP $CONF -l $LOGDIR $PASS_FIRST $BPFFILE $BPF && success || failure
RETVAL=$?
$BARNYARD2 -c /etc/snort/barnyard2.conf -d /var/log/snort -f snort.u2 -w /etc/snort/barnyard2.waldo -u snort -g snort -D
[ $RETVAL -eq 0 ] && touch $lockfile
echo
return $RETVAL
}
stop()
{
echo -n $"Stopping $prog: "
killproc $SNORTD
killproc $BARNYARD2
if [ -e $PID_FILE ]; then
chown -R $USER:$GROUP /var/run/snort_eth0.* && rm -f /var/run/snort_eth0.pi*
fi
RETVAL=$?
if [ "x$runlevel" = x0 -o "x$runlevel" = x6 ] ; then
trap TERM
killall $prog 2>/dev/null
trap TERM
fi
[ $RETVAL -eq 0 ] && rm -f $lockfile
echo
return $RETVAL
}
– Restart Snortd:

# /etc/init.d/snortd restart

Installing BASE

# tar -xzvf base-1.4.5.tar.gz
# cp -r base-1.4.5/ /var/www/base
# cd /var/www/base/
# cp base_conf.php.dist base_conf.php
– Edit BASE scripts configuration:

# vi base_conf.php

$BASE_urlpath = '/base';
$DBlib_path = '/usr/share/php/adodb';
$alert_dbname = 'snort';
$alert_host = 'localhost';
$alert_port = '3306';
$alert_user = 'snort';
$alert_password = 'snortpassword';

Configuring Apache

# vi /etc/httpd/conf.d/base.conf

Alias /base /var/www/base/
<directory "/var/www/base/">
AllowOverride None
Order allow,deny
Allow from all
AuthName "Snort IDS"
AuthType Basic
AuthUserFile /etc/snort/base.passwd
Require valid-user
</directory>
– Generating password file for web access for BASE:

# htpasswd -c /etc/snort/base.passwd snortadmin
– Restart apache:

# service httpd restart

Accessing to the BASE web environment
http://IP-WEB-SERVER/base/base_db_setup.php
and click create BASE AV


How to install Snort - Part I


An IDS is a security tool, that allow us to monitor our network events searching attempts to compromise the security of our systems. It’s possible matching predefinied rules emulating the behaviour of an attack and it’s possible to deny the package or simply alert us to an email or sending messages to log. Basically we can find two types of IDS:
  • HIDS: Host based IDS, monitors the activity of a single machine, searching anomaling behaviors.
  • NID: Network IDS, capture and analyze network packages to search attack patterns.
Generally an IDS can be located in each network segment, for example front of the firewall or back of the firewall or also can be implemented in the same firewall if we have a small network traffic, with this way we can analyze all input and output traffic.

SNORT
Snort is a NIDS, implements real time scanning of attack detection and port scanning detecting. The basic architecture of snort:
  • Packet capture module: Used to capture network traffic using libpcap library.
  • Decoder: It ensures to form the data structures of the packages captured and identify the network protocol.
  • Preprocessor: prepocessors are plugins developed generally in C and process the packets provided by the decoder and ensambles the packets received. This preprocessors are configured in snort.conf file configuration. Some preprocessor examples may be:
    – sfPortscan
    – Frag3
    – HTTP
    – SSH
    – To see a complete list visit: http://manual.snort.org/node17.html
  •  Detection engine: Analyze the packets based in our rules configued.
  •  Detection plugins: Used to modify the behaviour of the detection engine.
  • Output plugins: Defines how and where saves the alters and the packages generated.


For this post I’ll explain how to install and configure snort from the source code in CentOS 6 and download free ruleset for snort and configure for be used.

Installing dependencies and preparing the environment
– Installing rpmforge repository:
– Install prerequisites packages:

# yum -y install libdnet libdnet-devel libpcap libpcap-devel daq gcc make flex bison pcre pcre-devel zlib zlib-devel
– Downloading and installing daq:






# cd /tmp ; wget http://www.snort.org/downloads/1850 -O daq-1.1.1.tar.gz
# tar -xzvf daq-1.1.1.tar.gz
# cd daq-1.1.1/
# ./configure
# make && make install
# ldconfig -v
– Creating snort user and tree directories:








# groupadd snort
# useradd -g snort snort
# mkdir /usr/local/snort
# mkdir /etc/snort
# mkdir /var/log/snort
# mkdir /var/run/snort
# chown snort:snort /var/log/snort
# chown snort:snort /var/run/snort
Installing Snort and configuring the ruleset
– Downloading and installing snort:











# cd /tmp ; wget http://www.snort.org/downloads/1862 -O snort-2.9.3.1.tar.gz
# tar -xzvf snort-2.9.3.1.tar.gz
# cd snort-2.9.3.1/
# ./configure --prefix /usr/local/snort --enable-sourcefire --enable-ipv6
# make && make install
# ln -s /usr/local/snort/bin/snort /usr/bin/snort
# cp /tmp/snort-2.9.3.1/etc/snort.conf /etc/snort/
# cp /tmp/snort-2.9.3.1/etc/unicode.map /etc/snort/
# cp /tmp/snort-2.9.3.1/etc/classification.config /etc/snort/
# cp -r /usr/local/snort/lib/snort_dynamicpreprocessor/ /usr/local/lib/
# cp -r /usr/local/snort/lib/snort_dynamicengine /usr/local/lib/
– Downloading open source ruleset from emerging:




# tar -xzvf emerging.rules.tar.gz
# touch /etc/snort/rules/white_list.rules /etc/snort/rules/black_list.rules
# chown -R snort:snort /etc/snort/
– Edit snort configuration:

# vi /etc/snort/snort.conf







ipvar HOME_NET 192.168.1.0/24
var RULE_PATH /etc/snort/rules
var SO_RULE_PATH /etc/snort/so_rules
var PREPROC_RULE_PATH /etc/snort/preproc_rules
var WHITE_LIST_PATH /etc/snort/rules
var BLACK_LIST_PATH /etc/snort/rules
include $RULE_PATH/emerging.conf
Configuring the init script for Snort
– Create sysconfig snort configuration:

# vi /etc/sysconfig/snort














#### General Configuration
INTERFACE=eth0
CONF=/etc/snort/snort.conf
USER=snort
GROUP=snort
PASS_FIRST=0
#### Logging & Alerting
LOGDIR=/var/log/snort
ALERTMODE=fast
DUMP_APP=1
BINARY_LOG=1
NO_PACKET_LOG=0
PRINT_INTERFACE=0
– Adding the init script:

# vi /etc/init.d/snortd

#!/bin/bash
#
# snort Start up the Snort Intrusion Detection System daemon #
# chkconfig: 2345 55 25
# description: Snort is a Open Source Intrusion Detection System
# This service starts up the snort daemon. #
# processname: snort
# pidfile: /var/run/snort_eth0.pid
### BEGIN INIT INFO
# Provides: snort
# Required-Start: $local_fs $network $syslog
# Required-Stop: $local_fs $syslog
# Should-Start: $syslog
# Should-Stop: $network $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start up the Snort Intrusion Detection System daemon
# Description: Snort is an application for Open Source Intrusion Detection.
# This service starts up the Snort IDS daemon.
### END INIT INFO
# source function library
. /etc/rc.d/init.d/functions
# pull in sysconfig settings
[ -f /etc/sysconfig/snort ] && . /etc/sysconfig/snort
RETVAL=0
prog="snort"
lockfile=/var/lock/subsys/$prog
# Some functions to make the below more readable
SNORTD=/usr/bin/snort
#OPTIONS="-A fast -b -d -D -i eth0 -u snort -g snort -c /etc/snort/snort.conf -l /var/log/snort"
#PID_FILE=/var/run/snort_eth0.pid
# Convert the /etc/sysconfig/snort settings to something snort can
# use on the startup line.
if [ "$ALERTMODE"X = "X" ]; then
ALERTMODE=""
else
ALERTMODE="-A $ALERTMODE"
fi
if [ "$USER"X = "X" ]; then
USER="snort"
fi
if [ "$GROUP"X = "X" ]; then
GROUP="snort"
fi
if [ "$BINARY_LOG"X = "1X" ]; then
BINARY_LOG="-b"
else
BINARY_LOG=""
fi
if [ "$LINK_LAYER"X = "1X" ]; then
LINK_LAYER="-e"
else
LINK_LAYER=""
fi
if [ "$CONF"X = "X" ]; then
CONF="-c /etc/snort/snort.conf"
else
CONF="-c $CONF"
fi
if [ "$INTERFACE"X = "X" ]; then
INTERFACE="-i eth0"
PID_FILE="/var/run/snort_eth0.pid"
else
PID_FILE="/var/run/snort_$INTERFACE.pid"
INTERFACE="-i $INTERFACE"
fi
if [ "$DUMP_APP"X = "1X" ]; then
DUMP_APP="-d"
else
DUMP_APP=""
fi
if [ "$NO_PACKET_LOG"X = "1X" ]; then
NO_PACKET_LOG="-N"
else
NO_PACKET_LOG=""
fi
if [ "$PRINT_INTERFACE"X = "1X" ]; then
PRINT_INTERFACE="-I"
else
PRINT_INTERFACE=""
fi
if [ "$PASS_FIRST"X = "1X" ]; then
PASS_FIRST="-o"
else
PASS_FIRST=""
fi
if [ "$LOGDIR"X = "X" ]; then
LOGDIR=/var/log/snort
fi
# These are used by the 'stats' option
if [ "$SYSLOG"X = "X" ]; then
SYSLOG=/var/log/messages
fi
if [ "$SECS"X = "X" ]; then
SECS=5
fi
if [ ! "$BPFFILE"X = "X" ]; then
BPFFILE="-F $BPFFILE"
fi
runlevel=$(set -- $(runlevel); eval "echo $$#" )
start()
{
[ -x $SNORTD ] || exit 5
echo -n $"Starting $prog: "
daemon --pidfile=$PID_FILE $SNORTD $ALERTMODE $BINARY_LOG $LINK_LAYER $NO_PACKET_LOG $DUMP_APP -D $PRINT_INTERFACE $INTERFACE -u $USER -g $GROUP $CONF -l $LOGDIR $PASS_FIRST $BPFFILE $BPF && success || failure
RETVAL=$?
[ $RETVAL -eq 0 ] && touch $lockfile
echo
return $RETVAL
}
stop()
{
echo -n $"Stopping $prog: "
killproc $SNORTD
if [ -e $PID_FILE ]; then
chown -R $USER:$GROUP /var/run/snort_eth0.* && rm -f /var/run/snort_eth0.pi*
fi
RETVAL=$?
# if we are in halt or reboot runlevel kill all running sessions
# so the TCP connections are closed cleanly
if [ "x$runlevel" = x0 -o "x$runlevel" = x6 ] ; then
trap TERM
killall $prog 2> /dev/null
trap TERM
fi
[ $RETVAL -eq 0 ] && rm -f $lockfile
echo
return $RETVAL
}
restart() {
stop
start
}
rh_status() {
status -p $PID_FILE $SNORTD
}
rh_status_q() {
rh_status > /dev/null 2>&;1
}
case "$1" in
start)
rh_status_q && exit 0
start
;;
stop)
if ! rh_status_q; then
rm -f $lockfile
exit 0
fi
stop
;;
restart)
restart
;;
status)
rh_status
RETVAL=$?
if [ $RETVAL -eq 3 -a -f $lockfile ] ; then
RETVAL=2
fi
;;
*)
echo $"Usage: $0 {start|stop|restart|status}"
RETVAL=2
esac
exit $RETVAL
– Start snort at system boot time:


# chmod +x /etc/init.d/snortd
# chkconfig --levels 235 snortd on
– Starting snort:

# /etc/init.d/snortd start
Testing the basic functionality of port scanning detection with nmap

# tail -f /var/log/snort/alert