,

How to Change default MySQL Data Directory in Linux

As a System Administrator I don’t prefer to use / directory to store MySQL data files. Each time when I install MySQL for a production server, I tried to use secondary disk for storing application and database file. In that way I always change the default data directory of MySQL to secondary disk mounted on system.
Mostly MySQL uses /var/lib/mysql directory as default data directory for Linux based systems. Which are going to change to another location in this article.



Instruction’s to Change Default MySQL Data Directory:

Follow the below steps to make all the changes. In some cases service name, default data directory or MySQL configuration file path change. So use all the command as per you system settings.

1. Stop MySQL

Before making any changes, first make sure to stop mysql service
# service mysqld stop

2. Change Data Directory

Now copy default MySQL data directory (/var/lib/mysql) to other location as per your requirement. Also set the required MySQL ownership on new directory location. As per below command, we are relocating data directory to /data/mysql.
# cp -rap /var/lib/mysql /data/mysql
# chown mysql.mysql /data/mysql
Now edit MySQL default configuration file /etc/my.cnf and update values of datadir and socket variable.
Change From:
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock

Change To: 
datadir=/data/mysql
socket=/data/mysql/mysql.sock

3. Start MySQL

After making all above changes. finally start MySQL service. Now it will use new data directory path
# service mysqld start
This article has been tested with CentOS 6.5 with MySQL 5.5.37. If you face any issue during MySQL startup check mysql log file /var/log/mysqld.log for any errors.
Continue reading How to Change default MySQL Data Directory in Linux
, , ,

IP ROTATION VIA IP TABLES

First we need creating Interface aliases for your public IPs.


Let's say you have 5 ips


#ifup eth0:1
#ifup eth0:2
#ifup eth0:3
#ifup eth0:4




Now the iptables part.make sure your iptables support for statistic match module.


# iptables -m statistic -h
......
......
......
statistic match options:
--mode mode Match mode (random, nth)
random mode:
--probability p Probability
nth mode:
--every n Match every nth packet
--packet p Initial counter value (0 <= p <= n-1, default 0)
Next continue with iptables rule for rotating source IP addresses.


# iptables -t nat -I POSTROUTING -m state --state NEW -p tcp --dport 25 -o eth0 -m statistic --mode nth --every 5 -j SNAT --to-source 202.XXX.XX.2
# iptables -t nat -I POSTROUTING -m state --state NEW -p tcp --dport 25 -o eth0 -m statistic --mode nth --every 5 -j SNAT --to-source 202.XXX.XX.3
# iptables -t nat -I POSTROUTING -m state --state NEW -p tcp --dport 25 -o eth0 -m statistic --mode nth --every 5 -j SNAT --to-source 202.XXX.XX.4
# iptables -t nat -I POSTROUTING -m state --state NEW -p tcp --dport 25 -o eth0 -m statistic --mode nth --every 5 -j SNAT --to-source 202.XXX.XX.5
# iptables -t nat -I POSTROUTING -m state --state NEW -p tcp --dport 25 -o eth0 -m statistic --mode nth --every 5 -j SNAT --to-source 202.XXX.XX.6
done
Continue reading IP ROTATION VIA IP TABLES
,

Solved: Error compiling httpd-2.2.23: byterange_filter.c:(.text+0x12c1): undefined reference to `apr_array_clear’

modules/http/.libs/libmod_http.a(byterange_filter.o): In function `ap_set_byterange':
byterange_filter.c:(.text+0x12c1): undefined reference to `apr_array_clear’
collect2: ld returned 1 exit status
Solution: Add this to the configure command:
--with-included-apr
with compliments and kind regards to Stefan for providing this solution
Continue reading Solved: Error compiling httpd-2.2.23: byterange_filter.c:(.text+0x12c1): undefined reference to `apr_array_clear’
,

How to check if your Linux server is under DDOS Attack?

