Yegor's blog

Small blog about system administration.

HOWTO: Reset a MySQL Password

A MySQL password can be reset in 5 easy steps:

  1. Stop the mysqld daemon process.
  2. Start the mysqld daemon process with the –skip-grant-tables option.
  3. Start the mysql client with the -u root option.
  4. Execute the UPDATE mysql.user SET Password=PASSWORD(‘password’) WHERE User=’root’;
  5. Execute the FLUSH PRIVILEGES; command.
These steps reset the password for the “root” account to “password.” To change the password for a different account or to set a different password, just edit the variables in single quotes in step 4.

If the user knows his/her existing MySQL root password, steps 1-3 are not necessary.

No comments :

Post a Comment

Virtuozzo Parameters Explained

Primary Parameters

1. numproc = max ‘number of processes’ and kernel level threads allowed for a VE
It is the total number of processes that can be run on a server. Ie httpd, ftp, mail spawn a process to handle each client and limiting number of processes define how many clients the application will be able to handle in parallel. However number of processes does not limit how heavy the application may be. But increasing this value to more than about 16000 processes start to cause poor responsiveness of the system, worsening when the number grows. Total number of processes exceeding 32000 is very likely to cause hang of the system. With typical processes, it is normal to be able to run only up to 8000 processes in a system. The number of sockes needs to be controlled because each socket needs certain amount of memory for receive and transmit buffers. Barrier of this parameter should be set equal to the limit.

2. numtcpsock = max ‘number of TCP sockets’
This parameter limits the number of TCP connections and, thus, the number of clients the server application can handle in parallel. If each VE has its own set of IP addresses, there are no direct limits on the total number of TCP sockets in the system.Barrier of this parameter should be set equal to the limit.

3. numothersock = max ‘number of sockets other than TCP’
Local sockets (sockets used for communication inside the system), UDPsockets (DNS queries). The number of sockets needs to be controlled because each socket needs certain amount of memory for receive and transmit buffers. Barrier of this parameter should be set equal to the limit.

4. vmguarpages = ‘virtual memory guaranteed pages’
This parameter controls how much memory is available to the VE. The more clients are served or the more “heavy” the application is, the more memory it needs The meaning of the limit for the vmguarpages parameter is unspecified and should be set to the maximal allowed value.If the current amount of allocated memory space does not exceed the guaranteed amount (the barrier of vmguarpages), memory allocations of VE applications always succeed. If the current amount of allocated memory space exceeds the guarantee but below the barrier of privvmpages, allocations may or may not succeed, depending on the total amount of available memory in the system.

Secondary Parameters

1. kmemsize = ‘kernel memory size’
Size of unswappable kernel memory allocated for the internal kernel structures. This parameter is related to the number of processes, numproc.Kmemsize limits can’t be set arbitrarily high. It is important to have a certain safety gap between the barrier and the limit of the kmemsize parameter. Equal barrier and limit of the kmemsize parameter may lead to the situation where the kernel will need to kill Virtual Environment’ applications to keep the kmemsize usage under the limit.

2. tcpsndbuf = total size of ‘send buffers for TCP sockets’
The amount of kernel memory allocated for the data sent from an application to a TCP socket. tcpsndbuf parameter depends on number of TCP sockets, numtcpsock and should allow for some minimal amount of socket buffer memory for each socket.

3. tcprcvbuf = total size of ‘receive buffers for TCP’
The amount of kernel memory allocated for the data received from the remote side, but not read by the local application yet. Tcprcvbuf parameter depends on number of TCP sockets, numtcpsock and should allow for some minimal amount of socket buffer memory for each socket.

4. othersockbuf = total size of ‘buffers used by other sockets’
Othersockbuf parameter depends on number of non-TCP sockets,numothersock. Othersockbuf configuration should satisfy,othersockbuf_{lim} – othersockbuf_{bar} \ge 2.5KB \cdot numothersock.Increased limit for othersockbuf is necessary for high performance of communications through local sockets. However, similarly to tcpsndbuf, hitting othersockbuf affects the communication performance only and does not affect the functionality. The total amount of other sock buf consumable by all VE in the system plus the kmemsize and other socketbuffers is limited by the hardware resources of the system

