Friday, January 27, 2012

Fixing SNORT BASE Graph with no legends

Wow after breaking my head for around 4 hours I did find a way to display information on the Graph which BASE produces.

The problem which I am facing is exactly described here.  http://seclists.org/snort/2011/q1/722 though the complete solution is not so here goes.


First we need to see what is the font which BASE is using.  That can be done by grepping for graph_font_name.

root@Bodhidarmar:/home/bala# grep graph_font_name /var/www/base/base_conf.php
        // $graph_font_name = "Verdana";
       $graph_font_name = "DejaVuSans";
        // $graph_font_name = "Image_Graph_Font";

Now that we found that BASE is going to user DejaVuSans fonts, we need to make sure that our system has that fonts.  If you cannot see them then copy these fonts from someother system and paste them in here.

root@Bodhidarmar:/var/www/base# ll /usr/share/fonts/dejavu/
-rw-r--r-- 1 bala bala 524056 2012-01-27 03:20 DejaVuSans-BoldOblique.ttf
-rw-r--r-- 1 bala bala 573136 2012-01-27 03:19 DejaVuSans-Bold.ttf
-rw-r--r-- 1 root root 301928 2009-08-27 19:56 DejaVuSansMono-Bold.ttf
-rw-r--r-- 1 root root 321524 2009-08-27 19:56 DejaVuSansMono.ttf
-rw-r--r-- 1 bala bala 523804 2012-01-27 03:20 DejaVuSans-Oblique.ttf
-rw-r--r-- 1 bala bala 622280 2012-01-27 03:19 DejaVuSans.ttf
-rw-r--r-- 1 root root 306532 2009-08-27 19:56 DejaVuSerif-Bold.ttf
-rw-r--r-- 1 root root 328908 2009-08-27 19:56 DejaVuSerif.ttf

root@Bodhidarmar:/var/www/base#

Now this is the part which made me run mad,  this site came to my rescue https://help.ubuntu.com/community/PhpPear , I just need to have a soft link of the font being used inside the PHP directory.

root@Bodhidarmar:/usr/share/php/Image/Canvas# ln -s /usr/share/fonts/truetype/ttf-dejavu/ Fonts
root@Bodhidarmar:/usr/share/php/Image/Canvas# ll
-rw-r--r-- 1 root root  6604 2012-01-27 03:54 Color.php
lrwxrwxrwx 1 root root    37 2012-01-27 04:12 Fonts -> /usr/share/fonts/truetype/ttf-dejavu//

Thursday, January 26, 2012

Assembler Working with Strings

Singing with Strings in Assembly

My Guru for this is Vivek Ramachand

About MOVSx
We can use MOVSx to move Strings from one memory location to the other

MOVSB - To move a byte (8 bits)
MOVSW - To move a word (16 bits)
MOVSL - To move double word (32 bits)

The implied thing is Source is always where ESI points to in memory and Destination is always where EDI points in memory.

The Direction Flag (DF Flag)
The DF flag is part of the EFLAGS registers
This flag decides to i++ or i-- ESI, EDI after a MOVSx instruction
If DF is set ie 1, ESI and EDI are i--
If DF is clear ie 0, ESI & EDI are i++
We can set DF using the STD instruction
We can clear DF with the CLD instruction

The REP instruction

It is used to repeat a string instruction till ECX has a value > 0

    * Load ECX with str length
    * Use REP MOVSx to copy string from src to dst

Load Str from Memory into Registers

Loads into the EAX register, source is pointed by ESI

LODSB - Load a byte from memory location into AL
LODSW - Load a word from memory into AX
LODSL - Load a double word from memory into EAX

ESI is automatically i++ or i-- based on DF after LODSx instruction executes

Storing Str from Registers into Memory

Loads into Memory, source pointed by the EAX register

STOSB - store AL to memory
STOSW - store AX to memory
STOSL - store EAX to memory

EDI is i++ ori-- based on DF after STOSx instruction executes

Comparing Strings

Comparing Strings, ESI contains src string & EDI contains dst string

CMPSB - compares byte value
CMPSW - compares word value
CMPSL - compares double word value

EDI is i++ ori-- based on DF after STOSx instruction executes

REPZ and REPNZ
REPZ - repeat instruction if zero flag is set
REPNZ - repeat instruction if zero flag is not set

Program Starts here

.data
    HelloEarthStr:
        .ascii "Hello World of Assembly!"
    H3ll0:
        .asciz "H3ll0"
.bss
    .lcomm Destination, 100
    .lcomm DestinationUsingRep, 100
    .lcomm DestinationUsingStos, 100
.text
    .globl _start
    _start:
        nop
        #1. Simple copying using movsb, movsw, movsl
        movl $HelloEarthStr, %esi
        movl $Destination, %edi
        movsb
        movsw
        movsl
       
        #2. Setting / Clearing the DF flag
        std # set the DF flag
        cld # clear the DF flag
       
        #3. Using Rep
        movl $HelloEarthStr, %esi
        movl $DestinationUsingRep, %edi
        movl $25, %ecx # Set the string length in ECX
        cld # clear the DF
        rep movsb
        std
       
        #4. Loading strings from memory into EAX register
        cld
        # leal - Load Effective Address into Double Work L
        leal HelloEarthstr, %esi
        lodsb
        movb $0, %al
        dec %esi
        lodsw
        movw $0, %ax
        subl $2, %esi # Make ESI point back to the original string
        lodsl
       
        #5. Storing strings from EAX to memory
        leal DestinationUsingStos, %edi
        stosb
        stosw
        stosl
       
        #6. Comparing Strings
        cld
        leal HelloWorldString, %esi
        leal H3ll0, %edi
        cmpsb
       
        dec %esi
        dec %edi
        cmpsw
       
        subl $2, %esi
        subl $2, %edi
        cmpsl

        # The exit() routine called
        movl $1, %eax
        movl $10, %ebx
        int $0x80

Moving Data between Registers & Memory

My Guru for this is Vivek Ramachand.

Move command

movl = moves a 32 bit value
movl %eax, %ebx

movw = moves a 16 bit value
movw %ax, %bx

