Archive

Archive for the ‘Server Security Guides’ Category

to make your apache configuration more secure.

October 7th, 2009

Here are the 20 things you can do to make your apache configuration more secure.

First, make sure you’ve installed latest security patches

There is no sense in putting locks on the windows, if your door is wide open. As such, if you’re not patched up there isn’t really much point in continuing any longer on this list.

Hide the Apache Version number, and other sensitive information.

By default many Apache installations tell the world what version of Apache you’re running, what operating system/version you’re running, and even what Apache Modules are installed on the server. Attackers can use this information to their advantage when performing an attack. It also sends the message that you have left most defaults alone.

There are two directives that you need to add, or edit in your httpd.conf file:

ServerSignature Off
ServerTokens Prod

The ServerSignature appears on the bottom of pages generated by apache such as 404 pages, directory listings, etc.

The ServerTokens directive is used to determine what Apache will put in the Server HTTP response header. By setting it to Prod it sets the HTTP response header as follows:

Server: Apache

If you’re super paranoid you could change this to something other than “Apache” by editing the source code, or by using mod_security

Make sure apache is running under its own user account and group

Several apache installations have it run as the user nobody. So suppose both Apache, and your mail server were running as nobody an attack through Apache may allow the mail server to also be compromised, and vise versa.

User apache
Group apache

Ensure that files outside the web root are not served

We don’t want apache to be able to access any files out side of its web root. So assuming all your web sites are placed under one directory (we will call this /web), you would set it up as follows:

Order Deny,Allow
Deny from all
Options None
AllowOverride None

Order Allow,Deny
Allow from all

Note that because we set Options None and AllowOverride None this will turn off all options and overrides for the server. You now have to add them explicitly for each directory that requires an Option or Override.

Turn off directory browsing

You can do this with an Options directive inside a Directory tag. Set Options to either None or -Indexes

Options -Indexes

Turn off server side includes

This is also done with the Options directive inside a Directory tag. Set Options to either None or -Includes

Options -Includes

Turn off CGI execution

If you’re not using CGI turn it off with the Options directive inside a Directory tag. Set Options to either None or -ExecCGI

Options -ExecCGI

Don’t allow apache to follow symbolic links

This can again can be done using the Options directive inside a Directory tag. Set Options to either None or -FollowSymLinks

Options -FollowSymLinks

Turning off multiple Options

If you want to turn off all Options simply use:

Options None

If you only want to turn off some separate each option with a space in your Options directive:

Options -ExecCGI -FollowSymLinks -Indexes

Turn off support for .htaccess files

This is done in a Directory tag but with the AllowOverride directive. Set it to None.

AllowOverride None

If you require Overrides ensure that they cannot be downloaded, and/or change the name to something other than .htaccess. For example we could change it to .httpdoverride, and block all files that start with .ht from being downloaded as follows:

AccessFileName .httpdoverride

Order allow,deny
Deny from all
Satisfy All

Run mod_security

mod_security is a super handy Apache module written by Ivan Ristic, the author of Apache Security from O’Reilly press.

You can do the following with mod_security:

* Simple filtering
* Regular Expression based filtering
* URL Encoding Validation
* Unicode Encoding Validation
* Auditing
* Null byte attack prevention
* Upload memory limits
* Server identity masking
* Built in Chroot support
* And more

Disable any unnecessary modules

Apache typically comes with several modules installed. Go through the apache module documentation and learn what each module you have enabled actually does. Many times you will find that you don’t need to have the said module enabled.

Look for lines in your httpd.conf that contain LoadModule. To disable the module you can typically just add a # at the beginning of the line. To search for modules run:

grep LoadModule httpd.conf

Here are some modules that are typically enabled but often not needed: mod_imap, mod_include, mod_info, mod_userdir, mod_status, mod_cgi, mod_autoindex.
Make sure only root has read access to apache’s config and binaries

This can be done assuming your apache installation is located at /usr/local/apache as follows:

chown -R root:root /usr/local/apache
chmod -R o-rwx /usr/local/apache

Lower the Timeout value

By default the Timeout directive is set to 300 seconds. You can decrease help mitigate the potential effects of a denial of service attack.

Timeout 45

Limiting large requests

Apache has several directives that allow you to limit the size of a request, this can also be useful for mitigating the effects of a denial of service attack.

A good place to start is the LimitRequestBody directive. This directive is set to unlimited by default. If you are allowing file uploads of no larger than 1MB, you could set this setting to something like:

LimitRequestBody 1048576

