Saturday, March 1, 2008

webalizer errors : Unable to lock DNS cache file /usr/local/psa/var/webalizer.cache

If you get following error while running webalizer updater :

Error: Unable to lock DNS cache file /usr/local/psa/var/webalizer.cache

then do as follows:

rm -f /usr/local/psa/var/webalizer.cache
touch /usr/local/psa/var/webalizer.cache
chown root:root /usr/local/psa/var/webalizer.cache
chmod 644 /usr/local/psa/var/webalizer.cache
start /usr/local/psa/var/webalizer.cache
=====================================================================================
/usr/bin/webalizer -n 145street.com -D /usr/local/psa/var/webalizer.cache -p -N 15 -o /home/httpd/vhosts/145street.com/webstat -F clf /home/httpd/vhosts/145street.com/logs/access_log

replace the above domain name with therespective domain name .

500 internal server error

Just a quick note about "Internal Server Error" problems after upgrading Apache on these Plesk machines.

You may start getting the "500 Internal Server Error" errors after doing so, and that is because the upgraded Apache has overwritten the Plesk version of "suexec", a handy little program that allows the webserver to run CGI-BIN programs.

However, you are in luck! Plesk keeps a copy of their modified version of "suexec" around on the box.

How-To restore suexec:
1. log in as the 'root' user on yer box.
2. cd /usr/sbin
3. mv suexec suexec.old (or whatever you want to call it)
4. cp psa-suexec suexec

Technical Jazz:
The problem is that Apache's stock version of suexec doesn't allow (for safety reasons) cgi-bin programs to be execute from any but underneath the MAIN Apache document root. Which, in the case of these Plesk servers is /var/www... since all the virtually hosted addresses live under /home/httpd/vhosts..., the stock Apache suexec doesn't allow that. Modifying suexec is something of a hobby in the unix web administration world, so this isn't entirely odd.

BTW, you can also check the /var/log/suexec.log to see what is being suexec'ed, and what errors are happening. The error you'll see in this case is "command not in docroot".

login get locked due to incorrect logins?

login get locked due to incorrect logins?

Restart plesk service from shell(SSH) using
# service psa restart

How to rename the Domain Name

You can rename the domain name in Plesk using the following steps:
1) go to MySql prompt.
2) give following commands:
use psa;
Under this database there is a table called "domains" in which all the domain name are present under the field "display Name", all you have to do is update the record of the domain in issue to the new one.
The update query for MySql will be as follows:
UPDATE domains SET display Name='New Domain Name' WHERE age='old Domain name';
After this query check the domain in Plesk and it will be renamed.
Alternative Solution :
Here is the solution.
Go to control panel.
click on domain name.
click on Domain Administration option.
Enter the new domain and click ok.
The domain will be renamed.

qmail queue flush

You could run qmail-clean but that takes a long while.

Here is a quick and easy way to clear all email from the queue.
This will not remove anything it should not remove. It just clears
all email from the queue safely. This is just for qmail.
( Not for use with any other email programs )


1) login to your server via ssh
2) su -
3) wget http://wepraisehim.org/qmailclear.sh
5) sh qmailclear.sh
6) done.
=====================================================================================
If qmail is starting / not starting then you should check if smtp_psa and smtps_psa files in /etc/xinetd.d are not disabled.

/etc/xinetd.d/smtp_psa

/etc/xinetd.d/smtps_psa

change line :

disabled = yes
to
disabled = no

Then restart xinetd service then qmail.
=====================================================================================
Use following command to send a test mail from shell....


echo subject:testing | /var/qmail/bin/qmail-inject email@domain.com

=====================================================================================

How to reset windows Plesk password ?

How to reset windows Plesk password ?

C:\Program Files\SWsoft\Plesk\admin\bin\plesksrvclient.exe

execute this file and you will be prompted to enter in a new password for your "admin" plesk user. You can then log into the plesk interface again and use as normal.

How to reset plesk admin password

#cat /etc/psa/.psa.shadow
(This holds psa admin password)
#/etc/rc.d/init.d/psa stop
(This stops Plesk and everything it runs.)
#/usr/local/psa/mysql/bin/safe_mysqld --skip-grant-tables &
or
#/usr/bin/safe_mysqld --skip-grant-tables &
(This starts up MySQL, bypassing the grant [password] tables.)
#/usr/local/psa/mysql/bin/mysql mysql
(You're now in a mysql command line.)
#use mysql;
#FLUSH PRIVILEGES;
(This flushes everything out - too long to explain.)
#SET PASSWORD FOR admin=PASSWORD('your-password-here');
(Type that exactly as above, where 'your-password-here' is, put the password you entered in the Rackshack order form when ordering your server.)
#exit
(You exit the mysql command line and return to root.)
#killall mysqld
or
#/etc/rc.d/init.d/mysqld restart
(Shuts down the mysql daemon.)
#/etc/rc.d/init.d/psa start
(Starts Plesk back up, which restarts the mysql daemon which has your new password in it.)

Autoresponder not working in Plesk

Hello,

Here's what I did to fix it.

% mysql -uadmin -p'password' psa

mysql> create temporary table tmp_mn_param select distinct (mn_param.mn_id)
mn_id, 'locale' param, 'en' val from mn_param where mn_param.param <>
'locale' order by mn_param.mn_id;

mysql>insert into mn_param(mn_id, param, val) select tmp_mn_param.mn_id,
tmp_mn_param.param, tmp_mn_param.val from tmp_mn_param order by
tmp_mn_param.mn_id;

mysql> quit

That fixed it for me instantly, I gave mysql a restart just to be sure, but that should be all that's needed.

Accessing domain before resolving nameservers

To access domain before nameservers resolve,

I have a simple automated method for that.

Lets asume that your main domain is domain.xyz and the ip fior shared hosting is 123.123.123.123 on that server, then here is what you do:

- place in the dns of the main domain a new A record like this

*.s1.domain.xyz A 123.123.123.123

if you have more then 1 server then the next is *.s2.domain.xyz etc...

Then create a vhost.conf file in /home/httpd/vhosts/skel/0/conf with this line in it:

ServerAlias @domain_name@.s1.domain.xyz

The @domain_name@ will be automaticly changed in by Plesk to the domainname that you add. So if you add test.com then the vhost.conf file will say test.com.s1.domain.xyz

This then automaticly creates a serveralias of the patern domain.your.server.name for every created domain on the server and because the wildcard is in your dns it will resolve the minute the domain is created (and apache is restarted).

.skel/0 is the default skel. If you use another default skel or clients use there own skel you will need to create the vhost.conf file there also. If you have more then 1 shared ip then you need to add more then 1 A record to the dns, 1 for every shared ip.
=====================================================================================
One more method to do the same


a) Create an Apache Alias to forward all traffic to one specified directory on an already resolving site to another site. For example, create a vhost.conf under yourdomain.com's conf directory, and add to it:

AliasMatch ^/sites/([^/]+)(/(.*))? /usr/local/psa/home/vhosts/$1/httpdocs/$3