movb = moves a 8 bit value
movb %ah, %bh

Moving Data  

1. Between Registers
 movl %eax, %ebx

2. Between Registers and Memory
location:
                .int 20
movl %eax, location
movl location, %ebx

3. Immediate value into Register
 movl $10, %ebx

4. Immediate value into memory location
location:
                 .byte 0
movb $20, location

5. Moving Data into an Indexed Memory Location
IntegerArray:
                        .int 11,12,13,14,15

Let us select the 4th integer "14" and convert it into "20"
BaseAddress(Offset, Index, Size) = IntegerArray(0,3,4)
movl %eax, IntegerArray(0,3,4)

6. Indirect Addressing using Registers
To extract the memory location of a variable we need to put a $ sign before the variable, it is similar to using &variable in C programming.

movl $location, %edi
#The next command will copy value 9 into the address pointed by edi.
movl $9,(%edi)
#The next cmd will cpy value 9 into the address pointed by edi + 4 bytes.
movl $9,4(%edi)
#The next cmd will cpy value 9 into the address pointed by edi - 2 bytes.
movl $9,-2(%edi)

Now let us move to the code, which will demonstrate all the six shown above.

Program Starts here

#This program shows how to use Data types.
.data
    HelloEarth:
        .ascii "HelloEarth"
    ByteLocation:
        .byte 50
    Int32:
        .int 5
    Int16:
        .short 5
    Float:
        .float 50.55
    IntegerArray:
        .int 50,55,60,65,70
.bss
    .comm LargeBuff, 1000
.text
   
    .globl _start
    _start:
        nop
        #1. MOV immediate value into register
        movl $7, %eax
        #2. MOV immediate value into memory location
        movw $70, Int16
        #3. MOV data between registers
        movl %eax, %ebx
        #4. MOV data from memory to register
        movl Int32, %eax
        #5. MOV data from register to memory
        movb $7, %al
        movb %al, ByteLocation
        #6. MOV data into an indexed memory location
        # Location is decided by BaseAddress(Offset, Index, DataSize)
        # Offset and Index must be registers, Datasize can be a numerical value
        movl $0, %ecx
        movl $2, %edi
        movl $77, IntegerArray(%ecx, %edi, 4)

        #Exit Systemcall to exit the program
        movl $1, %eax
        movl $0, %ebx
        int $0x80

Now I am going to compile the code and link it to create the executable.

bala@lappi:~/ASM$ as -gstabs -o move.o move.s
bala@lappi:~/ASM$ ld -o move move.o
bala@lappi:~/ASM$ gdb ./move

Create a break point 
(gdb) break *_start+1
Breakpoint 2 at 0x4000b1: file move.s, line 23.
(gdb) run
Starting program: /home/bala/ASM/move
Breakpoint 2, _start () at move.s:23
23            movl $7, %eax

#1. MOV immediate value into register
(gdb) info registers
rax            0x0    0
rbx            0x0    0
(gdb) s
(gdb) info registers
rax            0x7    7
rbx            0x0    0
(gdb) s
25            movw $70, Int16
#2. MOV immediate value into memory location

(gdb) x/1dh &Int16
0x600103 :    5
(gdb) s
27            movl %eax, %ebx
#3. MOV data between registers
(gdb) x/1dh &Int16
0x600103 :    70
(gdb) info registers
rax            0x7    7
rbx            0x0    0
rcx            0x0    0

(gdb) s
29            movl Int32, %eax
#4. MOV data from memory to register

(gdb) info registers
rax            0x7    7
rbx            0x7    7
rcx            0x0    0

(gdb) x/1dw &Int32
0x6000ff :    5
(gdb) s
31            movb $7, %al
#5. MOV data from register to memory

(gdb) info registers
rax            0x5    5
rbx            0x7    7
rcx            0x0    0

(gdb) s
32            movb %al, ByteLocation
(gdb) x/1db &ByteLocation
0x6000fe :    50

(gdb) s
36            movl $0, %ecx
#6. MOV data into an indexed memory location

(gdb) x/1db &ByteLocation
0x6000fe :    7
(gdb)  s
37            movl $2, %edi
(gdb) s
38            movl $77, IntegerArray(%ecx, %edi, 4)
(gdb) x/5dw &IntegerArray
0x600109 :    50    55    60    65
0x600119 :    70

(gdb) s
40            movl $Int32, %eax
#7. MOV data in via indirect means ie Memory location
(gdb) x/5dw &IntegerArray
0x600109 :    50    55    77    65
0x600119 :    70

(gdb) print &Int32
$1 = ( *) 0x60010f
(gdb) s
41            movl (%eax), %ebx
(gdb) info registers
rax            0x60010f    6291727
rbx            0x7    7
rcx            0x0    0

(gdb) s
42            movl $777, (%eax)
(gdb) info registers
rax            0x60010f    6291727
rbx            0x5    5
rcx            0x0    0

(gdb) x/1dw &Int32
0x60010f :    5
(gdb) s
44            movl $1, %eax
(gdb) x/1dw &Int32
0x60010f :    777
(gdb)

Saturday, January 21, 2012

Data Types used in .DATA section

The following are the data types which are used in the .DATA section
All these spaces are reserved at the Compile Time

.byte = 1 byte
.ascii = string
.asciz = Null terminated string
.int = 32 bit integer
.short = 16 bit integer
.float = Single precision floating point number
.double = Double precision floating point number

The following are the data types which are used in the .BSS section
All these spaces are allocated at the Run Time
.comm - declares common memory area
.lcomm - declares a local common memory area

The program starts here.

bala@bala-laptop:~/ASM$ cat variable.s
#This program shows how to use Data types.
.data
    HelloEarth:
        .ascii "HelloEarth"
    ByteLocation:
        .byte 50
    Int32:
        .int 5
    Int16:
        .short 5
    Float:
        .float 50.55
    IntegerArray:
        .int 50,55,60,65,70
.bss
    .comm LargeBuff, 1000
.text
   
    .globl _start
    _start:
        nop
        #Exit Systemcall to exit the program
        movl $1, %eax
        movl $0, %ebx
        int $0x80

