Archive

Archive for October, 2009

What is PHP Safe Mode ?

October 8th, 2009

PHP SAFE MODE ON/OFF

The PHP safe mode is an attempt to solve the shared-server security problem. It is architecturally incorrect to try to solve this problem at the PHP level, but since the alternatives at the web server and OS levels aren’t very realistic, many people, especially ISP’s, use safe mode for now.

The configuration directives that control safe mode are:

safe_mode = Off
open_basedir =
safe_mode_exec_dir =
safe_mode_allowed_env_vars = PHP_
safe_mode_protected_env_vars = LD_LIBRARY_PATH
disable_functions =

When safe_mode is on, PHP checks to see if the owner of the current script matches the owner of the file to be operated on by a file function. For example: -

rw-rw-r– 1 rasmus rasmus 33 Jul 1 19:20 script.php
-rw-r–r– 1 root root 1116 May 26 18:01 /etc/passwd

Running this script.php

<?php
readfile(’/etc/passwd’);
?>

results in this error when safe mode is enabled:

Warning: SAFE MODE Restriction in effect. The script whose uid is 500 is not allowed to access /etc/passwd owned by uid 0 in /docroot/script.php on line 2

If instead of safe_mode, you set an open_basedir directory then all file operations will be limited to files under the specified directory

For example (Apache httpd.conf example):

<Directory /docroot>
php_admin_value open_basedir /docroot
</Directory>

If you run the same script.php with this open_basedir setting then this is the result:

Warning: open_basedir restriction in effect. File is in wrong directory in /docroot/script.php on line 2

You can also disable individual functions. Note that the disable_functions directive can not be used outside of the php.ini file which means that you cannot disable functions on a per-virtualhost or per-directory basis in your httpd.conf file.
If we add this to our php.ini file:

disable_functions readfile,system

Then we get this output:
Warning: readfile() has been disabled for security reasons in /docroot/script.php on line 2

PHP

How popular PHP is ?

October 8th, 2009

Just click on this link http://www.php.net/usage.php

PHP

What is PHP ?

October 8th, 2009

PHP- A New revolution in Server-side scripting

PHP (recursive acronym for “PHP: Hypertext Preprocessor”) is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML.

Simple answer, but what does that mean? An example:

Example 1-1. An introductory example

<html>
<head>
<title>Example</title>
</head>
<body>

<?php
echo “Hi, I’m a PHP script!”;
?>

</body>
</html>

Notice how this is different from a script written in other languages like Perl or C — instead of writing a program with lots of commands to output HTML, you write an HTML script with some embedded code to do something (in this case, output some text). The PHP code is enclosed in special start and end tags that allow you to jump into and out of “PHP mode”.

What distinguishes PHP from something like client-side JavaScript is that the code is executed on the server. If you were to have a script similar to the above on your server, the client would receive the results of running that script, with no way of determining what the underlying code may be. You can even configure your web server to process all your HTML files with PHP, and then there’s really no way that users can tell what you have up your sleeve.

The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don’t be afraid reading the long list of PHP’s features. You can jump in, in a short time, and start writing simple scripts in a few hours.

Although PHP’s development is focused on server-side scripting, you can do much more with it.

This is just an introduction to PHP. You can get more info from official site php.net

PHP

Return-path nobody@svrname bounced mail in PHP

October 8th, 2009

Return-path nobody bounced mail in PHP - Solution
Here is the implementation notes for those a little more challenged:

Open “WHM”
Under “Service Configuration” , click “Exim Configuration Editor”
Click “Switch to advanced mode”

In the first editable text box below
#!!# cPanel Exim 4 Config:

ADD:

local_from_check = false
untrusted_set_sender = root

In the textbox that follows (REWRITE CONFIGURATION)
begin rewrite:

ADD:

nobody@lsearch;/etc/localdomains “${if !eq {$header_From:}{}{$header_sender:$header_From:}fail}” Fs
cpanel@lsearch;/etc/localdomains “${if !eq {$header_From:}{}{$header_sender:$header_From:}fail}” Fs

Now Click Save, Exim will restart with the updated config

PHP

How to get rid of PHPSESSID in the URL

October 8th, 2009

Generally we will encounter a problem like ?PHPSESSID= would appear in the URLs while users are browsing, like http://example.com/node?PHPSESSID=7dd1d5d1471fa8be2fea8f163cce3257.

This string is a Session ID at the PHP level.

Having the PHPSESSID in the URL is not only ugly, but also a security risk. If you visit a page from a certain web site that has PHPSESSID turned on, a malicious admin on the site you are visiting can gain your privileges on that certain site.

For these two reason, you do not want the PHPSESSID in your URLs.

Using .htaccess

You need to put the following two lines in the .htaccess file, if your PHP as an Apache module:

php_value session.use_only_cookies 1
php_value session.use_trans_sid 0

Using a local php.ini

To make things more complicated, some hosts use PHP as a CGI executable. Many use this as an suExec environment, such as that from suphp.org.

For PHP as CGI, you need to make the changes in a file called php.ini that has a slightly different format. The above parameters would look like this:

session.use_only_cookies = 1
session.use_trans_sid = 0

PHP

PHP files are downloading instead of executing

October 8th, 2009

You need to edit httpd.conf and add following line at mime types so that apache can recognize php scripts..

AddType application/x-httpd-php .php

PHP

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