Login to your server as root and fire the following command, using  which you can check if your server is under DDOS attack or not:
netstat -anp |grep ‘tcp\|udp’ | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort –n
This command will show you the list of IP’s which have logged in is maximum number of connections to your server.
ddos becomes more complex as attackers  use fewer connections with more number of attacking IP’s.In such cases, you should get less number of connections even when your server is under ddos.One important thing that you should check is the number of active connections that your server currently has.For that execute the following command:
netstat -n | grep :80 |wc –l
The above command will show the active connections that are open to your server.
You can also fire the following command :
netstat -n | grep :80 | grep SYN |wc –l
Result of active connections from the first command will vary but if it shows connections more than 500, then you will be definitely having problems. If the result after you fire second command is 100 or above then you are having problems with sync attack.
Once you get an idea of the ip attacking your server, you can easily block it.
Fire the following command to block that ip or any other specific ip:
route add ipaddress reject
Once you block a paricular IP on the server, you can even crosscheck if the IP is blocked or not
by using the following command:
route -n |grep IPaddress
You can also block a IP with iptables on the server by using the following command.
iptables -A INPUT 1 -s IPADRESS -j DROP/REJECT
service iptables restart
service iptables save
After firing the above command, KILL all httpd connection and than restart httpd service by
using following command:
killall -KILL httpd
service httpd startssl
Continue reading How to check if your Linux server is under DDOS Attack?
, , ,

How To Implement SPF In Postfix