5. dgramrcvbuf = total size of ‘receive buffers of UDP and other datagram protocol’
The total size of buffers used to temporary store the incoming packets of UDP and other datagram protocols. Dgramrcvbuf parameters depend on number of non-TCP sockets (numothersock). dgramrcvbuf limits usually don’t need to be high. Only if the VE needs to send and receive very large datagrams, the barriers for both othersockbuf and dgramrcvbuf parameters should be raised.

6. oomguarpages = ‘out of memory guarantee in pages’
Any VE process will not be killed even in case of heavy memory shortage if the current memory consumption (including both physical memory and swap) does not reach the oomguarpages barrier.oomguarpages parameter is related to vmguarpages. If applications start to consume more memory than the computer has, the system faces an out-of-memory condition. In this case the operating system will start to kill VE processes to free some memory and prevent the total death of the system. oomguarpages parameter accounts the total amount of memory and swap space used by the processes of a particular Virtual Environment.The barrier of the oomguarpages parameter is the out-of-memory guarantee.

Auxiliary Parameters

1. privvmpages = ‘private virtual memory pages’
privvmpages parameter allows controlling the amount of memory allocated by applications. The memory that is always shared among different applications is not included in this resource parameter. The barrier and the limit of privvmpages parameter control the upper boundary of the total size of allocated memory. Note that this upper boundary doesn’t guarantee that the Virtual Environment will be able to allocate that much memory, neither does it guarantee that other Virtual Environments will be able to allocate their fair share of memory. The primary mechanism to control memory allocation is the vmguarpages guarantee.

Privvmpages parameter accounts allocated (but, possibly, not used yet) memory. The accounted value is an estimation how much memory will be really consumed when the Virtual Environment’s applications start to use the allocated memory. Consumed memory is accounted into oomguarpages parameter.

2. lockedpages
The memory not allowed to be swapped out in pages. The size of these pages is also accounted into kmemsize. The barrier may be set equal to the limit or may allow some gap between the barrier and the limit, depending on the nature of applications using memory locking features.

3. shmpages = total size of ‘shared memory pages’
These pages are also accounted into privvmpages. The barrier should be set equal to the limit. The configuration of this parameter doesn’t affect security and stability of the whole system or isolation between Virtual Environments. Its configuration affects functionality and resource shortage reaction of applications in the given Virtual Environment only.

No comments :

Post a Comment

HOWTO: Move Accounts From One cPanel Server To Another

This tutorial explains a simple, straightforward method for migrating cPanel accounts from one server to another. You can use this method to transfer accounts from an old server to a new one, help customers from another host move to your host, etc. This does not even require root access on one end of the migration. Basically, this is a more reliable method than the "Transfer Account from another Server" tool in WHM, which rarely works.

- cPanel on both servers
- WHM access on the new server (one that the accounts are being moved to)
- root access on the new server

The server you are transferring the accounts from = "old server"
The server you are transferring the accounts to = "new server"

1. Log into WHM of your new server and create a new account called "restore", or anything you like for that matter. Remember the FTP address, username ('restore', in this example), and account password. We will need these for later.

2. Log into the cPanel account you are wanting to transfer on the old server.

3. Click on "Backup >> Generate/Download a Full Backup".

4. Once here, select the backup destination to be "Remote FTP Server".

5. Enter your email address for verification, followed by all of the FTP account information for "restore", which we created on the new server.

-Remote Server: new server's address
-Remote User: restore
-Remote Password: restore's password
-Port: 21

Then, click "Generate Backup". This may take some time to backup the files, depending on how large the account is. You should receive an email provided in the above info once it is complete.

6. Now, log into SSH on your new server.

7. Type in the following commands:

cd /home/restore/public_html


After running the list command above (ls), you should see the tar file of the account on the old server. This means that you have successfully sent the file via FTP to your new server.

8. Now move the tar file to your new server's /home directory with the following command:

mv tar_file_name /home

9. Now, log into WHM on your new server and navigate to "Backup >> Restore a Full Backup/cpmove file"

Once here, you should see the old account's username under "Possible cpmove archives found:".
If you do not, log back into SSH and be sure that the account's tar file has been moved into /home.

10. Type in the account name in the text field in WHM, which is proceeded by "Enter the username for the account you wish to restore:".

11. Click "Restore".

12. Repeat process for additional accounts.

No comments :

Post a Comment

