Thursday, 16 August 2012

7 Linux read command examples for Shell scripting

                              Read Command Examples

read command is useful in scripts when reading an input from user. This read command is used when the script want to interact with user for his inputs.

read command syntax
read VARIABLE



Example1:Read a value from user input.
read VAR1

To display this value we have to use echo command.
echo $VAR1

Example2: Reading two words/variable/values at a time.
read VAR1 VAR2

Example3: Reading multiple values at a time.
read VAR1 VAR2 VAR3 VAR4

Example4: Read values in to an Array
read VAR1
ARR1=(VAR1)

to display first value in array use below command
echo ${ARR1[0]}

Example5: Read values from a command
read VAR1 VAR2 VAR3 << ( echo surendra kumar anne )
echo "Enter values are $VAR1 $VAR2 $VAR3"

Example6: Read user input and give some info to user what he have to give. For this use -p option to display some info when reading value.
read -p "Please enter 1 to 10 numbers: " VAL1

Note: You no need to echo command to display information to user, you can achieve that one using read -p option.

Example7: Read have inbuilt variable called REPLY. this is system variable which stores read value in to $REPLY.
read -p "Please enter a value"
echo "Enter value is $REPLY"



Linux/Unix sort command examples

This is a small tutorial on how to use sort command to soft a file. Sorting is very much useful when dealing with DB files, CSV, xls, log files in fact a text file to. By default sort command will sort according to alpha-bates. First sort tries to sort according to single character, if it finds the first character same in two lines, then it move on to sort second character. Suppose I have a following word list in a file

cat filename.txt

abc
cde
hij
klm
kle
ble

This will be sorted first with first char. When it finds both the char same in this example klm and kle start with same characters, so it tries to sort with third character which is different in them. The output of sort as below
sort filename.txt

abc

ble
cde
hij
kle
klm

Sort command syntax
sort filename.txt

Example1: Sort a given file according to alpha-bates
sort filename.txt

Example2: I have a file with host names in third column, how can i sort them according to this column?. Use -k for sorting according to column
sort -k3 filename.txt

The above command will sort according to third column.

Example3:I want to sort /etc/passwd file according to home directories but my sort is not working how can i sort them?. by default sort will take space/tabs as field separators. But in /etc/passwd file the field separator is : so we have to mention this one when sorting a file. This can be done with -t option
sort -t: -k6 /etc/passwd

Example4: I want to sort according to number, suppose i want to sort /etc/passwd file according to UID, use -n option to do that.
sort -n -t: -k3 /etc/passwd

Note: For example with out -n option sort will put 10 before 3 when it find this values, by default it will sort only first numerical char.

Example5: Sort the file and reverse the order
sort -r filename.txt

Example6: Some times its required to sort the file and display only uniq values.
sort -u filename

Note: though the values on other field are different this will not consider by -u option.

Example7: I want to sort a file according to my requirement and save it to a different file. Use -o option to save the sorted output to a file.
sort -o temp.txt filename.txt

You can now mix above options to get your sorting work done.


Linux Bash Shell auto completion and Wild cards


Bash is one of the best shell available in Linuix and Unix OS. This is due to its capabilities such as

history
shortcuts

Auto completion and file wild cards

command chaining

We already discussed about history and shortcuts in some older posts. Today we will see how we can use BASH Shell to do auto complete and file wild-cards.

Auto completion

When we are at prompt we can press press TAB to autocomplete commands, chang directories, removing files/directories etc. We will see these as examples below for better understanding.

Example1: Execute lsdiff command to see if any files are modified by using auto complete without executing entire command.

ls<press tab>

Below commands are displayed to see which commands starts with ls

ls lsb_release lshw lsof lspgpot
lsattr lscpu lsinitramfs lspci lss16toppm
lsblk lsdiff lsmod lspcmcia lsusb

Now if you type d then press <tab> it will complete the lsdiff command as shown below because there is no other command which start with lsd name.

lsdiff

Example2: Directory structure autocompletion. Suppose I want to open smb.conf which is located in /etc/samba folder we can open this by just typing /et<tab>/sa<tab>/sm<tab> to open /etc/samba/smb.conf file.

vi /et<tab>

vi /etc/sa<tab>

vi /etc/samba/sm<tab>

vi /etc/samba/smb.conf

Wildcards


Example3: Bash support wildcards. Delete all the files which are .sh file extension by using *.

rm -rf *.sh

Example4: I want to list all the files which starts with file and ends with .txt and having one character in between them.

ls -l file?.txt

This command will list all the files such as file1.txt, filea.txt, filez.txt etc.

Example5: List all the files which ends with a or b or c and start with file.

ls -l file[abc]

This will list filea, fileb and filec

Example6: List all the files which end with a to z, how can I do that?

ls -l file[a-z]

lists the files from filea, fileb to filec.


Learn Linux/Unix Find command with 60+ Practical examples Part-II


Advanced finds command usages

Playing with basics find command options

For basic Linux Find command usage please click here Example31:find all the files which are with more than size 100MB and less than 1GB and the owner of the file is xyz and the file name is Adda.txt in /red folder
find /red –size +100M –size -1G –user xyz –iname adda.txt

Example32:find all the files with SGID for the group sales and with size exactly 100MB with file name as pass.txt under /opt
find /opt –size 100M –group sales –perm g+s –name pass.txt


Linux find command AND Operator

By default find command will use AND option between two options. No need of mentioning any option. For example see below examples.

Example33: find all the files which are more than 100MB and less than 1GB in size.
find / -size +100M –size -1G

or
find / -size +100M -a -size -1G

Like above we can combine many options and your find command use AND operator by default no need of mentioning -a option.


Search for files and execute commands on Found files


Caution: Be careful when using -exec option which you are going to learn below. This is very dangerous option which can change/remove anything if don’t use wisely. There are some instances when you want to execute commands on the found files with find command. -exec is the option used in find command to execute shell commands directly on found files. Let’s discuss this with a basic example.

Example34:find a file with passwd.txt in /var folder and long list this file for checking file properties.
find /var –iname passwd.txt –exec ls –l {} \;

Let me explain above command. Up to find /var –iname passwd.txt, this command you are aware. This command will search for passwd.txt file in /var folder and give the paths and file names where this file is located.

-exec: with this option we are saying to find command to execute a command(here its ls -l) followed by this option

{} –This is used as input to the command which we get as files/folders from find command output.

\; –This indicates that find command is completed.

Actually ; is a command chaining capability and it’s a special character. In order to negate this special character we are using \ before;.

Example35: Find all the files with name test.txt in /mnt and change the ownership of the files from Surendra to Narendra
find /mnt –user surendra –name test.txt –exec chown narendra: {} \;

-exec command {} \; –for executing a command on find files -inum -For finding a file with inode number

Example36:Find all the files with name test.sh in /abc folder and then grep if for word is there in that file or not
find /abc –name test.sh –exec grep ‘for’ {} \;

chmod, grep, ls, rm, mv, cp,md5sum

Example37: Find all the files with name xyz.txt owned by Surendra in /var/ftp/pub and change the permissions to 775 to them.
find /var/ftp –user surendra –name xyz.txt –exec chmod 775 {} \;

Example 38:Find all the files with name temp.txt in /xyz folder and backup then compress them to send it for saving
Find /xyz –name xyz.txt –exec tar xvfz temp.tar.gz {} \;

Example39:Find files with name abc.txt in /home directory and take backup of each file before modifying it.
find /home –name abc.txt –exec cp {} {}.bkf \;

This above command will create files with .bkf extension whenever it finds abc.txt file.

Example40:Find files which are more than 1GB and not accessed for the past 6 months and delete them.
find / -size +1G -mtime +180 –exec rm –rf {} \;

Example41:Find all the files with executable permissions and display their checksum value
find / -perm /a=x -exec md5sum {} \;

Example42:find all the files with name abc.txt and owner as surendra then move them to /opt folder
find / -user surendra -name abc.txt -exec mv {} /opt/ \;

There are many other commands you can try your own. Some other commands which can work with –exec option is mv, md5sum etc.


Find command with multiple -exec option

Find command is capable of using multiple times using the same option(We seen it for finding files which are more than 200M and less then 1GB). In our previous examples we used –size to mention the size between two sizes. Similarly we can use –exec command multiple times.

Example43:Find files with abc.txt name in /opt directory change the owner permissions from Surendra to Narendra and change the permissions to 775
find /opt –user Surendra –name abc.txt –exec chown Narendra: {} \; -exec chmod 775 {} \;

Note: We can use this multiple –exec option more than two times.


Search for multiple files

Till this point if you observe we just search for single file. But sometimes there is a requirement to search for multiple files with single find command to save some valuable time. The following two examples we will see how to do that. Example44: Find all the commands which ends with .sh file extension in /opt folder
find /opt –name *.sh

Note: Sometimes the above command will not work properly because your shell will try to parse the * before find command is executed. So you have made * as not a special character or wild character. In order to understand more about this type of characters you have to learn RegExp. Please find our other posts on Basic RegExp and Advanced RegExp.

Example45:
find /opt –name \*.sh

Or
find /opt –name “*.sh”

Note: These two will work, because you negated your shell parsing * wild character.

Example46:Search for all the files which start with abc and ends with different extension in /opt folder
find /opt –name abc.\*

Example47:Search for files which start with red and ends with many names such as redhat, redtop, redsoap etc.
find / -name red\*

Example 48:How about search for files which always end with dump.
find / -name \*dump


Search for files in multiple locations


Search multiple locations using single find command We can accomplish searching multiple folders with single command without any options. Lets see below command.

Example49: Find abc.txt file in /opt and /var folder at a time
find /opt /var –name abc.txt

The above command will search in only two locations i.e. in /opt and /var Search multiple locations but not in particular location. Example50:Search in entire system expect /proc folder
find / -path /proc -prune -name cpuinfo

Let me explain above command. The -path variable to define the path of a location. And -prune combined with -path will say not to descend in to the mention path /proc

Example51:Search for abc.txt in /opt and /var expect in /var/tmp folder
find /opt /var -path /var/tmp -prune -name abc.txt