This tutorial shows how to implement SPF (Sender Policy Framework) in a Postfix 2.x installation. The Sender Policy Framework is an open standard specifying a technical method to prevent sender address forgery (see http://www.openspf.org/Introduction). There are lots of SPF extensions and patches available for Postfix, but most require that you recompile Postfix. Therefore we will install the postfix-policyd-spf-perl package from openspf.org which is a Perl package and can be implemented in existing Postfix installations (no Postfix compilation required).

1 Preliminary Note

I assume that you have already set up a working Postfix mail server.
The following procedure is distribution-independent, i.e., it should work on any Linux distribution (however, I tested this on Debian Etch).

2 Install Required Perl Modules

The postfix-policyd-spf-perl package depends on the Mail::SPF and the NetAddr::IP Perl modules. Therefore we are going to install them now using the Perl shell. Start the Perl shell like this:
perl -MCPAN -e shell
If you run the Perl shell for the first time, you will be asked a few questions. You can accept all default values. You will also be asked about the CPAN repositories to use. Select repositories that are close to you.
After the initial Perl shell configuration, we can start to install the needed modules. To install Mail::SPF, simply run
install Mail::SPF
In my case, it tried to install Module::Build (which is a dependency), but then it failed. If this happens to you, simply quit the Perl shell by typing
q
Then start the Perl shell again:
perl -MCPAN -e shell
and try to install Mail::SPF again:
install Mail::SPF
This time it should succeed, and you should see that it also installs the modules Net::DNS::Resolver::Programmable and NetAddr::IP on which Mail::SPF depends.
A successful installation of Mail:SPF should end like this:
Installing /usr/local/bin/spfquery
Writing /usr/local/lib/perl/5.8.8/auto/Mail/SPF/.packlist
  /usr/bin/make install  -- OK
Because NetAddr::IP has already been installed, we can now leave the Perl shell:
q

3 Install postfix-policyd-spf-perl

Next we download postfix-policyd-spf-perl from http://www.openspf.org/Software to the /usr/src/ directory and install it to the /usr/lib/postfix/ directory like this:
cd /usr/src
wget http://www.openspf.org/blobs/postfix-policyd-spf-perl-2.001.tar.gz
tar xvfz postfix-policyd-spf-perl-2.001.tar.gz
cd postfix-policyd-spf-perl-2.001
cp postfix-policyd-spf-perl /usr/lib/postfix/policyd-spf-perl
Then we edit /etc/postfix/master.cf and add the following stanza at the end:

vi /etc/postfix/master.cf

[...]
policy  unix  -       n       n       -       -       spawn
        user=nobody argv=/usr/bin/perl /usr/lib/postfix/policyd-spf-perl

(The leading spaces before user=nobody are important so that Postfix knows that this line belongs to the previous one!)
Then open /etc/postfix/main.cf and search for the smtpd_recipient_restrictions directive. You should have reject_unauth_destination in that directive, and right after reject_unauth_destination you add check_policy_service unix:private/policy like this:

vi /etc/postfix/main.cf

[...]
smtpd_recipient_restrictions = permit_sasl_authenticated,permit_mynetworks,reject_unauth_destination,check_policy_service unix:private/policy
[...]

or like this:

[...]
smtpd_recipient_restrictions =
            [...]
            reject_unauth_destination
            check_policy_service unix:private/policy
            [...]
[...]

It is important that you specify check_policy_service AFTER reject_unauth_destination or else your system can become an open relay!
Then restart Postfix:

/etc/init.d/postfix restart
That's it already. You should check the README file that comes with the postfix-policyd-spf-perl package, it contains some important details about how postfix-policyd-spf-perl processes emails, e.g. like this part from the postfix-policyd-spf-perl-2.0001 README:
This version of the policy server always checks HELO before Mail From (older
versions just checked HELO if Mail From was null). It will reject mail that
fails either Mail From or HELO SPF checks. It will defer mail if there is a
temporary SPF error and the message would othersise be permitted
(DEFER_IF_PERMIT). If the HELO check produces a REJECT/DEFER result, Mail From
will not be checked.

If the message is not rejected or deferred, the policy server will PREPEND the
appropriate SPF Received header. In the case of multi-recipient mail, multiple
headers will get appended. If Mail From is anything other than completely empty
(i.e. ) then the Mail From result will be used for SPF Received (e.g. Mail
From None even if HELO is Pass).

The policy server skips SPF checks for connections from the localhost (127.) and
instead prepends and logs 'SPF skipped - localhost is always allowed.'


4 Test policyd-spf-perl

We can test policyd-spf-perl by running
perl /usr/lib/postfix/policyd-spf-perl
The cursor will then wait on the policyd-spf-perl shell. We can now act as if we tried to send an email from a certain domain and a certain server to another email address. policyd-spf-perl will then check if that certain server is allowed to send emails for the sender domain and show us the result.
So let's see what happens if we try to send a mail from info@h****forge.com from the server h****.server*********.net (IP address 81.169.1**.**). The h****forge.com has an SPF record that allows 81.169.1**.** to send emails from h****forge.com.
 
So on the policyd-spf-perl shell we type:




request=smtpd_access_policy
protocol_state=RCPT
protocol_name=SMTP
helo_name=h****forge.com
queue_id=8045F2AB23
sender=info@h****forge.com
recipient=falko.timme@*******.de
client_address=81.169.1**.**
client_name=h****.server*********.net
[empty line]
The output should look like this:
action=PREPEND Received-SPF: pass (h****forge.com: 81.169.1**.** is authorized to use 'info@h****forge.com' in 'mfrom' identity (mechanism 'ip4:81.169.1**.**' matched)) receiver=server1.example.com; identity=mfrom; envelope-from="info@h****forge.com"; helo=h****forge.com; client-ip=81.169.1**.**
which means we passed the test.
Let's run another test, this time we will send from the client 1.2.3.4 (www.example.com) which is not allowed to send emails from h****forge.com:
request=smtpd_access_policy
protocol_state=RCPT
protocol_name=SMTP
helo_name=h****forge.com
queue_id=8045F2AB23
sender=info@h****forge.com
recipient=falko.timme@*******.de
client_address=1.2.3.4
client_name=www.example.com
[empty line]
This is the output, the test failed as expected:

action=PREPEND Received-SPF: softfail (h****forge.com: Sender is not authorized by default to use 'info@h****forge.com' in 'mfrom' identity, however domain is not currently prepared for false failures (mechanism '~all' matched)) receiver=server1.example.com; identity=mfrom; envelope-from="info@h****forge.com"; helo=h****forge.com; client-ip=1.2.3.4

We can now even try to leave the sender field empty, as many spammers do. Still, policyd-spf-perl should be able to complete its tests:
request=smtpd_access_policy
protocol_state=RCPT
protocol_name=SMTP
helo_name=h****forge.com
queue_id=8045F2AB23
sender=
recipient=falko.timme@*******.de
client_address=81.169.1**.**
client_name=h****.server*********.net
[empty line]
This is the output, we are still allowed to send from h****forge.com:

action=PREPEND Received-SPF: pass (h****forge.com: 81.169.1**.** is authorized to use 'h****forge.com' in 'helo' identity (mechanism 'ip4:81.169.1**.**' matched)) receiver=server1.example.com; identity=helo; helo=h****forge.com; client-ip=81.169.1**.**

Let's try the same test with an invalid client:
request=smtpd_access_policy
protocol_state=RCPT
protocol_name=SMTP
helo_name=h****forge.com
queue_id=8045F2AB23
sender=
recipient=falko.timme@*******.de
client_address=1.2.3.4
client_name=www.example.com
[empty line]
As expected, this is the output:

action=PREPEND Received-SPF: softfail (h****forge.com: Sender is not authorized by default to use 'h****forge.com' in 'helo' identity, however domain is not currently prepared for false failures (mechanism '~all' matched)) receiver=server1.example.com; identity=helo; helo=h****forge.com; client-ip=1.2.3.4 

To leave the policyd-spf-perl shell, type
[CTRL+C]
Continue reading How To Implement SPF In Postfix
,

Configuring Reverse DNS in BIND 9

Reverse DNS is the process of using DNS to translate IP addresses to hostnames. Reverse DNS is the opposite of Forward DNS, which is used to translate hostnames to IP addresses.

One way to see reverse DNS at work is to use nslookup a tool on most OS’s.
Let’s use `nslookup` to do a forward and reverse DNS lookup on redhat.com:
##FORWARD LOOKUP
[phil@ns1 ~]$ nslookup redhat.com
Server:         206.71.175.XX
Address:        206.71.175.XX#53
 
Non-authoritative answer:
Name:   redhat.com
Address: 209.132.177.50
##REVERSE LOOKUP
[phil@ns1 ~]$ nslookup 209.132.177.50
Server:         206.71.175.XX
Address:        206.71.175.XX#53
 
Non-authoritative answer:
50.177.132.209.in-addr.arpa     name = www.redhat.com.
 
Authoritative answers can be found from:
177.132.209.in-addr.arpa        nameserver = ns3.redhat.com.
177.132.209.in-addr.arpa        nameserver = ns2.redhat.com.
177.132.209.in-addr.arpa        nameserver = ns1.redhat.com.
Reverse DNS is setup by configuring PTR records (Pointer Records) on your DNS server.
This is in different to Forward DNS, which are configured with A records (Address Records).
Typically you or a DNS provider is in charge of Forward DNS. In the case of Reverse DNS most likely your ISP supplying your IP information will have responsibility. You would simply send them what Hostname resolves to what IP, and they would setup the PTR records. You can setup Reverse DNS on your own name servers if you choose which we will cover in this article.
Your ISP or hosting provider may delegate your own range of IP addresses, or you may have NAT setup for Private IP space you control, in this case you must configure Reverse DNS thru PTR records on your DNS server.
A lot of Systems Administrators configure Forward DNS but not Reverse DNS. In most cases when you do this things will work fine, however some applications require doing Reverse DNS lookups in which case you could run into latency issues and a whole slew of other issues.
Common applications and protocols such as IRC, SMTP, Backup utilities, and Databases sometimes use Reverse DNS.
It is best practice to configure Reverse DNS from the get go, to avoid troubleshooting headaches.
Below is a quick example how-to.
Say you NAT Private IP’s in your network 192.168.0.1-192.168.0.255
STEP 1 create a zone file and place it where you store your zone files named
0.168.192.in-addr.arpa
(Notate your address space backwards missing last octect with .in-addr.arpa appended)
Your zone file will look like this: (between ##)
#######
 
@       IN      SOA     ns1.yournameserver.com. root.domain.com.     (
2007040301      ;serial
14400                 ;refresh
3600                   ;retry
604800              ;expire
10800                ;minimum
)
 
0.168.192.in-addr.arpa.                IN      NS      ns1.yournameserver.com.
0.168.192.in-addr.arpa.                IN      NS      ns2.yournameserver.com.
 
2               IN      PTR     blah1.domain.com.
3               IN      PTR     blah2.domain.com.
4               IN      PTR     blah3.domain.com.
5               IN      PTR     blah4.domain.com.
6               IN      PTR     blah5.domain.com.
 
########
The example zone file above stipulates the below:
192.168.0.2 blah1.domain.com
192.168.0.3 blah2.domain.com
192.168.0.4 blah3.domain.com
192.168.0.5 blah4.domain.com
192.168.0.6 blah5.domain.com
The number 2-6 are the last octect of 192.168.0. and PTR is the pointer.
STEP 2 Enter the zone into your named.conf or named.boot as you would a regular zone.
This would go into your Master DNS server or Primary DNS server
zone "0.168.192.in-addr.arpa" IN {
type master;
file "0.168.192.in-addr.arpa";
allow-update { none; };
};
This would go into your Slave DNS server or Secondary DNS server
zone "0.168.192.in-addr.arpa" IN {
type slave;
file "0.168.192.in-addr.arpa";
masters { whateveryourmasteripis; };
};
STEP 3
Wholla if configured right you should be up and running. Make sure to tail your log file when you restart DNS for any errors in syntax
Continue reading Configuring Reverse DNS in BIND 9
,

SSH Connection: Wait long after entering username – ssh password prompt delay

When I make ssh connection I get long wait just after entering username. It’s most likely that ssh daemon  is set up to do a DNS reverse-lookup on the host that’s connecting. So, sshd try to find reverse DNS record for a while before prompting you password.
If you do not want to wait,  you can either add your client’s ip and hostname information to /etc/hosts file on linux or you can disable reverse dns lookup in /etc/ssh/sshd_config
1- Open your terminal window
2- Edit /etc/ssh/sshd_config
3- Add UseDNS no at the end
4- Restart your ssh daemon
Continue reading SSH Connection: Wait long after entering username – ssh password prompt delay
, ,

How to recover data from bad sector Hard Disks

Recovering files from a bad sector hard disk is not an easy job especially the files allocated in bad sectors are not readable and also recovering the corrupted files are time consuming. In this tutor, I use a freeware called Unstoppable copier which is simple and compact program that truly recovers every byte of information that is available for recovery. Directly recovering files from within Windows is not suggested using the above freeware since some file contents might not be readable. Instead using this freeware in a virtual OS or DOS mode gives full advantage over the hard disk.

1. Download Hiren's BootCD and extract the archive and Burn the image file to a CD.

2. Boot your PC with Hiren's BootCD by setting boot priority in BIOS menu.

3. Select and Enter the option "Mini Windows XP" from the menu.


4. Click Start > HBCD Menu.


5. Click Programs > Backup > Unstoppable Copier.


6. Navigate to Settings tab and move the slider to the extreme left corner for best data recovery.


(OR) Move the slider to the extreme right for the fastest data recovery and put a tick mark in Auto skip Damaged files for recovering only undamaged files.


7. After adjusting the desired settings navigate to Copy tab and select the Source (corrupted hard disk drives) and Target (external storage device/Physical drive2) and finally click Copy button.

8. Based on the settings and file contents the transfer speed may differ.


9. You can check the number of corrupt files and skipped files after the completion of process.


10. Once you have finished recovering all your partitions/drives, close this window and restart your PC and then eject the CD out.
Continue reading How to recover data from bad sector Hard Disks

IDM is not working in firefox - Solved

If you are using old version of Internet Download Manager plugin in New version of Firefox, IDM may or may not work properly. To fix this follow these simple steps.....



Solution:

1] Open your Firefox browser and download idmmzcc.xpi file.

2] Now open this file using your Firefox browser.