So whenever someone accesses yourdomain.com/sites/anotherdomain.com, they'll actually be accessing anotherdomain.com's directory. This has a few obvious security flaws (none too major though), and cgi scripts won't run properly under the suexec wrapper... it's the price you pay .

b) Just add the nameserver that is hosting the domain to your OS' DNS list. That way the request will stay internal, and will return correctly before your ISPs nameservers are updated.

NTFS

1) Find the exact matching distribution in the kernel-module-ntfs dists at:
http://www.linux-ntfs.org/content/view/128/64/
(must match the answer to uname -r)

# uname -r
2.6.9-55.ELsmp

If you get the above you need to download (kernel-module-ntfs-2.6.9-55.ELsmp-2.1.20-0.rr.10.0.i686.rpm)
http://prdownloads.sourceforge.net/linux-ntfs/kernel-module-ntfs-2.6.9-55.ELsmp-2.1.20-0.rr.10.0.i686.rpm

# get http://prdownloads.sourceforge.net/linux-ntfs/kernel-module-ntfs-2.6.9-55.ELsmp-2.1.20-0.rr.10.0.i686.rpm

2) Install the RPM using
# rpm -ihv kernel-module-ntfs-2.6.9-55.ELsmp-2.1.20-0.rr.10.0.i686.rpm
PrĂ©paration… ########################################### [100%]
1:kernel-module-ntfs-2.6.########################################### [100%]

# /sbin/modprobe ntfs
# dmesg|grep NTFS
NTFS driver 2.1.22 [Flags: R/W MODULE].

That’s better, almost done…

3) Now check the drive which you want to mount using "fdisk -l"

# fdisk -l

Disk /dev/sda: 251.0 GB, 251000193024 bytes
255 heads, 63 sectors/track, 30515 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot Start End Blocks Id System
/dev/sda1 * 1 13 104391 83 Linux
/dev/sda2 14 1318 10482412+ 83 Linux
/dev/sda3 1319 2623 10482412+ 83 Linux
/dev/sda4 2624 30515 224042490 5 Extended


Disk /dev/sdb: 251.0 GB, 251000193024 bytes
1 heads, 63 sectors/track, 7781504 cylinders
Units = cylinders of 63 * 512 = 32256 bytes

Device Boot Start End Blocks Id System
/dev/sdb1 * 2 7781071 245103705 7 HPFS/NTFS

Here you see /dev/sdb1 as the NTFS partition.

4) Now to mount the NTFS partition /dev/sdb1

# cd /
# mkdir windows
# mount -t ntfs -o nls=utf8 /dev/sdb1 /windows
# cd /windows

And you are done the NTFS partition is mounted as /windows

Adding IPs on Plesk

You will need to perform the following steps

1) Click the "Server" in question.

2) Click "IP Aliasing".

3) Click "Add".

5) Put ip to be added on the server

6) Click "Update".

Changing hostname for plesk

1) SSH to your box
2) login as root
3) type pico /etc/hosts
4) modify the line that says

216.40.226.??? ensim.rackshack.net ensim
to
216.40.226.??? srv01.yourdomain.com srv01

Substitue the above ip for your own and same with the server name. Change that to your own. It can be anything but it must contain at least 2 periods in the name and preferably ending in com or your ext, net, cc, tv or whatever. See my example above!

type cntrl-x and save your file.

5) type pico /etc/sysconfig/network and modify the second line in file network to match the address of your server name as you did in step 4:

NETWORKING=yes
HOSTNAME="ensim.rackshack.net"
GATEWAY="216.40.226.1"
GATEWAYDEV="eth0"
FORWARD_IPV4="yes"

So you would change the line
HOSTNAME="ensim.rackshack.net"
to
HOSTNAME="srv01.yourdomain.com"

Save with a ctrl-x

6)
You need to change it with following command:

mysql -uadmin -p`cat /etc/psa/.psa.shadow` psa -e "update misc set
val='new.domainname.com' where param='FullHostName'"

Where 'new.domainname.com' is the name to set as hostname in Plesk. Note that it should be typed as one line.


Now reboot your system. You must reboot for the server names to propagate throught the system.

DO NOT do anything to DNS till after the system reboots because all this will be changed when the server comes back online.


For more information please refer to
http://forum.plesk.com/showthread.php?s=84e937a10aecb08e8d5aa55f01467b4d&threadid=9523

Webstats for Plesk - Windows

I found out the solution. Go to IIS, single-click on the domain on the left side pane. You will see all the directories on the right hand side. You should see some virtual directories like 'webstat' , 'ftpstat' , and 'cgi-bin' which have been mapped to their actual locations.

Eg : for 'webstat' it should be ....../domainname.com/statistics/webstat

If you dont see any virtual directory for 'webstat', then create it which will map to the real webstat directory.

Similar is the case with 'ftpstat' and 'cgi-bin'.

Repairing Windows Plesk

Commands for Reparing Windows Plesk
Check out the following commands :

cd %plesk_bin% (ie cd c:\Program Files\SWsoft\Plesk\admin\bin\)
websrvmng --reconfigure-vhost --vhost-name=
cd \
C:\>cd "Program Files\SWsoft\Plesk\admin"
cd Program Files\SWsoft\Plesk\admin\bin
C:\Program Files\SWsoft\Plesk\admin\bin>websrvmng --reconfigure-vhost --vhost-name=abc.com

Let me know if anyone want's to repair PLESK for the entire server (Windows Server) or want to remove any domain from PLESK.

Connection to Plesk database

To connect to Plesk Database on Windows server you have to following steps:
click on Start > run
type cmd and press enter
then give following command:
cd C:\Program Files\SWsoft\Plesk\MySQL\bin
then give command
mysql
or mysql -uadmin -p password
Then you will be on MySql prompt.
Then give command:
use psa;

This is plesk database. From there you can access all the tables under it.

-------------------------------------------------------------------------------------

To connect to Plesk Database on Linux server you have to following steps:
Connect to the server and give following commands:
mysql
or mysql -uadmin -p password
Then you will be on MySql prompt.
Then give command:
use psa;
This is plesk database. From there you can access all the tables under it.

How to restart Qmail services in virtuzzo ( Plesk )

Go to your virtuzzo control panel.
Then click on systems --> virtuozzo --> SSH connection --> username as root and pwd of virtuozzo.
After getting the shell prompt just type cd /etc/init.d
Then ls –l
Then in the shell prompt type ./qmail start for restarting the qmail services.

Error in Plesk Control Panel

If you are getting following error in the Plesk Control Panel:

Code:
This action exceeds the limits defined by your software licence. If you received this message you may contact your provide or the manufacturer to clarify or extends the limits of this licence


then put in a note to Mark:
run:
/home/dedicated/bin/plesk.sh

How to restart FTP server?

To restart ftp server on linux servers run /usr/sbin/proftpd on command prompt.

[root@ds194-213 root]# /usr/sbin/proftpd

You can test this by following :
1. [root@ds194-213 root]# telnet 66.235.201.113 21
IF ftp server is running, you will get following kind of o/p
Trying 66.235.201.113...
Connected to 66.235.201.113.
Escape character is '^]'.
220 ProFTPD 1.2.9 Server (ProFTPD) [keaadvertising.com]