HOWTO: Find which container makes overload on the node.

When you notice than your node is overloaded you could run this simple command to know which container makes high load avg:

(root)>vzlist -o laverage,hostname,ctid

Keep it simple :-)

No comments :

Post a Comment

Qmail “Although I’m listed as a best-preference mx or a for that host”

Another one that I don’t have to fix often so I’ll likely forget it.

Qmail error “Although I’m listed as a best-preference MX or a for that host, it isn’t in my controls/locals file, so I don’t treat it as local. (#5.4.6)

It shows up in the log concatenated:

failure: Sorry._Although_I’m_listed_as_a_best-preference_MX_or_A_for_that_host,/it_isn’t_in_my_cont

Anyway, I fixed it, hopefully correctly, by placing the hostname in the /var/qmail/control/locals file and the /var/qmail/control/rcpthosts file and restarting qmail.

No comments :

Post a Comment

Can’t log in into cPanel after 11.32.2 b15 update

Maybe you also had experienced the situation where you could not log in into cPanel after the recent upgrade to 11.32.15 version. I had the same problem but fixed it with help of cPanel support staff. Here is what the error is and how to solve it..

The error display in browser is:


And sometimes backed up by this extensive error output

Internal Server Error

exit level [die] [pid=8572] (setuids failed: Could not resolve UID () or GID ())
at /usr/local/cpanel/Cpanel/ line 433
Cpanel::Logger::logger(‘Cpanel::Logger=HASH(0xdc17e0)’, ‘HASH(0xdcf640)’) called at /usr/local/cpanel/Cpanel/ line 306
Cpanel::Logger::die(‘Cpanel::Logger=HASH(0xdc17e0)’, ‘setuids failed: Could not resolve UID () or GID ()’) called at /usr/local/cpanel/Cpanel/AccessIds/ line 49
Cpanel::AccessIds::SetUids::setuids(‘cpanellogin’) called at cpsrvd-ssl line 4238
main::__ANON__() called at /usr/local/cpanel/Cpanel/SafeRun/ line 28
Cpanel::SafeRun::InOut::inout(‘GLOB(0xd5f130)’, ‘GLOB(0x2011d930)’, ‘CODE(0xd54030)’, ‘/usr/local/cpanel/base/show_template.stor’, ‘docroot’, ‘/usr/local/cpanel/base’, ‘default_login_theme’, ‘cpanel’, …) called at cpsrvd-ssl line 4244
main::process_login_template(‘cpanel’, ‘login’, 1, ‘goto_uri’, ‘/’, ‘dest_uri’, ‘/’, ‘user’, …) called at cpsrvd-ssl line 2634
main::badpass() called at cpsrvd-ssl line 4716
main::handle_auth() called at cpsrvd-ssl line 993
main::handle_one_connection() called at cpsrvd-ssl line 863

Regular forced upcp did not help,Ii had to run the sequence of commands as follow because problem was with perl packages as wells:

/etc/init.d/cpanel restart
/scripts/checkperlmodules –full –force
/etc/init.d/cpanel restart
mv /var/cpanel/sql/eximstats.sql /var/cpanel/sql/eximstats.sql.tmp_working_copy3
mysql eximstats < /var/cpanel/sql/eximstats.sql.tmp_working_copy3
/scripts/upcp –force

And now you should be able to log in without any problems.

No comments :

Post a Comment

Wordpress Owner/Group/Permission Issues on Plesk

Log into Plesk and enable CGI/FastCGI support for your domain.
Go to the Domains tab, click on your domain, then on Setup. 
Make sure PHP support, CGI support, and FastCGI support are all selected.
Click OK to save your changes.
Log into your server with a root or sudo user via SSH.
Make a local copy of the PHP CGI binary program for your domain:
cp /usr/bin/php-cgi /var/www/vhosts/

Change the ownership of the bin directory and your new local copy of PHP:

chown -R domainuser:psacln /var/www/vhosts/

Modify or create your local Apache configuration file, vhost.conf:

vim /var/www/vhosts/ 

Add the following lines to the file:

AddHandler fcgid-script .php
SuexecUserGroup domainuser psacln
<Directory /var/www/vhosts/>
FCGIWrapper /var/www/vhosts/ .php
Options +ExecCGI +
FollowSymLinks allow from all

Reload your Apache configuration settings:

/usr/local/psa/admin/sbin/websrvmng -av

Restart Apache:

/etc/init.d/httpd graceful

PHP will now be running as FastCGI as the same user and group that owns your website files.

Adjust your sessions directory:

Since PHP will now be running as the script's user rather than apache, the permissions for the session folder need adjusted to account for this.

chmod 777 /var/lib/php/session

Adjust permissions:

Most CMS software will warn you about security risks related to permissions in the administrative panel somewhere. You probably don't need to run these commands if you're configuring a new domain or have just installed your CMS.

cd /var/www/vhosts/ && chown -R domainuser:psacln * && find . -type f -exec chmod 644 {} \; && find . -type d -exec chmod 755 {} \;

You should consider adjusting the number of simultaneous FastCGI processes allowed for each domain and for the server overall, based on the number of domains that you have running FastCGI. The default configuration allows 64 total processes and 8 per domain. Edit your configuration file:

vim /etc/httpd/conf.d/fcgid.conf

Update the following variables, if desired:

MaxProcessCount 64 
DefaultMaxClassProcessCount 8

You should set the DefaultMaxClassProcessCount to the number of processes you want a single domain to be able to run simultaneously. Multiply that number by the number of domains that are running FastCGI, and use that number for the MaxProcessCount. 
For example, if you have 4 domains using FastCGI, and you want them to run a maximum of 10 simultaneous processes each, you can set the following values:

MaxProcessCount 40 
DefaultMaxClassProcessCount 10 

Do not set these values arbitrarily high, as this may interfere with your server's memory usage. 
Alternately, you can pick a server maximum first for the MaxProcessCount, and then divide by the number of your domains to set the DefaultMaxClassProcessCount value.

No comments :

Post a Comment

Something about line numbers in file

To print line # 26, enter:

# sed -n '26p' /etc/ssh/sshd_config

Use a text editor such as vi to edit the file, enter:
# vi +26 etc/ssh/sshd_config

No comments :

Post a Comment

spamd failed @ Tue Jan 24 8:38:56 2010 . A restart was attempted automatically

If the cPanel is alerting you repeatedly by filling your mail box with 

‘spamd failed @ Tue Jan 24 8:38:56 2010 . A restart was attempted automatically’ 

error message, then here is the best possible way to fix this problem. Perform the below mentioed steps one by one to fix it permanently.
* You can see the spamd process by executing ps with the combination of grep command.
root@cpanel [~]# ps -efH | grep spamd
root 16975 16861 0 04:49 pts/0 00:00:00 grep spamd
root 16463 1 0 04:31 ? 00:00:01 /usr/bin/spamd -d –allowed-ips= –pidfile=/var/run/ –max-children=3 –max-spare=1
root 16476 16463 0 04:31 ? 00:00:00 spamd child

* Remove the spamd process ids (pids) by running this command:

killall -9 spamd

* First, Make sure spamd is not running and then perform the following:

rm -rf /var/run/chkservd/spamd

* Once you removed the spamd chkservd script, restart the chkservd


That’s all.

No comments :

Post a Comment

Qmail not sending mail: qmail-queue[26720]: cannot reinject message to mail system

For those interested, i fixed this issue. Forced a refresh of the psa-qmail rpm using the following procedure. Then applied art's qmail-scanner rpm and everything is good!


Stop qmail:

service qmail stop
service courier-imap stop
service xinetd stop

Backup the bin and qmal queue directories:

mv /var/qmail/bin /var/qmail/bin.old
mv /var/qmail/queue /var/qmail/queue.old

Now refresh this installation. To do this, you will need a fresh copy of the psa-qmail rpm for your distribution. You can either download a tarball of all the rpms from the plesk website.

So then, refresh by running:

rpm -ivh --force psa-qmail*
Try again, and you should have overcome your injection problems!

service courier-imap start
service xinetd start

Keep it simple :-) 