Note: If Firefox is not listed in open with box, click Browse button and go to C:\Program files\Mozilla firefox and select Firefox.exe file.



3] Now the Install Add-ons popup dialogue box appears within few seconds and click Ok to install the IDM CC Add-on plugin.

4] After the installation is complete, Restart the Firefox.
Continue reading IDM is not working in firefox - Solved

Most Frequently Used Linux IPTables Rules Examples

These examples will act as a basic templates for you to tweak these rules to suite your specific requirement.
For easy reference, all these 25 iptables rules are in shell script format: iptables-rules

1. Delete Existing Rules

Before you start building new set of rules, you might want to clean-up all the default rules, and existing rules. Use the iptables flush command as shown below to do this.
iptables -F                                                               
(or)                                                                      
iptables --flush                                                          

2. Set Default Chain Policies

The default chain policy is ACCEPT. Change this to DROP for all INPUT, FORWARD, and OUTPUT chains as shown below.
iptables -P INPUT DROP                                                    
iptables -P FORWARD DROP                                                  
iptables -P OUTPUT DROP                                                   
When you make both INPUT, and OUTPUT chain’s default policy as DROP, for every firewall rule requirement you have, you should define two rules. i.e one for incoming and one for outgoing.

In all our examples below, we have two rules for each scenario, as we’ve set DROP as default policy for both INPUT and OUTPUT chain.
If you trust your internal users, you can omit the last line above. i.e Do not DROP all outgoing packets by default. In that case, for every firewall rule requirement you have, you just have to define only one rule. i.e define rule only for incoming, as the outgoing is ACCEPT for all packets.
Note: If you don’t know what a chain means, you should first familiarize yourself with the IPTables fundamentals.