2. You can create any user(test/test) and try using any FTP client to connect and upload files.

Apache doesn't start/restart

Issue : Apache doesn't start/restart

[root@ds194-238 root]# tail -f /var/log/httpd/error_log
[Sun Jun 06 12:32:00 2004] [alert] (22002)Name or service not known: mod_unique_id: unable to find IPv4 address of "ds194-238.hostname.com"
Configuration Failed!


Solution : Temporary Solution: Edit httpd.conf file. Search & comment this module mod_unique_id

Exact Solution :
1. This errors gets due to wrong hostname. if it is not resolving properly.

2. You can check hostname as following :

[root@ds194-181 root]# cat /etc/sysconfig/network
NETWORKING=yes
HOSTNAME=localhost.localdomain

Also you can check hostname using [root@ds194-181 root]# hostname

(You need to reboot if u change this )

3. Check whether it is resolving like following with host command:
[root@ds194-181 root]# host ds194-181.hostname.com
Host ds194-181.hostname.com not found: 3(NXDOMAIN)

You should get IP here.

How do I restart Plesk?

You can login to shell as root, and type following commands to restart the Plesk Server Administrator:

To stop the Plesk
service psa stop

To start the Plesk
service psa start

How To upgrade the License in Plesk

Yes we can upgrade the license file by refering teh above url :

https://register.swsoft.com/key_upgrade/

How do I enable root login with ssh? (SU)

If you are convinced that you really do want to reenable root login through ssh then you'll want to follow these two simple steps:

Open up /etc/ssh/sshd_config and set "PermitRootLogin" to "yes". (Your ISP probably set it to "without-password")
You also need to restart the sshd process. This is done by killing the existing one (use ps -aux|grep sshd to get the process ID, then use kill to zap it), then restarting /usr/sbin/sshd
Again, make me feel more secure. Make sure you really want to do this, and then make sure that you have a really solid, impossible to guess root password.

Solve PHP Fatal error: Allowed memory size of 8388608 bytes

Description
This error message can spring up in a previously functional PHP script when the memory requirements exceed the default 8MB limit. Don't fret, though, because this is an easy problem to overcome.


Directions
To change the memory limit for one specific script by including a line such as this at the top of the script:

Quote:
ini_set("memory_limit","12M");


The 12M sets the limit to 12 megabytes (12582912 bytes). If this doesn't work, keep increasing the memory limit until your script fits or your server squeals for mercy.

You can also make this change permanently for all PHP scripts running on the server by adding a line like this to the server's php.ini file:

Quote:
memory_limit = 12M


Keep in mind that a huge memory limit is a poor substitute for good coding. A poorly written script may inefficiently squander memory which can cause severe problems for frequently executed scripts. However, some applications are run infrequently and require lots of memory like importing and processing a big data file.

Increase / change max email size

To change the max size of email

edit sendmail.cf file and change the value to higher one

or just comment it to make uncontrolled(inifinity).


O MaxMessageSize=1000000

Getting Protected from DoS Attacks with Apache

Note
This tutorial uses Apache 1.3. You can perform the steps for this on Apache 2.0, however you will need to follow the documentation for the applicable software discussed here.


Warning
This tutorial is not a substitute for a good firewall configuration, it is only an addition. Do not rely soley upon the information found here to prevent DoS attacks!


Firewall settings are great for preventing Denial of Service (DoS) attacks, however it may not always be your only solution. The day has finally arrived when I found this excellent module called mod_dosevasive (DoS Evasive) which keeps track of how many requests each client makes to your server within intervals. If a client is being forceful with your server and making too many requests, then it is more than likely not just a web browser but some automated process unleashed on your site to try and take it down.

This handy Apache module we have found takes care of these issues. Let's get started by setting it up.


Preparing for mod_dosevasive


The first step to prepare to install this module is determine your server configuration. Did you install Apache with Dynamic Shared Object support (DSO)? or is your server configured without it? If have DSO enabled, you can simply run the apxs command to import the module on the fly, otherwise you may have to recompile Apache to make this work.



Download and Modify mod_dosevasive


First, you need to download mod_dosevasive to your server. Do so by going to the official site:
Nuclear Elephant: DosEvasive

Download the source code to a directory of your choice and then unpack it:


cd /usr/local/src
wget 'http://www.nuclearelephant.com/projects/dosevasive/mod_dosevasive.1.8.tar.gz'
tar zxpf mod_dosevasive.1.8.tar.gz


Our next task is to determine if we want to use mod_dosevasive's email features. Later in this tutorial, we are going create an addon with PHP which allows us to do the mailing with a more verbose log of what is going on, and do the iptables firewall DROP rules, but but just in case, you need to edit the mod_dosevasive.c file and point it to the correct mailing application such as Sendmail.

In our mod_dosevasive.c file, we have altered the define MAILER line to reflect the path to Sendmail on our system:



#define MAILER "/usr/sbin/sendmail -t %s"



Now that we have the file prepared, we are ready to figure out how to get it into Apache.


Apache with DSO Support

If you're using an RPM version of Apache 1.3, then chances are your have DSO support enabled and this installation will be a breeze. First, locate the path to your apxs executable in the Apache bin directory and then run this command:


/usr/local/apache/bin/apxs -iac /usr/local/src/mod_dosevasive/mod_dosevasive.c


Watch for the output and if everything looks ok, the module is installed and you are clear to restart Apache. We'll add the configuration directives later in this tutorial, so you may skip the next section for now.


Apache without DSO

If your Apache is configured without DSO support (ie: not using --with-dso), then you must recompile Apache. Here's how to configure Apache with mod_dosevasive:


cd /usr/local/src/apache_1.3.29
./configure \
--prefix=/www \
--add-module=/usr/local/src/mod_dosevasive/mod_dosevasive.c
make
make install


Note
You will definately want to include any other Apache modules in the configure line that you will need. Don't forget to add PHP!


Now you are all set with Apache non-DSO and mod_dosevasive. Let's move on to the configuration files.

Basic Configuration mod_dosevasive

Our next task is to configure mod_dosevasive for your server. There's a good handful of directives you may use, but we'll cover the ones we need for this tutorial. You really should read the documentation on this module to understand the other directives that are available for you.


Apache 1.3 with DSO Support:

You need to add the module to the httpd.conf. Find the AddModule section and enter this line to the bottom of it:


AddModule mod_dosevasive.c



All Apache 1.3 Configurations:

At the end of your httpd.conf file, add the following lines:


Normal Traffic Server:




DOSHashTableSize 3097
DOSPageCount 2
DOSSiteCount 50
DOSPageInterval 1
DOSSiteInterval 1
DOSBlockingPeriod 10




High Traffic Server:




DOSHashTableSize 3097
DOSPageCount 4
DOSSiteCount 100
DOSPageInterval 1
DOSSiteInterval 1
DOSBlockingPeriod 10



Let's break down only these configuration directives:

DOSHashTableSize is the size of the hash table that is created for the IP addresses monitored.
DOSPageCount is the number of pages allowed to be loaded for the DOSPageInterval setting. In our case, 2 pages per 1 second before the IP gets flagged.
DOSSiteCount is the number of objects (ie: images, style sheets, javascripts, SSI, etc) allowed to be accessed in the DOSSiteInterval second. In our case, 50 objects per 1 second.
DOSPageInterval is the number of seconds the intervals are set for DOSPageCount
DOSSiteInterval is the number of seconds the intervals are set for DOSSiteCount
DOSBlockingPeriod is the number of seconds the IP address will recieve the Error 403 (Forbidden) page when they have been flagged.


The next task is to tweak Apache while we are here. Change the following directives to these values:

The MaxRequestsPerChild directive which is normally set to zero (0) for unlimited needs to be set for proper cleanup:


MaxRequestsPerChild 10000


Note
Read the documentation (README) again for this module to ensure you have any additional tweaks covered.


Moving along, we can now build our custom PHP script that will do some magic for us. Let's discuss this on the next page.

mod_dosevasive does a wonderful job as it is. However, we believe in the Three Strike rule instead of just dropping someone from your server alltogether after one flagging by mod_dosevasive. Therefore, we have created a method by using PHP and MySQL to handle this.

From this point forward we assume that you have PHP abilities on the command line. You can check to be sure by running:php -v and if the command is found, PHP will print it's version on the screen. You are clear to proceed!

Our setup will do a couple of things here. First, if mod_dosevasive finds an offending user, it has the ability to call an external command, in this case, our PHP script. We can pass the offending IP address to the PHP script and process it into our database. This provides ammunition for us if we need to because we can also keep track of how many times an IP address has been flagged and we can also log what pages it was flagged for accessing by parsing our Apache log file for the relative information. Then, we can have PHP execute the iptables command when we find this user has been flagged three times. Let's move on and find out how.


Setting up the MySQL Database


Note
Before you begin, you will need to have access to MySQL and know your MySQL root password!


First, login to MySQL and create a database, create a user and grant privelages to that database for the new user:


mysql -u root -pyourpasword
CREATE DATABASE blacklist;
use blacklist;

CREATE TABLE blacklist (
id int(5) NOT NULL auto_increment,
ip varchar(40) NOT NULL default '',
date datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) TYPE=MyISAM;

CREATE TABLE blacklist_logs (
id varchar(150) NOT NULL default '',
log_entry text NOT NULL,
ip_address varchar(40) NOT NULL default '',
date varchar(25) NOT NULL default '',
uri varchar(200) NOT NULL default '',
response varchar(100) NOT NULL default '',
size varchar(100) NOT NULL default '',
UNIQUE KEY id (`id`)
) TYPE=MyISAM;

GRANT ALL PRIVILEGES ON blacklist.* TO 'blacklist'@'localhost' IDENTIFIED BY 'somepassword';
exit



Now our database should be all set! We are ready to setup the PHP script.


The PHP Script


Our PHP script will perform a couple of operations:

Receive the IP address from the command line
Log the IP address, date and time into the blacklist table
Retreive the information about this user from the log file and log normal files such as HTML, PHP and etc into our database.
Count how many times the user has been flagged, if the count is 3 or more, then run the IPTABLES rule for dropping all access for this IP address.
Sending an email notification to an administrator with a summary of the logfile access we have recorded.


Sound pretty cool? Let's move on! Create a PHP script somewhere on your hard drive. I prefer to locate it in /usr/local/etc and name it blacklist.php with the following contents:



$sql = mysql_connect('localhost', 'blacklist', 'somepassword');
mysql_select_db('blacklist', $sql);

$ip = $_SERVER['argv']['1'];

$sql = mysql_query("INSERT INTO blacklist (ip, date) VALUES ('$ip', now())");
$logs = `cat /path/to/logs/access.log | grep $ip`;

$arry = explode("n", $logs);


foreach($arry AS $line){
if(!eregi('gif', $line) && !eregi('jpg', $line) && !eregi('bmp', $line)
&& !eregi('png', $line) && !eregi('css', $line)
&& !eregi('js', $line)){

$larr = explode(" ", $line);
$ip_addr = $larr[0];
$date = str_replace("[", "", $larr[3]);
$date = mytime($date, 0);
$url = $larr[6];
$response = $larr[8];
$size = $larr[9];
$id = md5($ip.$date.$url);
mysql_query("INSERT INTO blacklist_logs (
id, log_entry, ip_address, date, uri, response, size)
VALUES ('$id', '$line', '$ip', '$date', '$url$

}
}

function mytime($str, $short = null){
$nstr = explode('/', $str);
$nstr2 = explode(":", $nstr['2']);
$m = $nstr['1']; $d = $nstr['0']; $y = $nstr2['0'];
$h = $nstr2['1']; $i = $nstr2['2']; $s = $nstr2['3'];
if($short){
return "$d-$m-$y";
} else {
return "$d-$m-$y | $h:$i:$s";
}
}


$ccount = mysql_result(mysql_query("SELECT COUNT(id) AS ccount FROM blacklist WHERE ip = '$ip'"),0);


if($ccount > 2){
$drop = "su - root -c '/sbin/iptables -I INPUT -s $ip -j DROP'";
// echo $drop;
`$drop`;

$subject = "$ip Banned from Server";
$to = "you@yourdomain.com";
$message = "The IP address: $ip has been banned from yoursite.comnn";
$message .= "Here is a summary of actions for this IP address:nn";

$sql = mysql_query("SELECT * FROM blacklist_logs WHERE ip_address = '$ip' ORDER BY id");
while($row = mysql_fetch_array($sql)){
$message .= $row['log_entry']."n";
echo $row['log_entry']."n";
}
$message .= "====================================================================";
$headers .= "From: Securityn";
$headers .= "Return-Path: n"; //Return bouned mails to.
$headers .= "X-Priority: 1n"; //Message priority is set to HIGH
$headers .= "X-MSMail-Priority: Highn"; //Message Priority for Exchange Servers
$headers .= "X-Mailer: PHPn"; //IP address of who sent the mail.
mail($to, $subject, $message, $headers);
echo "$ip dropped and email sent.n";
}
?>



Note
Do not be a bafoon. Read each line of the previous PHP script and make sure the relevant information is correct for your server, usernames, email address and etc.

Note
For the previous script to work properly, you must be using combined logging methods within Apache: CustomLog /path/to/access.log combined


Now save this file out and you are ready to add another directive for mod_evasive on your Apache httpd.conf file:


DOSSystemCommand "/path/to/php /usr/local/etc/blacklist.php %s"


Now, restart Apache and watch as the script kicks into action. If you use phpMyAdmin, you can browse the database and also tail your system log: tail -f /var/log/messages

When an IP address gets blocked, you SHOULD receive an email notifying you if you setup the PHP script properly.

Note
If you restart your firewall, or Flush iptables, all of the IP address will be flushed along with it. However, the next time they get flagged, they should automatically get dropped from your firewall.

To find out slow queries running for mysql

Sometimes php applications are not tuned up properly. In that case we can track the mysql queries running at very slow speed.

To do this
Edit /etc/init.d/mysql

$bindir/mysqld_safe --datadir=$datadir --pid-file=$pid_file >/dev/null 2>&1 &

Add --log-slow-queries=/var/log/slow-queries.log to above line as below.


$bindir/mysqld_safe --datadir=$datadir --pid-file=$pid_file --log-slow-queries=/var/log/slow-queries.log
>/dev/null 2>&1 &

Migrating from Linux to FreeBSD

Hello All,

Refer the link below for the difference between Linux and FreeBSD:

http://www.osnews.com/story.php?news_id=580

Ping

Here are all of the ping options:

example .. In DOS .. c:>ping 192.168.0.1 -t

-t Ping the specifed host until interrupted

-a Resolve addresses to hostnames

-n count Number of echo requests to send

-l size Send buffer size

-f Set Don't Fragment flag in packet

-i TTL Time To Live

-v TOS Type Of Service

-r count Record route for count hops

-s count Timestamp for count hops

-j host-list Loose source route along host-list

-k host-list Strict source route along host-list

-w timeout Timeout in milliseconds to wait for each reply

Experiment to see how helpful these can be!

APF Deny ALL for SSH - Limit IP Connections

That can be easly done using /etc/hosts.allow and only accepting ssh :

sshd : YOUR_IP_HERE

Then just put:

ALL : ALL at the /etc/hosts.deny, of course IP must be listed at the /etc/apf/allow.. file.
=====================================================================================
Another Method :

APF Deny ALL for SSH - Limit IP Connections

APF firewall can deny ALL connections for ssh and allow only a single or select few of IPs to connect to your server. We'll guide you through DENY ALL with APF firewall.

PROBLEM:
You want to deny all IPs to connect to shell/ssh on you server but only allow a select one or few to connect with APF firewall.

APF SOLUTION:
1) Login to your server as the root user.