No comments :

Post a Comment

Find files owned by user1 and chown to user2

find . -user user1 -exec chown user2 {} \;


find . -user user1 -exec chgrp grp2 {} \;

No comments :

Post a Comment

Mass rename (REMOVE ~ from beginning of files)

Have a directory with thousands of files each starting with a ~?

find . -depth|rename ’s/~//g’

No comments :

Post a Comment

allow_url_fopen per domain

On Plesk you can allow allow_url_fopen per domain by editting the vhost.conf file for that domain and set the php_admin_flag as bellow.

php_admin_flag allow_url_fopen on

Once you have done this, run the Plesk magicwand

/usr/local/psa/admin/sbin/websrvmng -v -a

No comments :

Post a Comment

Plesk domain status codes

List all active domains:

SELECT name FROM domains WHERE status = '0'

List all suspended domains:

SELECT name FROM domains WHERE status != '0'

List all expired (hosting) domains:

SELECT name FROM domains WHERE status = '256'

List all domains with backup/restore in progress:

SELECT name FROM domains WHERE status = '4'

List all domains suspended by client:

SELECT name FROM domains WHERE status = '64'

Connect to Plesk mysql database:

#mysql -uadmin -p`cat /etc/psa/.psa.shadow` -Dpsa

No comments :

Post a Comment