bala@bala-laptop:~/ASM$ as -gstabs -o variable.o variable.s
bala@bala-laptop:~/ASM$ ld -o variable variable.o
bala@bala-laptop:~/ASM$ gdb ./variable
Let us set a break point
(gdb) break *_start+1
Breakpoint 1 at 0x4000b1: file variable.s, line 23.
(gdb) run
Starting program: /home/bala/ASM/variable
Breakpoint 1, _start () at variable.s:23
23            movl $1, %eax

(gdb) info variables
All defined variables:
Non-debugging symbols:
0x00000000006000c0  HelloEarth
0x00000000006000ca  ByteLocation
0x00000000006000cb  Int32
0x00000000006000cf  Int16
0x00000000006000d1  Float
0x00000000006000d5  IntegerArray
0x00000000006000f0  LargeBuff

(gdb) x/11cb 0x00000000006000c0
0x6000c0 :    72 'H'    101 'e'    108 'l'    108 'l'    111 'o'    69 'E'    97 'a'    114 'r'
0x6000c8 :    116 't'    104 'h'    50 '2'

(gdb) x/1db 0x00000000006000ca
0x6000ca :    50
(gdb) x/1dw 0x00000000006000cb
0x6000cb :    5
(gdb) x/1dh 0x00000000006000cf
0x6000cf :    5
(gdb) x/1fw 0x00000000006000d1
0x6000d1 :    50.5499992
(gdb) x/5dw 0x00000000006000d5
0x6000d5 :    50    55    60    65
0x6000e5 :    70

(gdb) x/100db 0x00000000006000f0
0x6000f0 :    0    0    0    0    0    0    0    0
0x6000f8 :    0    0    0    0    0    0    0    0
0x600100 :    0    0    0    0    0    0    0    0
0x600108 :    0    0    0    0    0    0    0    0
0x600110 :    0    0    0    0    0    0    0    0
0x600118 :    0    0    0    0    0    0    0    0
0x600120 :    0    0    0    0    0    0    0    0
0x600128 :    0    0    0    0    0    0    0    0
0x600130 :    0    0    0    0    0    0    0    0
0x600138 :    0    0    0    0    0    0    0    0
0x600140 :    0    0    0    0    0    0    0    0
0x600148 :    0    0    0    0    0    0    0    0

---Type to continue, or q to quit---

Friday, January 20, 2012

Structure of Assembly Program

My Guru for this is Vivek Ramachand

Structure of an Assembly Program

.data - is where all initialized data resides.
.bss - is where all uninitialized data resides.
.text - is where the program instructions resides.
.globl _start - Will call external callable routines.
_start: is comparable with main() function of C programming.

Linux System calls

It is a library which kernel exposes to get various tasks done.
List of all calls are available in
bala@lappi:~/ASM$ cat /usr/include/asm/unistd.h
# ifdef __i386__
#  include "unistd_32.h"
# else
#  include "unistd_64.h"
# endif

bala@lappi:~/ASM$ head -15 /usr/include/asm/unistd_32.h
#ifndef _ASM_X86_UNISTD_32_H
#define _ASM_X86_UNISTD_32_H
/*
 * This file contains the system call numbers.
 */
#define __NR_restart_syscall      0
#define __NR_exit          1
#define __NR_fork          2
#define __NR_read          3
#define __NR_write          4
#define __NR_open          5
#define __NR_close          6
#define __NR_waitpid          7

We can call these system calls by invoking INT 0x80

Passing arguments to syscalls
EAX - System Call Number
EBX - First Argument
ECX - Second Argument
EDX - Third Argument
ESI - Fourth Argument
EDI - Fifth Argument

Coding Simple exit program in Assembly
Calling exit(0) to exit a program
Function definition
void_exit(int status);

1.Sys call # for exit() is 1, so we need to load EAX with 1 with the command
movl $1, %eax
2."Status" is "0" if program exited normally, so we need to load EBX with 0
movl $0, %ebx
3.Raise the software interrupt 0x80
int 0x80

Simple exit Program starts here
bala@bala-laptop:~/ASM$ cat exit.s
.text
.globl _start
_start:
    movl $1, %eax
    movl $0, %ebx
    int $0x80

bala@bala-laptop:~/ASM$
Now to compile the Assemble program we use the "as" compiler, to create the exit object file.
bala@bala-laptop:~/ASM$ as -o exit.o exit.s
This alone cannot do any thing we need to have a linker
bala@bala-laptop:~/ASM$ ld -o exit exit.o
Now we can run the program
bala@bala-laptop:~/ASM$ ./exit
The exit status is zero :-)
bala@bala-laptop:~/ASM$ echo $?
0
bala@bala-laptop:~/ASM$

Now we will attempt to write a Hello Earth program :-)

The syscall used to print "Hello Earth" is called write()
Then we need to exit the program gracefully with exit()

The write() syscall needs three parameters
ssize_t write(int fd, const void *buf, size_t count);
The syscall number for Write is 4 load it in EAX
The File Descriptor of STDOUT is 1 load in EBX
Buf -> is a pointer to the mem location containing "Hello Earth" in ECX
count = string length in EDX

Simple write Program starts here
bala@bala-laptop:~/ASM$ cat hello.s
# This is my 1st print program
.data
HelloEarthString:
    .ascii "Hello Earth\n"
.text
.globl _start
_start:
    #Let us load all argument for write in registers
    movl $4, %eax
    movl $1, %ebx
    movl $HelloEarthString, %ecx
    movl $12, %edx
    int $0x80

    #Now let us exit this program gracefully
    movl $1, %eax
    movl $0, %ebx
    int $0x80
bala@bala-laptop:~/ASM$ as -o hello.o hello.s
Now in the step above I have create the object file
bala@bala-laptop:~/ASM$ ld -o hello hello.o
Now in the step above I have create the linked executable
bala@bala-laptop:~/ASM$ ./hello
Hello Earth
bala@bala-laptop:~/ASM$ cat hello.s

Thursday, January 19, 2012

Starting SNORT on reboot

In order that snort start automatically on rebooting Ubuntu copy paste the script on to a text file and save it as snort in the path /etc/init.d/