2) cd /etc/apf

3) Use vi or nano to edit the /etc/apf/allow_hosts.rules file
EG: vi /etc/apf/allow_hosts.rules

4) Scroll down until after their last comment with the ##

Add the following in:

tcp:in:d=22:s=YOURHOMEIPHERE
out:d=22:d=YOURHOMEIPHERE

The d=22 part is the port, so you can repeat for other services as well to limit connections if you like.

Save the changes.

5) Edit the /etc/apf/deny_hosts.rules file
EG: vi /etc/apf/deny_hosts.rules

Scroll down until the last default comment ## then below it add the following:

tcp:in:d=22:s=0/0
out:d=22:d=0/0

Save the changes.

6) Restart APF firewall
apf -r


Your server is now only allowing connections to the SSH service from one IP using APF. To add more than one IP repeat the steps in 4) adding a new tcp and out line for each IP.

Common Internet Port List

Common Internet Port List
For the entire offical list of the latest IANA port assignments go to:
http://www.iana.org/assignments/port-numbers

Name Port Description
ftp-data 20 FTP Data
ftp 21 FTP
ssh 22 SSH
telnet 23 Telnet
smtp 25 mail
domain 53 Domain Name Service
gopher 70 Internet Gopher
http 80 WorldWideWeb HTTP
kerberos 88 kerberos5 krb5 Kerberos v5
pop3 110 POP version 3
nntp 119 untp USENET News Transfer Protocol
ntp 123 Network Time Protocol
netbios-ns 137 NETBIOS Name Service
netbios-dgm 138 NETBIOS Datagram Service
netbios-ssn 139 NETBIOS session service
imap 143 Interim Mail Access Proto v2
snmp 161 Simple Net Mgmt Proto
snmptrap 162 snmp-trap Traps for SNMP
irc 194 Internet Relay Chat
imap3 220 Interactive Mail Access
ldap 389 Local Directory Access Protocol
https 443 WorldWideWeb HTTP over SSL
nntps 563 NNTP over SSL
ldaps 636 LDAP over SSL
rsync 873 rsync
imaps 993 IMAP over SSL
ircs 994 irc over SSL
pop3s 995 POP-3 over SSL
ms-sql-s 1433 Microsoft-SQL-Server
ms-sql-m 1434 Microsoft-SQL-Monitor
wins 1512 Microsoft's Windows Internet Name Service
nfs 2049 NFS
mysql 3306 MySQL
rdp 3389 Windows Remote Desktop Protocol
pxe 4011 PXE server
rwhois 4321 Remote Who Is<
postgres 5432 POSTGRES
ircd 6667 Internet Relay Chat
webcache 8080 WWW caching service

What is a rootkit?

A rootkit is a set of software tools inteded to conceal running processes, files or system data from the operating system. Basically they let someone get access or run commands when they shouldn't be allowed and don't want to be found. Rootkits can go undetected for long periods of time so it's a good idea to check your system for them regularly in additional to virus scans.

The concept of the rootkit isn't a new one, and dates back to the days of Unix. An intruder could use a kit of common Unix tools, recompiled to allow an intruder to have administrative or root access without leaving traces behind. Rootkits, as we've come to know them today, are programs designed to conceal themselves from both the operating system and the user — usually by performing end-runs around common system APIs. It's possible for a legitimate program to do this, but the term rootkit typically applies to something that does so with hostile intent as a prelude toward stealing information, such as bank account numbers or passwords, or causing other kinds of havoc.

Many antivirus and security-software manufacturers have since added at least some rudimentary level of rootkit detection to their products, but there have been a number of free, standalone rootkit detection tools that have been in use for some time. In this article, I examine six of the more prevalent standalone applications, and talk about their relative merits and abilities. To test them out, I used them to scan a system for three varieties of rootkit: Fu or FuTo, which can "stealth" any process; the AFX Windows Rootkit 2003, which can hide processes and folders from the system; and Vanquish, which is similar to AFX but uses a slightly different concealment mechanism.

How They Work
The detectors themselves typically work by comparing different views of the system and seeing where there's a mismatch. One of the original ways to perform this kind of detection was to dump a complete list of all the files on the volume while inside the operating system, then boot to the Recovery Console and dump another file list, then compare the two. If a file shows up in the second list but not in the first and isn't a Windows file kept hidden by default, it's probably a culprit. More recent rootkit detectors use variations on this scheme that don't require exiting the operating system to get usable results.

I've also looked at these applications in a more general light and tried to consider how useful the program is likely to be in the future: how easy the detector is to use; how easy it is to interpret the results; how often the detector was updated; and so on. Remember that rootkits, like viruses, are a moving target. An anti-rootkit program that protects you today might be defenseless tomorrow against a whole new variety of threat — in fact, many rootkit makers write their programs to specifically avoid detection by some existing programs.

For the most part, these programs are for advanced- to expert-level users. They're not intended to be used as general-purpose solutions; they don't always distinguish between false positives (i.e., files hidden by the operating system deliberately) and real rootkits; they come with no warranty — they're provided "as-is" — and some of them (such as Trend Micro's product) have their core technologies available in a far more user-friendly version in a commercial product. In short, if you're not a professional, your best bet, at least for now, is to either hire a guru or use a mainstream product that has some kind of rootkit detection capability (such as Trend Micro Internet Security 2007).

-- Regards,
Dhananjay

APF Commands

check apf status
----
apf --status

List apf rules
----
apf -l

APF restart
----
apf -r

Block IP under apf
----
apf -d 192.168.1.1