HOWTO: Catching spam on Plesk server

Check how many messages are in the queue with Qmail:

# /var/qmail/bin/qmail-qstatmessages in queue: 27645messages in queue but not yet preprocessed: 82

If the queue has too many messages, try to discover the source of SPAM.

If mail is being sent by an authorized user but not from the PHP script, you can run the command below to find the user that has sent the most messages (available since Plesk 8.x). Note that you must have the 'SMTP authorization' activated on the server to see these records:

# cat /usr/local/psa/var/log/maillog |grep -I smtp_auth |grep -I user |awk '{print $11}' |sort |uniq -c |sort -n

The path to 'maillog' may differ depending on the OS you are using.

The next step is to use "qmail-qread," which can be used to read the message headers:

# /var/qmail/bin/qmail-qread18 Jul 2005 15:03:07 GMT #2996948 9073 <> bouncingdone remote user1@domain1.comdone remote user2@domain2.comdone remote

This shows the senders and recipients of messages. If the message contains too many recipients, probably this is spam. Now try to find this message in the queue by its ID ( # 2996948 in our example):

# find /var/qmail/queue/mess/ -name 2996948

Examine the message and find the line "Received" to find out from where it was sent for the first time. For example, if you find:

Received: (qmail 19514 invoked by uid 10003); 13 Sep 2005 17:48:22 +0700

it means that this message was sent via a CGI by user with UID 10003. Using this UID, it is possible to find the domain:

# grep 10003 /etc/passwd

If the 'Received' line contains a UID of a user 'apache' (for example invoked by uid 48), it means that spam was sent through a PHP script. In this case, you can try to find the spammer using information from spam email (address from/to or any other information). It is usually very difficult to discover the source of spam. If you are absolutely sure that this time there is a script which sends spam (tail grows rapidly for no apparent reason), you can use the following script to determine what PHP scripts are running at this time:

# lsof +r 1 -p `ps axww | grep httpd | grep -v grep | awk ' { if(!str) { str=$1 } else { str=str","$1}}END{print str}'` | grep vhosts | grep php

You can also apply the KB article which describes the procedure of discovering which domains are sending mail through PHP scripts.

Lines in Received section like

Received: (qmail 19622 invoked from network); 13 Sep 2005 17:52:36 +0700Received: from (

mean that the message has been accepted and delivered via SMTP, and that the sender is an authorized mail user.

No comments :

Post a Comment

HOWTO: Delete old directories from the commandline

The first one works quietly, while the second one will display what is being deleted. 
These are probably faster than putting it into a for loop, so feel free to use whatever works best in your particular situation!

# find /home/backup/ -maxdepth 1 -type d -mtime +7 -exec rm -r {} \;

# find /home/backup/ -maxdepth 1 -type d -mtime +7 -exec echo “Removing Directory => {}” \; -exec rm -rf “{}” \;

No comments :

Post a Comment

HOWTO: Finding number of connections to :25 port

To find out the largest number of established connections with port number.

#netstat -na | grep ‘ESTABLISHED’ | awk ‘{print $4}’ | uniq -c | sort -rn

To find out the number of connections to port 80 [http] from each IP.
#netstat -plan|grep :80|awk {’print $5′}|cut -d: -f 1|sort|uniq -c|sort -n

Similarly, you can find out the number of connections to port 25 from each IP as.
#netstat -plan|grep :25|awk {’print $5′}|cut -d: -f 1|sort|uniq -c|sort -n

NETSTAT is the most useful tool to detect and determine whether a server is under DoS or DDoS attack (Distributed Denial of Service).

No comments :

Post a Comment

VPS commands

1) vzlist -a : Shows list of all the VPS’s hosted on the Node.

(This is the ID)
1 96 running
358 77 running
454 124 running
525 79 running
527 92 running
568 73 running
570 86 running
574 11 running
579 13 running
583 79 running

2) vzctl start ID: To start the VPS.