3. Block a Specific ip-address

Before we proceed further will other examples, if you want to block a specific ip-address, you should do that first as shown below. Change the “x.x.x.x” in the following example to the specific ip-address that you like to block.
BLOCK_THIS_IP="x.x.x.x"                                                     
iptables -A INPUT -s "$BLOCK_THIS_IP" -j DROP                               
This is helpful when you find some strange activities from a specific ip-address in your log files, and you want to temporarily block that ip-address while you do further research.
You can also use one of the following variations, which blocks only TCP traffic on eth0 connection for this ip-address.
iptables -A INPUT -i eth0 -s "$BLOCK_THIS_IP" -j DROP                       
iptables -A INPUT -i eth0 -p tcp -s "$BLOCK_THIS_IP" -j DROP                

4. Allow ALL Incoming SSH

The following rules allow ALL incoming ssh connections on eth0 interface.
iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT   
Note: If you like to understand exactly what each and every one of the arguments means, you should read How to Add IPTables Firewall Rules

5. Allow Incoming SSH only from a Sepcific Network

The following rules allow incoming ssh connections only from 192.168.100.X network.
iptables -A INPUT -i eth0 -p tcp -s 192.168.100.0/24 --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT                       
In the above example, instead of /24, you can also use the full subnet mask. i.e “192.168.100.0/255.255.255.0″.