If you’re not allowing file uploads you can set it even smaller.

Some other directives to look at are LimitRequestFields, LimitRequestFieldSize and LimitRequestLine. These directives are set to a reasonable defaults for most servers, but you may want to tweak them to best fit your needs. See the documentation for more info.
Limiting the size of an XML Body

If you’re running mod_dav (typically used with subversion) then you may want to limit the max size of an XML request body. The LimitXMLRequestBody directive is only available on Apache 2, and its default value is 1 million bytes (approx 1mb). Many tutorials will have you set this value to 0 which means files of any size may be uploaded, which may be necessary if you’re using WebDAV to upload large files, but if you’re simply using it for source control, you can probably get away with setting an upper bound, such as 10mb:

LimitXMLRequestBody 10485760

Limiting Concurrency

Apache has several configuration settings that can be used to adjust handling of concurrent requests. The MaxClients is the maximum number of child processes that will be created to serve requests. This may be set too high if your server doesn’t have enough memory to handle a large number of concurrent requests.

Other directives such as MaxSpareServers, MaxRequestsPerChild, and on Apache2 ThreadsPerChild, ServerLimit, and MaxSpareThreads are important to adjust to match your operating system, and hardware.
Restricting Access by IP

If you have a resource that should only by accessed by a certain network, or IP address you can enforce this in your apache configuration. For instance if you want to restrict access to your intranet to allow only the 176.16 network:

Order Deny,Allow
Deny from all
Allow from 176.16.0.0/16

Or by IP:

Order Deny,Allow
Deny from all
Allow from 127.0.0.1

Adjusting KeepAlive settings

According to the Apache documentation using HTTP Keep Alive’s can improve client performance by as much as 50%, so be careful before changing these settings, you will be trading performance for a slight denial of service mitigation.

KeepAlive’s are turned on by default and you should leave them on, but you may consider changing the MaxKeepAliveRequests which defaults to 100, and the KeepAliveTimeout which defaults to 15. Analyze your log files to determine the appropriate values.
Run Apache in a Chroot environment

chroot allows you to run a program in its own isolated jail. This prevents a break in on one service from being able to effect anything else on the server.

It can be fairly tricky to set this up using chroot due to library dependencies. I mentioned above that the mod_security module has built in chroot support. It makes the process as simple as adding a mod_security directive to your configuration:

SecChrootDir /chroot/apache

There are however some caveats however, so check out the docs for more info

Server Security Guides

Swap ( Creating , Deleting & adding more swap space in live server )

October 7th, 2009

To create  a swap partations

1. Create a partations using fdisk /dev/hd(a,b) 1,2

2.Now that you have the swap partition, use the command mkswap to setup the swap partition. At a shell prompt as root, type the following:
mkswap /dev/hdb2

3.To enable the swap partition immediately, type the following command:

swapon /dev/hdb2

4.To enable it at boot time, edit /etc/fstab to include:

/dev/hdb2               swap                    swap    defaults        0 0

The next time the system boots, it will enable the new swap partition.

5. After adding the new swap partition and enabling it, make sure it is enabled by viewing the output of the command cat /proc/swaps or free.
===========================================================================
How to create a swap file
To add a swap file:

1.Determine the size of the new swap file and multiple by 1024 to determine the block size. For example, the block size of a 64 MB swap file is 65536.

2.At a shell prompt as root, type the following command with count being equal to the desired block size:

dd if=/dev/zero of=/swapfile bs=1024 count=65536

3.Setup the swap file with the command:

mkswap /swapfile

4.To enable the swap file immediately but not automatically at boot time:

swapon /swapfile

5.To enable it at boot time, edit /etc/fstab to include:

/swapfile               swap                    swap    defaults        0 0

The next time the system boots, it will enable the new swap file.
6.After adding the new swap file and enabling it, make sure it is enabled by viewing the output of the command cat /proc/swaps or free.

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

removing swap partations

To remove a swap partition:

1.The hard drive can not be in use (partitions can not be mounted, and swap space can not be enabled). The easiest way to achieve this it to boot your system in rescue mode. Refer to Chapter 9 Basic System Recovery for instructions on booting into rescue mode. When prompted to mount the file system, select Skip.

Alternately, if the drive does not contain any partitions in use, you can unmount them and turn off all the swap space on the hard drive with the swapoff command.

2. At a shell prompt as root, execute the following command to make sure the swap partition is disabled (where /dev/hdb2 is the swap partition):

swapoff /dev/hdb2