[root@virtuozzo06 ~]# vzctl start 111
Starting Container …
Container is mounted
Setup slm memory limit
Setup slm subgroup (default)
Setting devperms 20002 dev 0x7d00
Adding port redirection to Container(1): 8443 4643
Adding IP address(es) to pool:
Adding IP address(es):
arpsend: 4 is detected on another computer : 00:1a:30:38:90:00
vz-net_add WARNING: arpsend -c 1 -w 1 -D -e -e -e -e -e eth1 FAILED
Hostname for Container set:
File resolv.conf was modified
Container start in progress…
[root@virtuozzo06 ~]#

3) vzctl stop ID : To stop (Shut Down) the VPS

[root@virtuozzo06 ~]# vzctl stop 111
Stopping Container …
Container was stopped
Container is unmounted

4) vzctl status ID : To view the status of the particular VPS

[root@virtuozzo06 ~]# vzctl status 111
VEID 111 exist mounted running

5) vzctl stop ID –fast : to stop the VPS quickly and forcefully

[root@virtuozzo06 ~]# vzctl status 111
VEID 111 exist mounted running
[root@virtuozzo06 ~]# vzctl stop 111 –fast
Stopping Container …
Container was stopped
Container is unmounted

6) vzctl enter VPS_ID : To enter in a particular VPS

[root@virtuozzo06 ~]# vzctl enter 111
entered into Container 111

Configuration Commands

1) vzctl set ID –hostname –save : To set the Hostname of a VPS.
2) vzctl set ID –ipadd –save : To add a new IP to the hosting VPS.
3) vzctl set ID –ipdel –save : To delete the IP from VPS.
4) vzctl set ID –userpasswd root:new_password –save : to reset root password of a VPS.
5) vzctl set ID –nameserver –save : To add the nameserver IP’s to the VPS.
6) vzctl exec ID command : To run any command on a VPS from Node.
7) vzyum ID install package_name : To install any package/Software on a VPS from Node.

No comments :

Post a Comment

HOWTO: Suspend/Unsuspend user's account on cPanel from commandline

To suspend an account: 

# /scripts/suspendacct <username>
To unsuspend an account: 

# /scripts/unsuspendacct <username>
If you still see the suspension page after un-suspending an account, go to the /home/username/public_html/.htaccess file and remove the redirect lines.

No comments :

Post a Comment

IPTABLES: ip_conntrack: table full, dropping packet.

The server reporting the following message in /var/log/messages (syslog):

ip_conntrack: table full, dropping packet.

How do I fix this error?

Generally, the ip_conntrack_max is set to the total MB of RAM installed multiplied by 16. 
However, server had 4GB of RAM, but ip_conntrack_max was set to 65536:

# cat /proc/sys/net/ipv4/ip_conntrack_max 65536

If you want to check your server's current tracked connections, just run the following:

# cat /proc/sys/net/ipv4/netfilter/ip_conntrack_count

If you want to adjust it (as I did), just run the following as root:

# echo 131072 > /proc/sys/net/ipv4/ip_conntrack_max

This solves the problem at this moment, but after a reboot the initial value will be restored.
To make this persistent you have to add a line like 'net.ipv4.ip_conntrack_max=131072' to /etc/sysctl.conf

# echo 'net.ipv4.ip_conntrack_max=131072' >> /etc/sysctl.conf

No comments :

Post a Comment

Iptables: The Most Useful Rules

Displaying the Status of Your Firewall

Type the following command as root:

# iptables -L -n -v

-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.

To inspect firewall with line numbers, enter:

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

You can use line numbers to delete or insert new rules into the firewall. 

To display INPUT or OUTPUT chain rules, enter:

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

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

-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).

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

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 4OR find source IP 
and delete from rule:
# iptables -D INPUT -s -j DROP