Find command OR –o operator


Find have OR operator to do multiple file searches at a time.

Example52:I want to search for abc.txt and hash.c file at a time. This can be achieved by using -o operator
find / -name abc.txt -o -name hash.c

Here when ever find command sees -o it just or the options on its left and right hand side.

Example53:How about i want to find two directories say opt and var how can i find them?
find / -type d - name opt -o -type d -name var

This above command may trow error. Try below syntax
find / -type d \( -name opt -o -name var \)

let me explain above command. () are used to combine two or more options in to one. So \( -name opt -o -name var \) are combined in to single option and are treated as directories as we given -type is d. We will see more about this operator in our coming post on find command advanced usage.


Linux find command ! Negation operator


Example54: Negation operator is useful for negating a search team. for example we want to find all the files with name abc.txt which don’t have 755 permissions
find . -type f ! -perm 755 -name abc.txt
In above command -perm 755 is negated so that all the files with name abc.txt is displayed expect file abc.txt with permissions 755.
Stay tuned our next tutorial on find command to do following things
1)Dont search in .cvs folder
2)Search for files with out owner
3)Search for zero size files
4)Search for files and don’t show me permission denied error
5)Searching in hidden folders
6)Creating alias for frequently used find commands
7)Search for files with spaces
8)Search for files and grep for multiple pattern in one find command.
9) Miscellaneous examples




Learn Linux/Unix Find command with 60+ Practical examples Part-I

60+ Practical find commands examples with explanation

find command is very much powerful command which can do good work when its needed to find files with conditions. Find command is useful when finding files with complex requirement such as size, permissions etc. Suppose we want to find a file which is a regular file and its size is more than 1GB and its accessed more than 90 days back and its owner is none and then delete it. This entire requirement is done with single command without even writing a shell script. Let’s see how we can use find command from basics to advanced in this post.

find command can find files according to
1) File names

2) File types

3) Permissions

4) Owners

5) Modified date and time

6) Size

Advanced finds command usages
1) Mix of all the above things
2) AND operator
3) Search for files and execute commands on them
a) chown, chmod, grep, ls, rm, mv, cp,md5sum

4) Multiple execute commands

5) Search for multiple files
a) With different files with same extension
b) Same file With different extensions
6) Search in multiple locations
a) Exclude one location
b) Search in multiple locations

7) OR( –o ) operator
8) ! Negation operator
9) Linux find command with Regular Expressions
10) Linux find commnd practical examples


Basics of file/folders search using find command
find files with name

Syntax:

find path options filename

Example1: find all the files in /home with name test.txt. Here –name is used to specify the filename.
find /home –name test.txt

Example2: find the files whose name is test.txt and in present working directory
find . –name test.txt

Or
find –name test.txt

Example3: find all the files whose name contains both capital letters and small letters in it.
find /home –iname test.txt

-iname option is used to mention ignore the case sensitivity of a file.

Search for files depending on their File types:

Example4: Search for only directories whose name is var in / directory
find / -type d –name var

Example5: Search for an mp3 files whose name is temp.mp3
find / -type f –name temp.mp3

Below are the file types supported by find command, to know more about file types in Linux/Unix please have a look at our other post on File types.Sl.no Symbol Type
1 f Regular file
2 d Directory file
3 b Block file
4 c Character file
5 p Pipe file
6 l Symbolic link file
7 s Socket file.

Search for files depending on their Permissions

Example6:Search for a file name test.txt and its permissions are 775 in a given box
find / -perm 775 –name test.txt

Example7: How about searcing files with SUID bit set and file permissions are 755?
find / -perm 4755

Example8:How can i find SGID bit set files with 644 permissions?
find / -perm 2644

Example9: How can i find Sticky bit set files in my system with permissions 551?
find / -perm 1551

Example10:Search for all the files whose SUID bit is set
find / -perm /u=s

Example11: Search for all the files whose SGID bit is set
find / -perm /g+s

Note: We can use = or + interchangeably to check if a permissions is set or not as shown in above two examples.

Example12: Search for all the files whose StickyBit is set
find / -perm /o=t

Example13: Search for all the files whose owener permissions is read only.
find / -perm /u=r

Example14:Search for all the files which have user, group and others with executable permissions
find / -perm /a=x

To know about more on the permissions you have look at our other posts on chmod command.

Search according to Owners and group owners.

Example15: Search for all the files with name test.txt and the owner of this file is Surendra
find / -user Surendra –name test.txt

Example16: find all the files whos name is test.txt and owned by a group called redcluster
find / -group redcluster –name test.txt

to know more about owners and groups you have to look at our previous post on chown command.

Search according to Modified date and time.


Below is the matrix which give you brief idea on how to search according to modified date, accessed date etc.Sl. No -ctime -mtime -atime
+90 File status changed more then 90 days back Modified more than 90 days back Accessed more than 90 days back
90 File status changed exactly 90 days back Modified exactly 90 days back Accessed exactly 90 days back
-90 File status changed less than 90 days Modified less than 90 days Accessed less than 90 days back


Example17: Search for a file: test.txt whose file status is changed more than 90 days back
find / -ctime +90 –name test.txt

Example18: Search for all the files which are modified exactly 90 days back
find / -mtime 90

Example19: Search for all the files with name test.txt which is accessed less than 90 days
find / -atime -90

Example20: find all the files which are modified more than 90 days back and less than 180 days
find / -mtime +90 –mtime -180

Below is the matrix which gives you brief idea on how to search according to modified time, accessed time in minutes etc.Sl. No -cmin -mmin -amin
+30 File status changed more then 30 mins back Modified more than 30 mins back Accessed more than 30 mins back
30 File status changed exactly 30 mins back Modified exactly 30 days back Accessed exactly 30 mins back
-30 File status changed less than 30 mins Modified less than 30 mins Accessed less than 30 mins




Example21: find all the files changed less than 30mins
find / -cmin -30

Example22: find all the files modified exactly 30 mins back
find / -mmin 30

Example23: find all the files accessed more than 30 mins back
find / -amin +30

Example24: find all the files which are modified more than 5mins back and less than 25mins
find / -mmin +5 –mmin -25

Example25: I have new file called test.txt which is just created, now I want to get all the files which are created later this file creation.
find / -newer test.txt


Search for files/folders depending on the size with –size option


Sl.no +10 10 -10
c for bytes(8 bits) Search for files more than 10c size Search for files exactly 10b size Search for files less than 10b size
k for kilobytes Search for files more than 10k size Search for files exactly 10k size Search for files less than 10k size
M for Megabytes Search for files more than 10M size Search for files exactly 10M size Search for files less than 10M size
G for Gigabytes Search for files more than 10G size Search for files exactly 10G size Search for files less than 10G size




Example26: Search for files whose size is more than 10bytes
find / -size +10c

Example27: Search for files which are exactly 10kb in /opt folder
find /opt –size 10k

Example28: Search for files which are less than 10MB in /var folder
find /var –size -10M

Example29: Search for files which are more than 1GB size in /usr folder
find /usr –size +1G

Example30: find all the empty files in my system
find / -size 0k

In next post on find command we will see more depth in to this find command. Please click here for more advanced Linux Find command usage



BASH_History_Capabalities


Though this is a basic topic known to many of you, But I want to share so that some one will get new things.
BASH(Broune Again Shell) is the default shell in Linux, which will act as a communicator between Kernel and user. Its having so many capabilities such as

a.Short cuts
b.Command chaining
c.History

As I mention we will see all about BASH shell history capabilities here. And I have divided this BASH capabilities in to three parts like basics, medium and advanced.

Basic capabilities of BASH History:
1.To see all the commands what we executed previously
#history

2.To check the history size of your system
#echo $HISTSIZE

3.To check where is your history file, which stores all your previous commands
#echo $HISTFILE

4.To browse history.
Just press up/down arrow to browse history

5.To see all the commands which have particular word
#history | grep string

Example:
#history | grep cd

Medium capabilities of Bash history:
6.Some times browsing history is very tedious job and some times we are executing some big big commands so there is a capability in Bash to over come this ie search-i-reverse. For doing this press ctrl+r and type a string in previous command which you want to execute.

Lets see it with an example
root@krishna-laptop:~#(reverse-i-search)`se’: service winbind restart
if you see above I just pressed ctrl+r and then started to type se, it is showing service winbind restart command, so I no need to type entire command and I have to justent press enter
root@krishna-laptop:~# service winbind restart
* Stopping the Winbind daemon winbind [ OK ]
* Starting the Winbind daemon winbind [ OK ]
root@krishna-laptop:~#

7.Changing the size of history. Most of the Linux machines by default it can store up to 500 previously executed commands. Some people likes to change it to some value, here i want to keep my previously executed 3000 commands.
#HISTSIZE=3000

8.to execute previous command
#!!
or
!-1

9.To execute 25 command in bash history
#!25

10.To execute a recent command which start with a string
#!string

11.To clear all the history
#HISTSIZE=0
or
#history –c

12.In Linux when we execute some command there will be no output of the command, for example useradd or mount -a commands will not give you output saying that command is executed successfully or not at that time we can used the below command to see whether the previous command is executed successfully or not
#echo $?
If the out put of the above command is “0″, that indicates previous command executed successfully, for any other values the command is not executed successfully(total there are 256 values, 0-255).

Advanced capabilities of Bash history:
History Modifiersreferences:
http://linux.about.com/od/commands/l/blcmdl3_history.htm
http://www.linuxtopia.org/online_books/redhat_linux_debugging_with_gdb/using-history-interactively.html
http://docstore.mik.ua/orelly/linux/lnut/ch08_06.htm
http://www.catonmat.net/blog/the-definitive-guide-to-bash-command-line-history/


RHEL 4 vs RHEL 5