3. Remove its entry from /etc/fstab.

4. Remove the partition using parted or fdisk. Only parted will be discussed. To remove the partition with parted:

5. At a shell prompt as root, type the command parted /dev/hdb, where /dev/hdb is the device name for the hard drive with the swap space to be removed.

6. At the (parted) prompt, type print to view the existing partitions and determine the minor number of the swap partition you wish to delete.

At the (parted) prompt, type rm MINOR, where MINOR is the minor number of the partition you want to remove.

Warning    Warning

Changes take effect immediately; you must type the correct minor number.

Type quit to exit parted.

To remove a swap file:

1.At a shell prompt as root, execute the following command to disable the swap file (where /swapfile is the swap file):

swapoff /swapfile

2. Remove its entry from /etc/fstab.
3. Remove the actual file:

rm /swapfile

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

How to increase the swap space in live server ?

1) [root@svr92 ~]# swapon -s
Filename                                Type            Size    Used    Priority
/dev/sda7                               partition       2040212 135292  -1

If you want to make 2 Gb file it should be calculated as 2000 * 1024

2) [root@svr92 ~]# dd if=/dev/zero of=/swapfile01 bs=1024 count=2048000
2048000+0 records in
2048000+0 records out
2097152000 bytes (2.1 GB) copied, 189.598 seconds, 11.1 MB/s

3) [root@svr92 ~]# ls -l /swapfile01
-rw-r–r– 1 root root 2097152000 Apr 15 01:21 /swapfile01
[root@svr92 ~]# mkswap /swapfile01
Setting up swapspace version 1, size = 2097147 kB

4) [root@svr92 ~]# free
total       used       free     shared    buffers     cached
Mem:       3369592    3241120     128472          0      16232     528564
-/+ buffers/cache:    2696324     673268
Swap:      2040212     737076    1303136
5) [root@svr92 ~]# swapon /swapfile01

6) [root@svr92 ~]# free
total       used       free     shared    buffers     cached
Mem:       3369592    3245052     124540          0      24204     508808
-/+ buffers/cache:    2712040     657552
Swap:      4088204     861776    3226428

Add the line to /etc/fstab

/swapfile01             none                    swap    sw              0 0

So that swap will be up  once rebooting the server

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

Server Security Guides

catching spammer sending mails from nobody

October 7th, 2009

Below are the some ways to catch the spammer. But keep in mind Experience makes spam catcher :

=> You should be able to catch the spammer by checking exim_mainlog. To enable extended loggin in exim to trace nobody mails. Try the following tricks.
1. Edit /etc/exim.conf
2. On the second line add:
log_selector = +address_rewrite +all_parents +arguments +connection_reject +delay_delivery +delivery_size +dnslist_defer +incoming_interface +incoming_port +lost_incoming_connection +queue_run +received_sender +received_recipients +retry_defer +sender_on_delivery +size_reject +skip_delivery +smtp_confirmation +smtp_connection +smtp_protocol_error +smtp_syntax_error +subject +tls_cipher +tls_peerdn
Make sure all that comes on a single line.
3. Save and exit
4. Restart Exim
5. tail -f /var/log/exim_mainlog

=> If you fail to catch the spammer by checking exim_mainlig then he is using some other way of spamming and to catch her you will have to try the following steps :

1. Get the message ID from the header of the spam. It should be in format like 1DWJj4-00042i-74.This is the most important point else all thats given below is meaningless
2. grep exim_mainlog with the message ID ( Ex : grep 1DWJj4-00042i-74 /var/log/exim_mainlog )
3. Check the time on which the spam was sent and also check all that is shown after grep.
4. If you find out the domain name or path of the scripts from exim_mainlog then go ahead and suspend the spammer, else proceed to step 5.
5. Use this message ID to check the original message or bounced message in /var/spool/exim/input/. You should see 2 files there, one with -D at end and one with -H at the end. ( Ex : /var/spool/exim/input/4/1DWJj4-00042i-74-D & /var/spool/exim/input/4/1DWJj4-00042i-74-H ) This 2 files will have all the information that was sent in the spam message and if it was sent using mailing list then you will catch the username of spammer in auth_sender part of this files. If it shows nobody then its your bad luck Proceed to step 6.
6. If exim_mainlog shows the spams originating from /tmp of the server then check the files in /tmp of the server. user of the file will be seen as nobody:nobody. Take down the time of creation of file. This time is what we need to find out who uploaded the script. You will need to convert this time into the time format of /usr/local/apache/logs/error_log & then in the format of the domlogs located at /usr/local/apache/domlogs/*
7. for file in /usr/local/apache/domlogs/*; do cat $file |grep “example”; done; ( you cannot do direct grep for the query here as it will give error that the arguement list is too long )
8. If the results in step 2 have shown some domain name or some username in common as sender of the spam but now you dont see that domain name on the server then check /var/cpanel/accounting.log to see if that account has been terminated from the server ( Ex : grep ebayspammer.com /var/cpanel/accounting.log )

=> Major spamming issues are caught using the time of sending the spam. Use your logic to convert the time of sending the spams to the time format of respective log files (log files such as var/log/exim_mainlog, /usr/local/apache/domlogs/*, /var/log/formmail.log, /var/spool/exim/input/*/*, )