I have changed the font color where I have made my customization.
 
Source from snort's blog and Bullet-bala.blogspot.com made few changes & customization :-)

#! /bin/sh
### BEGIN INIT INFO
# Provides:          Snort
# Required-Start:    $local_fs $remote_fs $syslog $network mysql
# Required-Stop:     $local_fs $remote_fs $syslog $network mysql
# Default-Start:     2 3 4 5
# Default-Stop:      S 0 1 6
# Short-Description: Init script to start the Snort daemon
# Description:       Provides Snort service on startup and terminates
#                    on shutdown. Snort is an IDS or IPS. This script
#                    assumes that snort is installed in /usr/sbin and
#                    that it's main snort.conf file is in /etc/snort.
#                    The service will be started as a daemon, listening
#                    on eth0 and will also start quietly. If you require
#                    something other than this, you will have to edit
#                    the script accordingly.
#                    USE AT YOUR OWN RISK, YMMV. THIS SCRIPT COMES WITH
#                    ABSOLUTELY NO WARRANTY WHATSOEVER.
# License:           GPLv2 see http://www.gnu.org/licenses/gpl-2.0.txt
### END INIT INFO

# Author: Nigel Houghton

PATH=/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/sbin:/usr/local/bin

export LD_LIBRARY_PATH=/usr/local/lib
DESC="Snort service for IDS or IPS"
NAME=snort
CONFIG="/store/snort/etc/snort.conf"
INTERFACE="eth1"
DAEMON=/usr/local/bin/$NAME
SNORTUser="suser"
#The -q is for quite mode and -D is for deamon refer http://projects.cs.luc.edu/comp412/dredd/docs/software/man-snort
DAEMON_ARGS="-c $CONFIG -i $INTERFACE -u $SNORTUser -qD"
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME

# Exit if the package is not installed
[ -x "$DAEMON" ] || exit 1

# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME

# Load the VERBOSE setting and other rcS variables
[ -f /etc/default/rcS ] && . /etc/default/rcS

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions

#
# Function that starts the daemon/service
#
do_start()
{
 # Return
 #   0 if daemon has been started
 #   1 if daemon was already running
 #   2 if daemon could not be started
 start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \
  || return 1
 start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- \
  $DAEMON_ARGS \
  || return 2
}

#
# Function that stops the daemon/service
#
do_stop()
{
 # Return
 #   0 if daemon has been stopped
 #   1 if daemon was already stopped
 #   2 if daemon could not be stopped
 #   other if a failure occurred
   start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME
 RETVAL="$?"
 [ "$RETVAL" = 2 ] && return 2
 start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON
 [ "$?" = 2 ] && return 2
 # Many daemons don't delete their pidfiles when they exit.
 if [ -f "$PIDFILE" ]; then
    rm -f $PIDFILE
   fi
 return "$RETVAL"
}

#
# Function that sends a SIGHUP to the daemon/service
#
do_reload() {
 start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME
 return 0
}

case "$1" in
  start)
 [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
 do_start
 case "$?" in
  0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
  2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
 esac
 ;;
  stop)
 [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
 do_stop
 case "$?" in
  0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
  2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
 esac
 ;;
  restart|force-reload)
 log_daemon_msg "Restarting $DESC" "$NAME"
 do_stop
 case "$?" in
   0|1)
  do_start
  case "$?" in
   0) log_end_msg 0 ;;
   1) log_end_msg 1 ;; # Old process is still running
   *) log_end_msg 1 ;; # Failed to start
  esac
  ;;
   *)
    # Failed to stop
  log_end_msg 1
  ;;
 esac
 ;;
  *)
 echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
 exit 3
 ;;
esac

:

You need to paste upto the semicolon shown above. Just in case this does not show well on blogger here is a pastebin link http://pastebin.com/Ew9VBGBK. Once this is done we need to use update.rc.d script in Ubuntu.

A good article of how to use that is given here http://www.debuntu.org/how-to-manage-services-with-update-rc.d. Don't worry I will not make you read that to understand the next command.

Here I have asked Ubuntu to start my snort script with 99th priority (i.e start as late as possible) on runlevels 2 3 4 and 5 and to kill it with 99th priority (i.e immediately )when ubuntu hit runlevel 0 1 and 6.


  At the end you can confirm if snort is running with the command


bala@Bodhidarmar:~$ ps aux | grep snort
aravind    774  0.8 28.0 657556 211748 ?       Ssl  03:32   0:00 /usr/local/bin/snort -c /store/snort/etc/snort.conf -i eth1 -u suser -qD
bala       796  0.0  0.1   3324   784 pts/1    S+   03:32   0:00 grep --color=auto snort
bala@Bodhidarmar:~$


SNORT MYSQL

Here I have shown how to prepare mysql to work with Snort.  Assuming mysql is already installed.
 
root@snortbox:/store/snort/src/snort-2.9.1# mysql -u root -p
Enter password:
mysql> show databases;
+---------------------------------+
| Database                     |
+---------------------------------+
| information_schema     |
| mysql                         |
+---------------------------------+

2 rows in set (0.01 sec)
Now let us create the MySQL database and tables in order to receive the Snort logs:
mysql> create database snort;
Query OK, 1 row affected (0.01 sec) Since it is dangerous to access the database with the root user, we need to create a user who has only permissions on the snort database:
mysql> grant all on snort.* to snortuser@localhost identified by 'snortpassword';
Query OK, 0 rows affected (0.01 sec)
Now to reload mysql privileges.
mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)
mysql> exit;
Bye
Now we will import the mysql schema which snort knows to use.
root@snortbox:/store/snort/src/snort-2.9.1/schemas# ls
create_db2    create_mysql       create_postgresql  Makefile.am
create_mssql  create_oracle.sql  Makefile           Makefile.in
root@snortbox:/store/snort/src/snort-2.9.1/schemas# mkdir /usr/share/doc/snort-mysql/
root@snortbox:/store/snort/src/snort-2.9.1/schemas# cp create_mysql /usr/share/doc/snort-mysql/
Manual installation
#mysql -u root -p snort < schemas/create_mysql