Major differences between RHEL4 & RHEL5
1.Virtualization added in RHEL5
2.Package installation method changed to YUM(Yellow-dog Updater Modifier) in RHEL5
3.Redhat Clustring added in RHEL5
4.RHEL5 now supports unlimited RAM and Hard disk
5.Now varients in RHEL5 are
* Red Hat Enterprise Linux Advanced Platform (former AS)
* Red Hat Enterprise Linux (former ES) (limited to 2 CPU-s)
* Red Hat Enterprise Linux Desktop with Workstation and Multi-OS option
* Red Hat Enterprise Linux Desktop with Workstation option (former WS)
* Red Hat Enterprise Linux Desktop with Multi-OS option
* Red Hat Enterprise Linux Desktop (former Desktop)

Where as in RHEL4
* Red Hat Enterprise Linux AS for mission-critical/enterprise computer systems
* Red Hat Enterprise Linux ES for supported network servers
* Red Hat Enterprise Linux WS for technical power-user desktops or high- performance computing
* Red Hat Desktop ΓÇô for multiple deployments of single-user desktops

Minor differences
1.Newer kernel(2.6.18)
2.Newer softwares packages
3.Office removed from Server edition
4.More Hardware support
5.By default netconfig command is not there, we have to install it manually
6.SELinux improved a lot in RHEL5
7.We have to provide key at the time of installation so that we can choose to install most of the packages such as Clustring/Virtualization.
8.Some of the commands changed like in LVM

References
https://www.redhat.com/docs/manuals/enterprise/RHEL-5-manual/release-notes/package-changes.html
http://en.wikipedia.org/wiki/Red_Hat_Enterprise_Linux



Difference Between RHEL 5.x and RHEL 6


Red Hat Enterprise Linux (RHEL) is an open source, linux based operating system developed by Red Hat Inc. It is popularly used as server operating system. Its first release was the RHEl 2.1 which was released in the year 2002. After the first version of RHEL, new and better versions quickly followed like RHEL 3,4,5,etc. Now in 2010, the newest version has been released. It is RHEL 6. Now in this post lets discuss the main advantages of RHEL6 over RHEL5.

RHEL6 being the latest release obviously have a lot of new features.
The advantages are:

• A new level of virtualisation
RHEL6 introduces the use of KVM (Kernel-based Virtual Machine) as its hypervisor. In the earlier releases Xen hypervisor was used. The main advantage of KVM is that a new kernel should not be installed like in Xen. It also supports the installation of many virtual operating systems like Windows, Linux, Solaris,etc. It is easy to manage.
• Ext4 is made the default filesystem
Ext4 has many new advantages than Ext3 which is used in earlier versions of RHEL. Ext4 is comparatively faster and easy to manage. It supports supports up to 100TB with the addition of Scalable Filesystem Add-one.

• Improved level of Security
RHEL6 has advanced level of security. SELinux (Security Enhanced Linux) features are improved and a new set of SELinux rules has been added to provide security to virtual machines from hackers and attackers. This new feature is called SVirt.
• New Networking Features
RHEL6 is released with improved and new networking features. It supportsIPv6. It uses NFSv4 (Network File Transfer) for the sharing of files in the network rather than NFSv3. It also supports iSCSI (internet Small Computer System Interface) partitions. The network manager in RHEL6 supports Wi-Fi capabilities.

• Use of Drivers
RHEL6 has drivers for speeding up operations under KVM, VMware and Xen.

• Increase in the support period provided by Red Hat.
RHEL6 has a long period of support provided by Redhat. It provides updates for 7 years and also extra 3 years of service as paid service. Therefore it means that its period of support is twice the period of support provided by other linux distributors like Ubuntu, Debian, etc.

• Improvements of minor updates
Red Hat releases minor versions such as 6.1, 6.2. These minor versions are the accumulated updates of the major version. The new minor releases will not only contain bug fixes but will also have major changes and new features.
RHEL6 has been released with many new feature which make RHEL6 more useful than RHEL5. RHEL6 is somewhat similar to Fedora 12, so the Fedora users should find RHEL6 familiar. Due to all these reasons the release of RHEL6 is a huge step of advancement and also an achievement in the field of open source.


Friday, 10 August 2012

Linux Securirty Notes 15: IPTables 4 :IPTables Statefullness

IPTables Statefullness(-m state --state):
IPTables provide state fullness. The state full firewall is considered more secure than stateless firewall because of their connection tracking capability and their ability to determine whether or not the session is new,related, invalid or established. Based on this criteria we can create more powerfull rules.
State Module:
# rpm -ql iptables | grep -i conntrack

/lib/iptables/libipt_conntrack.so



This is the module that makes IPTables to behave as statefull. It is applicable for all the protocols (TCP/UDP/ICMP)
The states are:
NEW (The First SYN traffic)
ESTABLISHED
RELATED(SESSION/STATE)
INVALID
When a user creates a TCP/UDP based session IPTables can follow the connection. Here IPTable will keep a track with SYN, ACK-SYN, ACK and labelled with NEW(for SYN), ESTABLISHED or RELATED (For all other subsequent connections).

Example:
Permit Host to Initialte the connection and deny other hosts from initiating traffic to our host.
# Default Policy to Drop All connection
# iptables -P INPUT DROP
# iptables -P OUTPUT DROP
# State Rule
# iptables -A OUTPUT -m state --state NEW,ESTABLISHED -j ACCEPT
This will allow creating a NEW session (SYN) with outside and continue the ESTABLISHED connections(regardless of protocol(UDP/TCP))
# iptables -A INPUT -m state --state ESTABLISHED -j ACCEPT
After initiating a traffic to any other machine, the traffic will be permitted when it comes back.(regardles of protocol(UDP/TCP))
End Result:
The host will be able to make all connections to out side(NEW & ESTABLISHED is allowed in OUTPUT chain).
All new connection coming to our system will be dropped(No NEW is defined in INPUT chain only ESTABLISED as well the default rule of DROP) only allows the ESTABLISHED connections(Initiated by our host)

The details of the connection tracking will be stored in
# cat /proc/net/ip_conntrack

This file contains the status of all the established connections in the system for all protocols. The number of packets that transmitted, The
source and destination address, source and destination port etc.


IPTables - Firewall Script

#------------------------------------------------------

#-------------------------------MODULES-------------------------------------
#Load Mdules
/sbin/modprobe ip_tables
/sbin/modprobe iptable_mangle
/sbin/modprobe iptable_filter
/sbin/modprobe iptable_nat
/sbin/modprobe ipt_limit
/sbin/modprobe ipt_LOG
/sbin/modprobe ipt_MASQUERADE
/sbin/modprobe ipt_state
/sbin/modprobe ip_conntrack
#Enable passive ftp
/sbin/modprobe ip_nat_ftp
/sbin/modprobe ip_nat_irc
/sbin/modprobe ip_conntrack_irc
#---------------------------------------------------------------------------

#----------------------------INTERFACES-------------------------------------
#Interface Definitions

int_nic="eth1"
ext_nic="eth0"
anywhere="0.0.0.0/0"
lan="192.168.1.0/24"
ext_ip="6x.x.x.4"
dns1="1x.x2.xx7.1xx"
dns2="2xx.5x.2x.5x"

#----------------------------FLUSH POLICIES AND RULES------------------------

#Clear out any existing firewall rules

/sbin/iptables -F
/sbin/iptables -F INPUT
/sbin/iptables -F OUTPUT
/sbin/iptables -F FORWARD
/sbin/iptables -F -t mangle
/sbin/iptables -F -t nat
/sbin/iptables -X -t nat
/sbin/iptables -X -t mangle
/sbin/iptables -X
#-------------------------------------------------------------------------------------------

#----------------------------BASIC SECURITY RESTRICTIONS------------------------------------

#Enable ip forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward

#Disabling IP Spoofing attacks
echo 2 > /proc/sys/net/ipv4/conf/all/rp_filter

#Don't respond to broadcast pings
echo "1" > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts

#Block source routing
echo 0 >/proc/sys/net/ipv4/conf/all/accept_source_route

#Kill timestamps. These have been the subject of a recent bugtraq
#thread
echo 0 > /proc/sys/net/ipv4/tcp_timestamps

#Enable SYN Cookies
echo 1 > /proc/sys/net/ipv4/tcp_syncookies

#Kill ICMP redirects
echo 0 >/proc/sys/net/ipv4/conf/all/accept_redirects

#Enable bad error message protection
echo 1 > /proc/sys/net/ipv4/icmp_ignore_bogus_error_responses

#Allow dynamic ip addresses
echo "1" > /proc/sys/net/ipv4/ip_dynaddr

#Log martians (packets with impossible addresses)
#RiVaL said that certain NICs don't like this. Comment out if necessary.
# echo 1 >/proc/sys/net/ipv4/conf/all/log_martians

#Set out local port range
echo "32768 61000" >/proc/sys/net/ipv4/ip_local_port_range

#PING OF DEATH
/sbin/iptables -A FORWARD -p icmp --icmp-type 8 -m limit --limit 3/second -j ACCEPT

#SYN-FLOOD PROTECTION
/sbin/iptables -A FORWARD -p tcp --syn -m limit --limit 1/s -j ACCEPT
#------------------------------------------------------------------------------

#---------------------------DENIAL OF SERVICE-----------------------------------

#Reduce DoS'ing ability by timeouts
echo 30 > /proc/sys/net/ipv4/tcp_fin_timeout
echo 1800 > /proc/sys/net/ipv4/tcp_keepalive_time
echo 1 > /proc/sys/net/ipv4/tcp_window_scaling
echo 0 > /proc/sys/net/ipv4/tcp_sack
echo 1280 > /proc/sys/net/ipv4/tcp_max_syn_backlog
#---------------------------------------------------------------------------------------------------

#---------------------------FIREWALL POLICIES AND TRAFFIC DETAILS-----------------------------------
#Default POLICIES
/sbin/iptables -P INPUT DROP
/sbin/iptables -P OUTPUT ACCEPT
/sbin/iptables -P FORWARD DROP

#LOOPBACK ALLOW TRAFFIC ON THE LOOPBACK INTERFACE
/sbin/iptables -A INPUT -i lo -j ACCEPT

#ALLOW ESTABLISHED AND RELATED TRAFFIC
/sbin/iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
/sbin/iptables -A FORWARD -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT


#Allow every traffic from local lan
/sbin/iptables -A INPUT -s $lan -p all -j ACCEPT
/sbin/iptables -A FORWARD -s $lan -p all -j ACCEPT

#Masquerade all internal traffic reaching external world
/sbin/iptables -t nat -A POSTROUTING -s $lan -d ! 192.168.1.0/24 -j MASQUERADE
#----------------------------------------------------------------------------------------------------
/sbin/iptables -t nat -A PREROUTING -i eth1 -p tcp --dport 80 -j REDIRECT --to-port 3128
#--------------------------ICMP CONNECTIONS----------------------------------------------------------

#Allow and Accept icmp traffic with restrictions

/sbin/iptables -A INPUT -p 1 -s $lan -j ACCEPT
/sbin/iptables -A INPUT -p 1 -d $ext_ip --icmp-type 8 -j DROP

#--------------------------TCP CONNECTIONS------------------------------------

#Allow access to SSH from outside when required
/sbin/iptables -A INPUT -p tcp -s $anywhere -d $ext_ip --dport 222 -m limit -j ACCEPT

#------------------------------UDP CONNECTIONS----------------------------------------------------------

/sbin/iptables -A INPUT -p tcp -s $dns1 -d $ext_ip --dport 53 -j ACCEPT
/sbin/iptables -A INPUT -p tcp -s $dns2 -d $ext_ip --dport 53 -j ACCEPT
/sbin/iptables -A INPUT -p udp -s $dns1 -d $ext_ip --dport 53 -j ACCEPT
/sbin/iptables -A INPUT -p udp -s $dns2 -d $ext_ip --dport 53 -j ACCEPT


#---------------------------------------------------------------------------------------------------------

#DNAT
# make internal mail server accessbile

$IPTABLES -t nat -A PREROUTING -i eth0 -d 99.90.80.70 -p tcp --dport 25 -j DNAT --to 10.0.0.3
$IPTABLES -t nat -A PREROUTING -i eth0 -d 99.90.80.70 -p tcp --dport 110 -j DNAT --to 10.0.0.3
$IPTABLES -t nat -A PREROUTING -i eth0 -d 99.90.80.70 -p tcp --dport 80 -j DNAT --to 10.0.0.3

#SNAT
# Mask the internal IP address to appear as Public IP
$IPTABLES -t nat -A POSTROUTING -o eth0 -s 10.0.0.3 -p tcp --sport 25 -j SNAT --to 99.90.80.70
$IPTABLES -t nat -A POSTROUTING -o eth0 -s 10.0.0.3 -p tcp --sport 80 -j SNAT --to 99.90.80.70
$IPTABLES -t nat -A POSTROUTING -o eth0 -s 10.0.0.3 -p tcp --sport 110 -j SNAT --to 99.90.80.70

# //Lin u x --> Wor Ld



The Bash Script To Configure The Firewall Using IPTABLES

#!/bin/bash

##############################
#########Lin u X --> Wor Ld########
##############################

echo -e "***********Welcome*************"
#IPTABLE SERVICES PROGRAM BEGINS HERE#
checkstatus()
{
opt_checkstatus=1
while [ $opt_checkstatus != 7 ]
do
clear
#echo -e "\nChoose the Option Bellow!!!\n
echo -e "\n\t*****Note: Save your Iptables before stop/Restart the iptables Services*****\n"
echo -e " 1. Save the iptables\n
2. Status of Iptables\n
3. Start iptables Services\n
4. Stop iptables Services\n
5. Restart iptable Services\n
6. Flush iptables (**Use Carefully_it will remove all the rules from iptables**)\n
7. Go back to Main Menu"
read opt_checkstatus
case $opt_checkstatus in
1) echo -e "*******************************************************\n"
/etc/init.d/iptables save
echo -e "\n*******************************************************\n"
echo -e "Press Enter key to Continue..."
read temp;;
2) echo -e "*******************************************************\n"
/etc/init.d/iptables status
echo -e "*******************************************************"
echo -e "Press Enter key to Continue..."
read temp;;
3) echo -e "*******************************************************\n"
/etc/init.d/iptables start
echo -e "*******************************************************\n"
echo -e "Press Enter key to Continue..."
read temp;;

4) echo -e "*******************************************************\n"
/etc/init.d/iptables stop
echo -e "*******************************************************\n"
echo -e "Press Enter key to Continue..."
read temp;;

5) echo -e "*******************************************************\n"
/etc/init.d/iptables restart
echo -e "*******************************************************\n"
echo -e "Press Enter key to Continue..."
read temp;;
6) iptables -F
echo -e "*******************************************************"
echo -e "All the Rules from the Iptables are Flushed!!!"
echo -e "*******************************************************\n"
echo -e "Press Enter key to Continue..."
read temp;;
7) main;;
*) echo -e "Wrong Option Selected!!!"
esac
done
}
###############################BUILD FIREWALL PROGRAM BEGINS FROM HERE###############################
buildfirewall()
{
###############Getting the Chain############
echo -e "Using Which Chain of Filter Table?\n
1. INPUT
2. OUTPUT
3. Forward"
read opt_ch
case $opt_ch in
1) chain="INPUT" ;;
2) chain="OUTPUT" ;;
3) chain="FORWARD" ;;
*) echo -e "Wrong Option Selected!!!"
esac

#########Getting Source IP Address##########
#Label

echo -e "
1. Firewall using Single Source IP\n
2. Firewall using Source Subnet\n
3. Firewall using for All Source Networks\n"
read opt_ip

case $opt_ip in
1) echo -e "\nPlease Enter the IP Address of the Source"
read ip_source ;;
2) echo -e "\nPlease Enter the Source Subnet (e.g 192.168.10.0/24)"
read ip_source ;;
3) ip_source="0/0" ;;
#4) ip_source = "NULL" ;;
*) echo -e "Wrong Option Selected"
esac
#########Getting Destination IP Address##########
echo -e "
1. Firewall using Single Destination IP\n
2. Firewall using Destination Subnet\n
3. Firewall using for All Destination Networks\n"

read opt_ip
case $opt_ip in
1) echo -e "\nPlease Enter the IP Address of the Destination"
read ip_dest ;;
2) echo -e "\nPlease Enter the Destination Subnet (e.g 192.168.10.0/24)"
read ip_dest ;;
3) ip_dest="0/0" ;;
#4) ip_dest = "NULL" ;;
*) echo -e "Wrong Option Selected"
esac
###############Getting the Protocol#############
echo -e "
1. Block All Traffic of TCP
2. Block Specific TCP Service
3. Block Specific Port
4. Using no Protocol"
read proto_ch
case $proto_ch in
1) proto=TCP ;;
2) echo -e "Enter the TCP Service Name: (CAPITAL LETTERS!!!)"
read proto ;;
3) echo -e "Enter the Port Name: (CAPITAL LETTERS!!!)"
read proto ;;
4) proto="NULL" ;;
*) echo -e "Wrong option Selected!!!"
esac

#############What to do With Rule#############
echo -e "What to do with Rule?
1. Accept the Packet
2. Reject the Packet
3. Drop the Packet
4. Create Log"
read rule_ch
case $rule_ch in
1) rule="ACCEPT" ;;
2) rule="REJECT" ;;
3) rule="DROP" ;;
4) rule="LOG" ;;
esac
###################Generating the Rule####################
echo -e "\n\tPress Enter key to Generate the Complete Rule!!!"
read temp
echo -e "The Generated Rule is \n"
if [ $proto == "NULL" ]; then
echo -e "\niptables -A $chain -s $ip_source -d $ip_dest -j $rule\n"
gen=1
else
echo -e "\niptables -A $chain -s $ip_source -d $ip_dest -p $proto -j $rule\n"
gen=2
fi
echo -e "\n\tDo you want to Enter the Above rule to the IPTABLES? Yes=1 , No=2"
read yesno
if [ $yesno == 1 ] && [ $gen == 1 ]; then
iptables -A $chain -s $ip_source -d $ip_dest -j $rule
else if [ $yesno == 1 ] && [ $gen == 2 ]; then
iptables -A $chain -s $ip_source -d $ip_dest -p $proto -j $rule

else if [ $yesno == 2 ]; then

main
fi
fi
fi
}

main()
{
ROOT_UID=0
if [ $UID == $ROOT_UID ];
then
clear
opt_main=1
while [ $opt_main != 4 ]
do
echo -e "/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n"
#############Check Whether the iptables installed or not############
echo -e "\t*****Main Menu*****\n
1. Check Iptables Package\n
2. Iptables Services\n
3. Build Your Firewall with Iptables\n
4. Exit"
read opt_main
case $opt_main in
1) echo -e "******************************"
rpm -q iptables
echo -e "******************************" ;;
2) checkstatus ;;
3) buildfirewall ;;
4) exit 0 ;;
*) echo -e "Wrong option Selected!!!"
esac
done
else
echo -e "You Must be the ROOT to Perfom this Task!!!"
fi
}
main
exit 0


Linux Securirty Notes 15: IPTables 1: Introduction

IPTABLES
The integrated firewall feature in Linux Kernel is IPTables. Using IPTables can turn the Linux machine to a fully fledged firewall. Since the IPTable netfilter frame work is capacble to filter pretty much most of the level of OSI models & with in all the various field in TCP, UDP and ICMP packets it has a significant value in corporate enviornment to build the security.

OSI Models
The Open System Interconnection Reference Model (OSI Reference Model or OSI Model) is an abstract description for layered communications and computer network protocol design. It was developed as part of the Open Systems Interconnection (OSI) initiative. In its most basic form, it divides network architecture into seven layers which, from top to bottom, are
Layer 1: Physical Layer
Layer 2: Data Link Layer
Layer 3: Network Layer
Layer 4: Transport Layer
Layer 5: Session Layer
Layer 6: Presentation Layer
Layer 7: Application Layer