=> If you fail to catch active spamming on the server in short time then rename /etc/exim.conf and killall -KILL exim. If this has not stopped the process then check the running MySQL Server processes and stop MySQL Server if needed. If no results then stop http service or find the process ID and kill it.

Server Security Guides

Dictionary attack spamming on cpanel servers

October 7th, 2009

Never again..It was bad and tough to fight against the Dictionary attack spamming. Either the server load will rise or

Dictionary attack
—————–

From wikipedia :

Spammers may also use a form of dictionary attack in order to harvest e-mail addresses. For example, a spammer may send messages to adam@example.com, betty@example.com, carl@example.com, etc. Any addresses to which messages are delivered, as opposed to being bounced back, the spammer can then add to his or her sending list.

My issue was that, the attacker was spamming the domain in such a way that in matter of seconds, the cPanel server, which had the setting of smtp_accept_max = 150 will show

Connection refused from [xx.xx.xx.xx] : too many connections

not allowing other legit customers to send and receive emails. The spammers were targetting only one domain and I didnt have to go for some automate application.

RBLs were not working as expected and had to end up using acl_smtp_connect (Exim 4.53), It was dropping after a connection is made.

acl_smtp_connect = check_host

Touched two files, /etc/eximwhites and /etc/eximblacks and just after begin acl, added this

check_host:
accept
hosts = /etc/eximwhites

deny
log_message = match eximblacks
hosts = /etc/eximblacks
accept

I could configure ACL to use the RBL in the connect, but 50% of many spammer IPs being used was not on any RBL lists. So executed two piped commands as below to start with,

For adding server Ips to white list

ifconfig | grep ‘inet addr’ | cut -d “:” -f 2 | cut -d ” ” -f 1 >> /etc/eximwhites

To add spammer’s IP to black list. Replace example.com with the domain under attack.

grep example.com /var/log/exim_mainlog | grep “rejected RCPT” | cut -d “[" -f 2 | cut -d "]” -f 1 | sort | uniq >> /etc/eximblacks

Server Security Guides

cPHulk Brute Force Protection

October 7th, 2009

cPHulk Brute Force Protection prevents malicious attempts at accessing your server’s services by guessing the login password for that service.
Steps

1. To access the cPHulk Brute Force Protection feature, click on Security, on the main screen of your WebHost Manager interface.
2. Then click on Security Center.
3. Then click on cPHulk Brute Force Protection.
4. Click on the Enable button to enable cPHulk Brute Force Protection or click on the Disable button to disable cPHulk Brute Force Protection.
5. Next to IP Based Brute Force Protection Period in minutes, enter the number of minutes IP Based Brute Force Protection should last.
6. Next to Brute Force Protection Period in minutes, enter the number of minutes Brute Force Protection should last.
7. Next to Maximum Failures By Account, enter the number of times an account is permitted to fail.
8. Next to Maximum Failures Per IP, enter the maximum failures allowed per IP.
9. Next to Maximum Failures Per IP before IP is blocked for two week period, enter the maximum amount of failures before the IP is blocked for two weeks.
10. Place a check-mark in the check box next to Extend account lockout time upon additional authentication failures if you wish to enable this option.
11. Place a check-mark in the check box next to Send notification when brute force user is detected if you wish to enable this option.

Server Security Guides

How to know who is doing spamming from nobody?

October 7th, 2009

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.

Article provided by WebHostGear.com

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 (<STDIN> ) {
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 8)
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 =)

Server Security Guides

Disabling Dangerous PHP Functions..

October 7th, 2009

Have you ever wondered which PHP functions are termed to be highly
dangerous in web hosting & should promptly be left disabled in the
configuration ?