Tuesday, January 17, 2012

Gnu Not Unix Debugger

To load a compiler with GDB we need to compile it with specifying the GDB argument.  My Guru for this is Vivek Ramachand awesome guy :-)
bala@bala-laptop:~$ gcc -ggdb -o add add.c

To learn more about GDB we need to load it with GDB
bala@bala-laptop:~$ gdb ./add

We can List the source file with the list command.
(gdb) list 1
1    #include
2    int add(int x, int y)
3    {

Now to Run the program we need type run along with the parameter.
(gdb) run 3 4
Starting program: /home/bala/add 3 4
bala
bala
sum of 3+4 = 7
Program exited normally.

(gdb)

Disassemble a program we need to give the key word disassemble with the function name.
(gdb) disassemble main
Dump of assembler code for function main:
   0x00000000004006a5 <+47>:    add    $0x8,%rax
   0x00000000004006b4 <+62>:    callq  0x400548
   0x00000000004006c6 <+80>:    add    $0x10,%rax
   0x00000000004006d5 <+95>:    callq  0x400548

We can also disassemble the add function.
(gdb) disassemble add
Dump of assembler code for function add:
   0x0000000000400654 <+0>:    push   %rbp
   0x0000000000400655 <+1>:    mov    %rsp,%rbp
   0x0000000000400658 <+4>:    mov    %edi,-0x14(%rbp)
   0x000000000040065b <+7>:    mov    %esi,-0x18(%rbp)


Breakpoint can be set by giving the key word break and line number.
(gdb) break 5
Breakpoint 1 at 0x400665: file add.c, line 5.
If we need to know more about how to set breakpoint.
(gdb) help break
Set breakpoint at specified line or function.
break [LOCATION] [thread THREADNUM] [if CONDITION]
LOCATION may be a line number, function name, or "*" and an address.

 (gdb) run 4 5
Starting program: /home/bala/add 4 5
bala
bala
Breakpoint 1, add (x=4, y=5) at add.c:5
5    z=x+y;

(gdb) print x
$1 = 4
(gdb) print y
$2 = 5

Registers information can be got by the command info registers
(gdb) info registers
rax            0x4    4
rbx            0x0    0
rcx            0x7ffff7b32500    140737349100800
rdx            0x5    5
rsi            0x5    5
rdi            0x4    4
rbp            0x7fffffffe230    0x7fffffffe230
rsp            0x7fffffffe230    0x7fffffffe230  - This is the STACK pointer
rip            0x400665    0x400665 - This is the instruction pointer
eflags         0x202    [ IF ]
cs             0x33    51
ss             0x2b    43
ds             0x0    0
es             0x0    0
fs             0x0    0
gs             0x0    0

(gdb)

STACK information can be got by x command,
(gdb) help x
Examine memory: x/FMT ADDRESS.
ADDRESS is an expression for the memory address to examine.
FMT is a repeat count followed by a format letter and a size letter.
Format letters are o(octal), x(hex), d(decimal), u(unsigned decimal), t(binary), f(float), a(address), i(instruction), c(char) and s(string). Size letters are b(byte), h(halfword), w(word), g(giant, 8 bytes). The specified number of objects of the specified size are printed according to the format. Defaults for format and size letters are those previously used.
Default count is 1.  Default address is following last thing printed with this command or "print".

(gdb) x/10xb 0x7fffffffe230
0x7fffffffe230:    0xe0    0xe2    0xff    0xff    0xff    0x7f    0x00    0x00
0x7fffffffe238:    0x0d    0x07

(gdb) We are generally interested in word (4 bytes) as push and pop happens here
(gdb) x/20xw 0x7fffffffe230
0x7fffffffe230:    0xffffe2e0    0x00007fff    0x0040070d    0x00000000
0x7fffffffe240:    0xffffe3c8    0x00007fff    0x005657f0    0x00000003
0x7fffffffe250:    0x000000bf    0x00000000    0x00000005    0x00000004


Steping into a function
(gdb) s
6    return z;
(gdb) list 4
1    #include
2    int add(int x, int y)
3    {
4    int z=10;
5    z=x+y;
6    return z;
7    }
8    main(int argc, char **argv)
9    {
10    int a = atoi(argv[1]);

(gdb) s
7    }
(gdb) s
main (argc=3, argv=0x7fffffffe3c8) at add.c:20
20    printf("sum of %d+%d = %d\n",a,b,c);
(gdb) s
sum of 4+5 = 9
21    exit(0);

(gdb) s
Program exited normally.


Continue can be used to run the complete program after it hit a breakpoint 
(gdb) continue
Continuing.
sum of 7+8 = 15
Program exited normally.

(gdb) 

Remove Breakpoint
(gdb) info b - listing all the breakpoint in a code
Num     Type           Disp Enb Address            What
1       breakpoint     keep y   0x0000000000400665 in add at add.c:5
    breakpoint already hit 1 time
(gdb) clear 5 - clearing breakpoint set by us.
Deleted breakpoints 1
(gdb) info b
No breakpoints or watchpoints.
(gdb)
 

Sudo echo does not work :-0

Today I found the hard way that sudo echo will not work in Ubuntu and a good explanation is given here

http://blogs.oracle.com/joshis/entry/sudo_echo_does_not_work

Here is a small script I use to start a VM and point the system to use the VM as gateway to the internet :-)

bala@lapi:~$ cat ./Go_through_SNORT.sh
#!/bin/bash
#Author: Balasubramaniam Natarajan
#Date: 13-Dec-2011
#This script will set the default route to Bodhidarmar
# and will add in the name server
VBoxManage startvm SNORT
sudo route add default gw 192.168.56.101
sudo sh -c 'echo "nameserver 192.168.1.1" >> /etc/resolv
bala@lapi:~$

Monday, January 16, 2012

Snort's Classfication.config

Here you can see that I have arranged the snort rule classification in ascending to descending order.
 