6. Allow Incoming HTTP and HTTPS

The following rules allow all incoming web traffic. i.e HTTP traffic to port 80.
iptables -A INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT   
The following rules allow all incoming secure web traffic. i.e HTTPS traffic to port 443.
iptables -A INPUT -i eth0 -p tcp --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 443 -m state --state ESTABLISHED -j ACCEPT   

7. Combine Multiple Rules Together using MultiPorts

When you are allowing incoming connections from outside world to multiple ports, instead of writing individual rules for each and every port, you can combine them together using the multiport extension as shown below.
The following example allows all incoming SSH, HTTP and HTTPS traffic.
iptables -A INPUT -i eth0 -p tcp -m multiport --dports 22,80,443 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp -m multiport --sports 22,80,443 -m state --state ESTABLISHED -j ACCEPT   

8. Allow Outgoing SSH

The following rules allow outgoing ssh connection. i.e When you ssh from inside to an outside server.
iptables -A OUTPUT -o eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT     
Please note that this is slightly different than the incoming rule. i.e We allow both the NEW and ESTABLISHED state on the OUTPUT chain, and only ESTABLISHED state on the INPUT chain. For the incoming rule, it is vice versa.

9. Allow Outgoing SSH only to a Specific Network

The following rules allow outgoing ssh connection only to a specific network. i.e You an ssh only to 192.168.100.0/24 network from the inside.
iptables -A OUTPUT -o eth0 -p tcp -d 192.168.100.0/24 --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT                         

