Sunday, 8 November 2015

Find to take Backup MySQL Databases and Web server Files to a FTP Server on Linux/CentOs





This is a simple backup solution for people who run their own web server and MySQL database server on a dedicated or VPS server. Most dedicated hosting provider provides backup service using NAS or FTP servers. These service providers will hook you to their redundant centralized storage array over private VLAN. Since, I manage couple of boxes, here is my own automated solution. If you just want a shell script, go here (you just need to provided appropriate input and it will generate FTP backup script for you on fly, you can also grab my php script generator code).

Making Incremental Backups With tar

You can make tape backups. However, sometime tape is not an option. GNU tar allows you to make incremental backups with -g option. In this example, tar command will make incremental backup of /var/www/html, /home, and /etc directories, run:
# tar -g /var/log/tar-incremental.log -zcvf /backup/today.tar.gz /var/www/html /home /etc
Where,
  • -g: Create/list/extract new GNU-format incremental backup and store information to /var/log/tar-incremental.log file.

Making MySQL Databases Backup

mysqldump is a client program for dumping or backing up mysql databases, tables and data. For example, the following command displays the list of databases:
$ mysql -u root -h localhost -p -Bse 'show databases'
Output:
Enter password:
brutelog
cake
faqs
mysql
phpads
snews
test
tmp
van
wp
Next, you can backup each database with the mysqldump command:
$ mysqldump -u root -h localhost -pmypassword faqs | gzip -9 > faqs-db.sql.gz

Creating A Simple Backup System For Your Installation

The main advantage of using FTP or NAS backup is a protection from data loss. You can use various protocols to backup data:
  1. FTP
  2. SSH
  3. RSYNC
  4. Other Commercial solutions
However, I am going to write about FTP backup solution here. The idea is as follows:
  • Make a full backup every Sunday night i.e. backup everything every Sunday
  • Next backup only those files that has been modified since the full backup (incremental backup).
  • This is a seven-day backup cycle.

Our Sample Setup

   Your-server     ===>       ftp/nas server
IP:202.54.1.10   ===>       208.111.2.5
Let us assume that your ftp login details are as follows:
  • FTP server IP: 208.111.2.5
  • FTP Username: nixcraft
  • FTP Password: somepassword
  • FTP Directory: /home/nixcraft (or /)
You store all data as follows:
=> /home/nixcraft/full/mm-dd-yy/files - Full backup
=> /home/nixcraft/incremental/mm-dd-yy/files - Incremental backup

Automating Backup With tar

Now, you know how to backup files and mysql databases using the tar and mysqldump commands. It is time to write a shell script that will automate entire procedure:
  1. First, our script will collect all data from both MySQL database server and file system into a temporary directory called /backup using a tar command.
  2. Next, script will login to your ftp server and create a directory structure as discussed above.
  3. Script will dump all files from /backup to the ftp server.
  4. Script will remove temporary backup from /backup directory.
  5. Script will send you an email notification if ftp backups failed due to any reason.
You must have the following commands installed (use yum or apt-get package manager to install ftp client called ncftp):
  • ncftp ftp client
  • mysqldump command
  • GNU tar command