bala@Bodhidarmar:/store/snort/etc$ cat classification.config | grep "config classification: " | sort -t"," -k3
config classification: attempted-admin,Attempted Administrator Privilege Gain,1
config classification: attempted-user,Attempted User Privilege Gain,1
config classification: inappropriate-content,Inappropriate Content was Detected,1
config classification: policy-violation,Potential Corporate Privacy Violation,1
config classification: shellcode-detect,Executable Code was Detected,1
config classification: successful-admin,Successful Administrator Privilege Gain,1
config classification: successful-user,Successful User Privilege Gain,1
config classification: unsuccessful-user,Unsuccessful User Privilege Gain,1
config classification: web-application-attack,Web Application Attack,1
config classification: trojan-activity,A Network Trojan was Detected, 1
config classification: attempted-dos,Attempted Denial of Service,2
config classification: attempted-recon,Attempted Information Leak,2
config classification: default-login-attempt,Attempt to Login By a Default Username and Password,2
config classification: denial-of-service,Detection of a Denial of Service Attack,2
config classification: misc-attack,Misc Attack,2
config classification: non-standard-protocol,Detection of a Non-Standard Protocol or Event,2
config classification: rpc-portmap-decode,Decode of an RPC Query,2
config classification: sdf,Sensitive Data was Transmitted Across the Network,2
config classification: successful-dos,Denial of Service,2
config classification: successful-recon-largescale,Large Scale Information Leak,2
config classification: successful-recon-limited,Information Leak,2
config classification: suspicious-filename-detect,A Suspicious Filename was Detected,2
config classification: suspicious-login,An Attempted Login Using a Suspicious Username was Detected,2
config classification: system-call-detect,A System Call was Detected,2
config classification: unusual-client-port-connection,A Client was Using an Unusual Port,2
config classification: web-application-activity,Access to a Potentially Vulnerable Web Application,2
config classification: bad-unknown,Potentially Bad Traffic, 2
config classification: icmp-event,Generic ICMP event,3
config classification: misc-activity,Misc activity,3
config classification: network-scan,Detection of a Network Scan,3
config classification: not-suspicious,Not Suspicious Traffic,3
config classification: protocol-command-decode,Generic Protocol Command Decode,3
config classification: string-detect,A Suspicious String was Detected,3
config classification: unknown,Unknown Traffic,3
config classification: tcp-connection,A TCP Connection was Detected,4
bala@Bodhidarmar:/store/snort/etc$

Turning Off Virtual Address Space Randomization on Linux based OS

This is how we turn off Virtual Address Space Randomization on Linux based OS.



NOTE: This is not advised as it makes an attacker job easy to attack a system.

Saturday, January 14, 2012

Writing SNORT Rules :-D

Follow these simple steps to write a snort rule.


After writing the second row in a notepad, save it as streamingvideo.rules and we have to include it in the snort config file along with other rules.

Wola that is it, we have created our first snort rule :-)

Friday, January 13, 2012

HTTP Redirect

We can use this code here inside index.html to redirect to the base running on a folder.

Thursday, January 12, 2012

AIDE - Usage

AIDE will generate a DB the first time it runs.

[root@localhost AIDE]# aide -c aide.conf --init
AIDE, version 0.15.1
### AIDE database at aide.db.new initialized.
[root@localhost AIDE]# ls
aide-0.15.1  aide.conf  aide.db.new  software
[root@localhost AIDE]# file aide.db.new
aide.db.new: ASCII text
[root@localhost AIDE]# grep hosts aide.db.new
/etc/hosts 0 34359745469 100644 269 0 103 1 aLeAic+G8OYpNZ/CRUWDEQ== 0 0 0 0 0 0 0 0 MTMxNzkxNjc3Mg== MTMxNzkxNjc3Mg==