10. Allow Outgoing HTTPS

The following rules allow outgoing secure web traffic. This is helpful when you want to allow internet traffic for your users. On servers, these rules are also helpful when you want to use wget to download some files from outside.
iptables -A OUTPUT -o eth0 -p tcp --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 443 -m state --state ESTABLISHED -j ACCEPT     
Note: For outgoing HTTP web traffic, add two additional rules like the above, and change 443 to 80.

11. Load Balance Incoming Web Traffic

You can also load balance your incoming web traffic using iptables firewall rules.
This uses the iptables nth extension. The following example load balances the HTTPS traffic to three different ip-address. For every 3th packet, it is load balanced to the appropriate server (using the counter 0).
iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 0 -j DNAT --to-destination 192.168.1.101:443
iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 1 -j DNAT --to-destination 192.168.1.102:443
iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 2 -j DNAT --to-destination 192.168.1.103:443

12. Allow Ping from Outside to Inside

The following rules allow outside users to be able to ping your servers.
iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT                     
iptables -A OUTPUT -p icmp --icmp-type echo-reply -j ACCEPT                      

13. Allow Ping from Inside to Outside

The following rules allow you to ping from inside to any of the outside servers.
iptables -A OUTPUT -p icmp --icmp-type echo-request -j ACCEPT                    
iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT                       

14. Allow Loopback Access

You should allow full loopback access on your servers. i.e access using 127.0.0.1
iptables -A INPUT -i lo -j ACCEPT                                                
iptables -A OUTPUT -o lo -j ACCEPT                                               

15. Allow Internal Network to External network.

On the firewall server where one ethernet card is connected to the external, and another ethernet card connected to the internal servers, use the following rules to allow internal network talk to external network.
In this example, eth1 is connected to external network (internet), and eth0 is connected to internal network (For example: 192.168.1.x).
iptables -A FORWARD -i eth0 -o eth1 -j ACCEPT                                    

16. Allow outbound DNS

The following rules allow outgoing DNS connections.
iptables -A OUTPUT -p udp -o eth0 --dport 53 -j ACCEPT                           
iptables -A INPUT -p udp -i eth0 --sport 53 -j ACCEPT                            

17. Allow NIS Connections

If you are running NIS to manage your user accounts, you should allow the NIS connections. Even when the SSH connection is allowed, if you don’t allow the NIS related ypbind connections, users will not be able to login.
The NIS ports are dynamic. i.e When the ypbind starts it allocates the ports.
First do a rpcinfo -p as shown below and get the port numbers. In this example, it was using port 853 and 850.
rpcinfo -p | grep ypbind                                                         
Now allow incoming connection to the port 111, and the ports that were used by ypbind.
iptables -A INPUT -p tcp --dport 111 -j ACCEPT                                   
iptables -A INPUT -p udp --dport 111 -j ACCEPT                                   
iptables -A INPUT -p tcp --dport 853 -j ACCEPT                                   
iptables -A INPUT -p udp --dport 853 -j ACCEPT                                   
iptables -A INPUT -p tcp --dport 850 -j ACCEPT                                   
iptables -A INPUT -p udp --dport 850 -j ACCEPT                                   
The above will not work when you restart the ypbind, as it will have different port numbers that time.
There are two solutions to this: 1) Use static ip-address for your NIS, or 2) Use some clever shell scripting techniques to automatically grab the dynamic port number from the “rpcinfo -p” command output, and use those in the above iptables rules.