PHP is a powerful language which; when used in an improper way, either
unknowingly; carries the potential to mess up with a web hosting server &
hack/exploit user accounts further upto root level. Hackers using an
insecure PHP script as an entry point to a web hosting server can start
unleashing dangerous commands and take control over the complete server
quickly.. Certain functions which are used in such scripts are termed to
be dangerous & are turned off in the PHP configuration. Let’s find out
which functions are dangerous & how they are turned off..

Here’s a complete list of such functions which are needed to be stopped
from being executed within any website on your web hosting server:
Quote:

“apache_child_terminate, apache_setenv, define_syslog_variables,
escapeshellarg, escapeshellcmd, eval, exec, fp, fput, ftp_connect,
ftp_exec, ftp_get, ftp_login, ftp_nb_fput, ftp_put, ftp_raw, ftp_rawlist,
highlight_file, ini_alter, ini_get_all, ini_restore, inject_code,
mysql_pconnect, openlog, passthru, php_uname, phpAds_remoteInfo,
phpAds_XmlRpc, phpAds_xmlrpcDecode, phpAds_xmlrpcEncode, popen,
posix_getpwuid, posix_kill, posix_mkfifo, posix_setpgid, posix_setsid,
posix_setuid, posix_setuid, posix_uname, proc_close, proc_get_status,
proc_nice, proc_open, proc_terminate, shell_exec, syslog, system,
xmlrpc_entity_decode”

Quote:

vi  /usr/local/lib/php.ini

disable_functions = “apache_child_terminate, apache_setenv,
define_syslog_variables, escapeshellarg, escapeshellcmd, eval, exec, fp,
fput, ftp_connect, ftp_exec, ftp_get, ftp_login, ftp_nb_fput, ftp_put,
ftp_raw, ftp_rawlist, highlight_file, ini_alter, ini_get_all, ini_restore,
inject_code, mysql_pconnect, openlog, passthru, php_uname,
phpAds_remoteInfo, phpAds_XmlRpc, phpAds_xmlrpcDecode,
phpAds_xmlrpcEncode, popen, posix_getpwuid, posix_kill, posix_mkfifo,
posix_setpgid, posix_setsid, posix_setuid, posix_setuid, posix_uname,
proc_close, proc_get_status, proc_nice, proc_open, proc_terminate,
shell_exec, syslog, system, xmlrpc_entity_decode, dl, myshellexec”

!wq

service httpd restart

That’s it

Server Security Guides

Securing /tmp

October 7th, 2009

Every system needs temporary folders that any user is able to read and write BUT these directories should not be able to execute programs or scripts. Though this will only protect you from somebody running the script directly it will help with a large portion of the automated rootkits and trojans that script kiddies use. They will still be able to put the files on the system but they will be unable to execute them and create the back door. One of the biggest problems is php injection via apache in which people will have apache download and then run an exploit. Securing the temp directories is probably the single biggest thing you can do towards securing your server.

This guide will work fine with cPanel, ensim, plesk, and of course with no control panel. It is designed for Redhat but should work on any linux varient.

The first step is to check if /tmp is already secure. Some datacenters do not create a /tmp partition while others do.
—–command—–
df -h |grep tmp
—–command—–

If that displays nothing then go below to create a tmp partition. If you do have a tmp partition you need to see if it mounted with noexec.
—–command—–
cat /etc/fstab |grep tmp
—–command—–

If there is a line that includes /tmp and noexec then it is already mounted as non-executable. If not follow the instructions below to create one without having to physically format your disk. Idealy you would make a real partition when the disk was originally formated, that being said I have not had any trouble create a /tmp partition using the following method.

Create a ~800Mb partition
—–command—–
cd /dev/; dd if=/dev/zero of=tmpMnt bs=1024 count=800000
—–command—–

Format the partion
—–command—–
mkfs.ext2 /dev/tmpMnt
—–command—–
When it asks about not being a block special device press Y

Make a backup of the old data
—–command—–
cp -Rp /tmp /tmp_backup
—–command—–

Mount the temp filesystem
—–command—–
mount -o loop,noexec,nosuid,rw /dev/tmpMnt /tmp
—–command—–

Set the permissions
—–command—–
chmod 0777 /tmp
—–command—–