How to find file with 750 file permission?

How to find file with 750 file permission

# find / -type f -perm 750

Extra headers you enabled to help track Spammers

Extra headers you enabled to help track Spammers

Lets start by knowing where Exim keeps it logs
– Linux
● /var/log/exim_mainlog
– FreeBSD
● /var/log/exim/mainlog

Check the headers
– Is your hostname in there?
– Is your IP in there?
– Use the extra headers you enabled to help track down the spammer for you!

In the Exim Configuration add
– log_selector = +arguments + subject

Lets start by knowing where Exim keeps it logs
– Linux
● /var/log/exim_mainlog
– FreeBSD
● /var/log/exim/mainlog

It makes looking through the logs easier
– Take a look at the following example. You can
see exactly where the email was sent from.
● 2006-05-08 17:24
cwd=/home/user/public_html/phpBB 5 args: /
usr/sbin/exim -Mc 19Z8vf-0023mp-E2

Ports that must be open to run cPanel behind a firewall / IP

Ports that must be open to run cPanel behind a firewall / IPTables
port service protocol direction

20 ftp tcp inbound/outbound

21 ftp tcp,udp inbound/outbound

22 ssh tcp inbound

25 smtp tcp inbound/outbound

26 smtp tcp inbound/outbound

37 rdate tcp outbound

43 whois tcp outbound

53 DNS tcp/udp inbound/outbound
(inbound is only needed if you run your own public DNS server you)

80 http tcp inbound/outbound

110 pop3 tcp inbound

113 ident tcp outbound

143 imap4 tcp inbound

443 https tcp inbound

465 smtp tls/ssl tcp/udp inbound/outbound

873 rsync tcp/udp outbound

993 imap4 ssl tcp inbound

995 pop3 ssl tcp inbound

2082 cpanel tcp inbound

2083 cpanel ssl tcp inbound

2086 whm tcp inbound

2087 whm ssl tcp inbound

2089 cp licence tcp outbound

2095 Webmail tcp inbound

2096 Webmail SSL tcp inbound

3306 mysql tcp (only if you need to connect remotely)

6666 chat tcp inbound

ddos command

ddos command :


netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n
route add 12.219.178.143 reject
route add 202.173.147.138 reject

===============

netstat -a | grep SYN | wc -l
iptables -A INPUT -s 124.177.148.139 -j DROP
netstat -anp |grep 'tcp\|udp' | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n

===============

Kill nobody /user process

Kill nobody /user process :

Kill nobody process
----
ps aux | grep nobody | awk '{print $2}'| xargs kill -9

Kill user process
----
ps aux | grep apache | awk '{print $2}' | xargs kill -9

Steps to prevent or mitigate future DDoS attack

Steps to prevent or mitigate future DDoS attack

To prevent or mitigate future DDoS attacks, follow these steps:

* Create and implement a good security policy
* Conduct regular audits on each host on the network to find installed DDoS tools and vulnerable applications.
* Use tools like Rkdet, Rootkit Hunter, or chkrootkit to find if a rootkit has been installed on your system.
* Perform a general security audit on your systems on a regular basis.
* Keep your systems up to date to minimize software vulnerabilities (kernel and software upgrades)
* Check for rootkits
* Check logs for evidence of port sniffing, etc.
* Check for hidden processes by comparing the output of 'ps' and 'lsof'.
* Add 'Mod_dosevasive' to your Apache installation. This is an Apache module which performs 'evasive' action in the event of an HTTP DDoS attack or brute force attack.
* Install the 'Mod_security' module. Since DDoS often targets HTTP(port 80), it's a good idea to have a filtering system for Apache. 'Mod_security' will analyze requests before passing them to the web server.

How to check windows server uptime ?

How to check windows server uptime :

command is

systeminfo | find "System Up Time"

Forcefully RDC

Forcefully RDC :

mstsc -v Ipaddress

The ipaddress of the server where you want to rdc

OR else
Try using this one mstsc -v:ipaddress /f -console

How to Edit RDP properties

How to Edit RDP properties :

start->run->tscc.msc

double click RDP-Tcp
Network Adapter tab
select the required

Compiling the kernel

Wanted to try out the 2.6 edition kernel? Never knew how to do it? Well heres how! Includes everything from compiling the kernel to configuring your bootloader.

Lets Begin!

cd /usr/src
wget -c http://kernel.org/pub/linux/kernel/v2.6/linux-2.6.7.tar.bz2
tar xvfj linux-2.6.7.tar.bz2
cd linux-2.6.7
make clean && make mrproper
make oldconfig ( or make menuconfig )
make bzImage
make modules
make modules_install
( i prefer this method rather then just "make" )

If you get alot of errors about .ko modules when you run make modules_install you need to update your modutils package with module-init-tools, see below.

Now to copy the files over for the kernel itself.

cp .config /boot/config-2.6.7
cp arch/i386/boot/bzImage /boot/vmlinuz-2.6.7
cp System.map /boot/System.map-2.6.7
mkinitrd /boot/initrd-2.6.7.img 2.6.7

You may experience an error such as this:

/dev/mapper/control: open failed: No such file or directory

if you receive that error run the following commands:

rm -rf /boot/initrd-2.6.7.img
mkinitrd --omit-lvm-modules /boot/initrd-2.6.7.img 2.6.7

Now to add it to the grub / lilo configuration.

[Grub]
Your config will look something like this. Please note you need to follow the format for your current config.

title Red Hat Linux (2.6.7)
root (hd0,0)
kernel /vmlinuz-2.6.7 ro root=LABEL=/
initrd /initrd-2.6.7.img

Add your new entry to the top of the kernel list. Set the default to your working kernel. NOTE: the first kernel in the list is "0". (ex. default=1)

Now exit. Type "grub" at the bash prompt.

savedefault --default=0 --once

issue that at the grub prompt then use quit to exit. Once your reboot you need to go back in and set the default to the 2.6 kernel by setting default=0

[lilo]
Your config will look something like this. Please note you need to follow the format for your current config.

image=/boot/vmlinuz-2.6.7
label=2.6.7
append="root=LABEL=/"
read-only
initrd=/boot/initrd-2.6.7.img

Leave the default as is.

/sbin/lilo -v -v
/sbin/lilo -R 2.6.7

Once it reboots and comes back online you can change the default to be 2.6.7 and /sbin/lilo -v -v

The above tells you how to enable failsafe in your kernels. SO that if the box panics the dc tech does not have to console in he just has to reboot the box.

How to install module-init-tools:
cd /usr/src
wget -c http://www.kernel.org/pub/linux/kernel/people/rusty/modules/module-init-tools-3.0.tar.gz
tar -zxvf module-init-tools-3.0.tar.gz
cd module-init-tools-3.0
./configure --prefix=""
make moveold
make install
./generate-modprobe.conf /etc/modprobe.conf

How to determine what boot loader you are using?
dd if=/dev/hda bs=512 count=1 2>&1 | grep GRUB
dd if=/dev/hda bs=512 count=1 2>&1 | grep LILO

one of them will kick back something like:

root@w00t [~]# dd if=/dev/hda bs=512 count=1 2>&1 | grep GRUB
Binary file (standard input) matches
root@w00t [~]#

which means its using grub.

Stop PHP nobody Spammers

PHP and Apache has a history of not being able to track which users are sending out mail through the PHP mail function from the nobody user causing leaks in formmail scripts and malicious users to spam from your server without you knowing who or where.
Watching your exim_mainlog doesn't exactly help, you see th email going out but you can't track from which user or script is sending it. This is a quick and dirty way to get around the nobody spam problem on your Linux server.

If you check out your PHP.ini file you'll notice that your mail program is set to: /usr/sbin/sendmail and 99.99% of PHP scripts will just use the built in mail(); function for PHP - so everything will go through /usr/sbin/sendmail =)

Requirements:
We assume you're using Apache 1.3x, PHP 4.3x and Exim. This may work on other systems but we're only tested it on a Cpanel/WHM Red Hat Enterprise system.



Time:
10 Minutes, Root access required.

Step 1)
Login to your server and su - to root.

Step 2)
Turn off exim while we do this so it doesn't freak out.
/etc/init.d/exim stop

Step 3)
Backup your original /usr/sbin/sendmail file. On systems using Exim MTA, the sendmail file is just basically a pointer to Exim itself.
mv /usr/sbin/sendmail /usr/sbin/sendmail.hidden

Step 4)
Create the spam monitoring script for the new sendmail.
pico /usr/sbin/sendmail

Paste in the following:


#!/usr/local/bin/perl

# use strict;
use Env;
my $date = `date`;
chomp $date;
open (INFO, ">>/var/log/spam_log") || die "Failed to open file ::$!";
my $uid = $>;
my @info = getpwuid($uid);
if($REMOTE_ADDR) {
print INFO "$date - $REMOTE_ADDR ran $SCRIPT_NAME at $SERVER_NAME n";
}
else {

print INFO "$date - $PWD - @infon";

}
my $mailprog = '/usr/sbin/sendmail.hidden';
foreach (@ARGV) {
$arg="$arg" . " $_";
}

open (MAIL,"|$mailprog $arg") || die "cannot open $mailprog: $!n";
while ( ) {
print MAIL;
}
close (INFO);
close (MAIL);


Step 5)
Change the new sendmail permissions
chmod +x /usr/sbin/sendmail

Step 6)
Create a new log file to keep a history of all mail going out of the server using web scripts
touch /var/log/spam_log

chmod 0777 /var/log/spam_log

Step 7)
Start Exim up again.
/etc/init.d/exim start

Step
Monitor your spam_log file for spam, try using any formmail or script that uses a mail function - a message board, a contact script.
tail - f /var/log/spam_log

Sample Log Output

Mon Apr 11 07:12:21 EDT 2005 - /home/username/public_html/directory/subdirectory - nobody x 99 99 Nobody / /sbin/nologin

Log Rotation Details
Your spam_log file isn't set to be rotated so it might get to be very large quickly. Keep an eye on it and consider adding it to your logrotation.

pico /etc/logrotate.conf

FIND:
# no packages own wtmp -- we'll rotate them here
/var/log/wtmp {
monthly
create 0664 root utmp
rotate 1
}

ADD BELOW:

# SPAM LOG rotation
/var/log/spam_log {
monthly
create 0777 root root
rotate 1
}



Notes:
You may also want to chattr + i /usr/sbin/sendmail so it doesn't get overwritten.

Enjoy knowing you can see nobody is actually somebody =)

Close Open DNS Servers

For those of you who check your nameservers and other DNS related issues using the popular site dnsreport you're probbaly seeing Fail Open DNS Servers. We'll show you have to fixed named to close open dns servers.
How do I check my system?
Go to www.dnsreport.com and enter your domain name, eg webhostgear.com

You're safe if you see:
PASS Open DNS servers

You need to follow this tutorial if you see:
FAIL Open DNS servers

Closing Open DNS Servers Tutorial

1) Login to your server and su to root.

2) Edit the /etc/named.conf file such as:# vi /etc/named.conf

Look for:

key "rndckey" {};
After this add the following, replacing mainIP and secondaryIP with your systems nameservers.

acl "trusted" {mainIP;secondaryIP;127.0.0.1;};


3) After that's done you want to add the section that says only the trusted is allowed for certain functions. Check your options area and make sure you add the following:

allow-recursion { trusted; };
allow-notify { trusted; };allow-transfer { trusted; };
So the final result looks something like:

options { directory "/var/named"; allow-recursion { trusted; }; allow-notify { trusted; }; allow-transfer { trusted; };
dump-file "/var/named/data/cache_dump.db"; statistics-file "/var/named/data/named_stats.txt"; /* * If there is a firewall between you and nameservers you want
* to talk to, you might need to uncomment the query-source * directive below. Previous versions of BIND always asked * questions using port 53, but BIND 8.1 uses an unprivileged * port by default.
*/ // query-source address * port 53;};
4) Save the changes and restart the named service: service named restart

5) Recheck your site at dnsreport.com, you should be good!

How to install Root Check ?

RootCheck scans the system looking for possible trojans ,scans the ports for malicious activity ,and checks for rootkits,and also the logs,permissions and more.
Installation Instructions
Login to your server and su to root.

wget http://www.ossec.net/rootcheck/files/rootcheck-0.4.tar.gz

tar -xvzf rootcheck-0.4.tar.gz
cd rootcheck-0.4
./install

This will take you to an interactive installtion. Make sure you have CPAN on your box because rootcheck requires the Perl Modules IO::Interface.

If the installtion is finished you will get this message

Compilation sucessfull. Ready to go. --------------------------------------------------------- That's it! If everything went ok, you should be ready
to run RootCheck. If you any doubts about installation, please refer to INSTALL file. You can also find additional information at : http://www.ossec.net/rootcheck/
Improves, patches, comments are very welcome.---------------------------------------------------------


Scanning the System
Now you are ready to run rootcheck.

There are quite a few options butthe simplest one is

./rootcheck.pl

If the installation was perfect you would get a progress screen of the scan after which the results wiill be writen into results.txt the result is quite explanatory and gives details of all suspected files.

There is also an example file that explains the different options for root check
More Information about rootcheck is available at http://www.ossec.net/

E-mail Alert on Root SSH Login

Want to be notified instantly when someone logs into your server as root? No problem, check out this nice tutorial on email notification for root logins. Keeping track of who logs into your server and when is very important, especially when you're dealing with the super user account. We recommend that you use an email address not hosted on the server your sending the alert from.

So lets get started!

1. Login to your server and su to root, I know the irony!

2. cd /root

3. pico .bashrc

4. Scroll to the end of the file then add the following:
echo 'ALERT - Root Shell Access (YourserverName) on:' `date` `who` | mail -s "Alert: Root Access from `who | cut -d"(" -f2 | cut -d")" -f1`" you@yourdomain.com

Replace YourServerName with the handle for your actual server
Replace you@yourdomain.com with your actual email address


5. Crtl + X then Y

Now logout of SSH, close the connection and log back in! You should receive an email address of the root login alert a few minutes afterwards.

