Total Hit Counter

Friday, May 17, 2013

Configuring Gmail as a Sendmail email relay


Introduction


 In this configuration tutorial I will guide you through the process of configuring sendmail to be an email relay for your gmail or google apps account. This allows you to send email from your bash scripts, hosted website or from command line using mail command. Other examples where you can utilize this setting is for a notification purposes such or failed backups etc. Sendmail is just one of many utilities which can be configured to rely on gmail account where the others include postfix, exim , ssmpt etc. In this tutorial I will use Debian and sendmail for this task.

Install prerequisites

# apt-get install sendmail mailutils sendmail-bin 

Create Gmail Authentication file

# mkdir -m 700 /etc/mail/authinfo/
# cd /etc/mail/
next we need to create a auth file with a following content. File can have any name, in this example the name is gmail-auth:
AuthInfo: "U:root" "I:shankar.patel@gmail.com" "P:xxxxxxxxx"
Replace the above email with your gmail or google apps email.
Please note that in the above password example you need to keep 'P:' as it is not a part of the actual password.
In the next step we will need to create a hash map for the above authentication file:
# makemap hash gmail-auth < gmail-auth

Configure your sendmail 

Put bellow lines into your sendmail.mc configuration file right above first "MAILER" definition line:
define(`SMART_HOST',`[smtp.gmail.com]')dnl
define(`RELAY_MAILER_ARGS', `TCP $h 587')dnl
define(`ESMTP_MAILER_ARGS', `TCP $h 587')dnl
define(`confAUTH_OPTIONS', `A p')dnl
TRUST_AUTH_MECH(`EXTERNAL DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash -o /etc/mail/gmail-auth.db')dnl
Do not put the above lines on the top of your sendmail.mc configuration file !
In the next step we will need to re-build sendmail's configuration. To do that execute:
# make -C /etc/mail
Reload sendmail service:
/etc/init.d/sendmail reload
and you are done.

Configuration test

Now you can send an email from your command line using mail command:
echo "Just testing my sendmail gmail relay" | mail -s "Sendmail gmail Relay" shankar.h.patel@yahoo.com


SNMP Trap Monitoring in nagios



Introduction

To monitor SNMP supported devices like switches, router, firewall, UPS, Thermometer we need not to check actively the status of device. SNMP supported device provides trap incase of status change as described in MIB file of that device.
 SNMP Trap monitoring
The scenario is about nagios acting as a "manager" or (part of) a Network Management System (NMS), receiving messages from "Trap Agents" - conceptually similar to NSCA agents sending msgs to the NSCA Daemon with interacts with a Nagios passive service (add links), except that the values to be checked and the thresholds that trigger a message are handled with snmp tools.

Installation

To accept and process all traps from snmp supported devices we need to install few packages.
Following is the list of packages:
  • snmpd
  • snmp
  • snmptt
  • libnet-snmp-perl
  • libsnmp-perl
  • libsnmp-python
  • libconfig-inifiles-perl
  • libconfig-inifiles-perl

Installation methods:
All above mentioned packages are available in our repositories we can install it as follows
apt-get install snmpd snmp libnet-snmp-perl libsnmp-perl libsnmp-python libconfig-inifiles-perl libconfig-inifiles-perl snmptt                                                                           
Now it is required to start snmpd service at boot time so we need to add it startup 
insserv snmpd


Configuration

[ Note :  * In configuration part you need to remove those parameters which written with RED color and add  those parameters which written with GREEN colour. ]

vim /etc/snmp/snmpd.conf
  • agentAddress udp:127.0.0.1:161                     ###     (remove this line )
  •  agentAddress  udp:192.168.1.66:161              ###    (add this line)

In  /etc/defaults/snmp update following parameters. 
==>Default TRAPD is disabled
  • TRAPDRUN=no  
 Which is required to enable So enable it by changing "no" to "yes"
  • TRAPDRUN=yes  
  • TRAPDOPTS='-n -Lf /var/log/snmptrapd.log -p /var/run/snmptrapd.pid'
==>Default SNMPD is enabled
  • SNMPDRUN=yes
Which is not required to enable So disable it by changing "yes" to "no" 
  • SNMPDRUN=no

In  /etc/snmp/snmptrapd.conf  update following parameters. Add following lines.
  • disableAuthorization yes
  •  traphandle default /usr/sbin/snmptthandler

In  /etc/snmp/snmptt.ini  update following parameters.
  •  mode = daemon
  •  net_snmp_perl_enable = 1
  •  net_snmp_perl_best_guess = 2
  •  translate_log_trap_oid = 2
  •  remove_backslash_from_quotes = 1
  •  description_mode = 2
  •  date_time_format = %Y-%m-%d %H:%M:%S
  •  unknown_trap_log_enable = 1
  •  DEBUGGING_FILE = /var/log/snmptt.debug
  •  DEBUGGING = 0 
 Update follwoing perameteres if you want to configure smtp with eventdb
  •  db_translate_enterprise = 1
  •  db_unknown_trap_format = 'Unknown Trap: $-*'
  •  mysql_dbi_enable = 1
  •  mysql_dbi_host = <eventdb database host)
  •  mysql_dbi_database = <eventdb database name>
  •  mysql_dbi_table = <eventdb table name for known traps>
  •  mysql_dbi_table_unknown = <eventdb table name for known traps>
  •  mysql_dbi_username = <Username for eventdb database access>
  •  mysql_dbi_password = < Password for eventdb database access>
  •  date_time_format_sql = %Y-%m-%d %H:%M:%S
  •  stat_time_format_sql = %Y-%m-%d %H:%M:%S

Upload Trap definition for devices

Generate trap definition from mibs for all devices by following command and add those file names in /etc/snmp/snmptt.ini


snmpttconvertmib --in=MIBFILE --out=/etc/snmp/snmptt.conf --exec='/usr/local/nagios/libexec/eventhandlers/submit_check_result $A TRAP <STATUS_NO_NAGIOS>' 

For Example:
snmpttconvertmib --in=MIBFILE --out=/etc/snmp/snmptt.conf --exec='/usr/local/nagios/libexec/eventhandlers/submit_check_result $A TRAP 2' 

$A is the hostipaddress can be found in received traps
TRAP is the service defined on host 
2 is the status of service which you can have in nagios

Create Service in NAGIOS

Now create service (like. TRAP) in NAGIOS with following parameters.
EXAMPLE : Service name TRAP 
define service{ 
name trap-service 
register 0 
service_description TRAP 
is_volatile 1 
check_command check-host-alive 
max_check_attempts 1 
normal_check_interval 1 
retry_check_interval 1 
passive_checks_enabled 1 
check_period never
notification_interval 0 
contact_groups admins
check_period 24x7 
max_check_attempts 3 
normal_check_interval 15 
retry_check_interval 5 
active_checks_enabled 1 
passive_checks_enabled 0 
parallelize_check 1 
obsess_over_service 0 
check_freshness 0 
event_handler_enabled 0 
flap_detection_enabled 0 
process_perf_data 1 
retain_status_information 1 
retain_nonstatus_information 1 
notification_interval 60 
notification_period 24x7 
notification_options w,u,c,r 
notifications_enabled 1 
}


###################################

SUBMIT_CHECK_RESULT Plugin For nagios
###################################

#!/bin/bash
########################################################################################################
#Description  : This script will write a command to the Nagios command file to cause Nagios to process a passive service check result. Note: This script is intended to be run on the same host that is running Nagios  Main host and it will send those traps on that host to nagios instances if the trap found for the device configured on any of the nagios instance.
#################################################################s########################################
##Change Log  :
# Arguments:
#  $1 = ipaddress of host that the service is associated with
#  $2 = svc_description (Description of the service)
#  $3 = return_code (An integer that determines the state of the service check, 0=OK, 1=WARNING, 2=CRITICAL, 3=UNKNOWN).
#  $4 = plugin_output (A text string that should be used as the plugin output for the service check)
#
#################################################################s########################################
#binary paths
check_nrpe="/usr/lib/nagios/plugins/check_nrpe"
echocmd="/bin/echo"
db_name="nagios"
db_user="root"
db_passwd="password"

#Nagios CommandFile in which command will be passed to nagios 

CommandFile="/var/lib/nagios/rw/nagios.cmd"

#gets nagios instance and host_name of the source of trap from the ipaddress

host_name=`/usr/bin/mysql --skip-column-names -u $db_user -p$db_passwd $db_name -e"select instance_id,display_name from nagios_hosts where address=\"$1\"" | /usr/bin/expand -t 1`
instance=`echo $host_name|cut -d' ' -f1`
host_name=`echo $host_name|cut -d' ' -f2`

# get the current date/time in seconds since UNIX epoch

datetime=`date +%s`

# check thwe instance and forward nagios command to respected nagios instance

if [ $instance -eq 1 ]
then
        cmdline="$host_name;$2;$3;$4"
#       append the command to the end of the command file
        echo "[$datetime] PROCESS_SERVICE_CHECK_RESULT;$cmdline" >> $CommandFile
else
        print "Unknown. Host not found."
fi

Wednesday, May 1, 2013

Recieving and Sending SNMP TRAP Configuration


SNMP Traps

Sending SNMP traps on a Remote Linux/Windows System 

Download SNMP Trap sender from following link.
http://trapgen.trapreceiver.com/
Now Edit input file and change ip address of remote host where you want to send snmp traps.
Change "-d 192.168.1.1" to your destination host.
and 
execute like as under
root@localhost:~#./trapgen -f input
 AND same time check the syslog file of remote SNMPTRAP manager syst
root@localhost:~# tail -f /var/log/syslog

Receive and handle SNMP traps on a Linux system

Scope

This is a quickstart guide on howto get an Ubuntu or Debian Linux system to listen for SNMP traps, and log them. In SNMP parlance, where' talking about configuring a linux system to be a "manager". We're not talking about how to monitor a linux host by means of SNMP.
We'll cover the basics of how to get it up and running, and provide some pointers to where to go next.

Prerequisites

It is assumed you have a basic understanding of what SNMP is, and are looking for a generic way to collect SNMP-generated messages (a.k.a. "trap's") from 1 or more devices onto a "manager" system, for centralized monitoring.
You might be interested in a generic, linux-based solution because this allows you to connect SNMP-based monitoring to other central monitoring solutions such as a central syslog server and/or a Nagios monitoring system.
It is assumed that you have a working linux system where you want to implement this. The following guide is based on Debian Squeeze and will most likele work as-is on other Debian bases server systems such as Ubuntu. It should also work on other linux sysems, though some details such as names of packages, commands and config files may be different.

Basic Setup

                                       apt-get install snmpd
this installs a number of snmp-related tools, including snmptrapd, which is the one we need to be able to listen for "traps"
snmpbulkget    snmpdf         snmpnetstat    snmptranslate  snmpwalk
snmpbulkwalk   snmpget        snmpset        snmptrap       
snmpconf       snmpgetnext    snmpstatus     snmptrapd      
snmpd          snmpinform     snmptable      snmpusm        
snmpdelta      snmpkey        snmptest       snmpvacm   
snmptrapd does not start up by default, you need to enable it in /etc/defaults/snmp ; it will then be started by /etc/init.d/snmpd (if /etc/snmp/snmptrapd.conf exists
/etc/defaults/snmp

                     TRAPDRUN=yes
we don't need to run snmpd if we only want to recive traps, rather than monitor this system by snmp, so we can disable it:
                     SNMPDRUN=no
Also have a look at the other default options : Debian sets them to "log to syslog" by default, so that traps will be reported in /var/log/syslog. This is OK for us (for now)
snmptrapd will not accept any traps unless they're "authorized" in /etc/snmp/snmptrapd.conf :

# simple test catch-all for any trap that has community=public
authCommunity log,execute,net public
Restart snmpd to get all the changes applied, then check if it works by sending a test trap (from the local host, and from a remote system) :
  • local :
                                                                  snmptrap -v1 -c public localhost .1.3.6.1.6.3.1.1.5.2 0 0 "" "" .1.3.6.1.4.1 s "hello"
  • remote:
                                                                        snmptrap -v1 -c public myserver .1.3.6.1.6.3.1.1.5.2 0 0 "" "" .1.3.6.1.4.1 s "hello" 
result : /var/log/syslog should now show te submitted trap msg :

May 1 12:35:00 localhost snmptrapd[1594]: 2013-05-01 12:35:00 0.0.0.0(via UDP: [127.0.0.1]:51633->[127.0.0.1]) TRAP, SNMP v1, community public#012#011.1.3.6.1.6.3.1.1.5.2 Cold Start Trap (0) Uptime: 0:26:53.33#012#011.1.3.6.1.4.1 = STRING: "hello"
this shows snmptrapd is working: it is capable of receiving snmp traps and handling them (in this case: logging them to syslog)

Further configuration

further config will involve :
  1. define traps on the monitored hosts
  2. add appropriate authorization config for those hosts in /etc/snmp/snmptrapd.conf  see  http://net-snmp.sourceforge.net/docs/man/snmptrapd.conf.html

More on Trap Handling

Syslog

Now you have snmptrapd logs in local syslog file. By configuring SYSLOG server you can integrate your snmp traps in a centralised syslog configuration.

Nagios

You can integrate SNMP trap with nagios to monitor traps using snmp traps and will improve your monitoring. See SNMP Trap monitoring in nagios

Wednesday, April 10, 2013

Nagios Perl Plugin (Service Check did not exit properly) issue


Hi Friends,

In this post I will talk about solving perl plugin related issue. Sometimes we are facing issue when we are creating plugin for nagios in perl language. Sometimes what happens we executing plugin on command prompt then it is working fine and giving properl result but when we are deploying that plugin in to production nagios environment then we are getting error in output.

If we are getting following error in nagios then 
 (Service Check did not exit properly) 
Add following lines in to beginning of the your perl script.

########################################################
use strict;
require 5.6.0;
use lib qw( /usr/lib/nagios/plugins );
use utils qw(%ERRORS $TIMEOUT &print_revision &support &usage);
############################################################################

Friday, March 22, 2013

Play with VIM editor




  • To use mouse in vim editor copy and paste following line in to /etc/vim/vimrc file.Using mouse we can move cursor like we are moving in notepad.

set mouse=a             " Enable mouse usage (all modes)



  • To make variables and system functions colorful add folowing line in to  /etc/vim/vimrc file.
syntax on



  • By default in debian we opens a file in vim editor then vim is not saving our last position of the cursor.
      To enable that write following lines in to the /etc/vim/vimrc file.

if has("autocmd")
  au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
endif



Continue.......

Friday, March 8, 2013

Date command in linux

Hi Friends,

We can convert Unix timestamp to date and date to unix timestamp using date command .

Unix timestamp to date conversion.


root@SHANKAR:~# date -d @1285977600
Fri Oct  1 17:00:00 PDT 2010


Date to Unix timestamp conversion.

root@SHANKAR:~# date -d "2010-10-30" "+%s"
1288422000


Thursday, March 7, 2013

Rebuild your deb package by updating some files

#!/bin/bash

# script name: rebuild-deb.sh
# extracts/rebuilds a deb package
# Put your deb and the script in a new directory and run it from there


echo "This script extracts and rebuilds a deb package. "
echo "It should called from the directory containing the original deb and run as:"
echo "./rebuild-deb.sh"
echo
ls
echo
echo "1.   Extract deb?"
echo "2.   Make deb?"
echo "Enter <1/2> :"
read REPLY
echo

   if [ "$REPLY" = "1" ]; then
ls

DEB=$(ls *.deb 2>&1)
mkdir package
cd ./package
ar -x ../$DEB

   rm debian-binary
   tar xvzf data.tar.gz && rm data.tar.gz
   mkdir DEBIAN && cd DEBIAN
   tar xvzf ../control.tar.gz && rm ../control.tar.gz

   echo "Extracted to './package'"
   echo "Make your changes. Make sure to update control and md5sum files"   
   elif [ "$REPLY" = "2" ]; then

PACKAGE=$(cat 'package/DEBIAN/control'|grep Package|sed 's|Package: ||')
VERSION=$(cat 'package/DEBIAN/control'|grep Version|sed 's|Version: ||')
ARCH=$(cat 'package/DEBIAN/control'|grep Architecture|sed 's|Architecture: ||')
fakeroot dpkg-deb -b package $PACKAGE\_$VERSION\_$ARCH.deb
   
   echo "Done"
fi

Tuesday, February 26, 2013

TCPDUMP NETWORK TRAFFIC



    tcpdump is the premier network analysis tool for information securityprofessionals. Having a solid grasp of this über-powerful application is mandatory for anyone desiring a thorough understanding of TCP/IP. Many prefer to use higher level analysis tools such as Ethereal Wireshark, but I believe this to usually be a mistake.

    In a discipline so dependent on a true understanding of concepts vs. rote learning, it's important to stay fluent in the underlying mechanics of the TCP/IP suite. A thorough grasp of these protocols allows one to troubleshoot at a level far beyond the average analyst, but mastery of the protocols is only possible through continued exposure to them.

    When using a tool that displays network traffic a more natural (raw) way the burden of analysis is placed directly on the human rather than the application. This approach cultivates continued and elevated understanding of the TCP/IP suite, and for this reason I strongly advocate using tcpdump instead of other tools whenever possible.


    15:31:34.079416 IP (tos 0x0, ttl  64, id 20244, offset 0, flags [DF], 
    proto: TCP (6), length: 60) source.35970 > dest.80: S, cksum 0x0ac1 
    (correct), 2647022145:2647022145(0) win 5840 0x0000:  4500 003c 4f14 4000 
    4006 7417 0afb 0257  E..  0x0010:  4815 222a 8c82 0050 9dc6 5a41 0000 
    0000  H."*...P..ZA....  0x0020:  a002 16d0 0ac1 0000 0204 05b4 
    0402 080a  ................  0x0030:  14b4 1555 0000 0000 0103 0302

    Options

    Below are a few options (with examples) that will help you greatly when working with the tool. They're easy to forget and/or confuse with other types of filters, i.e. ethereal, so hopefully this page can serve as a reference for you, as it does me.
    First off, I like to add a few options to the tcpdump command itself, depending on what I'm looking at. The first of these is -n, which requests that names are not resolved, resulting in the IPs themselves always being displayed. The second is -X, which displays both hex and ascii content within the packet. The final one is -S, which changes the display of sequence numbers to absolute rather than relative. The idea there is that you can't see weirdness in the sequence numbers if they're being hidden from you. Remember, the advantage of using tcpdump vs. another tool is getting manual interaction with the packets.
    It's also important to note that tcpdump only takes the first 68 96 bytes of data from a packet by default. If you would like to look at more, add the -s numberoption to the mix, where number is the number of bytes you want to capture. I recommend using 0 (zero) for a snaplength, which gets everything. Here's a short list of the options I use most:
    • -i any : Listen on all interfaces just to see if you're seeing any traffic.
    • -n : Don't resolve hostnames.
    • -nn : Don't resolve hostnames or port names.
    • -X : Show the packet's contents in both hex and ASCII.
    • -XX : Same as -X, but also shows the ethernet header.
    • -v, -vv, -vvv : Increase the amount of packet information you get back.
    • -c : Only get x number of packets and then stop.
    • -s : Define the snaplength (size) of the capture in bytes. Use -s0 to get everything, unless you are intentionally capturing less.
    • -S : Print absolute sequence numbers.
    • -e : Get the ethernet header as well.
    • -q : Show less protocol information.
    • -E : Decrypt IPSEC traffic by providing an encryption key.
    [ The default snaplength as of tcpdump 4.0 has changed from 68 bytes to 96 bytes. While this will give you more of a packet to see, it still won't get everything. Use -s 1514 to get full coverage ]

    Basic Usage

    So, based on the kind of traffic I'm looking for, I use a different combination of options to tcpdump, as can be seen below:
    1. Basic communication // see the basics without many options
      tcpdump -nS

    2. Basic communication (very verbose) // see a good amount of traffic, with verbosity and no name help
      tcpdump -nnvvS

    3. A deeper look at the traffic // adds -X for payload but doesn't grab any more of the packet
      tcpdump -nnvvXS

    4. Heavy packet viewing // the final "s" increases the snaplength, grabbing the whole packet
      tcpdump -nnvvXSs 1514
    Here's a capture of exactly two (-c2ICMP packets (a ping and pong) using some of the options described above. Notice how much we see about each packet.
    hermes root # tcpdump -nnvXSs 0 -c2 icmp
    tcpdump: listening on eth0, link-type EN10MB (Ethernet), 23:11:10.370321 IP 
    (tos 0x20, ttl  48, id 34859, offset 0, flags [none], length: 84) 
    69.254.213.43 > 72.21.34.42: icmp 64: echo request seq 0
    
            0x0000:  4520 0054 882b 0000 3001 7cf5 45fe d52b  E..T.+..0.|.E..+
            0x0010:  4815 222a 0800 3530 272a 0000 25ff d744  H."*..50'*..%..D
            0x0020:  ae5e 0500 0809 0a0b 0c0d 0e0f 1011 1213  .^..............
            0x0030:  1415 1617 1819 1a1b 1c1d 1e1f 2021 2223  .............!"#
            0x0040:  2425 2627 2829 2a2b 2c2d 2e2f 3031 3233  $%&'()*+,-./0123
            0x0050:  3435 3637                                4567
    23:11:10.370344 IP (tos 0x20, ttl  64, id 35612, offset 0, flags [none], 
    length: 84) 72.21.34.42 > 69.254.213.43: icmp 64: echo reply seq 0
            0x0000:  4520 0054 8b1c 0000 4001 6a04 4815 222a  E..T....@.j.H."*
            0x0010:  45fe d52b 0000 3d30 272a 0000 25ff d744  E..+..=0'*..%..D
            0x0020:  ae5e 0500 0809 0a0b 0c0d 0e0f 1011 1213  .^..............
            0x0030:  1415 1617 1819 1a1b 1c1d 1e1f 2021 2223  .............!"#
            0x0040:  2425 2627 2829 2a2b 2c2d 2e2f 3031 3233  $%&'()*+,-./0123
            0x0050:  3435 3637                                4567
    2 packets captured
    2 packets received by filter
    0 packets dropped by kernel
    hermes root # 
    

    Common Syntax

    Expressions allow you to trim out various types of traffic and find exactly what you're looking for. Mastering the expressions and learning to combine them creatively is what makes one truly powerful with tcpdump. There are three main types of expression: typedir, and proto.
    Type options are hostnet, and port. Direction is indicated by dir, and there you can have srcdstsrc or dst, and src and dst. Here are a few that you should definitely be comfortable with:
    • host // look for traffic based on IP address (also works with hostname if you're not using -n)
      tcpdump host 1.2.3.4

    • srcdst // find traffic from only a source or destination (eliminates one side of a hostconversation)
      tcpdump src 2.3.4.5
      tcpdump dst 3.4.5.6

    • net // capture an entire network using CIDR notation
      tcpdump net 1.2.3.0/24

    • proto // works for tcp, udp, and icmp. Note that you don't have to type proto
      tcpdump icmp

    • port // see only traffic to or from a certain port
      tcpdump port 3389

    • src, dst port // filter based on the source or destination port
      tcpdump src port 1025
      tcpdump dst port 389

    • src/dst, port, protocol // combine all three
      tcpdump src port 1025 and tcp
      tcpdump udp and src port 53
    You also have the option to filter by a range of ports instead of declaring them individually, and to only see packets that are above or below a certain size.
    • Port Ranges // see traffic to any port in a range
      tcpdump portrange 21-23

    • Packet Size Filter // only see packets below or above a certain size (in bytes)
      tcpdump less 32
      tcpdump greater 128
    • [ You can use the symbols for less thangreater than, and less than or equalgreater than or equal signs as well. ]
      // filtering for size using symbols
      tcpdump > 32
      tcpdump <= 128

    Writing to a File

    tcpdump allows you to send what you're capturing to a file for later use using the-w option, and then to read it back using the -r option. This is an excellent way to capture raw traffic and then run it through various tools later.
    The traffic captured in this way is stored in tcpdump format, which is pretty much universal in the network analysis space. This means it can be read in by all sorts of tools, including WiresharkSnort, etc.

    Capture all Port 80 Traffic to a File

    tcpdump -s 1514 port 80 -w capture_file
    Then, at some point in the future, you can then read the traffic back in like so:

    Read Captured Traffic back into tcpdump

    tcpdump -r capture_file

    Getting Creative

    Expressions are nice, but the real magic of tcpdump comes from the ability tocombine them in creative ways in order to isolate exactly what you're looking for. There are three ways to do combinations, and if you've studied computers at all they'll be pretty familar to you:
    1. AND
      and or &&
    2. OR
      or or ||
    3. EXCEPT
      not or !

    More Examples

    # TCP traffic from 10.5.2.3 destined for port 3389
    tcpdump -nnvvS and src 10.5.2.3 and dst port 3389
    # Traffic originating from the 192.168 network headed for the 10 or 172.16 networks
    tcpdump -nvX src net 192.168.0.0/16 and dst net 10.0.0.0/8 or 172.16.0.0/16
    # Non-ICMP traffic destined for 192.168.0.2 from the 172.16 network
    tcpdump -nvvXSs 1514 dst 192.168.0.2 and src net and not icmp
    # Traffic originating from Mars or Pluto that isn't to the SSH port
    tcpdump -vv src mars and not dst port 22
    As you can see, you can build queries to find just about anything you need. The key is to first figure out precisely what you're looking for and then to build the syntax to isolate that specific type of traffic.

    Grouping

    Also keep in mind that when you're building complex queries you might have to group your options using single quotes. Single quotes are used in order to telltcpdump to ignore certain special characters -- in this case the "( )" brackets. This same technique can be used to group using other expressions such as hostport,net, etc. Take a look at the command below:
    # Traffic that's from 10.0.2.4 AND destined for ports 3389 or 22(incorrect)
    tcpdump src 10.0.2.4 and (dst port 3389 or 22)
    If you tried to run this otherwise very useful command, you'd get an error because of the parenthesis. You can either fix this by escaping the parenthesis (putting a \ before each one), or by putting the entire command within single quotes:
    # Traffic that's from 10.0.2.4 AND destined for ports 3389 or 22 (correct)
    tcpdump 'src 10.0.2.4 and (dst port 3389 or 22)'

    Advanced

    You can also filter based on specific portions of a packet, as well as combine multiple conditions into groups. The former is useful when looking for only SYNs or RSTs, for example, and the latter for even more advanced traffic isolation.
    [ Hint: An anagram for the TCP flags: Unskilled Attackers Pester Real SecurityFolk ]
    Show me all URGENT (URG) packets...
    # tcpdump 'tcp[13] & 32!=0'
    Show me all ACKNOWLEDGE (ACK) packets...
    # tcpdump 'tcp[13] & 16!=0'
    Show me all PUSH (PSH) packets...
    # tcpdump 'tcp[13] & 8!=0'
    Show me all RESET (RST) packets...
    # tcpdump 'tcp[13] & 4!=0'
    Show me all SYNCHRONIZE (SYN) packets...
    # tcpdump 'tcp[13] & 2!=0'
    Show me all FINISH (FIN) packets...
    # tcpdump 'tcp[13] & 1!=0'
    Show me all SYNCHRONIZE/ACKNOWLEDGE (SYNACK) packets...
    # tcpdump 'tcp[13]=18'
    [ Note: Only the PSH, RST, SYN, and FIN flags are displayed in tcpdump's flag field output. URGs and ACKs are displayed, but they are shown elsewhere in the output rather than in the flags field ]
    Keep in mind the reasons these filters work. The filters above find these various packets because tcp[13] looks at offset 13 in the TCP header, the number represents the location within the byte, and the !=0 means that the flag in question is set to 1, i.e. it's on.
    As with most powerful tools, however, there are multiple ways to do things. The example below shows another way to capture packets with specific TCP flags set.
    Capture TCP Flags Using the tcpflags Option...
    # tcpdump 'tcp[tcpflags] & & tcp-syn != 0'

    Specialized Traffic

    Finally, there are a few quick recipes you'll want to remember for catching specific and specialized traffic, such as IPv6 and malformed/likely-malicious packets.
    IPv6 traffic
    # tcpdump ip6
    Packets with both the RST and SYN flags set (why?)
    # tcpdump 'tcp[13] = 6'
    Traffic with the 'Evil Bit' Set
    # tcpdump 'ip[6] & 128 != 0'

    Conclusion

    Well, this primer should get you going strong, but the man page should always be handy for the most advanced and one-off usage scenarios. I truly hope this has been useful to you, and feel free to contact me if you have any questions. ::

    Additional Resources and References


    ☐ If you enjoyed this content, consider connecting via RSS or Twitter.