Copy the old files back
—–command—–
cp -Rp /tmp_backup/* /tmp/
—–command—–

Once you do that go ahead and restart mysql and make sure it works ok. We do this because mysql places the mysql.sock in /tmp which neeeds to be moved. If not it migth have trouble starting. If it does you can add this line to the bottom of the /etc/fstab to automatically have it mounted:

Open the file in pico:
—–command—–
pico -w /etc/fstab
—–command—–
Now add this single line at the bottom:

/dev/tmpMnt /tmp ext2 loop,noexec,nosuid,rw 0 0

While we are at it we are going to secure /dev/shm. Look for the mount line for /dev/shm and change it to the following:
none /dev/shm tmpfs noexec,nosuid 0 0

Umount and remount /dev/shm for the changes to take effect.
—–command—–
umount /dev/shm
mount /dev/shm
—–command—–

Next delete the old /var/tmp and create a link to /tmp
—–command—–
rm -rf /var/tmp/
ln -s /tmp/ /var/
—–command—–

If everything still works fine you can go ahead and delete the /tmp_backup directory.
—–command—–
rm -rf /tmp_backup
—–command—–

You /tmp, /var/tmp, and /dev/shm are now mounted in a way that no program can be directly run from these directories. Like I have said in other articles there are still ways in but this is one of the many layers of security you should have on your system.

OR

But we have a option in cpanel run the below command in your server that’s it everything will be done automatically

/scripts/securetmp

Server Security Guides

syctl hardening

October 7th, 2009

The purpose of syctl hardening is to help prevent spoofing and dos attacks. This short guide will show what I have found to be a good configuration for the sysctl.conf configuration file. The most important of the variables listed below is the enabling of syn cookie protection. Only place the bottom two if you do not want your server to respond to ICMP echo, commonly referred to as ICMP ping or just ping requests.

NOTICE: Make sure that eth0 is your primary interface, if it is not replace eth0 with eth1 in the code below.

—–command—–
pico -w /etc/sysctl.conf
—–command—–

Now paste the following into the file, you can overwrite the current information.

#Kernel sysctl configuration file for Red Hat Linux
#
# For binary values, 0 is disabled, 1 is enabled. See sysctl(8) and
# sysctl.conf(5) for more details.

# Disables packet forwarding
net.ipv4.ip_forward=0

# Disables IP source routing
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.lo.accept_source_route = 0
net.ipv4.conf.eth0.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0

# Enable IP spoofing protection, turn on source route verification
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.lo.rp_filter = 1
net.ipv4.conf.eth0.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1

# Disable ICMP Redirect Acceptance
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.lo.accept_redirects = 0
net.ipv4.conf.eth0.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0

# Enable Log Spoofed Packets, Source Routed Packets, Redirect Packets
net.ipv4.conf.all.log_martians = 0
net.ipv4.conf.lo.log_martians = 0
net.ipv4.conf.eth0.log_martians = 0

# Disables IP source routing
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.lo.accept_source_route = 0
net.ipv4.conf.eth0.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0

# Enable IP spoofing protection, turn on source route verification
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.lo.rp_filter = 1
net.ipv4.conf.eth0.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1

# Disable ICMP Redirect Acceptance
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.lo.accept_redirects = 0
net.ipv4.conf.eth0.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0

# Disables the magic-sysrq key
kernel.sysrq = 0

# Decrease the time default value for tcp_fin_timeout connection
net.ipv4.tcp_fin_timeout = 15

# Decrease the time default value for tcp_keepalive_time connection
net.ipv4.tcp_keepalive_time = 1800

# Turn off the tcp_window_scaling
net.ipv4.tcp_window_scaling = 0

# Turn off the tcp_sack
net.ipv4.tcp_sack = 0

# Turn off the tcp_timestamps
net.ipv4.tcp_timestamps = 0

# Enable TCP SYN Cookie Protection
net.ipv4.tcp_syncookies = 1

# Enable ignoring broadcasts request
net.ipv4.icmp_echo_ignore_broadcasts = 1

# Enable bad error message Protection
net.ipv4.icmp_ignore_bogus_error_responses = 1

# Log Spoofed Packets, Source Routed Packets, Redirect Packets
net.ipv4.conf.all.log_martians = 1

# Increases the size of the socket queue (effectively, q0).
net.ipv4.tcp_max_syn_backlog = 1024

# Increase the tcp-time-wait buckets pool size
net.ipv4.tcp_max_tw_buckets = 1440000

# Allowed local port range
net.ipv4.ip_local_port_range = 16384 65536

———————————————————-

After you make the changes to the file you need to run /sbin/sysctl -p and sysctl -w net.ipv4.route.flush=1 to enable the changes without a reboot.

Server Security Guides

E-mail Alert on Root SSH Login ?

October 7th, 2009

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.

Server Security Guides