Here is the sample script:
  1. #!/bin/sh
  2. # System + MySQL backup script
  3. # Full backup day - Sun (rest of the day do incremental backup)
  4. # Copyright (c) 2005-2006 nixCraft <http://www.cyberciti.biz/fb/>
  5. # This script is licensed under GNU GPL version 2.0 or above
  6. # Automatically generated by http://bash.cyberciti.biz/backup/wizard-ftp-script.php
  7. # ---------------------------------------------------------------------
  8. ### System Setup ###
  9. DIRS="/home /etc /var/www"
  10. BACKUP=/tmp/backup.$$
  11. NOW=$(date +"%d-%m-%Y")
  12. INCFILE="/root/tar-inc-backup.dat"
  13. DAY=$(date +"%a")
  14. FULLBACKUP="Sun"
  15. ### MySQL Setup ###
  16. MUSER="admin"
  17. MPASS="mysqladminpassword"
  18. MHOST="localhost"
  19. MYSQL="$(which mysql)"
  20. MYSQLDUMP="$(which mysqldump)"
  21. GZIP="$(which gzip)"
  22. ### FTP server Setup ###
  23. FTPD="/home/vivek/incremental"
  24. FTPU="vivek"
  25. FTPP="ftppassword"
  26. FTPS="208.111.11.2"
  27. NCFTP="$(which ncftpput)"
  28. ### Other stuff ###
  29. EMAILID="admin@theos.in"
  30. ### Start Backup for file system ###
  31. [ ! -d $BACKUP ] && mkdir -p $BACKUP || :
  32. ### See if we want to make a full backup ###
  33. if [ "$DAY" == "$FULLBACKUP" ]; then
  34. FTPD="/home/vivek/full"
  35. FILE="fs-full-$NOW.tar.gz"
  36. tar -zcvf $BACKUP/$FILE $DIRS
  37. else
  38. i=$(date +"%Hh%Mm%Ss")
  39. FILE="fs-i-$NOW-$i.tar.gz"
  40. tar -g $INCFILE -zcvf $BACKUP/$FILE $DIRS
  41. fi
  42. ### Start MySQL Backup ###
  43. # Get all databases name
  44. DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"
  45. for db in $DBS
  46. do
  47. FILE=$BACKUP/mysql-$db.$NOW-$(date +"%T").gz
  48. $MYSQLDUMP -u $MUSER -h $MHOST -p$MPASS $db | $GZIP -9 > $FILE
  49. done
  50. ### Dump backup using FTP ###
  51. #Start FTP backup using ncftp
  52. ncftp -u"$FTPU" -p"$FTPP" $FTPS<<EOF
  53. mkdir $FTPD
  54. mkdir $FTPD/$NOW
  55. cd $FTPD/$NOW
  56. lcd $BACKUP
  57. mput *
  58. quit
  59. EOF
  60. ### Find out if ftp backup failed or not ###
  61. if [ "$?" == "0" ]; then
  62. rm -f $BACKUP/*
  63. else
  64. T=/tmp/backup.fail
  65. echo "Date: $(date)">$T
  66. echo "Hostname: $(hostname)" >>$T
  67. echo "Backup failed" >>$T
  68. mail -s "BACKUP FAILED" "$EMAILID" <$T
  69. rm -f $T
  70. fi
More Details Click
          Autherby-cyberciti.biz

Take Backup MySQL Databases and Web server Files to a FTP Server on Linux/CentOs





This is a simple backup solution for people who run their own web server and MySQL database server on a dedicated or VPS server. Most dedicated hosting provider provides backup service using NAS or FTP servers. These service providers will hook you to their redundant centralized storage array over private VLAN. Since, I manage couple of boxes, here is my own automated solution. If you just want a shell script, go here (you just need to provided appropriate input and it will generate FTP backup script for you on fly, you can also grab my php script generator code).

Making Incremental Backups With tar

You can make tape backups. However, sometime tape is not an option. GNU tar allows you to make incremental backups with -g option. In this example, tar command will make incremental backup of /var/www/html, /home, and /etc directories, run:
# tar -g /var/log/tar-incremental.log -zcvf /backup/today.tar.gz /var/www/html /home /etc
Where,
  • -g: Create/list/extract new GNU-format incremental backup and store information to /var/log/tar-incremental.log file.

Making MySQL Databases Backup

mysqldump is a client program for dumping or backing up mysql databases, tables and data. For example, the following command displays the list of databases:
$ mysql -u root -h localhost -p -Bse 'show databases'
Output:
Enter password:
brutelog
cake
faqs
mysql
phpads
snews
test
tmp
van
wp
Next, you can backup each database with the mysqldump command:
$ mysqldump -u root -h localhost -pmypassword faqs | gzip -9 > faqs-db.sql.gz

Creating A Simple Backup System For Your Installation

The main advantage of using FTP or NAS backup is a protection from data loss. You can use various protocols to backup data:
  1. FTP
  2. SSH
  3. RSYNC
  4. Other Commercial solutions
However, I am going to write about FTP backup solution here. The idea is as follows:
  • Make a full backup every Sunday night i.e. backup everything every Sunday
  • Next backup only those files that has been modified since the full backup (incremental backup).
  • This is a seven-day backup cycle.

Our Sample Setup

   Your-server     ===>       ftp/nas server
IP:202.54.1.10   ===>       208.111.2.5
Let us assume that your ftp login details are as follows:
  • FTP server IP: 208.111.2.5
  • FTP Username: nixcraft
  • FTP Password: somepassword
  • FTP Directory: /home/nixcraft (or /)
You store all data as follows:
=> /home/nixcraft/full/mm-dd-yy/files - Full backup
=> /home/nixcraft/incremental/mm-dd-yy/files - Incremental backup

Automating Backup With tar

Now, you know how to backup files and mysql databases using the tar and mysqldump commands. It is time to write a shell script that will automate entire procedure:
  1. First, our script will collect all data from both MySQL database server and file system into a temporary directory called /backup using a tar command.
  2. Next, script will login to your ftp server and create a directory structure as discussed above.
  3. Script will dump all files from /backup to the ftp server.
  4. Script will remove temporary backup from /backup directory.
  5. Script will send you an email notification if ftp backups failed due to any reason.
You must have the following commands installed (use yum or apt-get package manager to install ftp client called ncftp):
  • ncftp ftp client
  • mysqldump command
  • GNU tar command
Here is the sample script:
  1. #!/bin/sh
  2. # System + MySQL backup script
  3. # Full backup day - Sun (rest of the day do incremental backup)
  4. # Copyright (c) 2005-2006 nixCraft <http://www.cyberciti.biz/fb/>
  5. # This script is licensed under GNU GPL version 2.0 or above
  6. # Automatically generated by http://bash.cyberciti.biz/backup/wizard-ftp-script.php
  7. # ---------------------------------------------------------------------
  8. ### System Setup ###
  9. DIRS="/home /etc /var/www"
  10. BACKUP=/tmp/backup.$$
  11. NOW=$(date +"%d-%m-%Y")
  12. INCFILE="/root/tar-inc-backup.dat"
  13. DAY=$(date +"%a")
  14. FULLBACKUP="Sun"
  15. ### MySQL Setup ###
  16. MUSER="admin"
  17. MPASS="mysqladminpassword"
  18. MHOST="localhost"
  19. MYSQL="$(which mysql)"
  20. MYSQLDUMP="$(which mysqldump)"
  21. GZIP="$(which gzip)"
  22. ### FTP server Setup ###
  23. FTPD="/home/vivek/incremental"
  24. FTPU="vivek"
  25. FTPP="ftppassword"
  26. FTPS="208.111.11.2"
  27. NCFTP="$(which ncftpput)"
  28. ### Other stuff ###
  29. EMAILID="admin@theos.in"
  30. ### Start Backup for file system ###
  31. [ ! -d $BACKUP ] && mkdir -p $BACKUP || :
  32. ### See if we want to make a full backup ###
  33. if [ "$DAY" == "$FULLBACKUP" ]; then
  34. FTPD="/home/vivek/full"
  35. FILE="fs-full-$NOW.tar.gz"
  36. tar -zcvf $BACKUP/$FILE $DIRS
  37. else
  38. i=$(date +"%Hh%Mm%Ss")
  39. FILE="fs-i-$NOW-$i.tar.gz"
  40. tar -g $INCFILE -zcvf $BACKUP/$FILE $DIRS
  41. fi
  42. ### Start MySQL Backup ###
  43. # Get all databases name
  44. DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"
  45. for db in $DBS
  46. do
  47. FILE=$BACKUP/mysql-$db.$NOW-$(date +"%T").gz
  48. $MYSQLDUMP -u $MUSER -h $MHOST -p$MPASS $db | $GZIP -9 > $FILE
  49. done
  50. ### Dump backup using FTP ###
  51. #Start FTP backup using ncftp
  52. ncftp -u"$FTPU" -p"$FTPP" $FTPS<<EOF
  53. mkdir $FTPD
  54. mkdir $FTPD/$NOW
  55. cd $FTPD/$NOW
  56. lcd $BACKUP
  57. mput *
  58. quit
  59. EOF
  60. ### Find out if ftp backup failed or not ###
  61. if [ "$?" == "0" ]; then
  62. rm -f $BACKUP/*
  63. else
  64. T=/tmp/backup.fail
  65. echo "Date: $(date)">$T
  66. echo "Hostname: $(hostname)" >>$T
  67. echo "Backup failed" >>$T
  68. mail -s "BACKUP FAILED" "$EMAILID" <$T
  69. rm -f $T
  70. fi
More Details Click
          Autherby-cyberciti.biz

Cron Job To Backup Data on Linux Automatically both Centos

Just add cron job as per your requirements:
13 0 * * * /home/admin/bin/ftpbackup.sh >/dev/null 2>&1

Description:


The cron daemon is a long running process that executes commands at specific dates and times. To schedule one-time only tasks with cron, use at or batch. For commands that need to be executed repeatedly (e.g. hourly, daily or weekly), use crontab, which has the following options:
crontab filename Install filename as your crontab file.
crontab -e Edit your crontab file.
crontab -l Show your crontab file.
crontab -r Remove your crontab file.
MAILTO=user@domain.com Emails the output to the specified address.
The crontab command creates a crontab file containing commands and how often cron should execute them. Each entry in a crontab file consists of six fields, specified in the following order:

    minute(s) hour(s) day(s) month(s) weekday(s) command(s)
The fields are separated by spaces or tabs. The first five are integer patterns and the sixth is the command to be executed. The following table briefly describes each of the fields:

Field Value Description
minute 0-59 The exact minute that the command sequence executes.
hour 0-23 The hour of the day that the command sequence executes.
day 1-31 The day of the month that the command sequence executes.
month 1-12 The month of the year that the command sequence executes.
weekday 0-6 The day of the week that the command sequence executes. Sunday=0, Monday = 1, Tuesday = 2, and so forth.
command Special The complete command sequence variable that is to be executed.
Each of the patterns from the first five fields may either be an asterisk (*) (meaning all legal values) or a list of elements separated by commas. An element is either a number or two numbers separated by a minus sign (meaning an inclusive range). Note that the specification of days may be made by two fields (day of the month and day of the week). If both are specified as a list of elements, both are followed. For example:

    MAILTO=user@domain.com
    0 0 1,15 * 1 /big/dom/xdomain/cgi-bin/scriptname.cgi
The cron daemon would run the program scriptname.cgi in the cgi-bin directory on the first and fifteenth of each month, as well as on every Monday. To specify days by only one field, the other field should be set to *. For example:

    MAILTO=user@domain.com
    0 0 * * 1 /big/dom/xdomain/cgi-bin/scriptname.cgi
The program would then only run on Mondays.
If a cron job specified in your crontab entry produces any error messages when it runs, they will be reported to you via email.
You may create crontab files in notepad (being sure to upload them in ASCII) or you may create them from the command line (via SSH) by simply typing:

    mcedit cronfile.txt
For more information, consult the man pages. man pages are the directions and tutorials available to you right at the command line. Type any of the following lines to open the relevant tutorials ([Enter] means to hit the Enter (return) key):

    man 5 crontab [Enter]
    man 1 crontab [Enter]
    man cron [Enter]
    man at [Enter]
    man batch [Enter]
    man 1 cron [Enter]
Note:Your crontab file must end with a line feed - in other words, make sure to press [Enter] after the last line in the file.


Try It!

Now that you have read an overview of cron, test your skills by following the steps below. Once completed, you should have a cron file of your own! Step 1: Create a simple text file using Notepad or any simple text editor that contains the following text:

    MAILTO=yourusername@yourdomain.com [Enter]
    58 23 * * * /big/dom/xdomain/cgi-bin/yourscript.pl
    [Enter]
Notes for Step 1

  1. You may create this file using your CNC File Manager by navigating to the /big/dom/xdomain/ directory and clicking 'Create New File' or any other simple text editor such as Notepad.
  2. [Enter] should not actually be typed. [Enter] means hit the "Enter" (return) key to begin the next line and to add a blank line feed at the end of the last line of your cron file. It is important to always remember to do this.
  3. MAILTO: Replace the email address with a valid email address of your own. This will ensure that when your cron runs, any output from the script, such as an error message, will be emailed to you.
  4. The second line tells your server when to run this script. In this example, the script will be run at 11:58 PM Eastern Time every day of the year.
  5. It is very important that you double-check the script path to ensure it is correct and remember the file names are CaSe-SeNsiTive.
Step 2: Name the text file (example: cronfile.txt).
The cronfile name may be replaced with any name you choose. For instance, if you are running a cron to trigger an email reminder script, it could be called reminder.txt. Many choose to simply call it cronfile.txt. Step 3: Upload the file in ASCII.
Any standard FTP client or your account's CNC upload feature will work for this. The file must be uploaded in ASCII mode and it is recommended that it be placed in your /big/dom/xdomain/ directory. It may be placed anywhere in your account but to prevent browser access (security risks) it is strongly recommended to place it above your /www directory.
Step 4: Connect to your account via SSH and issue the following command:

    crontab /big/dom/xdomain/cronfile.txt
The above tells the server's crontab where the file is located and that you wish to make it active. Make sure the path to the file is the actual path to where the file was placed. If successful, you will be returned to the command bash line. If not, an error will be displayed.
IMPORTANT NOTES
Removing/Stopping the Cron: Deleting the cronfile.txt file from your account will not stop the cron. You may remove this file at any time, however since the server's crontab already has the contents, the cron will still run once it has been made active.
To turn the cron off, you must connect to your account via SSH and issue the following command:

    crontab -r
The crontab -r will deactivate the cronjob and remove the file contents from the server.
Security Note: If the script the cron is set up to run is in the /cgi-bin/ or /www/ directory, it may be run at any time by anyone with browser access. If the crontab is all that should run the script and you do not want the public to be able to run the script, then you will need to place the script in a directory above the /cgi-bin/ and /www/ directories such as: /big/dom/xdom/user/cronscripts/scriptname
                                          More Details Click

Find to setup cron Job To Backup Data on Linux Automatically both Centos

Just add cron job as per your requirements:
13 0 * * * /home/admin/bin/ftpbackup.sh >/dev/null 2>&1

Description:


The cron daemon is a long running process that executes commands at specific dates and times. To schedule one-time only tasks with cron, use at or batch. For commands that need to be executed repeatedly (e.g. hourly, daily or weekly), use crontab, which has the following options:
crontab filename Install filename as your crontab file.
crontab -e Edit your crontab file.
crontab -l Show your crontab file.
crontab -r Remove your crontab file.
MAILTO=user@domain.com Emails the output to the specified address.
The crontab command creates a crontab file containing commands and how often cron should execute them. Each entry in a crontab file consists of six fields, specified in the following order:

    minute(s) hour(s) day(s) month(s) weekday(s) command(s)
The fields are separated by spaces or tabs. The first five are integer patterns and the sixth is the command to be executed. The following table briefly describes each of the fields:

Field Value Description
minute 0-59 The exact minute that the command sequence executes.
hour 0-23 The hour of the day that the command sequence executes.
day 1-31 The day of the month that the command sequence executes.
month 1-12 The month of the year that the command sequence executes.
weekday 0-6 The day of the week that the command sequence executes. Sunday=0, Monday = 1, Tuesday = 2, and so forth.
command Special The complete command sequence variable that is to be executed.
Each of the patterns from the first five fields may either be an asterisk (*) (meaning all legal values) or a list of elements separated by commas. An element is either a number or two numbers separated by a minus sign (meaning an inclusive range). Note that the specification of days may be made by two fields (day of the month and day of the week). If both are specified as a list of elements, both are followed. For example:

    MAILTO=user@domain.com
    0 0 1,15 * 1 /big/dom/xdomain/cgi-bin/scriptname.cgi
The cron daemon would run the program scriptname.cgi in the cgi-bin directory on the first and fifteenth of each month, as well as on every Monday. To specify days by only one field, the other field should be set to *. For example:

    MAILTO=user@domain.com
    0 0 * * 1 /big/dom/xdomain/cgi-bin/scriptname.cgi
The program would then only run on Mondays.
If a cron job specified in your crontab entry produces any error messages when it runs, they will be reported to you via email.
You may create crontab files in notepad (being sure to upload them in ASCII) or you may create them from the command line (via SSH) by simply typing:

    mcedit cronfile.txt
For more information, consult the man pages. man pages are the directions and tutorials available to you right at the command line. Type any of the following lines to open the relevant tutorials ([Enter] means to hit the Enter (return) key):

    man 5 crontab [Enter]
    man 1 crontab [Enter]
    man cron [Enter]
    man at [Enter]
    man batch [Enter]
    man 1 cron [Enter]
Note:Your crontab file must end with a line feed - in other words, make sure to press [Enter] after the last line in the file.


Try It!

Now that you have read an overview of cron, test your skills by following the steps below. Once completed, you should have a cron file of your own! Step 1: Create a simple text file using Notepad or any simple text editor that contains the following text:

    MAILTO=yourusername@yourdomain.com [Enter]
    58 23 * * * /big/dom/xdomain/cgi-bin/yourscript.pl
    [Enter]
Notes for Step 1

  1. You may create this file using your CNC File Manager by navigating to the /big/dom/xdomain/ directory and clicking 'Create New File' or any other simple text editor such as Notepad.
  2. [Enter] should not actually be typed. [Enter] means hit the "Enter" (return) key to begin the next line and to add a blank line feed at the end of the last line of your cron file. It is important to always remember to do this.
  3. MAILTO: Replace the email address with a valid email address of your own. This will ensure that when your cron runs, any output from the script, such as an error message, will be emailed to you.
  4. The second line tells your server when to run this script. In this example, the script will be run at 11:58 PM Eastern Time every day of the year.
  5. It is very important that you double-check the script path to ensure it is correct and remember the file names are CaSe-SeNsiTive.
Step 2: Name the text file (example: cronfile.txt).
The cronfile name may be replaced with any name you choose. For instance, if you are running a cron to trigger an email reminder script, it could be called reminder.txt. Many choose to simply call it cronfile.txt. Step 3: Upload the file in ASCII.
Any standard FTP client or your account's CNC upload feature will work for this. The file must be uploaded in ASCII mode and it is recommended that it be placed in your /big/dom/xdomain/ directory. It may be placed anywhere in your account but to prevent browser access (security risks) it is strongly recommended to place it above your /www directory.
Step 4: Connect to your account via SSH and issue the following command:

    crontab /big/dom/xdomain/cronfile.txt
The above tells the server's crontab where the file is located and that you wish to make it active. Make sure the path to the file is the actual path to where the file was placed. If successful, you will be returned to the command bash line. If not, an error will be displayed.
IMPORTANT NOTES
Removing/Stopping the Cron: Deleting the cronfile.txt file from your account will not stop the cron. You may remove this file at any time, however since the server's crontab already has the contents, the cron will still run once it has been made active.
To turn the cron off, you must connect to your account via SSH and issue the following command:

    crontab -r
The crontab -r will deactivate the cronjob and remove the file contents from the server.
Security Note: If the script the cron is set up to run is in the /cgi-bin/ or /www/ directory, it may be run at any time by anyone with browser access. If the crontab is all that should run the script and you do not want the public to be able to run the script, then you will need to place the script in a directory above the /cgi-bin/ and /www/ directories such as: /big/dom/xdom/user/cronscripts/scriptname
                                          More Details Click

IpTables Configuration and Secure the Firewall on Linux and Centos


Linux comes with a host based firewall called Netfilter. According to the official project site:
netfilter is a set of hooks inside the Linux kernel that allows kernel modules to register callback functions with the network stack. A registered callback function is then called back for every packet that traverses the respective hook within the network stack.
This Linux based firewall is controlled by the program called iptables to handles filtering for IPv4, and ip6tables handles filtering for IPv6. I strongly recommend that you first read our quick tutorial that explains how to configure a host-based firewall called Netfilter (iptables) under CentOS / RHEL / Fedora / Redhat Enterprise Linux. This post list most common iptables solutions required by a new Linux user to secure his or her Linux operating system from intruders.

IPTABLES Rules Example

  • Most of the actions listed in this post are written with the assumption that they will be executed by the root user running the bash or any other modern shell. Do not type commands on remote system as it will disconnect your access.
  • For demonstration purpose I've used RHEL 6.x, but the following command should work with any modern Linux distro.
  • This is NOT a tutorial on how to set iptables. See tutorial here. It is a quick cheat sheet to common iptables commands.

#1: Displaying the Status of Your Firewall

Type the following command as root:
# iptables -L -n -v
Sample outputs:
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source         destination
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source         destination
Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source         destination
Above output indicates that the firewall is not active. The following sample shows an active firewall:
# iptables -L -n -v
Sample outputs:
Chain INPUT (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 DROP       all  --  *      *       0.0.0.0/0            0.0.0.0/0           state INVALID
  394 43586 ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
   93 17292 ACCEPT     all  --  br0    *       0.0.0.0/0            0.0.0.0/0
    1   142 ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0
Chain FORWARD (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 ACCEPT     all  --  br0    br0     0.0.0.0/0            0.0.0.0/0
    0     0 DROP       all  --  *      *       0.0.0.0/0            0.0.0.0/0           state INVALID
    0     0 TCPMSS     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp flags:0x06/0x02 TCPMSS clamp to PMTU
    0     0 ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
    0     0 wanin      all  --  vlan2  *       0.0.0.0/0            0.0.0.0/0
    0     0 wanout     all  --  *      vlan2   0.0.0.0/0            0.0.0.0/0
    0     0 ACCEPT     all  --  br0    *       0.0.0.0/0            0.0.0.0/0
Chain OUTPUT (policy ACCEPT 425 packets, 113K bytes)
 pkts bytes target     prot opt in     out     source               destination
Chain wanin (1 references)
 pkts bytes target     prot opt in     out     source               destination
Chain wanout (1 references)
 pkts bytes target     prot opt in     out     source               destination
Where,
  • -L : List rules.
  • -v : Display detailed information. This option makes the list command show the interface name, the rule options, and the TOS masks. The packet and byte counters are also listed, with the suffix 'K', 'M' or 'G' for 1000, 1,000,000 and 1,000,000,000 multipliers respectively.
  • -n : Display IP address and port in numeric format. Do not use DNS to resolve names. This will speed up listing.

#1.1: To inspect firewall with line numbers, enter:

# iptables -n -L -v --line-numbers
Sample outputs:
Chain INPUT (policy DROP)
num  target     prot opt source               destination
1    DROP       all  --  0.0.0.0/0            0.0.0.0/0           state INVALID
2    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
3    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
4    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
Chain FORWARD (policy DROP)
num  target     prot opt source               destination
1    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
2    DROP       all  --  0.0.0.0/0            0.0.0.0/0           state INVALID
3    TCPMSS     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp flags:0x06/0x02 TCPMSS clamp to PMTU
4    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
5    wanin      all  --  0.0.0.0/0            0.0.0.0/0
6    wanout     all  --  0.0.0.0/0            0.0.0.0/0
7    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
Chain OUTPUT (policy ACCEPT)
num  target     prot opt source               destination
Chain wanin (1 references)
num  target     prot opt source               destination
Chain wanout (1 references)
num  target     prot opt source               destination
You can use line numbers to delete or insert new rules into the firewall.

#1.2: To display INPUT or OUTPUT chain rules, enter:

# iptables -L INPUT -n -v
# iptables -L OUTPUT -n -v --line-numbers

#2: Stop / Start / Restart the Firewall

If you are using CentOS / RHEL / Fedora Linux, enter:
# service iptables stop
# service iptables start
# service iptables restart

You can use the iptables command itself to stop the firewall and delete all rules:
# iptables -F
# iptables -X
# iptables -t nat -F
# iptables -t nat -X
# iptables -t mangle -F
# iptables -t mangle -X
# iptables -P INPUT ACCEPT
# iptables -P OUTPUT ACCEPT
# iptables -P FORWARD ACCEPT

Where,
  • -F : Deleting (flushing) all the rules.
  • -X : Delete chain.
  • -t table_name : Select table (called nat or mangle) and delete/flush rules.
  • -P : Set the default policy (such as DROP, REJECT, or ACCEPT).

#3: Delete Firewall Rules

To display line number along with other information for existing rules, enter:
# iptables -L INPUT -n --line-numbers
# iptables -L OUTPUT -n --line-numbers
# iptables -L OUTPUT -n --line-numbers | less
# iptables -L OUTPUT -n --line-numbers | grep 202.54.1.1

You will get the list of IP. Look at the number on the left, then use number to delete it. For example delete line number 4, enter:
# iptables -D INPUT 4
OR find source IP 202.54.1.1 and delete from rule:
# iptables -D INPUT -s 202.54.1.1 -j DROP
Where,
  • -D : Delete one or more rules from the selected chain

#4: Insert Firewall Rules

To insert one or more rules in the selected chain as the given rule number use the following syntax. First find out line numbers, enter:
# iptables -L INPUT -n --line-numbers
Sample outputs:
Chain INPUT (policy DROP)
num  target     prot opt source               destination
1    DROP       all  --  202.54.1.1           0.0.0.0/0
2    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state NEW,ESTABLISHED 
To insert rule between 1 and 2, enter:
# iptables -I INPUT 2 -s 202.54.1.2 -j DROP
To view updated rules, enter:
# iptables -L INPUT -n --line-numbers
Sample outputs:
Chain INPUT (policy DROP)
num  target     prot opt source               destination
1    DROP       all  --  202.54.1.1           0.0.0.0/0
2    DROP       all  --  202.54.1.2           0.0.0.0/0
3    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state NEW,ESTABLISHED

#5: Save Firewall Rules

To save firewall rules under CentOS / RHEL / Fedora Linux, enter:
# service iptables save
In this example, drop an IP and save firewall rules:
# iptables -A INPUT -s 202.5.4.1 -j DROP
# service iptables save

For all other distros use the iptables-save command:
# iptables-save > /root/my.active.firewall.rules
# cat /root/my.active.firewall.rules

#6: Restore Firewall Rules

To restore firewall rules form a file called /root/my.active.firewall.rules, enter:
# iptables-restore < /root/my.active.firewall.rules
To restore firewall rules under CentOS / RHEL / Fedora Linux, enter:
# service iptables restart

#7: Set the Default Firewall Policies

To drop all traffic:
# iptables -P INPUT DROP
# iptables -P OUTPUT DROP
# iptables -P FORWARD DROP
# iptables -L -v -n
#### you will not able to connect anywhere as all traffic is dropped ###
# ping cyberciti.biz
# wget http://www.kernel.org/pub/linux/kernel/v3.0/testing/linux-3.2-rc5.tar.bz2

#7.1: Only Block Incoming Traffic

To drop all incoming / forwarded packets, but allow outgoing traffic, enter:
# iptables -P INPUT DROP
# iptables -P FORWARD DROP
# iptables -P OUTPUT ACCEPT
# iptables -A INPUT -m state --state NEW,ESTABLISHED -j ACCEPT
# iptables -L -v -n
### *** now ping and wget should work *** ###
# ping cyberciti.biz
# wget http://www.kernel.org/pub/linux/kernel/v3.0/testing/linux-3.2-rc5.tar.bz2

#8:Drop Private Network Address On Public Interface

IP spoofing is nothing but to stop the following IPv4 address ranges for private networks on your public interfaces. Packets with non-routable source addresses should be rejected using the following syntax:
# iptables -A INPUT -i eth1 -s 192.168.0.0/24 -j DROP
# iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP

#8.1: IPv4 Address Ranges For Private Networks (make sure you block them on public interface)

  • 10.0.0.0/8 -j (A)
  • 172.16.0.0/12 (B)
  • 192.168.0.0/16 (C)
  • 224.0.0.0/4 (MULTICAST D)
  • 240.0.0.0/5 (E)
  • 127.0.0.0/8 (LOOPBACK)

#9: Blocking an IP Address (BLOCK IP)

To block an attackers ip address called 1.2.3.4, enter:
# iptables -A INPUT -s 1.2.3.4 -j DROP
# iptables -A INPUT -s 192.168.0.0/24 -j DROP

#10: Block Incoming Port Requests (BLOCK PORT)

To block all service requests on port 80, enter:
# iptables -A INPUT -p tcp --dport 80 -j DROP
# iptables -A INPUT -i eth1 -p tcp --dport 80 -j DROP

To block port 80 only for an ip address 1.2.3.4, enter:
# iptables -A INPUT -p tcp -s 1.2.3.4 --dport 80 -j DROP
# iptables -A INPUT -i eth1 -p tcp -s 192.168.1.0/24 --dport 80 -j DROP

#11: Block Outgoing IP Address

To block outgoing traffic to a particular host or domain such as cyberciti.biz, enter:
# host -t a cyberciti.biz
Sample outputs:
cyberciti.biz has address 75.126.153.206
Note down its ip address and type the following to block all outgoing traffic to 75.126.153.206:
# iptables -A OUTPUT -d 75.126.153.206 -j DROP
You can use a subnet as follows:
# iptables -A OUTPUT -d 192.168.1.0/24 -j DROP
# iptables -A OUTPUT -o eth1 -d 192.168.1.0/24 -j DROP

#11.1: Example - Block Facebook.com Domain

First, find out all ip address of facebook.com, enter:
# host -t a www.facebook.com
Sample outputs:
www.facebook.com has address 69.171.228.40
Find CIDR for 69.171.228.40, enter:
# whois 69.171.228.40 | grep CIDR
Sample outputs:
CIDR:           69.171.224.0/19
To prevent outgoing access to www.facebook.com, enter:
# iptables -A OUTPUT -p tcp -d 69.171.224.0/19 -j DROP
You can also use domain name, enter:
# iptables -A OUTPUT -p tcp -d www.facebook.com -j DROP
# iptables -A OUTPUT -p tcp -d facebook.com -j DROP

From the iptables man page:
... specifying any name to be resolved with a remote query such as DNS (e.g., facebook.com is a really bad idea), a network IP address (with /mask), or a plain IP address ...

#12: Log and Drop Packets

Type the following to log and block IP spoofing on public interface called eth1
# iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j LOG --log-prefix "IP_SPOOF A: "
# iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP

By default everything is logged to /var/log/messages file.
# tail -f /var/log/messages
# grep --color 'IP SPOOF' /var/log/messages

#13: Log and Drop Packets with Limited Number of Log Entries

The -m limit module can limit the number of log entries created per time. This is used to prevent flooding your log file. To log and drop spoofing per 5 minutes, in bursts of at most 7 entries .
# iptables -A INPUT -i eth1 -s 10.0.0.0/8 -m limit --limit 5/m --limit-burst 7 -j LOG --log-prefix "IP_SPOOF A: "
# iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP

#14: Drop or Accept Traffic From Mac Address

Use the following syntax:
# iptables -A INPUT -m mac --mac-source 00:0F:EA:91:04:08 -j DROP
## *only accept traffic for TCP port # 8080 from mac 00:0F:EA:91:04:07 * ##
# iptables -A INPUT -p tcp --destination-port 22 -m mac --mac-source 00:0F:EA:91:04:07 -j ACCEPT

#15: Block or Allow ICMP Ping Request

Type the following command to block ICMP ping requests:
# iptables -A INPUT -p icmp --icmp-type echo-request -j DROP
# iptables -A INPUT -i eth1 -p icmp --icmp-type echo-request -j DROP

Ping responses can also be limited to certain networks or hosts:
# iptables -A INPUT -s 192.168.1.0/24 -p icmp --icmp-type echo-request -j ACCEPT
The following only accepts limited type of ICMP requests:
### ** assumed that default INPUT policy set to DROP ** #############
iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT
iptables -A INPUT -p icmp --icmp-type destination-unreachable -j ACCEPT
iptables -A INPUT -p icmp --icmp-type time-exceeded -j ACCEPT
## ** all our server to respond to pings ** ##
iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT

#16: Open Range of Ports

Use the following syntax to open a range of ports:
iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 7000:7010 -j ACCEPT

#17: Open Range of IP Addresses

Use the following syntax to open a range of IP address:
## only accept connection to tcp port 80 (Apache) if ip is between 192.168.1.100 and 192.168.1.200 ##
iptables -A INPUT -p tcp --destination-port 80 -m iprange --src-range 192.168.1.100-192.168.1.200 -j ACCEPT

## nat example ##
iptables -t nat -A POSTROUTING -j SNAT --to-source 192.168.1.20-192.168.1.25

#18: Established Connections and Restaring The Firewall

When you restart the iptables service it will drop established connections as it unload modules from the system under RHEL / Fedora / CentOS Linux. Edit, /etc/sysconfig/iptables-config and set IPTABLES_MODULES_UNLOAD as follows:
IPTABLES_MODULES_UNLOAD = no

#19: Help Iptables Flooding My Server Screen

Use the crit log level to send messages to a log file instead of console:
iptables -A INPUT -s 1.2.3.4 -p tcp --destination-port 80 -j LOG --log-level crit

#20: Block or Open Common Ports

The following shows syntax for opening and closing common TCP and UDP ports:
  1.  
  2. Replace ACCEPT with DROP to block port:
  3. ## open port ssh tcp port 22 ##
  4. iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
  5. iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 22 -j ACCEPT
  6.  
  7. ## open cups (printing service) udp/tcp port 631 for LAN users ##
  8. iptables -A INPUT -s 192.168.1.0/24 -p udp -m udp --dport 631 -j ACCEPT
  9. iptables -A INPUT -s 192.168.1.0/24 -p tcp -m tcp --dport 631 -j ACCEPT
  10.  
  11. ## allow time sync via NTP for lan users (open udp port 123) ##
  12. iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p udp --dport 123 -j ACCEPT
  13.  
  14. ## open tcp port 25 (smtp) for all ##
  15. iptables -A INPUT -m state --state NEW -p tcp --dport 25 -j ACCEPT
  16.  
  17. # open dns server ports for all ##
  18. iptables -A INPUT -m state --state NEW -p udp --dport 53 -j ACCEPT
  19. iptables -A INPUT -m state --state NEW -p tcp --dport 53 -j ACCEPT
  20.  
  21. ## open http/https (Apache) server port to all ##
  22. iptables -A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT
  23. iptables -A INPUT -m state --state NEW -p tcp --dport 443 -j ACCEPT
  24.  
  25. ## open tcp port 110 (pop3) for all ##
  26. iptables -A INPUT -m state --state NEW -p tcp --dport 110 -j ACCEPT
  27.  
  28. ## open tcp port 143 (imap) for all ##
  29. iptables -A INPUT -m state --state NEW -p tcp --dport 143 -j ACCEPT
  30.  
  31. ## open access to Samba file server for lan users only ##
  32. iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 137 -j ACCEPT
  33. iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 138 -j ACCEPT
  34. iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 139 -j ACCEPT
  35. iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 445 -j ACCEPT
  36.  
  37. ## open access to proxy server for lan users only ##
  38. iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 3128 -j ACCEPT
  39.  
  40. ## open access to mysql server for lan users only ##
  41. iptables -I INPUT -p tcp --dport 3306 -j ACCEPT
  42.  

#21: Restrict the Number of Parallel Connections To a Server Per Client IP

You can use connlimit module to put such restrictions. To allow 3 ssh connections per client host, enter:
# iptables -A INPUT -p tcp --syn --dport 22 -m connlimit --connlimit-above 3 -j REJECT
Set HTTP requests to 20:
# iptables -p tcp --syn --dport 80 -m connlimit --connlimit-above 20 --connlimit-mask 24 -j DROP
Where,
  1. --connlimit-above 3 : Match if the number of existing connections is above 3.
  2. --connlimit-mask 24 : Group hosts using the prefix length. For IPv4, this must be a number between (including) 0 and 32.

#22: HowTO: Use iptables Like a Pro

For more information about iptables, please see the manual page by typing man iptables from the command line:
$ man iptables
You can see the help using the following syntax too:
# iptables -h
To see help with specific commands and targets, enter:
# iptables -j DROP -h

#22.1: Testing Your Firewall

Find out if ports are open or not, enter:
# netstat -tulpn
Find out if tcp port 80 open or not, enter:
# netstat -tulpn | grep :80
If port 80 is not open, start the Apache, enter:
# service httpd start
Make sure iptables allowing access to the port 80:
# iptables -L INPUT -v -n | grep 80
Otherwise open port 80 using the iptables for all users:
# iptables -A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT
# service iptables save

Use the telnet command to see if firewall allows to connect to port 80:
$ telnet www.cyberciti.biz 80
Sample outputs:
Trying 75.126.153.206...
Connected to www.cyberciti.biz.
Escape character is '^]'.
^]
telnet> quit
Connection closed.
You can use nmap to probe your own server using the following syntax:
$ nmap -sS -p 80 www.cyberciti.biz
Sample outputs:
Starting Nmap 5.00 ( http://nmap.org ) at 2011-12-13 13:19 IST
Interesting ports on www.cyberciti.biz (75.126.153.206):
PORT   STATE SERVICE
80/tcp open  http
Nmap done: 1 IP address (1 host up) scanned in 1.00 seconds
I also recommend you install and use sniffer such as tcpdupm and ngrep to test your firewall settings.

Conclusion:

This post only list basic rules for new Linux users. You can create and build more complex rules. This requires good understanding of TCP/IP, Linux kernel tuning via sysctl.conf, and good knowledge of your own setup. Stay tuned for next topics:
  • Stateful packet inspection.
  • Using connection tracking helpers.
  • Network address translation.
  • Layer 2 filtering.
  • Firewall testing tools.
  • Dealing with VPNs, DNS, Web, Proxy, and other protocols.
More Details Click
                            Authorby--cyberciti.biz

Find to Firewall Configuration and IpTables Configuration and Secure the Firewall on Linux and Centos


Linux comes with a host based firewall called Netfilter. According to the official project site:
netfilter is a set of hooks inside the Linux kernel that allows kernel modules to register callback functions with the network stack. A registered callback function is then called back for every packet that traverses the respective hook within the network stack.
This Linux based firewall is controlled by the program called iptables to handles filtering for IPv4, and ip6tables handles filtering for IPv6. I strongly recommend that you first read our quick tutorial that explains how to configure a host-based firewall called Netfilter (iptables) under CentOS / RHEL / Fedora / Redhat Enterprise Linux. This post list most common iptables solutions required by a new Linux user to secure his or her Linux operating system from intruders.

IPTABLES Rules Example

  • Most of the actions listed in this post are written with the assumption that they will be executed by the root user running the bash or any other modern shell. Do not type commands on remote system as it will disconnect your access.
  • For demonstration purpose I've used RHEL 6.x, but the following command should work with any modern Linux distro.
  • This is NOT a tutorial on how to set iptables. See tutorial here. It is a quick cheat sheet to common iptables commands.

#1: Displaying the Status of Your Firewall

Type the following command as root:
# iptables -L -n -v
Sample outputs:
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source         destination
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source         destination
Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source         destination
Above output indicates that the firewall is not active. The following sample shows an active firewall:
# iptables -L -n -v
Sample outputs:
Chain INPUT (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 DROP       all  --  *      *       0.0.0.0/0            0.0.0.0/0           state INVALID
  394 43586 ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
   93 17292 ACCEPT     all  --  br0    *       0.0.0.0/0            0.0.0.0/0
    1   142 ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0
Chain FORWARD (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 ACCEPT     all  --  br0    br0     0.0.0.0/0            0.0.0.0/0
    0     0 DROP       all  --  *      *       0.0.0.0/0            0.0.0.0/0           state INVALID
    0     0 TCPMSS     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp flags:0x06/0x02 TCPMSS clamp to PMTU
    0     0 ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
    0     0 wanin      all  --  vlan2  *       0.0.0.0/0            0.0.0.0/0
    0     0 wanout     all  --  *      vlan2   0.0.0.0/0            0.0.0.0/0
    0     0 ACCEPT     all  --  br0    *       0.0.0.0/0            0.0.0.0/0
Chain OUTPUT (policy ACCEPT 425 packets, 113K bytes)
 pkts bytes target     prot opt in     out     source               destination
Chain wanin (1 references)
 pkts bytes target     prot opt in     out     source               destination
Chain wanout (1 references)
 pkts bytes target     prot opt in     out     source               destination
Where,
  • -L : List rules.
  • -v : Display detailed information. This option makes the list command show the interface name, the rule options, and the TOS masks. The packet and byte counters are also listed, with the suffix 'K', 'M' or 'G' for 1000, 1,000,000 and 1,000,000,000 multipliers respectively.
  • -n : Display IP address and port in numeric format. Do not use DNS to resolve names. This will speed up listing.

#1.1: To inspect firewall with line numbers, enter:

# iptables -n -L -v --line-numbers
Sample outputs:
Chain INPUT (policy DROP)
num  target     prot opt source               destination
1    DROP       all  --  0.0.0.0/0            0.0.0.0/0           state INVALID
2    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
3    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
4    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
Chain FORWARD (policy DROP)
num  target     prot opt source               destination
1    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
2    DROP       all  --  0.0.0.0/0            0.0.0.0/0           state INVALID
3    TCPMSS     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp flags:0x06/0x02 TCPMSS clamp to PMTU
4    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
5    wanin      all  --  0.0.0.0/0            0.0.0.0/0
6    wanout     all  --  0.0.0.0/0            0.0.0.0/0
7    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
Chain OUTPUT (policy ACCEPT)
num  target     prot opt source               destination
Chain wanin (1 references)
num  target     prot opt source               destination
Chain wanout (1 references)
num  target     prot opt source               destination
You can use line numbers to delete or insert new rules into the firewall.

#1.2: To display INPUT or OUTPUT chain rules, enter:

# iptables -L INPUT -n -v
# iptables -L OUTPUT -n -v --line-numbers

#2: Stop / Start / Restart the Firewall

If you are using CentOS / RHEL / Fedora Linux, enter:
# service iptables stop
# service iptables start
# service iptables restart

You can use the iptables command itself to stop the firewall and delete all rules:
# iptables -F
# iptables -X
# iptables -t nat -F
# iptables -t nat -X
# iptables -t mangle -F
# iptables -t mangle -X
# iptables -P INPUT ACCEPT
# iptables -P OUTPUT ACCEPT
# iptables -P FORWARD ACCEPT

Where,
  • -F : Deleting (flushing) all the rules.
  • -X : Delete chain.
  • -t table_name : Select table (called nat or mangle) and delete/flush rules.
  • -P : Set the default policy (such as DROP, REJECT, or ACCEPT).

#3: Delete Firewall Rules

To display line number along with other information for existing rules, enter:
# iptables -L INPUT -n --line-numbers
# iptables -L OUTPUT -n --line-numbers
# iptables -L OUTPUT -n --line-numbers | less
# iptables -L OUTPUT -n --line-numbers | grep 202.54.1.1

You will get the list of IP. Look at the number on the left, then use number to delete it. For example delete line number 4, enter:
# iptables -D INPUT 4
OR find source IP 202.54.1.1 and delete from rule:
# iptables -D INPUT -s 202.54.1.1 -j DROP
Where,
  • -D : Delete one or more rules from the selected chain

#4: Insert Firewall Rules

To insert one or more rules in the selected chain as the given rule number use the following syntax. First find out line numbers, enter:
# iptables -L INPUT -n --line-numbers
Sample outputs:
Chain INPUT (policy DROP)
num  target     prot opt source               destination
1    DROP       all  --  202.54.1.1           0.0.0.0/0
2    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state NEW,ESTABLISHED 
To insert rule between 1 and 2, enter:
# iptables -I INPUT 2 -s 202.54.1.2 -j DROP
To view updated rules, enter:
# iptables -L INPUT -n --line-numbers
Sample outputs:
Chain INPUT (policy DROP)
num  target     prot opt source               destination
1    DROP       all  --  202.54.1.1           0.0.0.0/0
2    DROP       all  --  202.54.1.2           0.0.0.0/0
3    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state NEW,ESTABLISHED

#5: Save Firewall Rules

To save firewall rules under CentOS / RHEL / Fedora Linux, enter:
# service iptables save
In this example, drop an IP and save firewall rules:
# iptables -A INPUT -s 202.5.4.1 -j DROP
# service iptables save

For all other distros use the iptables-save command:
# iptables-save > /root/my.active.firewall.rules
# cat /root/my.active.firewall.rules

#6: Restore Firewall Rules

To restore firewall rules form a file called /root/my.active.firewall.rules, enter:
# iptables-restore < /root/my.active.firewall.rules
To restore firewall rules under CentOS / RHEL / Fedora Linux, enter:
# service iptables restart

#7: Set the Default Firewall Policies

To drop all traffic:
# iptables -P INPUT DROP
# iptables -P OUTPUT DROP
# iptables -P FORWARD DROP
# iptables -L -v -n
#### you will not able to connect anywhere as all traffic is dropped ###
# ping cyberciti.biz
# wget http://www.kernel.org/pub/linux/kernel/v3.0/testing/linux-3.2-rc5.tar.bz2

#7.1: Only Block Incoming Traffic

To drop all incoming / forwarded packets, but allow outgoing traffic, enter:
# iptables -P INPUT DROP
# iptables -P FORWARD DROP
# iptables -P OUTPUT ACCEPT
# iptables -A INPUT -m state --state NEW,ESTABLISHED -j ACCEPT
# iptables -L -v -n
### *** now ping and wget should work *** ###
# ping cyberciti.biz
# wget http://www.kernel.org/pub/linux/kernel/v3.0/testing/linux-3.2-rc5.tar.bz2

#8:Drop Private Network Address On Public Interface

IP spoofing is nothing but to stop the following IPv4 address ranges for private networks on your public interfaces. Packets with non-routable source addresses should be rejected using the following syntax:
# iptables -A INPUT -i eth1 -s 192.168.0.0/24 -j DROP
# iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP

#8.1: IPv4 Address Ranges For Private Networks (make sure you block them on public interface)

  • 10.0.0.0/8 -j (A)
  • 172.16.0.0/12 (B)
  • 192.168.0.0/16 (C)
  • 224.0.0.0/4 (MULTICAST D)
  • 240.0.0.0/5 (E)
  • 127.0.0.0/8 (LOOPBACK)

#9: Blocking an IP Address (BLOCK IP)

To block an attackers ip address called 1.2.3.4, enter:
# iptables -A INPUT -s 1.2.3.4 -j DROP
# iptables -A INPUT -s 192.168.0.0/24 -j DROP

#10: Block Incoming Port Requests (BLOCK PORT)

To block all service requests on port 80, enter:
# iptables -A INPUT -p tcp --dport 80 -j DROP
# iptables -A INPUT -i eth1 -p tcp --dport 80 -j DROP

To block port 80 only for an ip address 1.2.3.4, enter:
# iptables -A INPUT -p tcp -s 1.2.3.4 --dport 80 -j DROP
# iptables -A INPUT -i eth1 -p tcp -s 192.168.1.0/24 --dport 80 -j DROP

#11: Block Outgoing IP Address

To block outgoing traffic to a particular host or domain such as cyberciti.biz, enter:
# host -t a cyberciti.biz
Sample outputs:
cyberciti.biz has address 75.126.153.206
Note down its ip address and type the following to block all outgoing traffic to 75.126.153.206:
# iptables -A OUTPUT -d 75.126.153.206 -j DROP
You can use a subnet as follows:
# iptables -A OUTPUT -d 192.168.1.0/24 -j DROP
# iptables -A OUTPUT -o eth1 -d 192.168.1.0/24 -j DROP

#11.1: Example - Block Facebook.com Domain

First, find out all ip address of facebook.com, enter:
# host -t a www.facebook.com
Sample outputs:
www.facebook.com has address 69.171.228.40
Find CIDR for 69.171.228.40, enter:
# whois 69.171.228.40 | grep CIDR
Sample outputs:
CIDR:           69.171.224.0/19
To prevent outgoing access to www.facebook.com, enter:
# iptables -A OUTPUT -p tcp -d 69.171.224.0/19 -j DROP
You can also use domain name, enter:
# iptables -A OUTPUT -p tcp -d www.facebook.com -j DROP
# iptables -A OUTPUT -p tcp -d facebook.com -j DROP

From the iptables man page:
... specifying any name to be resolved with a remote query such as DNS (e.g., facebook.com is a really bad idea), a network IP address (with /mask), or a plain IP address ...

#12: Log and Drop Packets

Type the following to log and block IP spoofing on public interface called eth1
# iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j LOG --log-prefix "IP_SPOOF A: "
# iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP

By default everything is logged to /var/log/messages file.
# tail -f /var/log/messages
# grep --color 'IP SPOOF' /var/log/messages

#13: Log and Drop Packets with Limited Number of Log Entries

The -m limit module can limit the number of log entries created per time. This is used to prevent flooding your log file. To log and drop spoofing per 5 minutes, in bursts of at most 7 entries .
# iptables -A INPUT -i eth1 -s 10.0.0.0/8 -m limit --limit 5/m --limit-burst 7 -j LOG --log-prefix "IP_SPOOF A: "
# iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP

#14: Drop or Accept Traffic From Mac Address

Use the following syntax:
# iptables -A INPUT -m mac --mac-source 00:0F:EA:91:04:08 -j DROP
## *only accept traffic for TCP port # 8080 from mac 00:0F:EA:91:04:07 * ##
# iptables -A INPUT -p tcp --destination-port 22 -m mac --mac-source 00:0F:EA:91:04:07 -j ACCEPT

#15: Block or Allow ICMP Ping Request

Type the following command to block ICMP ping requests:
# iptables -A INPUT -p icmp --icmp-type echo-request -j DROP
# iptables -A INPUT -i eth1 -p icmp --icmp-type echo-request -j DROP

Ping responses can also be limited to certain networks or hosts:
# iptables -A INPUT -s 192.168.1.0/24 -p icmp --icmp-type echo-request -j ACCEPT
The following only accepts limited type of ICMP requests:
### ** assumed that default INPUT policy set to DROP ** #############
iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT
iptables -A INPUT -p icmp --icmp-type destination-unreachable -j ACCEPT
iptables -A INPUT -p icmp --icmp-type time-exceeded -j ACCEPT
## ** all our server to respond to pings ** ##
iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT

#16: Open Range of Ports

Use the following syntax to open a range of ports:
iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 7000:7010 -j ACCEPT

#17: Open Range of IP Addresses

Use the following syntax to open a range of IP address:
## only accept connection to tcp port 80 (Apache) if ip is between 192.168.1.100 and 192.168.1.200 ##
iptables -A INPUT -p tcp --destination-port 80 -m iprange --src-range 192.168.1.100-192.168.1.200 -j ACCEPT

## nat example ##
iptables -t nat -A POSTROUTING -j SNAT --to-source 192.168.1.20-192.168.1.25

#18: Established Connections and Restaring The Firewall

When you restart the iptables service it will drop established connections as it unload modules from the system under RHEL / Fedora / CentOS Linux. Edit, /etc/sysconfig/iptables-config and set IPTABLES_MODULES_UNLOAD as follows:
IPTABLES_MODULES_UNLOAD = no

#19: Help Iptables Flooding My Server Screen

Use the crit log level to send messages to a log file instead of console:
iptables -A INPUT -s 1.2.3.4 -p tcp --destination-port 80 -j LOG --log-level crit

#20: Block or Open Common Ports

The following shows syntax for opening and closing common TCP and UDP ports:
  1.  
  2. Replace ACCEPT with DROP to block port:
  3. ## open port ssh tcp port 22 ##
  4. iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
  5. iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 22 -j ACCEPT
  6.  
  7. ## open cups (printing service) udp/tcp port 631 for LAN users ##
  8. iptables -A INPUT -s 192.168.1.0/24 -p udp -m udp --dport 631 -j ACCEPT
  9. iptables -A INPUT -s 192.168.1.0/24 -p tcp -m tcp --dport 631 -j ACCEPT
  10.  
  11. ## allow time sync via NTP for lan users (open udp port 123) ##
  12. iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p udp --dport 123 -j ACCEPT
  13.  
  14. ## open tcp port 25 (smtp) for all ##
  15. iptables -A INPUT -m state --state NEW -p tcp --dport 25 -j ACCEPT
  16.  
  17. # open dns server ports for all ##
  18. iptables -A INPUT -m state --state NEW -p udp --dport 53 -j ACCEPT
  19. iptables -A INPUT -m state --state NEW -p tcp --dport 53 -j ACCEPT
  20.  
  21. ## open http/https (Apache) server port to all ##
  22. iptables -A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT
  23. iptables -A INPUT -m state --state NEW -p tcp --dport 443 -j ACCEPT
  24.  
  25. ## open tcp port 110 (pop3) for all ##
  26. iptables -A INPUT -m state --state NEW -p tcp --dport 110 -j ACCEPT
  27.  
  28. ## open tcp port 143 (imap) for all ##
  29. iptables -A INPUT -m state --state NEW -p tcp --dport 143 -j ACCEPT
  30.  
  31. ## open access to Samba file server for lan users only ##
  32. iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 137 -j ACCEPT
  33. iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 138 -j ACCEPT
  34. iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 139 -j ACCEPT
  35. iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 445 -j ACCEPT
  36.  
  37. ## open access to proxy server for lan users only ##
  38. iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 3128 -j ACCEPT
  39.  
  40. ## open access to mysql server for lan users only ##
  41. iptables -I INPUT -p tcp --dport 3306 -j ACCEPT
  42.  

#21: Restrict the Number of Parallel Connections To a Server Per Client IP

You can use connlimit module to put such restrictions. To allow 3 ssh connections per client host, enter:
# iptables -A INPUT -p tcp --syn --dport 22 -m connlimit --connlimit-above 3 -j REJECT
Set HTTP requests to 20:
# iptables -p tcp --syn --dport 80 -m connlimit --connlimit-above 20 --connlimit-mask 24 -j DROP
Where,
  1. --connlimit-above 3 : Match if the number of existing connections is above 3.
  2. --connlimit-mask 24 : Group hosts using the prefix length. For IPv4, this must be a number between (including) 0 and 32.

#22: HowTO: Use iptables Like a Pro

For more information about iptables, please see the manual page by typing man iptables from the command line:
$ man iptables
You can see the help using the following syntax too:
# iptables -h
To see help with specific commands and targets, enter:
# iptables -j DROP -h

#22.1: Testing Your Firewall

Find out if ports are open or not, enter:
# netstat -tulpn
Find out if tcp port 80 open or not, enter:
# netstat -tulpn | grep :80
If port 80 is not open, start the Apache, enter:
# service httpd start
Make sure iptables allowing access to the port 80:
# iptables -L INPUT -v -n | grep 80
Otherwise open port 80 using the iptables for all users:
# iptables -A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT
# service iptables save

Use the telnet command to see if firewall allows to connect to port 80:
$ telnet www.cyberciti.biz 80
Sample outputs:
Trying 75.126.153.206...
Connected to www.cyberciti.biz.
Escape character is '^]'.
^]
telnet> quit
Connection closed.
You can use nmap to probe your own server using the following syntax:
$ nmap -sS -p 80 www.cyberciti.biz
Sample outputs:
Starting Nmap 5.00 ( http://nmap.org ) at 2011-12-13 13:19 IST
Interesting ports on www.cyberciti.biz (75.126.153.206):
PORT   STATE SERVICE
80/tcp open  http
Nmap done: 1 IP address (1 host up) scanned in 1.00 seconds
I also recommend you install and use sniffer such as tcpdupm and ngrep to test your firewall settings.

Conclusion:

This post only list basic rules for new Linux users. You can create and build more complex rules. This requires good understanding of TCP/IP, Linux kernel tuning via sysctl.conf, and good knowledge of your own setup. Stay tuned for next topics:
  • Stateful packet inspection.
  • Using connection tracking helpers.
  • Network address translation.
  • Layer 2 filtering.
  • Firewall testing tools.
  • Dealing with VPNs, DNS, Web, Proxy, and other protocols.
More Details Click
                            Authorby--cyberciti.biz