some of the Protocols in each Layer are given below.
7. Application Layer
NNTP · SIP · SSI · DNS · FTP · Gopher · HTTP · NFS · NTP · SMPP · SMTP · SNMP · Telnet (more)
6. Presentation Layer
MIME · XDR · SSL · TLS
5. Session Layer
Named Pipes · NetBIOS · SAP
4. Transport Layer
TCP · UDP · PPTP · L2TP · SCTP
3. Network Layer
IP · ICMP · IPsec · IGMP
2. Data Link Layer
ARP · CSLIP · SLIP · Frame relay · ITU-T G.hn DLL
1. Physical Layer
RS-232 · V.35 · V.34 · I.430 · I.431 · T1 · E1 · Ethernet · POTS · SONET · DSL · 802.11a/b/g/n PHY · ITU-T G.hn PHY

IPTables is a front end user space tool to manage Netfilter in Linux kernel. IPTables functions primarily in the Transport (Layer4) and Network (Layer 3), even it can work in the DataLink layer too. IPTables can manage the ICMP .

Layer 4 -Transport- Focuses on Protocols & Ports (TCP/UDP & Ports(0-65535)). The ports are based on 16bit value
Layer 3 -Network- Focuses on Source & Destination (IP Address). The IP address is based on 32 bit value

Installing IPTables
The package IPTables will be installed by default in most of the Linux distro.

# rpm -qa |grep -i IPTables
Or download the Latest package of IPTables from http://www.netfiler.org