Most of the result which aide gives are from stat.
[root@localhost AIDE]# stat /etc/hosts
  File: `/etc/hosts'
  Size: 103           Blocks: 8          IO Block: 4096   regular file
Device: fd00h/64768d    Inode: 269         Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2011-10-06 21:30:37.763070627 +0530
Modify: 2011-10-06 21:29:32.134043697 +0530
Change: 2011-10-06 21:29:32.134043697 +0530

[root@localhost AIDE]# aide -c aide.conf --check
AIDE, version 0.15.1
### All files match AIDE database. Looks okay!

 
Now let us try to edit the hosts file

[root@localhost AIDE]# vim /etc/hosts
[root@localhost AIDE]# aide -c aide.conf --check
AIDE 0.15.1 found differences between database and filesystem!!
Start timestamp: 2011-10-07 01:47:14
Summary:
  Total number of files:    2447
  Added files:            0
  Removed files:        0
  Changed files:        2
---------------------------------------------------
Changed files:
---------------------------------------------------
changed: /etc
changed: /etc/hosts
---------------------------------------------------
Detailed information about changes:
---------------------------------------------------
Directory: /etc
 Mtime    : 2011-10-06 23:16:45              , 2011-10-07 01:47:11
 Ctime    : 2011-10-06 23:16:45              , 2011-10-07 01:47:11
File: /etc/hosts
 Size     : 103                              , 128
 Mtime    : 2011-10-06 21:29:32              , 2011-10-07 01:47:11
 Ctime    : 2011-10-06 21:29:32              , 2011-10-07 01:47:11
 Inode    : 269                              , 68060
 MD5      : aLeAic+G8OYpNZ/CRUWDEQ==         , SjcyC62yuuHGTIGZ7Air7g==

AIDE - Configuring

Let us try to edit the aide.conf after copying it to out AIDE toplevel directory.

[bala@localhost AIDE]$ cp aide-0.15.1/doc/aide.conf . 
[bala@localhost AIDE]$ vim aide.conf 

There are three kindly of lines in the configuration files they are

1. VARIABLES
@@define TOPDIR /home/bala/Download/AIDE/aide-0.15.1

2. MACROS - if not defined get it defined here

@@ifndef TOPDIR
@@define TOPDIR /
@@endif

3. Type of files and Directory to be monitored

Now we will modify the place where AIDE will write the MD5SUM onto

# The location of the database to be read.
#database=file:aide.db
database=file:/home/bala/Download/AIDE/aide.db.new

#This is the link where aide writes the output on to
database_out=file:aide.db.new
#We can also asking to be verbose
verbose=20
#This is the place where AIDE is going to shout if it finds errors.
report_url=stdout

These are all the things which AIDE can check for

# @@{TOPDIR} is replaced with /home/bala/Download/AIDE/aide-0.15.1 when
# read by aide.
#p:             permissions
#ftype: file type
#i:             inode
#n:             number of links
#l:             link name
#u:             user
#g:             group
#s:             size
#b:             block count
#m:             mtime
#a:             atime
#c:             ctime
#S:             check for growing size
#I:             ignore changed filename
#md5:           md5 checksum
#sha1:          sha1 checksum
#sha256:        sha256 checksum
#sha512:        sha512 checksum
#rmd160:        rmd160 checksum
#tiger:         tiger checksum
#haval:         haval checksum
#crc32:         crc32 checksum
#R:             p+ftype+i+l+n+u+g+s+m+c+md5
#L:             p+ftype+i+l+n+u+g
#E:             Empty group
#>:             Growing logfile p+ftype+l+u+g+i+n+S
#The following are available if you have mhash support enabled:
#gost:          gost checksum
#whirlpool:     whirlpool checksum
#The following are available and added to the default groups R, L and >
#only when explicitly enabled using configure:
#acl:           access control list
#selinux        SELinux security context
#xattrs:        extended file attributes
#e2fsattrs:     file attributes on a second extende

# Rule definition
All=R+a+sha1+rmd160+sha256+sha512+tiger+whirlpool


#We need to be careful in asking AIDE to just monitor those files which do not change frequently.

#We will try to write our own rules inside AIDE config files now :-D
#Modified by Bala, first rule recursively, second rule just the var directory.
/etc R
=/var

If we want to just negate certain folders we can do like the following

# we will include the root directory recursively
/ R
# We will exclude the home directory like
!/home R

AIDE can also compress the output database file all we need to do is change the following line in aide.conf file
gzip_dbout=yes
However for the above stuff to work we need zlib to be installed on the system.



 

AIDE (Advance Intrustion Detection Environment) - Installation

Go to sourceforge.net and search for AIDE.  Download both the aide...tar.gz and the aide....asc file so that we can verify if we have downloaded the correct file.

http://sourceforge.net/projects/aide/files/aide/0.15.1/
http://sourceforge.net/projects/aide/files/PGP  key/
[bala@localhost AIDE]$ gpg --import aide-2011_0xF4474E5A.asc
gpg: directory `/home/bala/.gnupg' created
gpg: new configuration file `/home/bala/.gnupg/gpg.conf' created
gpg: WARNING: options in `/home/bala/.gnupg/gpg.conf' are not yet active during this run
gpg: keyring `/home/bala/.gnupg/secring.gpg' created
gpg: keyring `/home/bala/.gnupg/pubring.gpg' created
gpg: /home/bala/.gnupg/trustdb.gpg: trustdb created
gpg: key F4474E5A: public key "Aide Developers " imported
gpg: Total number processed: 1
gpg:               imported: 1  (RSA: 1)
gpg: no ultimately trusted keys found

[bala@localhost AIDE]$ gpg --list-keys
/home/bala/.gnupg/pubring.gpg
-----------------------------
pub   4096R/F4474E5A 2011-01-30 [expires: 2012-01-31]
uid                  Aide Developers

[bala@localhost AIDE]$ gpg --verify aide-0.15.1.tar.gz.asc aide-0.15.1.tar.gz
gpg: Signature made Monday 13 September 2010 11:35:07 PM IST using DSA key ID CBF11FCD
gpg: Good signature from "Aide Developers <aide-devel@lists.sourceforge.net>"
gpg: Note: This key has expired!
Primary key fingerprint: 4D05 1BA3 1D8C E060 A99F  6668 9FC1 CC3D CBF1 1FCD

[bala@localhost AIDE]$ tar -xzvf aide-0.15.1.tar.gz

Next AIDE requires the help of mhash let us download that from http://sourceforge.net/projects/mhash/

[bala@localhost AIDE]$ tar -xjvf mhash-0.9.9.9.tar.bz2
[bala@localhost mhash-0.9.9.9]$ ./configure
[bala@localhost mhash-0.9.9.9]$ make
[bala@localhost mhash-0.9.9.9]$ make install

Now that we have installed mhash we will proceed with installing AIDE

bala@localhost aide-0.15.1]$ ./configure
checking for bison... no
checking for byacc... no
AIDE requires GNU bison

[bala@localhost aide-0.15.1]$ su
Password:
[root@localhost aide-0.15.1]# yum install bison flex

After a lot of fighting and surfing found that I need to add the bolded letters.

[root@localhost aide-0.15.1]$ ./configure --without-zlib --disable-static
[root@localhost aide-0.15.1]$ make

[root@localhost aide-0.15.1]# make install
[root@localhost aide-0.15.1]# ls -ltrh /usr/local/bin/
-rwxr-xr-x 1 root root 382K Oct  7 00:26 aide
[root@localhost aide-0.15.1]# md5sum /usr/local/bin/aide > md5sum_aide.txt
[root@localhost aide-0.15.1]# cat md5sum_aide.txt
34cf97cdf3ae7dbc9e8872a4c9a71a87  /usr/local/bin/aide

Important Command to Privilege 15

Now we will try to move certain commands to level 15.
router1>enable
Password:
router1#
Now let us try to configure
router1#config t
Now we will try to move certain commands like telnet, connect, rlogin to level 15
router1(config)#privilege exec level 15 telnet
router1(config)#privilege exec level 15 connect
router1(config)#privilege exec level 15 rlogin
router1(config)#privilege exec level 15 show ip access-group
router1(config)#privilege exec level 15 show access-lists
router1(config)#privilege exec level 15 show logging 


Creating a User Account, Setup telnet & Banner

Now we will create a user, before doing that we need to enter the command shown below.  This command will encrypt the password of the user being created, if not it will be shown in clear text