-D : Delete one or more rules from the selected chain

 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
To insert rule between 1 and 2, enter:
# iptables -I INPUT 2 -s -j DROP
To view updated rules, enter:
# iptables -L INPUT -n --line-numbers
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 -j DROP
# service iptables save

For all other distros use the iptables-save command:
# iptables-save > /root/
# cat /root/

Restore Firewall Rules

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

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
# wget

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
# wget

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 -j DROP
# iptables -A INPUT -i eth1 -s -j DROP

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

  • -j (A)
  • (B)
  • (C)
  • (E)

Blocking an IP Address (BLOCK IP)

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

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, enter:
# iptables -A INPUT -p tcp -s --dport 80 -j DROP
# iptables -A INPUT -i eth1 -p tcp -s --dport 80 -j DROP

Block Outgoing IP Address

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

Example - Block Domain

First, find out all ip address of, enter:
# host -t a
Sample outputs: has address
Find CIDR for, enter:
# whois | grep CIDR
Sample outputs:
To prevent outgoing access to, enter:
# iptables -A OUTPUT -p tcp -d -j DROP
You can also use domain name, enter:
# iptables -A OUTPUT -p tcp -d -j DROP
# iptables -A OUTPUT -p tcp -d -j DROP
From the iptables man page:
... specifying any name to be resolved with a remote query such as DNS (e.g., 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 -j LOG --log-prefix "IP_SPOOF A: "
# iptables -A INPUT -i eth1 -s -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 -m limit --limit 5/m --limit-burst 7 -j LOG --log-prefix "IP_SPOOF A: "
# iptables -A INPUT -i eth1 -s -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 -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 and ##
iptables -A INPUT -p tcp --destination-port 80 -m iprange --src-range -j ACCEPT
## nat example ##
iptables -t nat -A POSTROUTING -j SNAT --to-source

#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:

#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 -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:
Replace ACCEPT with DROP to block port:
## open port ssh tcp port 22 ##
iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -s -m state --state NEW -p tcp --dport 22 -j ACCEPT
## open cups (printing service) udp/tcp port 631 for LAN users ##
iptables -A INPUT -s -p udp -m udp --dport 631 -j ACCEPT
iptables -A INPUT -s -p tcp -m tcp --dport 631 -j ACCEPT
## allow time sync via NTP for lan users (open udp port 123) ##
iptables -A INPUT -s -m state --state NEW -p udp --dport 123 -j ACCEPT
## open tcp port 25 (smtp) for all ##
iptables -A INPUT -m state --state NEW -p tcp --dport 25 -j ACCEPT
# open dns server ports for all ##
iptables -A INPUT -m state --state NEW -p udp --dport 53 -j ACCEPT
iptables -A INPUT -m state --state NEW -p tcp --dport 53 -j ACCEPT
## open http/https (Apache) server port to all ##
iptables -A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -m state --state NEW -p tcp --dport 443 -j ACCEPT
## open tcp port 110 (pop3) for all ##
iptables -A INPUT -m state --state NEW -p tcp --dport 110 -j ACCEPT
## open tcp port 143 (imap) for all ##
iptables -A INPUT -m state --state NEW -p tcp --dport 143 -j ACCEPT
## open access to Samba file server for lan users only ##
iptables -A INPUT -s -m state --state NEW -p tcp --dport 137 -j ACCEPT
iptables -A INPUT -s -m state --state NEW -p tcp --dport 138 -j ACCEPT
iptables -A INPUT -s -m state --state NEW -p tcp --dport 139 -j ACCEPT
iptables -A INPUT -s -m state --state NEW -p tcp --dport 445 -j ACCEPT
## open access to proxy server for lan users only ##
iptables -A INPUT -s -m state --state NEW -p tcp --dport 3128 -j ACCEPT
## open access to mysql server for lan users only ##
iptables -I INPUT -p tcp --dport 3306 -j ACCEPT

#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
  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 80
Sample outputs:
Connected to
Escape character is '^]'.
telnet> quit
Connection closed.
You can use nmap to probe your own server using the following syntax:
$ nmap -sS -p 80
Sample outputs:
Starting Nmap 5.00 ( ) at 2011-12-13 13:19 IST
Interesting ports on (
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.


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.

No comments :

Post a Comment