# rpm -ql iptables
IPTables ships with many modules that provides the functionality of Masquerading, Rejecting, Mapping etc. The modules that installed can be found in /lib/iptables/*.so.
Checking the kernel for the support of the IPTables.

Find the area for "NETFILTER" in Kernel config file.

# uname -a

# vim /boot/config-

CONFIG_NETFILTER=y

(y)This means the netfilter basic support has been integrated and compiled to the kernel.If (m) option is defined then this means the module can be loaded on the fly so here we need to check the iptables modules has been loaded by command "lsmod".

Default Tables & Chains in IPTables
There are 3 default tables which cannot be deleted. Each table contains chains and the rules are written to the chains
1. Mangle
This allows to alter packets eg:- Type Of Service, Time To Live etc.
2. NAT
Network Address Translation, This allows to change IP Address & Ports. Eg:- Source NAT / DST NAT etc
3. Filter
Here we perform the Filtering the traffic (INPUT, OUTPUT & FORWARD). It works between Layer 3 & Layer 4.

Rule Syntax IPTables.

# /sbin/iptables
commands are used in the following syntax:
name of chain - action done to chain (Append/Incert or Replace)
name of table - default it will append to filter table
Layer 3 object - src or dst of ip address
Layer 4 object - protocols & ports
Jump/Target - if the above criteria meets the do this action

Example of iptables
Drop All the packages from a Host

# iptables -A INPUT -t filter -s 192.168.1.233 -j DROP
This will Drop all the packages coming from the source 192.168.1.233.
Now Test by pinging to the destination host 192.168.1.233
Here we have the OUTPUT chain opened and the rule is defined in INPUT chain. This means our system is able to send the packages to the destination and while the destination machines replies back we drop the packets.

Saving and Restoring the rules in IPTables

# iptables-save
This will dump the rules to STDOUT(to the terminal). The output will be in the iptables default format.

# iptables-save > firewall-rules
This will write the rule the file firewall-rules

# iptables-restore
Default reads the rule from STDIN and loads in to the kernel.

# iptables-restore < firewall-rules
This will restore the rule that saved in the file firewall-rules.


Linux Securirty Notes 15: IPTables 2: Chain Management

IPTables Chain Management

Listing all the chains in Table Filter
# iptables -L -n

It lists INPUT, FORWARD and OUTPUT chains and rules associated with. Each of the chains will have a default policy. i.e the default policy is accept the traffic in IPTables.
# iptables -L OUTPUT

It will list all the rules in the chain OUTPUT for the default table.

Listing all the chains in Table NAT.
# iptables -L -n -t nat

It contains the chains PREROUTING(will use NAT before routing occurred -destination nat-), POSTROUTING(uses NAT to after the packets get routed -source nat-) & OUTPUT (Reserved for packets that sourced locally that need the NAT)

Listing all the chains in Table Mangle.
# iptables -L -n -t mangle

It contains chains INPUT,OUTPUT,FORWARD, PREROUTE & POSTROUTE. Mangle Table is the ANDing of Filter & NAT table.

To List the amount of traffic that processed by the a chain
# iptables -L -n -v -t filter

This will show the total amount of traffic in each chains. Even if there is no rule defined it shows the traffic in chains. This is because there is default rule of accept all in IPTables.

Determine the Line number of the rule in a chain
# iptables -L -n -v --line-numbers
# iptables -L -n -v --line-numbers -t nat

This will show the line numbers column for all the chains.

Appending(-A) and Inserting(-I) rules to Chains

We will try to understand each chains with a real time scenario
Source (192.168.1.1)pings to -> destination (192.168.254)
In this case the source sends a ICMP (echo-request) packet to 192.168.254 which pass across the OUTPUT chain in filter table. Once the request reaches the destination it responds with a echo-reply to the source 192.168.1.1 which pass across the INPUT chain in filter table.

Now we will create rule in source all traffic for SSH will be permitted and Telnet traffic will be denied
Appending a rule(-A):
# iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# iptables -A INPUT -p tcp --dport 23 -j DROP

This will make the server to accept only the ssh based connection and telnet sessions wll be droped.
The append (-A) will add the rule to the last rule in the chain(to the end of the rule list in chain).
# iptables -L -n -v --line-number

This will list the newly added rule

Inserting a rule (-I):
We can insert the rule into a particular line number using this option. (Keep in mind the iptable checks the rule from above to bottom and once it matches the criteria it executes the rule).(We can even insert a same rule to the chain, creating a duplicate rule. IPTables doesn't have a feature to detect the duplicate rules that have appended or inserted.
# iptables -I INPUT 1 -p tcp --dport 23 -j DROP
# iptables -L -n -v --line-number

Here we can see that the rule for dropping the telnet session has been added to first line in the chain. So IPTables will process the rule number 1 before it hitting the rule number 2.
Other examples:
# iptables -I INPUT 2 -p tcp --dport 21 -j DROP

It inserts a rule to line number 2 in INPUT Chain for the table Filter,for Dropping all FTP traffic.

Deleting(-D) and Replacing(-R) Rules
Deleting a Rule:
Syntax for deleting the rule from the chain:
# iptables -D
# iptables -D
Type 1
# iptables -L -n -v --line-number
# iptables -D INPUT 2

This will delete the 2nd rule in the chain INPUT.
Type 2
# iptables -D INPUT -p tcp --dport 21 -j DROP

This will delete the rule as mentioned . This need the exact match and in case of any duplicate rules the first match will be deleted.

Replacing Rules:
Syntax:
# iptables -R

# iptables -L -n -v --line-number
# iptables -R INPUT 1 -p tcp --dport 23 -j ACCEPT

This will replace the existing rule from DROP to ACCEPT (we had previously denied the telnet access)

Flush(-F) rules and Zero counters (-Z)

Flush rules:
syntax:
# iptables -F

# iptables -F INPUT

This will flush all the rules in the chain INPUT.
# iptables -F

This will flush all the rules from all the chains in default Table. But the flusing will not zero the packet counters (iptables -L -v).

Zero Counters:
Syntax:
# iptables -Z

# iptables -Z INPUT
# iptables -L -n -v

This will reset the packet count for the chain INPUT
# iptables -Z

This will reset all the chain packet counts in default table.
# iptables -Z POSTROUTING -t nat

This will reset the packet counter for the chain POSTROUTING for table nat.

User Defined Tables/Chains (Creating (-N) and Renaming (-E old new)):
IPTables ships with 3 default tables which cannot be deleted.

Creating a New chain called INTRANET
# iptables -N INTRANET
# iptables -L -n

This will create a new chain called INTRANET in the filter table. This will create a chain with the default refereces as "0". reference is the link towards the default chains(INPUT, OUTPUT & FORWARD).
Now we define the new chain INTRANET how to behave. i.e, which traffic should be this chain responsilbe for.
# iptables -R INPUT 1 -s 192.168.1.0/24 -j INTRANET

This will tell IPTables that - In rule number 1, any trafic having the source network ID 192.168.1.0 should be contacted the chain INTRANET
# iptables -L -n

Here we can see that a new entry for the Chain is added into the Line number 1 stating that for all the packages having source address in the network 192.168.1.0/24 should jump to target chain INTRANET.

Now create the rules
# iptables -A INTRANET -p tcp --dport 23 -j DROP

So when a packet comes with a source address in 192.168.1.0/24 with the destination port 23. The iptables will refer from the INPUT chain to the INTRANET chain and Then IPTables will start matching the rule. If the packet has the destitantion port 23 then it will DROP.

Note:-
User defined chains must have unique names. Because it function has the target (-j).

Rename a Chain(-E):
If we need to rename a user defined chain
Syntax:
# iptables -E

# iptables -E INTRANET SUBINTRANET
This will rename the chain to SUBINTRANET. The iptables "will update the references as well"(The reference to the default chain).
Chain Policy (-P):
It is usually "accept" in RedHat environment for all the chains in filter table. should be very careful while setting the chain default policy to DROP(Update the iptables to permit the appropriate access, else if we are using a remote session this may freez the access).
Syntax:
# iptables -P

# iptables -P INPUT DROP
This will make the default policy of INPUT chain to DROP.
# iptables -L -n
Check the "chain INPUT (policy DROP)" to verify.
Note:-
Default DROP Policy may prevent typical TCP/UDP/ICMP communication.So a state matching rule should be added in case of such scenarios.



Linux Securirty Notes 15: IPTables 3: Matching Traffic

IPTables Building Rules with Source, Destination of IP, MAC, Protocols & Port

Here we will deal with the possibilities to match the traffic to define the rule, i.e, matching destination & source IP/MAC/PORT/PROTOCOL, Interfaces,Usage of Wildcards etc.

Matching the traffic based on Source and destination:
--src/-s/--source
--dst/-d/--destination
These are the switches used to match the source and destination of the traffic. Widely used while rules created based on source and destination address
Eg:-
Blocking all the traffic from a source (192.168.1.200) (--src)

# iptables -A INPUT --src 192.168.1.200 -j DROP
This Drops all the incoming traffic to out server from the Source 192.168.1.200. Here the match of source is used by "--src".
Blocking all the traffic To a destination from our server (--dst)

# iptables -A OUTPUT --dst 192.168.1.200 -j DROP
This Drops all the outgoing traffic in our server to 192.168.1.200. Here the match of destination is used by "--dst".

Matching Based on Interface:
It is useful while creating the rules based on a particular interface.
(-i eth0/eth1.. etc)
switch "-i" is used to match the traffic with the interface to define the rule.
Eg:-
(-i eth1)

# iptables -A INPUT -i eth1 --src 192.168.1.200 -j DROP
Any incoming traffic from the ip address on the interface eth1 will be dropped.

Negation rule:

# iptables -A INPUT -i eth1 --src !192.168.1.200 -j DROP
This will Drop all the incoming traffic to the interface eth1 other than the IP 192.168.1.200. Only the incoming traffic from ip 192.168.1.200 will be accepted.

# iptables -A INPUT -i eth1 -j DROP
This Drops all the incoming traffic on the interface eth1.

Wildcard for Matching all interfaces(eth+):
For eg:-
IF we have more interfaces like eth0, eth1, eth2, eth3, eth4 etc and need to define a rule that matched all the interface, we can use the wild-card eth+ . eth+ will match all the interfaces starting with "eth".
For Eg:-

# iptables -A INPUT -i eth+ -p tcp --dport 23 -j DROP
This will drop all the incoming telnet traffic to all interfaces, which starts with eth.

TCP Based Matching (--protocol/-p): (Connection Oriented)
Majority of the rules are based on TCP . TCP is on Transport Layer (layer 4).
-p tcp/ --protocol tcp
This switch will make IPTables to initiate the tcp modules and allow/deny the tcp based traffic. This switch makes sense to IPTables about the three way handshake of TCP. The protocol type (tcp/udp) has to be specified while using the "-p" match.
--sport/--source-port
Generally the --sport of TCP client will be greater than 1024, and it is generaly picked arbitrarily from greater than 1024. So usally we wont filter based on the source port for TCP based traffic until and unless we know exactly how a application behaves.
--dport/--destination-port
This is the common match that used along with the "-p" switch. Each and every TCP connection will have a well defined destination port. so based on this destination port we created/matched the rule.
--tcp-flags SYN, ACK SYN, ACK, FIN
This is used to match the three way handshake of the tcp protocols.
SYN - Step 1 of Three way Handshake (Initial synchronization) (From Server)
ACK SYN - Step 2 of three way Handshake (To Acknowledge that the SYN has recieved) (From Client)
ACK - Step 3 of Three way HandShake(From Server)
FIN (Finishing a TCP Session)
Eg:-

# iptables -A INPUT -p tcp --dport 23 -j DROP
Here Match is made with the protocol TCP having the destination port of 23. So all the incoming traffic to telnet will be dropped.

# iptables -A OUTPUT -p tcp --dport 21 -j DROP
This will Drop all the FTP outbound traffic(all request to ftp access from our server)

UDP Based Match: (Connection Less)
Some of the UDP based applications are TFTP:69, Syslog:514, NTP:123, DHCP:67/68, DNS:53
-p udp/--protocol udp
--dport/--destination-port
--sport/--source-port
In majority of the cases, the UDP based traffic having same source port as the destination port.Eg:- The NTP client packets has same destination-port and source-port as 123 in header.
Eg:-
If we are running the syslogd daemon we have to block all other traffic to the service other than the syslog server.

# iptables -A INPUT -p udp --dport 514 -s !192.168.1.3 -j DROP
So here only the traffic from the host 192.168.1.3 with UDP:514 will be accepted and all other source will be denied. Here the match is made with the protocol UDP and --dport 514 along with the Source(-s) using Negation(!).

ICMP based traffic Match.
This is designed to communicate the status information.
various types of ICMP:
echo-request - PING (sends the request via output chains using echo-request to destination)
echo-reply - PONG (Remote system Recieves the echo-request and responds with an echo-reply (PONG))
-p icmp/--protocol icmp
Here defines the protocol type
--icmp-type name/number of icmp type
Here we specifies the ICMP-Types. It can be name or number.eg:- echo-reply, icmp-request etc.
To get the list of icmp types that supported by the IPTables

# iptables -p icmp --help
Using this we can build the rules. The above command can be used for both the tcp and udp protocols

# iptables -p tcp --help
# iptables -p udp --help
Eg:-

# iptables -A INPUT -p icmp --icmp-type echo-reply -j DROP
All the echo-reply from outside will be droped.
Rule to drop all the echo-request to our filrewall from all outbound destination.

# iptables -A INPUT -i eth1 -p icmp --icmp-type echo-request -j DROP
This will disable all the echo-request from the outside interface. But from this server we will be able to ping to any other system because we have not doped any incoming echo-reply.

Multiport Matching in single rule (-m):
This feature uses to match multiple ports in a single rule.
-m multiport
Checking the Multiport module installation

# rpm -ql iptables |grep multiport
/lib/iptables/libipt_multiport.so
This is the modlue responsible for multiport
Eg:-


# iptables -A INPUT -p tcp -m multiport --dport 21,23 -j DROP
Here we defined the multiple ports in single rule.

Matching Layer 2 Traffic (MAC-address):
The MAC address is least changable.
Checking the capability of iptables to match the Layer 2 traffic

# rpm -ql iptables |grep mac
/lib/iptables/libipt_mac.so
This is the modlue responsible for mac address based rule.
-m mac
This will tell iptables to consult the libipt_mac.so module for processing the rule
--mac-source
Source MAC address. Same as the --src option in Layer 3 (IP Adress)
--mac-destination
Destination MAC address. Same as the --dst option in Layer 3 (IP Address)
Eg:-

# iptables -A INPUT -p tcp -m mac --mac-source 00:09:8F:3E:10:3A -j DROP
IF the source mac address is matched then the traffic will be DROPed.
Filtering based on Layer 2 (MAC Address) is more secure because the IP Address can easily be changed.


Linux Securirty Notes 15: IPTables 4 :IPTables Statefullness

IPTables Statefullness(-m state --state):
IPTables provide state fullness. The state full firewall is considered more secure than stateless firewall because of their connection tracking capability and their ability to determine whether or not the session is new,related, invalid or established. Based on this criteria we can create more powerfull rules.
State Module:
# rpm -ql iptables | grep -i conntrack

/lib/iptables/libipt_conntrack.so



This is the module that makes IPTables to behave as statefull. It is applicable for all the protocols (TCP/UDP/ICMP)
The states are:
NEW (The First SYN traffic)
ESTABLISHED
RELATED(SESSION/STATE)
INVALID
When a user creates a TCP/UDP based session IPTables can follow the connection. Here IPTable will keep a track with SYN, ACK-SYN, ACK and labelled with NEW(for SYN), ESTABLISHED or RELATED (For all other subsequent connections).

Example:
Permit Host to Initialte the connection and deny other hosts from initiating traffic to our host.
# Default Policy to Drop All connection
# iptables -P INPUT DROP
# iptables -P OUTPUT DROP
# State Rule
# iptables -A OUTPUT -m state --state NEW,ESTABLISHED -j ACCEPT
This will allow creating a NEW session (SYN) with outside and continue the ESTABLISHED connections(regardless of protocol(UDP/TCP))
# iptables -A INPUT -m state --state ESTABLISHED -j ACCEPT
After initiating a traffic to any other machine, the traffic will be permitted when it comes back.(regardles of protocol(UDP/TCP))
End Result:
The host will be able to make all connections to out side(NEW & ESTABLISHED is allowed in OUTPUT chain).
All new connection coming to our system will be dropped(No NEW is defined in INPUT chain only ESTABLISED as well the default rule of DROP) only allows the ESTABLISHED connections(Initiated by our host)

The details of the connection tracking will be stored in
# cat /proc/net/ip_conntrack

This file contains the status of all the established connections in the system for all protocols. The number of packets that transmitted, The
source and destination address, source and destination port etc.


Linux Securirty Notes 15: IPTables 5 :IPTables Targets (-j)

IPTables Targets(-j)
Commonly used targets are
1. ACCEPT
Sends packtes to other rule or process

2. DROP
Drops the packet silently. Remote machine will not be aware about what happend to the packet.

3. REJECT
When the rule met an error msg is send to client.
Eg of Reject:-


# iptables -A INPUT -p icmp --icmp-type echo-request -j REJECT
This will reject all the echo request part with a msg icmp-port-unreachable. If we ping to the host we will get a destination host unreachable.

4. REDIRECT
This is used to redirect a current traffic to a desired target. It is applied to PREROUTING chain of NAT table.
Eg:-

# iptables -t nat -A PREROUTING -p tcp --dport 3128 -j REDIRECT --to-port 80
This will redirect all the trafic coming to the destination port 3128 to 80.

# iptables -L -n -t nat -v
Test with the verbose mode to get the packet count which hits the rule.

5. LOG
This allow us to log the traffic which meets the rules from the level of debug to emergency using syslog.

IPTable Logs:
It relies upon the kernel(kern) facility in syslog. So have to setup the syslog for logging the iptables activities.

Setup Logging
Primarily we enable the logging in IPTables
Enabling the Log for a chain

# iptables -I INPUT 1 -p tcp --dport 22 -j LOG
This will start logging for the traffic which meets the above rule.(Logs all the incoming ssh request.) The default level of logging is warning. The Log level corresponds to the syslog.

# iptables -L -n -v
Check any packets hits the log

# tail -f /var/log/messages
This is the default place where undefined facilities logs to.So we the kern facility has been logging to /var/log/messages.
Configure syslog to log iptables activity separately:
We will change the facility to log to a seperate file

# vi /etc/syslog.conf
kern.none /var/log/messeges
kern.* /var/log/firewall.log
This will stop the kern facility to log to /var/log/messeges and redirects all levels of logs to /var/log/firewall.log

# service syslog reload
This will restart the syslog daemon and creates the file /var/log/firewall.log.
Test the Logging information by creating the traffic to port 22 on host.

# tail -f /var/log/firewall.log

brief about the log format:-
time- syslog facility - interface that revived the tracfic- MAC address of the remote system- MAC address of the local system - SRC IP- DSTIP - ID=packet sequence number - SPT=source port - DPT=destination port etc

Note:-
Generally logging should be enabled for separate chains & a specific rule. A catch all log for all the traffic will grow the log file numerously.

Loging All trafic

# iptables -A INPUT -j LOG
# tail -f /var/log/firewall.log
This will Log all traffic destined to the local server(INPUT). This will log all the protocols

Log All except a perticular protocol from host 192.168.1.53

# iptables -I INPUT 1 -p tcp ! --dport 22 -src 192.168.1.53 -j LOG
# tail -f /var/log/firewall.log
This will log everything except traffic to destination port 22

Log Excluding Multiple port in single rule

# iptables -I INPUT 1 -m multiport -p tcp --dport !80,8080 -j LOG
# tail -f /var/log/firewall.log
This will log all traffic except packet destined to port 80 and 8080.

Log using separate chains
Now we will check how to create a separate chain in IPTables for logging activities.
Create a New chain

# iptables -N LOGGER
Create a reference in INPUT chain to new chain LOG

# iptables -I INPUT 1 -j LOGGER
Create the logging rule in chain LOG

# iptables -A LOGGER -m multiport -p tcp --dport 21,22,80,143,8080 -j LOG
# tail -f /var/log/firewall.log
This will start logging ports 21,22,80,143 & 8080.

Loging the ssh access to the console.
In iptables:
Create a New CHAIN

# iptables -N SSHLOG
Create a reference in INPUT chain to new chain SSHLOG

# iptables -I INPUT 1 -j SSHLOG
Create the loging rule in chain LOG

# iptables -A LOGGER -p tcp --dport 22 -j LOG
In syslog:

# vim /etc/syslog.conf
kern.* /dev/console
# service syslogd restart
This will start logging any ssh access to the console.

Prefixing Interesting Traffic with a Log Prefix(--log-prefix "log prefix")

# iptables -A LOGGER -p tcp --dport 22 -j LOG --log-prefix "SSH Access Logs"
This will prefix the given string to the log. So it is easy to grep/awk the content from the log file.
Note:-
The Maximum prefix length is 29 characters.

Note:-
--log-level (debug to emer)
This will decide the level of log from debug to emergency level.


Linux Securirty Notes 15: IPTables 6: Routing - Forward Chain

IPTables Routing (Forward Chain)
The Forward chain holds the rules that take care of routing
Enabling the Routing.
#sysctl
This is the key utilities which shows the running kernel parameters.
#syscltl net.ipv4.ip_forward
This will show the status of the IPV4 routing in our local system.
# echo 1 > /proc/sys/net/ipv4/ip_forward
This will turn on the routing in kernel.
# vim /etcv/sysctl.conf
net.ipv4.ip_forward = 1
This will make the routing permanent.
# route add -net 10.0.0.0 netmask 255.0.0.0 gw 192.168.1.10
This will make the net routing in Linux host.

Forward Chain to Manage the Routing.
All the packets that is subjected to route will traverse through Forward Chain in a Linux router.

Defining the Forward chain policy
1. Initially make the default policy to Drop all the routing traffic in firewall
# iptables -P FORWARD DROP
This will make all the routing traffic to be dropped as a default policy.
2. Specify only certain source network to be routed
# iptables -A FORWARD -s 192.168.1.0/24 -d 10.0.0.0/8 -j ACCEPT
This will allow the traffic from 192.168.1.0 network to 10.0.0.0. But the traffic from 10.0.0.0/8 network if comes back will not be accepted until & unless we define a state rule or a rule that allows the traffic from the given source.
or
# iptables -A FORWARD -m state --state NEW,ESTABLISHED -s 192.168.1.0/24 -j ACCPET
This will allow and route all the new and established connection from the network 192.168.1.0 to any destination
3. Accept the return traffic
# iptables -A FORWARD -m state --state ESTABLISHED -j ACCEPT
This will allow/accept all the established connection in the forward chain. This will allow the return traffic.
or define a rule that allows the return traffic from the network 10.0.0.0/8. Here usage of the "state" rule makes the definition of the firewall rule more easier and secure.

Logging the routing traffic in FORWARD Chain:
# iptables -N ROUTELOG
# iptables -A FORWARD -j ROUTELOG
# IPTABLES -I ROUTELOG -j LOG
This will create a new chain and starts logging all the routing activities.

Allowing a subnet to access outer world web
# iptables -A FORWARD -s 10.0.0.0/24 -p tcp --dport 80 -j ACCEPT

Allow the UDP(DNS) queries to outside
# iptables -A FORWARD -s 10.0.0.0/24 -p udp --dport 53 -j ACCEPT


Linux Securirty Notes 15: IPTables 7: NAT

IPTables NAT
Network Address Translation is the feature that makes Linux based firewall mostly in use. NAT is commonly used to masquerade the IP address

NAT CHAINS
The NAT table contains 3 chains
1. PREROUTING
The DNAT is defined in the PREROUTING chain. Using this we will make available of our internal service to external (Internet).i.e, from internet to lan (changes the packets before it routes to lan)
2. POSTROUTING
This is responsible for MASQUERADE (dynamic SNAT) & SNAT. When packet needs to leave from one subnet(internel) through the linux firewall to another it traverse through POSTROUTING chain. (Changes the packet after it leaves the route from lan). eg:- MASQUERADE option is used in certain cases like, if ISP provides the DHCP address and the internel LAN needs to brows, then we have to masquerade all the request from the lan to the DHCP address provided by isp
3. OUTPUT
Locally sourced/generated packets are subjected to NAT. Eg:- If the firewall has more than one IP address using this chain we can re-write the packets going out from this linux machine to a single IP.

TYPEs in NAT
3 types of NATing is used.
masquerade
snat
dnat
1. MASQUERADE
This feature of NAT is used to dynamically masquerade all the internal address to the external IP

The following example will masquerade all the outgoing traffic to the externel bound IP of the firewall.

# iptables -t nat -A POSTROUTING -j MASQUERADE
Another example that masquerades all the traffic from network 10.0.0.0/8

# iptables -t nat -A POSTROUTING -j MASQUERADE -s 10.0.0.0/8
This will masquerade all the request from the 10.0.0.0/8 subnet to the external ip of the firewall.
Test by enabling logging for nat and check the log file.

Masquerading Port:

#iptables -A POSTROUTING -t nat -p tcp -j MASQUERADE --to-ports 1024-10240
This will masquerade all the ports to the range from 1024 to 10240. So when a external client makes connection to the internal server (for eg:- # telnet 22) then the port allocated to the client will be in between 1024 to 10240. As a result the internal system will be only able to source the port in range of 1024 to 10240.

2.SNAT
This feature of NAT is used to masquerade a particular internal ip adress to a given external address. Though SNAT and masquerading perform the same fundamental function, mapping one address space into another one, the details differ slightly. Most noticeably, masquerading chooses the source IP address for the outbound packet from the IP bound to the interface through which the packet will exit. i.e, SNAT permits 1-to-1 and/or 1-to-many mappings. It is used when we have a static public IP address.

This example will masquerade all the outgoing traffic from the subnet 10.0.0./8 to the ip 123.12.23.43.

# iptables -t nat -A POSTROUTING -s 10.0.0.0/8 -j SNAT --to-source 12.34.56.78
or


# iptables -t nat -A POSTROUTING -j SNAT -s 10.0.0.0/8 --to-source 11.22.33.44

SNAT using multiple address:

# iptables -A POSTROUTING -p tcp -s 10.0.0.55 -j SNAT --to-source 192.168.1.100
# iptables -A POSTROUTING -p tcp -s 10.0.0.0/8 -j SNAT --to-source 192.168.1.200
The first rule will nat all the traffic from source 10.0.0.55 to 192.168.1.100, and second rule states that all other traffic from the subnet 10.0.0.0/8 should be NATed to 192.168.1.200.
Test the functionality by enabling the LOG and use # netstat -ant

3.DNAT
This feature of NAT is used to translate the packet coming to a perticular destination.Destination NAT with netfilter is commonly used to publish or make available of a internal network service to a publicly accessible IP. The connection tracking mechanism of netfilter will ensure that subsequent packets exchanged in either direction (which can be identified as part of the existing DNAT connection) are also transformed.

In this following example, all packets arriving on the router with a destination of 10.10.20.99 will depart from the router with a destination of 10.10.14.2

# iptables -t nat -A PREROUTING -d 10.10.20.99 -j DNAT --to-destination 10.10.14.2
Make the internal mail server available for external access.

# iptables -A PREROUTING -t nat -d mail.domain.com -p tcp --dport 25 -j DNAT --to-destination 192.168.1.25
# iptables -A PREROUTING -t nat -d mail.domain.com -p tcp --dport 110 -j DNAT --to-destination 192.168.1.25
Here if any request comes to the ip of mail.domain.com with the destination port of 25 or 110, then IPTables will redirect (nat) to the internel address of 192.168.1.25.

Netmap TAGRGET in NAT:
It is implemented in NAT table PREROUTING Chain. This is used to translate the one to one address from one subnet to another subnet.
For Eg:-
Consider we have one subnet 10.0.0.0/24. and we need to translate all the ip in this subnet equalent to 192.168.1.0/24

# iptables -A PREROUTING -t nat -s 10.0.0.0/24 -j NETMAP --to 192.168.1.0/24
This will convert/rewrite all the packets coming from the subnet 10.0.0.0/24 to 192.168.1.0/24.
i.e, the request from the ip 10.0.0.1 will be masked as 192.168.1.1.


Linux Securirty Notes 15: IPTables 8: DMZ

IPTables with DMZ
Let consider the interface to setup/understand the DMZ.
eth0: external interface (192.168.1.0/24)
eth1: Internal Interface (10.0.0.0/8)
eth2: The DMZ zone (172.16.0.0/16)

Step 1:
Create DNAT for all the servers in the DMZ zone (eth2) for accessing the service externally
# iptables -t nat -A PREROUTING -d 192.168.1.2 -p tcp --dport 80 -j DNAT --to-destination 172.16.0.2
# iptables -t nat -A PREROUTING -d 192.168.1.2 -p tcp --dport 443 -j DNAT --to-destination 172.16.0.2
If any request comes to firewall with the destination IP as 192.168.1.2 and port as 80 will be DNATed to 172.16.0.2 in DMZone.
Now test accessing the service in DMZone from Internel as well externel network. From both the network we will be able to access the server in the DMZone using the IP 192.168.1.2.

Step2:
Configure the split DNS or 2 DNS systems (Inside&Outside of the DMZone).
Step3:
Setup rule for trusted network from the outside network(Internet) for the traffic which will allow system access (SSH).
# iptables -A FORWARD -s 10.0.0.0/8 -j ACCEPT
# iptables -A FORWARD -s 172.16.0.0/16 -m state --state ESTABLISHED -j ACCEPT
# iptables -P FORWARD DROP
This will deny all access to the DMZone from the internet hosts, only allows the Internal network. Because the default policy of FORWARD chain is set to drop, we need to create the "state match" for the hosts in the DMZone(This will deny sourcing a new connection from the DMZone, only established connection will be permitted).


Dual DMZ Configuration
This is the way of segmenting the servers to separate DMZones.
Let consider the interface to setup/understand the Dual DMZ.
eth0: externel interface (192.168.1.0/24)
eth1: Internel Interface (10.0.0.0/8)
eth2: The DMZ1 zone (172.16.0.0/16) (Web servers)
eth3: The DMZ2 zone (172.17.0.0/16) (DBMS, App servers like JBOSS, TOMCAT etc)
Using this method we will be able to control the traffic from one DMZone to another. This is used for the scenarios of Application servers which need to contact the DB Servers located on separate server.

Here we have to permit only the DMZ1 to contact the DMZ2. all other traffic will be denied.So the servers in the DMZ2 zone will be more secured.
# iptables -t nat -A FORWARD -s 172.16.0.0/16 -d 172.7.0.0/16 -j ACCEPT
# iptables -t nat -A FORWARD -m state --state ESTABLISED -s 172.17.0.0/16 -j ACCEPT
# iptables -t nat -P FORWARD DROP
This will make only the DMZ1 to contact the DMZ2. And from DMZ2 only the established connection will be permitted. All other request will be dropped in the FORWARD chain.
Note:-
These rules are the basic backbone for setting up the routing and Natting in DMZone. All other rules should be defined according to our network need.


Shell script to get uptime, disk , cpu , RAM , system load, from multiple Linux servers – output the information on a single server in html format

http://bash.cyberciti.biz/monitoring/get-system-information-in-html-format/

The Bash Script To Configure The Firewall Using IPTABLES


#!/bin/bash

##############################
#########Lin U X --> Wor Ld########
##############################

echo -e "***********Welcome*************"
#IPTABLE SERVICES PROGRAM BEGINS HERE#
checkstatus()
{
opt_checkstatus=1
while [ $opt_checkstatus != 7 ]
do
clear
#echo -e "\nChoose the Option Bellow!!!\n
echo -e "\n\t*****Note: Save your Iptables before stop/Restart the iptables Services*****\n"
echo -e " 1. Save the iptables\n
2. Status of Iptables\n
3. Start iptables Services\n
4. Stop iptables Services\n
5. Restart iptable Services\n
6. Flush iptables (**Use Carefully_it will remove all the rules from iptables**)\n
7. Go back to Main Menu"
read opt_checkstatus
case $opt_checkstatus in
1) echo -e "*******************************************************\n"
/etc/init.d/iptables save
echo -e "\n*******************************************************\n"
echo -e "Press Enter key to Continue..."
read temp;;
2) echo -e "*******************************************************\n"
/etc/init.d/iptables status
echo -e "*******************************************************"
echo -e "Press Enter key to Continue..."
read temp;;
3) echo -e "*******************************************************\n"
/etc/init.d/iptables start
echo -e "*******************************************************\n"
echo -e "Press Enter key to Continue..."
read temp;;

4) echo -e "*******************************************************\n"
/etc/init.d/iptables stop
echo -e "*******************************************************\n"
echo -e "Press Enter key to Continue..."
read temp;;

5) echo -e "*******************************************************\n"
/etc/init.d/iptables restart
echo -e "*******************************************************\n"
echo -e "Press Enter key to Continue..."
read temp;;
6) iptables -F
echo -e "*******************************************************"
echo -e "All the Rules from the Iptables are Flushed!!!"
echo -e "*******************************************************\n"
echo -e "Press Enter key to Continue..."
read temp;;
7) main;;
*) echo -e "Wrong Option Selected!!!"
esac
done
}
###############################BUILD FIREWALL PROGRAM BEGINS FROM HERE###############################
buildfirewall()
{
###############Getting the Chain############
echo -e "Using Which Chain of Filter Table?\n
1. INPUT
2. OUTPUT
3. Forward"
read opt_ch
case $opt_ch in
1) chain="INPUT" ;;
2) chain="OUTPUT" ;;
3) chain="FORWARD" ;;
*) echo -e "Wrong Option Selected!!!"
esac

#########Getting Source IP Address##########
#Label

echo -e "
1. Firewall using Single Source IP\n
2. Firewall using Source Subnet\n
3. Firewall using for All Source Networks\n"
read opt_ip

case $opt_ip in
1) echo -e "\nPlease Enter the IP Address of the Source"
read ip_source ;;
2) echo -e "\nPlease Enter the Source Subnet (e.g 192.168.10.0/24)"
read ip_source ;;
3) ip_source="0/0" ;;
#4) ip_source = "NULL" ;;
*) echo -e "Wrong Option Selected"
esac
#########Getting Destination IP Address##########
echo -e "
1. Firewall using Single Destination IP\n
2. Firewall using Destination Subnet\n
3. Firewall using for All Destination Networks\n"

read opt_ip
case $opt_ip in
1) echo -e "\nPlease Enter the IP Address of the Destination"
read ip_dest ;;
2) echo -e "\nPlease Enter the Destination Subnet (e.g 192.168.10.0/24)"
read ip_dest ;;
3) ip_dest="0/0" ;;
#4) ip_dest = "NULL" ;;
*) echo -e "Wrong Option Selected"
esac
###############Getting the Protocol#############
echo -e "
1. Block All Traffic of TCP
2. Block Specific TCP Service
3. Block Specific Port
4. Using no Protocol"
read proto_ch
case $proto_ch in
1) proto=TCP ;;
2) echo -e "Enter the TCP Service Name: (CAPITAL LETTERS!!!)"
read proto ;;
3) echo -e "Enter the Port Name: (CAPITAL LETTERS!!!)"
read proto ;;
4) proto="NULL" ;;
*) echo -e "Wrong option Selected!!!"
esac

#############What to do With Rule#############
echo -e "What to do with Rule?
1. Accept the Packet
2. Reject the Packet
3. Drop the Packet
4. Create Log"
read rule_ch
case $rule_ch in
1) rule="ACCEPT" ;;
2) rule="REJECT" ;;
3) rule="DROP" ;;
4) rule="LOG" ;;
esac
###################Generating the Rule####################
echo -e "\n\tPress Enter key to Generate the Complete Rule!!!"
read temp
echo -e "The Generated Rule is \n"
if [ $proto == "NULL" ]; then
echo -e "\niptables -A $chain -s $ip_source -d $ip_dest -j $rule\n"
gen=1
else
echo -e "\niptables -A $chain -s $ip_source -d $ip_dest -p $proto -j $rule\n"
gen=2
fi
echo -e "\n\tDo you want to Enter the Above rule to the IPTABLES? Yes=1 , No=2"
read yesno
if [ $yesno == 1 ] && [ $gen == 1 ]; then
iptables -A $chain -s $ip_source -d $ip_dest -j $rule
else if [ $yesno == 1 ] && [ $gen == 2 ]; then
iptables -A $chain -s $ip_source -d $ip_dest -p $proto -j $rule

else if [ $yesno == 2 ]; then

main
fi
fi
fi
}

main()
{
ROOT_UID=0
if [ $UID == $ROOT_UID ];
then
clear
opt_main=1
while [ $opt_main != 4 ]
do
echo -e "/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n"
#############Check Whether the iptables installed or not############
echo -e "\t*****Main Menu*****\n
1. Check Iptables Package\n
2. Iptables Services\n
3. Build Your Firewall with Iptables\n
4. Exit"
read opt_main
case $opt_main in
1) echo -e "******************************"
rpm -q iptables
echo -e "******************************" ;;
2) checkstatus ;;
3) buildfirewall ;;
4) exit 0 ;;
*) echo -e "Wrong option Selected!!!"
esac
done
else
echo -e "You Must be the ROOT to Perfom this Task!!!"
fi
}
main
exit 0



Create Users And Change Passwords With A Bash Script


These two scripts are very important for the system admin who regularly works with mail servers and somehow forgets to backup his system username and password! Let’s say somehow we lost the usernames and passwords of the mail server. In this case the admin has to manually create all the users and then change the passwords for all the users. Tedious job. Let’s make our life easier.
First create a file which contains all the user name. Something like this:
nurealam
nayeem
mrahman
farid
rubi
sankar
Save the file as userlist.txt. Now create the following bash file:
#!/bin/sh
for i in `more userlist.txt `
do
echo $i
adduser $i
done
Save the file and exit.
chmod 755 userlist.txt
Now run the file:
./userlist.txt
This will add all the users to the system. Now we have to change the passwords. Let's say we want username123 as password. So for user nayeem the password will be nayeem123, rubi123 for user rubi and so on.
Create another bash file as follows:
#!/bin/sh
for i in `more userlist.txt `
do
echo $i
echo $i"123" | passwd –-stdin "$i"
echo; echo "User $username’s password changed!"
done
Run the file. All the passwords are changed.