18. Allow Rsync From a Specific Network

The following rules allows rsync only from a specific network.
iptables -A INPUT -i eth0 -p tcp -s 192.168.101.0/24 --dport 873 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 873 -m state --state ESTABLISHED -j ACCEPT                       

19. Allow MySQL connection only from a specific network

If you are running MySQL, typically you don’t want to allow direct connection from outside. In most cases, you might have web server running on the same server where the MySQL database runs.
However DBA and developers might need to login directly to the MySQL from their laptop and desktop using MySQL client. In those case, you might want to allow your internal network to talk to the MySQL directly as shown below.
iptables -A INPUT -i eth0 -p tcp -s 192.168.100.0/24 --dport 3306 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 3306 -m state --state ESTABLISHED -j ACCEPT                       

20. Allow Sendmail or Postfix Traffic

The following rules allow mail traffic. It may be sendmail or postfix.
iptables -A INPUT -i eth0 -p tcp --dport 25 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 25 -m state --state ESTABLISHED -j ACCEPT   

21. Allow IMAP and IMAPS

The following rules allow IMAP/IMAP2 traffic.
iptables -A INPUT -i eth0 -p tcp --dport 143 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 143 -m state --state ESTABLISHED -j ACCEPT   
The following rules allow IMAPS traffic.
iptables -A INPUT -i eth0 -p tcp --dport 993 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 993 -m state --state ESTABLISHED -j ACCEPT   

22. Allow POP3 and POP3S

The following rules allow POP3 access.
iptables -A INPUT -i eth0 -p tcp --dport 110 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 110 -m state --state ESTABLISHED -j ACCEPT   
The following rules allow POP3S access.
iptables -A INPUT -i eth0 -p tcp --dport 995 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 995 -m state --state ESTABLISHED -j ACCEPT   

23. Prevent DoS Attack

The following iptables rule will help you prevent the Denial of Service (DoS) attack on your webserver.
iptables -A INPUT -p tcp --dport 80 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT
In the above example:
  • -m limit: This uses the limit iptables extension
  • –limit 25/minute: This limits only maximum of 25 connection per minute. Change this value based on your specific requirement
  • –limit-burst 100: This value indicates that the limit/minute will be enforced only after the total number of connection have reached the limit-burst level.

24. Port Forwarding

The following example routes all traffic that comes to the port 442 to 22. This means that the incoming ssh connection can come from both port 22 and 422.
iptables -t nat -A PREROUTING -p tcp -d 192.168.102.37 --dport 422 -j DNAT --to 192.168.102.37:22
If you do the above, you also need to explicitly allow incoming connection on the port 422.
iptables -A INPUT -i eth0 -p tcp --dport 422 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 422 -m state --state ESTABLISHED -j ACCEPT   

25. Log Dropped Packets

You might also want to log all the dropped packets. These rules should be at the bottom.
First, create a new chain called LOGGING.
iptables -N LOGGING                                                                    
Next, make sure all the remaining incoming connections jump to the LOGGING chain as shown below.
iptables -A INPUT -j LOGGING                                                           
Next, log these packets by specifying a custom “log-prefix”.
iptables -A LOGGING -m limit --limit 2/min -j LOG --log-prefix "IPTables Packet Dropped: " --log-level 7
Finally, drop these packets.
iptables -A LOGGING -j DROP                                                                             
Continue reading Most Frequently Used Linux IPTables Rules Examples