router1(config)# service password-encryption
Now I will create a username called bala
router1(config)# username bala password @ust!nlol
Now I will set the privilege level of bala
router1(config)# username bala privilege 1
Now we will strengthen the enable password to use MD5sum type 5 in other words.
router1(config)# enable secret T3stP@ssw06d
Now we will tell the router to always use type5 password by
router1(config)# no enable password
Now we will control from where Bala can connect from, I am going to use telnet for test purpose
router1(config)# access-list 1 permit 192.168.1.15
router1(config)# access-list 1 deny any
router1(config)# line vty 0 4
Now we are applying the STD access list to our Virtual Telnet lines.
router1(config-line)# access-class 1 in
Now we will also set the exec-timeout, so it will auto timeout if left unattended.
router1(config-line)# exec-timeout 5 0
Now we will apply this to telnet
router1(config-line)# transport input telnet
Now we will make it use of the local database of usename and password
router1(config-line)# login local
Now let us execute the same
router1(config-line)# exec
Now we will create a banner from Privilege exec level.
router1(config)# banner login #For authorized users only !!!#

Tuesday, January 10, 2012

Time Services

Setting Time Manually
This method is very tedious, error prone as the initial time source may be wrong.

router1# show clock detail
router1# config t
router1(config)# clock timezone IST +5.30
router1(config)# exit
router1# clock set 05:11:00 01 January 2012
router1# show clock

Configuring NTP
For a Cisco router to participate in an NTP network, we must set the NTP source interface and then designate one or more NTP servers. The source interface is the same interface on the same network as the designated server. We can use access lists to control NTP transactions between the client and server.

router1# config t
router1(config)# interface eth 0
router1(config-if)# ntp enable
router1(config-if)#  exit
router1(config)# ntp server 192.168.1.15 source eth 0
router1(config)# access-list 2 permit host 192.168.1.15
router1(config)# access-list 2 deny any log
router1(config)# ntp access-group peer 21
router1(config)#  exit
router1# show ntp associations

Disabling NTP
 
router1# config t
router1(config)# interface eth 0
router1(config-if)# ntp disable
router1(config-if)# end

NTP Authentication

router1# config t
router1(config)# ntp authenticate
router1(config)# ntp authentication-key 1 md5 router
router1(config)# ntp trusted-key 1
router1(config)# ntp server 192.168.1.15 key 1 source eth 0
router1(config)# exit

 

Setting Up Syslog Logging

router1# config t
Here I say I need to log everything from Emergencies to Informational
router1(config)# logging trap information
Here I say I need to log to the syslog server 192.168.1.1
router1(config)# logging 192.168.1.1
Here I say the syslog server to log all events from router1 to local6 facility.
router1(config)# logging facility local6
Here I say I need to send the syslog info through eth0.
router1(config)# logging source-interface eth 0
router1(config)# exit



router1# local6.debug /var/log/router.log

SNMP Trap Logging

Here we will make the router to report to a centralized management server on port 162.

router1# config t
router1(config)# logging trap informational
router1(config)# snmp-server host 192.168.1.1 traps public
router1(config)# snmp-server trap-source ethernet 0
router1(config)# snmp-server enable traps syslog
router1(config)#  exit

Log message Severity

Level0 - Emergencies which indicate router is becoming unusable.
Level1 - Alert which need immediate action.
Level2 - Critical Alert which need urgent Attention.
Level3 - Error log, may continue operation.
Level4 - Warning Log, may continue operation.
Level5 - Notifications which indicate normal & important events like interface state changing up to down.
Level6 - Informational indicating packet denied by ACL.
Level7 - Debugging message appear only if debugging is enabled.

Router Logging

To setup logging in router

router1#config t
router1(config)# logging buffered 16000
router1(config)# service timestamp log date msec local show-timezo
router1(config)# exit
router1#show logging

Saturday, January 7, 2012

ACL Standard & Extended

Let us create a Std access list and apply it to an interface

router1(config)#access-list 1 permit  [src_IP]
Now we will apply it to Interface 1 of the router1
router1(config)#interface eth 1
router1(config-if)#ip access-group 1 in
router1(config-if)#end

 Let us create an extended access list and apply it to an interface

router1(config)#access-list 101 permit tcp [src_IP wildcard mask] [src_Port optional] [dst_IP wildcard mask [dst Port optional]
Now we will apply it to Interface 1 of the router1
router1(config)#interface eth 1
router1(config-if)#ip access-group 101 in
router1(config-if)#end

Friday, January 6, 2012

Turning Off unwanted Services in Cisco Routers

General Services
Now we will disable Cisco Discover Protocol at layer 2.
router1#config t
router1(config)# no cdp run

Now we will disable tcp and udp small servers
router1(config)# no service tcp-small-servers
router1(config)# no service udp-small-servers

Now we will disable Finger service
router1(config)# no ip finger
router1(config)# no service finger

Now we will disable HTTP Server
router1(config)# no ip http server

Now we will disable bootp server to prevent other system booting over network
router1(config)# noip bootp server

Now we will disable SNMP
router1(config)# no snmp-server community public RO
router1(config)# no snmp-server community private TW
router1(config)# no snmp-server enable traps
router1(config)# no snmp-server system-shutdown
router1(config)# no snmp-server trap-auth
router1(config)# no snmp-server

Now we will disable DNS lookup to broadcast addresses
router1(config)# no ip domain-lookup

Now we will disable Auto Loading
router1(config)# no boot network
router1(config)# no service config

Now we will disable IP source Routing
router1(config)# no  ip source-route

Now we will see about disabling Interface services

Now we will disable IP Directed Broadcast
router1(config)# interface eth1
router1(config-if)# no ip directed-broadcast

Now we will disable ICMP
router1(config)# interface eth1
router1(config-if)# no ip redirect

router1(config-if)# no ip unreachable
router1(config-if)# no ip mask-reply
router1(config-if)# end

Now we will disable Address Resolution Protocol over different LAN.
router1(config)# no  ip proxy-arp

Now we will disable NTP
router1(config)#access-list 101 deny [ntp|tcp] any any eq 123
router1(config)#interface eth1
router(config-if)#ip access-group 101 in
router(config-if)#ntp disble
router(config-if)#end
         
Now we will disable unused Interfaces
router1#config t
router1(config)#interface eth2
router1(config-if)#shutdown
router1(config-ig)#end