Note: This is a great tool for servers that have multiple admins or if you give someone SSH access for whatever reason, although you should give out the root password to as few people as humanly possible and be sure to change it often.

This will not magically alert you when a hacker runs the latest kernel exploit on your server and logs into SSH because they will create their own SSH/telnet connection. You should keep your system up to date, install a firewall and follow the latest security releases.

10 Steps to Securing your Server

10 Steps to Securing your Server

So many people are getting their own dedicated servers but are completely clueless about security. Usually they leave it up to the company where they purchase it or hire someone. That's fine but make sure you have these 10 items covered.
1) Use a Firewall
Make absolutely sure that your server has a firewall running all the time. A firewall is like a screen door to your porch. It blocks out flies, rodents and other pests but you can still walk out and use your BBQ. If someone ever were to get into your server, which is very very likely, the first thing they're going to try and do is upload something to start a daemon or their own service like an IRC server or use a port to launch attacks to other systems. A firewall with egress and ingress protection can stop both incoming and outgoing attacks even when you're not aware of it. We recommend using APF on Linux systems or TinyFirewall on Windows Servers. These are software firewalls so there's no extra monthly cost like a hardware firewall. For very busy systems a hardware firewall is recommended so it takes the burden off your system CPU/RAM and resources to do the work.

Know what ports are open and why, know how to block and unblock an IP. These are basic things you need to understand in the daily security of your system. If someone from an IP begins a brute force attack you want to know how to stop them, right away. Installing APF Firewall, Preventing Brute Force Attacks, Installing KISS Firewall

2) Update your kernel and OS
Make sure your server is using current, updated software. Use the stable version which has been tested more than any beta and update as soon as possible. An old kernel can lead to an easy target for your server. If you're not sure then ask your provider for the latest update.


3) Monitor Logs
Do you know what logs record which activities? How often are they updated and rotated?
LogWatch is a great tool to email you the daily reports of your systems activity of anything it determines unusual, EG repeated failed logins. Besides using this you should check your logs manually to see what's up. Tail –f /var/log/messages and view your Apache logs as well. Apache Log Files Explained

4) Backups
I still never understand why no one backs up their data yet you spend hundreds of hours working on your website or application then you absolutely must have a second hard drive for backups or use a remote back up system or a combination of these. Second Hard Drive Means Life or Death

5) Limit Access to a Minimum
Do not give users more access than the absolute minimum they require. Never give them shell access, restrict file access to a bare minimum and leave other services turned off by default until specifically requested and you determine that its safe to do so.


6) Lock down PHP and use Mod_Security with Apache
PHP is actually a large security risk but there are a few things to do to help lock it down. CGI has Suexec,which helps runs proccesess as the user and PHP has something similar called PHPSuexec but there are a few downfalls. You should also use open_base directory protection, have safe_mode on system wide, turn off register_globals, enable_dl and allow_url_open to help lock things down further.

You can use server wide protection with mod_security, a web server filter that can watch all requests to see if they match a rule and react by logging, denying the request or other programs. I highly recommend this on Apache based servers and can be extremely useful in blocking attacks and stopping hackers before they do any damage. Securing Safe Mode , Installing Mod_Security


7) Lock /tmp /var/tmp and /dev/shm partitions
On Linux each partition can have certain access restrictions. Since /tmp /var/tmp and /dev/shm are world writable directories they're often home to uploads, sessions storage and hacker executables. Since anyone can read-write-excute anything from these directories it becomes a major security concern. With /etc/fstab however you can limit what can be done in these locations. If you see defaults beside the /tmp line remove it and replace it with noexec,nosuid this will stop any executables from being allowed to run. Do the same for /dev/shm and make /var/tmp and shortcut (symbolic link) to /tmp. Securing Your TMP Partition

Intrusion Detection System (IDS)
An intrusion detection system or IDS is like a burglar alarm on your server. It keeps a record of which files were changed when and alerts you of anything new or altered. This is critical because hackers usually try to replace binary applications like ps, top, netstat and others. This means when you run this new version of ps or top to see processes running they make it so it actually HIDES their hacker software, even though its running it won't show up. Some IDS systems include TripWire, Snort and AIDE. Installing Chkrootkit

9) Review Processes Running and Remove Extra Software
You can't protect a system if you don't know what's on it. If a hacker adds an extra process that you see in PS but you wouldn't notice if you didn't know what should be there usually. Know what runs on your system and why which user. How does Perl or Apache run, under which user? You can check your processes usually with top or ps auxfww which gives you a tree view. Check these every time you login to your server. Getting started with Shell (SSH) , Common Shell Commands

10) Keep an Eye on the Servers Performance
Know what speed your server is running at and how much bandwidth it uses on a daily basis. If an attacker compromises your system and you don't know you'll probably notice the system responding slowly or using a lot of bandwidth. If you don't know what your system is usually like how will you notice something out of the ordinary. This is all common sense but some people never bother to check until they ask their provider after a system has been slow for 2 weeks – it's usually to late then. Server Loads Explained

Knowing your system makes you one step ahead of an intruder. Check it often and ask an expert if you're ever over your head. There are MANY other things you can and should do to ensure your server is secure but these are a few basics that everyone should use.

Disable Direct Root Logins

Allowing the root user to login directly is a major security issue, we'll show you how to disable it so you can still login as root but just not directly, reducing the security issue.

This will force a hacker to have to guess 2 seperate passwords to gain root access.
(you do have 2 seperate passwords for admin and root right?)
What happens is you'll first need to login as your admin user in SSH, then switch to the super user with the su command to get root.

We also will be forcing the use of SSH protocol 2, which is a newer, more secure SSH protocol
Just a couple more ways to help your server stay safe from the bad guys. If you're using cPanel make sure you add your admin user to the ' wheel' group so that you will be able to 'su -' to root, otherwise you may lock yourself out of root.

1. SSH into your server as ' admin' and gain root access by su

2. Copy and paste this line to edit the file for SSH logins
pico -w /etc/ssh/sshd_config

3. Find the line
Protocol 2, 1

4. Uncomment it and change it to look like
Protocol 2

5. Next, find the line
PermitRootLogin yes

6. Uncomment it and make it look like PermitRootLogin no

7. Save the file Ctrl+X then Y then enter

8. Now you can restart SSH
/etc/rc.d/init.d/sshd restart

Now, no one will be able to login to root with out first loggin in as admin and 'su -' to root, and you will be forcing the use of a more secure protocol. Just make sure you remember both passwords!

Creating a Welcome message for SSH logins

Did you ever want to change or create a new login message antime someone logs into SSH? We'll show you how it's done.

First off login to our server as root. Then type in the following:
pico /etc/motd

Now type in the security login message you wish all users to see once they login to your server through SSH.
Try something like this as a start:

This computer system is for authorized users only. All activity is logged and regulary checked by systems personal. Individuals using this system without authority or in excess of their authority are subject to having all their services revoked. Any illegal services run by user or attempts to take down this server or its services will be reported to local law enforcement, and said user will be punished to the full extent of the law. Anyone using this system consents to these terms.

Now type Ctrl+X then hit Y and enter

Logout of SSH then log back in, you will receive your new greeting!