Archive for the ‘Tuning Linux’ Category

h1

Automated Process monitoring during high server load

August 26, 2010

root@myServer [/root]# cat load-process-monitor.sh
#!/bin/bash

# Define Variables
DT=`date +”%A %b %e %r”`
HOSTNAME=`hostname`

# Create dir to store data
mkdir -p /opt/loadcheck/

# Retrieve the load average of the past 1 minute
LAVG=`uptime | awk {‘print $10}’ | cut -d. -f1`
LCURRENT=`uptime | awk {‘print $10,$11,$12}’`

# Define Threshold. This value will be compared with the current load average. Set the value as per your wish.
LIMIT=-1

# Compare the current load average with Threshold and email the server administrator if threshold is greater.

if [ $LAVG -gt $LIMIT ]
then

#Save the current running processes in a file
/bin/ps -auxf >> /opt/ps_output

echo “Current Time :: $DT. >> /tmp/loadmon.txt
echo “Current Load Average :: $LCURRENT. >> /tmp/loadmon.txt
echo “current processes list attached with the email 1 instance. >> /tmp/loadmon.txt
echo “Also check loadps.txt :: loadtop.txt :: netstat_all.txt :: netstat_port80.txt inside /opt/loadcheck/ on the server” >> /tmp/loadmon.txt
# Send email to support
/usr/bin/mutt -s “Server Load ALERT!!! High 1 minute load average on ‘$HOSTNAME’” -a /opt/ps_output support@somedomain.com > /opt/ps_output

echo “Current Time :: $DT” >> /tmp/loadmon.txt
echo “Current Load Average :: $LCURRENT” >> /tmp/loadmon.txt
echo “current processes list attached with the email 1 instance” >> /tmp/loadmon.txt
echo “Also check loadps.txt :: loadtop.txt :: netstat_all.txt :: netstat_port80.txt inside /opt/loadcheck/ on the server” >> /tmp/loadmon.txt
# Send email to support
/usr/bin/mutt -s ” Server Load ALERT ::: High 1 minute load average on ‘$HOSTNAME’ ” -a /opt/ps_output support@integrityhost.com > /opt/loadcheck/loadps.txt
echo “#########################################################################################################################” >> /opt/loadcheck/loadps.txt
/bin/top -c -n1 >> /opt/loadcheck/loadtop.txt
echo “#########################################################################################################################” >> /opt/loadcheck/loadtop.txt
/bin/netstat -ntu | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n >> /opt/loadcheck/netstat_all.txt
echo “#########################################################################################################################” >> /opt/loadcheck/netstat_all.txt
/bin/netstat -alntp | grep :80 | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n >> /opt/loadcheck/netstat_port80.txt
echo “#########################################################################################################################” >> /opt/loadcheck/netstat_port80.txt

/bin/ps -auxf >> /opt/loadcheck/loadps.txt
echo “#########################################################################################################################” >> /opt/loadcheck/loadps.txt
/bin/top -c -n1 >> /opt/loadcheck/loadtop.txt
echo “#########################################################################################################################” >> /opt/loadcheck/loadtop.txt
/bin/netstat -ntu | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n >> /opt/loadcheck/netstat_all.txt
echo “#########################################################################################################################” >> /opt/loadcheck/netstat_all.txt
/bin/netstat -alntp | grep :80 | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n >> /opt/loadcheck/netstat_port80.txt
echo “#########################################################################################################################” >> /opt/loadcheck/netstat_port80.txt

/bin/ps -auxf >> /opt/loadcheck/loadps.txt
echo “#########################################################################################################################” >> /opt/loadcheck/loadps.txt
/bin/top -c -n1 >> /opt/loadcheck/loadtop.txt
echo “#########################################################################################################################” >> /opt/loadcheck/loadtop.txt
/bin/netstat -ntu | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n >> /opt/loadcheck/netstat_all.txt
echo “#########################################################################################################################” >> /opt/loadcheck/netstat_all.txt
/bin/netstat -alntp | grep :80 | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n >> /opt/loadcheck/netstat_port80.txt
echo “#########################################################################################################################” >> /opt/loadcheck/netstat_port80.txt

/bin/ps -auxf >> /opt/loadcheck/loadps.txt
echo “#########################################################################################################################” >> /opt/loadcheck/loadps.txt
/bin/top -c -n1 >> /opt/loadcheck/loadtop.txt
echo “#########################################################################################################################” >> /opt/loadcheck/loadtop.txt
/bin/netstat -ntu | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n >> /opt/loadcheck/netstat_all.txt
echo “#########################################################################################################################” >> /opt/loadcheck/netstat_all.txt
/bin/netstat -alntp | grep :80 | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n >> /opt/loadcheck/netstat_port80.txt
echo “#########################################################################################################################” >> /opt/loadcheck/netstat_port80.txt

/bin/ps -auxf >> /opt/loadcheck/loadps.txt
echo “#########################################################################################################################” >> /opt/loadcheck/loadps.txt
/bin/top -c -n1 >> /opt/loadcheck/loadtop.txt
echo “#########################################################################################################################” >> /opt/loadcheck/loadtop.txt
/bin/netstat -ntu | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n >> /opt/loadcheck/netstat_all.txt
echo “#########################################################################################################################” >> /opt/loadcheck/netstat_all.txt
/bin/netstat -alntp | grep :80 | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n >> /opt/loadcheck/netstat_port80.txt
echo ” ######################################################################################################################### ” >> /opt/loadcheck/netstat_port80.txt

fi

# Remove residue logs
/bin/rm -f /tmp/loadmon.txt
/bin/rm -f /opt/ps_output

root@myServer [/root]#

Add a cron to run load-process-monitor.sh ( * * * * * /bin/sh /path-to/load-process-monitor.sh ) every min and when server load goes beyond 4, it will send you email and log some important details, which can help to some extent to find some pointers to load issue from process and netstat listings.

h1

Virtuozzo Upgrade : Upgrading from Virtuozzo3 to Virtuozzo4

August 18, 2008

Upgrading from Virtuozzo 3 to Virtuozzo 4
================================

First of all refer to :  http://www.parallels.com/en/products/virtuozzo/easy-upgrade/ for detailed explanation. When I decided to upgrade, there was not much available except the above docs. I used the inbuilt vzup2date for the upgrade purpose.

First of all apply all updates on your current Virtuozzo 3 using vzup2date , by selecting udate for virtuozzo 3.0.x only. Once updates are applied, it also does a kernel upgrade. It will finally ask if you want to reboot. Just select finish, and dont reboot. It is better to reboot manually, so that you can swith back to old kernel, in case the new kernel panics or hang up during boot.

Step 1
===================================================

[root@vpsMainNode virtuozzo]# vzup2date

Apply all updates on your current Virtuozzo 3.
Select option reboot manually and dont hit the reboot option, just select finish.

Next,

Edit /etc/grub.conf  and change the option

default=0 to default=1 , so that the current kernel is selected in grub , instead of the new kernel , that was just installed.

Next we configure grub to boot the new kernel only for the next reboot. If the reboot does not go well and the system does not boot properly, do a hard reset ( ask your DC, if

reqd. ) and you will successfully boot into the last working kernel.

[root@vpsMainNode virtuozzo]# grub shell
Probing devices to guess BIOS drives. This may take a long time.

GNU GRUB  version 0.95  (640K lower / 3072K upper memory)

[ Minimal BASH-like line editing is supported.  For the first word, TAB
lists possible command completions.  Anywhere else TAB lists the possible
completions of a device/filename.]

grub> savedefault –default=0 –once
grub> quit

[root@vpsMainNode virtuozzo]#

Reboot the server. If all goes fine, and the server comes up with the new kernel, edit /etc/grub.conf  and change the option

default=1 to default=0

Next,

Run vzup2date again and select updates for Virtuozzo 3 , and go next , next to finish install ( select option manual reboot )
[root@vpsMainNode virtuozzo]# vzup2date

If all Virtuozzo 3 are already applied, you will see no more update available message.

Now that Virtuozzo 3 has all its latest stuff in its version, we will update Virtuozzo 3 to Virtuozzo 4.

Run vzup2date again,
[root@vpsMainNode virtuozzo]# vzup2date

This time, select Virtuozzo 4 for upgrades, do the usual next , next to apply updates. ( select option manual reboot )

This process will take some time depending on speed. Usually 20 to 60 minutes.

Again this will install a newer kernel, so

Next we configure grub to boot the new kernel only for the next reboot. If the reboot does not go well and the system does not boot properly, do a hard reset ( ask your DC, if

reqd. ) and you will successfully boot into the last working kernel.

[root@vpsMainNode virtuozzo]# grub shell
Probing devices to guess BIOS drives. This may take a long time.

GNU GRUB  version 0.95  (640K lower / 3072K upper memory)

[ Minimal BASH-like line editing is supported.  For the first word, TAB
lists possible command completions.  Anywhere else TAB lists the possible
completions of a device/filename.]

grub> savedefault –default=0 –once
grub> quit

[root@vpsMainNode virtuozzo]#

Reboot the server. If all goes fine, and the server comes up with the new kernel, edit /etc/grub.conf  and change the option

default=1 to default=0

Voila !   you have upgraded your server from Virtuozzo 3 to Virtuozzo 4. You will see that all nodes will work properly, start the nodes, if any active node is down in the usual

way.

[root@vpsMainNode virtuozzo]# vzctl start VE_ID

Note VE_ID is now also called as CT_ID ( container ID )

You will find that the Service VE ( now called as Service Container )  will fail to start. If not, then fine. You have nothing left to do , except running a vzup2date again and

apply any newer updates for one more time. If any new kernel is installed , then modify grub.conf as already discussed, while rebooting.

In case Service VE ( now called as Service Container )  fails to start or does not start, you will be unable to access your virtuozzo control panel.

Note , I destroyed old Service VE and recreated it, if for any reason, you want backup of old service , you might chose to make a backup of it.

Here is what I did to install the service CT
###############################################
[root@vpsMainNode virtuozzo]# vzctl destroy 1
[root@vpsMainNode virtuozzo]# cd /root/
[root@vpsMainNode virtuozzo]# wget http://download.parallels.com/virtuozzo/virtuozzo4.0/linux/iso/lin-i386.iso
[root@vpsMainNode virtuozzo]# mkdir /mnt/iso
[root@vpsMainNode virtuozzo]# mount -o loop lin-i386.iso /mnt/iso
[root@vpsMainNode virtuozzo]# vzsveinstall -D /mnt/iso -s xx.yy.zz.IP

[root@vpsMainNode virtuozzo]# vzlist -a | grep CT
CTID      NPROC STATUS    IP_ADDR         HOSTNAME
1         77 running   xx.yy.zz.IP  ServiceCT
[root@vpsMainNode virtuozzo]#

[root@vpsMainNode virtuozzo]# lsof  -i :4643
COMMAND   PID   USER   FD   TYPE   DEVICE SIZE NODE NAME
vzaproxy  531   root    4u  IPv4 10286471       TCP *:4643 (LISTEN)
vzcp      591   root    4u  IPv4 10286403       TCP *:4643 (LISTEN)
vzcp      595 apache    4u  IPv4 10286403       TCP *:4643 (LISTEN)
vzcp      596 apache    4u  IPv4 10286403       TCP *:4643 (LISTEN)
vzcp     3004 apache    4u  IPv4 10286403       TCP *:4643 (LISTEN)
[root@vpsMainNode virtuozzo]#

[root@vpsMainNode virtuozzo]# vzctl  restart 1
Restart Container
Stopping Container …
Container was stopped
[  OK  ] down vzagent: [  OK  ]
[  OK  ] vzagent: [  OK  ]
Container is unmounted
Starting Container …
Starting vzagent: [  OK  ]
Starting vzagent: [  OK  ]
Container is mounted
Setting devperms 20006 dev 0x7d00
Adding IP address(es): xx.yy.zz.IP
Hostname for Container set: ServiceCT
File resolv.conf was modified
Container start in progress…

[root@vpsMainNode virtuozzo]# vzlist  -a | grep CT
CTID      NPROC STATUS    IP_ADDR         HOSTNAME
1         77 running   xx.yy.zz.IP  ServiceCT
[root@vpsMainNode virtuozzo]#

[root@vpsMainNode log]# cd /root/
[root@vpsMainNode ~]# df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/sda2             9.9G  4.1G  5.3G  44% /
/dev/sda1             494M   81M  388M  18% /boot
none                  4.0G     0  4.0G   0% /dev/shm
/dev/sda3             448G  267G  158G  63% /vz
/dev/sdb1             459G  123G  313G  29% /backup
/root/lin-i386.iso    582M  582M     0 100% /mnt/iso

[root@vpsMainNode ~]# mkdir /root/virt4_source
[root@vpsMainNode ~]# cp -r /mnt/iso/* /root/virt4_source/
[root@vpsMainNode ~]# umount /mnt/iso

[root@vpsMainNode ~]# df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/sda2             9.9G  4.7G  4.8G  50% /
/dev/sda1             494M   81M  388M  18% /boot
none                  4.0G     0  4.0G   0% /dev/shm
/dev/sda3             448G  267G  158G  63% /vz
/dev/sdb1             459G  123G  313G  29% /backup
[root@vpsMainNode ~]#

Congrats !!! , now that you have got the Service Container Up and Running, time to explore/enjoy the new looks in Virtuozzo 4 control panel.

h1

iptables string match to drop malicious urls

August 5, 2008

iptables string match to drop malicious urls

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

Usually modsecurity rules can help filter many malicious url attack patterns combined with apache on apache port (http|https).  But what if a malicious attack using a vulnerable url pattern, that exposes or tries to break into your system is coming onto another port?

This is where iptables string match comes in handy.

/usr/local/sbin/iptables -I INPUT -p tcp -s 0.0.0.0/0 -m stringstring “download?file=%2e%2e” –algo bm -j DROP

[root@server ~]# iptables -L -v | grep STR
73 49908 DROP       tcp  –  any    any     anywhere             anywhere            STRING match “download?file=%2e%2e” ALGO name bm TO 65535

[root@server ~]#

The above iptable rule will block any url  that has the string “download?file=%2e%2e” on any port on your server.

Note: your iptables binary path may be /sbin/iptables

Say http://yourserverIP:9132/blah/download?file=%2e%2e

h1

tune2fs practical

July 1, 2008

How do I make the system perform a filesystem check after a certain number of mounts?

If the system is fairly reliable, it is safe to increase the maximum mount count. However, you should strongly consider the implications. Bad disk drives, cables, memory and kernel bugs can all corrupt a filesystem without marking the filesystem dirty or have it error out. A filesystem error detected by the kernel will force an fsck on the next reboot, but by that time, it may already be too late to prevent data loss.

With these in mind, here are the instructions to performing filesystem checks after a certain number of mounts. To adjust the maximum mount count, the filesystem should be unmounted before using tune2fs .

The example below will check the filesystem or partition after 50 mounts or 2 months, whichever comes first. You need to type in this command in a root shell:

tune2fs -c 50 -i 2m /dev/hda1

root@server61 [/etc/pam.d]# tune2fs -c 300 -i 11m /dev/sda8
tune2fs 1.35 (28-Feb-2004)
Setting maximal mount count to 300
Setting interval between check 28512000 seconds

root@server61 [/etc/pam.d]# tune2fs -c 300 -i 11m /dev/sda2
tune2fs 1.35 (28-Feb-2004)
Setting maximal mount count to 300
Setting interval between check 28512000 seconds

root@server61 [/etc/pam.d]# fdisk  -l

Disk /dev/sda: 250.8 GB, 250808893440 bytes
255 heads, 63 sectors/track, 30492 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           1          65      522081   83  Linux
/dev/sda2              66        2023    15727635   83  Linux
/dev/sda3            2024        3720    13631152+  83  Linux
/dev/sda4            3721       30492   215046090    5  Extended
/dev/sda5            3721        4112     3148708+  83  Linux
/dev/sda6            4113        4373     2096451   83  Linux
/dev/sda7            4374        4634     2096451   82  Linux swap
/dev/sda8            4635       30492   207704353+  83  Linux

Disk /dev/sdb: 250.8 GB, 250808893440 bytes
255 heads, 63 sectors/track, 30492 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot      Start         End      Blocks   Id  System
/dev/sdb1   *           1       30492   244926958+  83  Linux
root@server61 [/etc/pam.d]# mkdir /backup
root@server61 [/etc/pam.d]# mount /dev/sdb1 /backup

tune2fs disable disk check
##############################

one of my disk using etx3,and as usual e2fsck will check the disk every 20 mounts or 180 days or whichever come first. This is annoying especially if you have very big volume in your system. We can disable this feature by using this command.
tune2fs -i 0 /dev/hdxx

root@server61 [/etc/pam.d]# tune2fs -i 0 /dev/sdb1
tune2fs 1.35 (28-Feb-2004)
Setting interval between check 0 seconds
root@server61 [/etc/pam.d]#

h1

Prevent non-root users from logging

May 9, 2007

Prevent non-root users from logging

Imagine that for some reason (i.e. maintenance tasks) you want to prevent non-root users from logging into the system. The next tip is a very simple way to achieve this goal.

If a file called /etc/nologin exists login will disable the begin of a session in this system. If you put some text into the file, users will be shown this text and their login attempts will be refused.

vi /etc/nologin

Server under maintenance. No access allowed at this moment.

h1

Tips and tricks

August 11, 2006

———————————————————————–

Q:- Find out top 10 directories eating up your disk space:
A:- du -csh * –max-depth=0 | sort -rn | head -10
———————————————————————–

Q:- Find Harddisk Capacity on the box.
A:- fdisk -l | grep -iE ‘mb|gb|tb’
———————————————————————–

Q:- Find out performance of your hard disk with following command:
A:- hdparm -t -T /dev/hda
———————————————————————–

Q:- You can block all login access with following command:
A:- touch /etc/nologin
———————————————————————–

Q:- It is good idea to encrypt backup made with tar command:
A:- tar -zcvf – *| openssl des3 -salt -k PASSWORD | dd of=mybackup.tbz
tar zcvf – /home |openssl des3 -salt -k PASSWORD | dd of=/dev/st0
To extract encrypted tar file use command:
dd if= mybackup.tbz |openssl des3 -d -k PASSWORD| tar zvxf -
dd if=/dev/st0|openssl des3 -d -k PASSWORD | tar xzf ————————————————————————

Q:- Delete a file securely, first overwriting it to hide its contents.
A:- $ shred -n 200 -z -u personalinfo.tar.gz
A:- srm filename
A:- wipe filename
—————————————
Q:- Delete file by inode:
A:- $ find . -inum 782263 -exec rm -i {} \;
————————————————————————

Q:- Forcefully unmount CD/DVD Rom or any other mounted partitions with
fuser command:
Ans:- fuser -km /dev/cdrom
fuser -km /mnt/cdrom\n
fuser -km /data2
————————————————————————

Q: List open files under user nobody

A:- lsof -u nobody
————————————————————————-

h1

What is /dev/shm and its practical usage ?

July 25, 2006

What is /dev/shm and its practical usage ?

/dev/shm is nothing but implementation of traditional shared memory concept. It is an efficient means of passing data between programs. One program will create a memory portion, which other processes (if permitted) can access. This will result into speeding up things on Linux.

If you type mount command you will see /dev/shm as a tempfs file system. Therefore, it is a file system, which keeps all files in virtual memory. Everything in tmpfs is temporary in the sense that no files will be created on your hard drive. If you unmount a tmpfs instance, everything stored therein is lost. By default almost all distro configured to use /dev/shm.

Nevertheless, where can I use /dev/shm?
You can use /dev/shm to improve the performance of application software or overall Linux system performance. On heavily loaded system, it can make tons of difference. For example VMware workstation/server can be optimized to improve your Linux host’s performance (i.e. improve the performance of your virtual machines).

For example, if you have 8GB RAM then remount /dev/shm as follows:

# mount -o remount,size=8G /dev/shm

To be frank if you have more than 2GB RAM and if you running multiple Virtual machines this hack always improves performance.

h1

How do I Drop or block attackers IP with null routes?

July 4, 2006

Someone might attack on your system. You can drop attacker IP using IPtables. However one of our sr. sys admin highlighted something new for me. You can nullroute (like some time ISP do prevent your network device from sending any data to a remote system.) stopping various attacks coming from a single IP (read as spammers or hackers):

Suppose that bad IP is 65.21.34.4, type following command at shell:

# route add 65.21.34.4 127.0.0.1

You can verify it with following command:

# netstat -nr

This is cool, as you do not have to play with iptables rules.

h1

All .htaccess tips and tricks

July 2, 2006

.htaccess, a primer…

Submitted by sandip on Thu, 09/04/2003 – 10:48. Scripting

The Apache web server has a number of configuration options that are available to the server administrator. In a shared hosting environment, you don’t have access to the main Apache configuration so you’re stuck with the default configuration. However, it is possible to override some of the default settings by creating (or editing) a file named “.htaccess”.

The .htaccess is a simple ASCII text file placed in your www directory or in a subdirectory of your www directory. You can create or edit this file in any text editor (such as NotePad) and then upload it to the directory for which you want to modify the settings. Be sure that the file is uploaded in ASCII (not BINARY) format, and be sure that the file permissions for the file are set to 644 (rw-r–r–). This allows the server to access the file, but prevents visitors from accessing the file through their web browser (a security risk.)

Commands in the .htaccess file affect the directory that it’s placed in and all subdirectories. If you place the .htaccess file in your www directory, it will affect your entire web site. If you place it in a subdirectory of your www directory, it will affect only that directory plus and subdirectories of that directory.

Most .htaccess commands are designed to be placed on one line. If your text editor wraps lines automatically, you should disable that function before saving and uploading your file. Also, note that .htaccess commands are case-sensitive.

 

The information presented here may work and it may not, or it may work today and not tomorrow. Use it at your own risk.

Some of the things you can do with .htaccess include:

Customize Error Messages

If you want to override the server’s error pages, you can use .htaccess to define your own messages. An example of the syntax is:

ErrorDocument 500 /error.html

Override SSI Settings

By default, only pages ending in the .shtml extension will parse server-side includes (SSI). You can override this restriction in your .htaccess file:

If you want to override the default server configuration so that SSI will work with .html documents, you can create a file named .htaccess and upload it (in ASCII mode) to your main www directory. Add the following lines to your .htaccess file:

AddType text/html .html



AddHandler server-parsed .html

If you want both .html and .htm documents to parse SSI, create your .htaccess file with these lines:

AddType text/html .html



AddHandler server-parsed .html



AddHandler server-parsed .htm

Change Your Default Home Page

In order to browse your site by specifying the domain name only (e.g., http://www.yourdomain.com) instead of having to specify an exact page filename (e.g., http://www.yourdomain.com/filename.html), you must have an index page in your www directory. Default acceptable file names for index pages include index.htm, index.html, index.cgi, index.shtml, index.php, etc. Note that they’re all named index.*.

There is also a default order of precedence for these names. So if you have both a file named index.cgi and a file named index.html in your directory, the server will display index.cgi because that name takes a higher precedence than index.html.

Using .htaccess, you can define additional index filenames and/or change the order of precedence. To define your index page as custom.html add the following line to your .htaccess file:

DirectoryIndex custom.html

This will cause the server to look for a file named custom.html. If it finds that file, it will display it. If it does not find that file, it will return a 404 Missing Page error.

To change the order of precedence, enter a DirectoryIndex command with multiple file names on the same line. The order in which the file names are listed (from left to right) determines the order of precedence. For example,

DirectoryIndex custom.html index.cgi index.php index.html

Enable Directory Browsing

This is the option that allows the contents of a directory to be displayed in the browser when the directory does not contain an index page.

For example, if you make an http call to a directory such as http://yourdomain.com/images/, it would list all the images in that directory without the need for an html page with links.

If you require this option on specific directories it is still available. You can reactivate it by adding the following line to your .htaccess file:

Options +Indexes

Once this is added, the directory will fully index again. (Note: Coversely “Options -Indexes” will prevent directory browsing.)

Preventing Directory Listing

Do you have a directory full of images or zips that you do not want people to be able to browse through? Typically a server is setup to prevent directory listing, but sometimes they are not. If not, become self-sufficient and fix it yourself:

IndexIgnore *

The * is a wildcard that matches all files, so if you stick that line into an htaccess file in your images directory, nothing in that directory will be allowed to be listed.

On the other hand, what if you did want the directory contents to be listed, but only if they were HTML pages and not images? Simple says I:

IndexIgnore *.gif *.jpg

This would return a list of all files not ending in .jpg or .gif, but would still list .txt, .html, etc.

Block Users from Accessing Your Web Site

If you want to deny access to a particular individual, and you know the IP address or domain name that the individual uses to connect to the Internet, you can use .htaccess to block that individual from your web site.

<Limit GET>



order deny,allow



deny from 123.456.789.000



deny from 456.78.90.



deny from .aol.com



allow from all



</Limit>

In the example above, a user from the exact IP number 123.456.789.000 would be blocked; all users within a range of IP numbers from 456.78.90.000 to 456.78.90.999 would be blocked; and all users connecting from America Online (aol.com) would be blocked. When they attempted to browse your web site, they would be presented with the 403 Forbidden (“You do not have permission to access this site”) error.

Redirect Visitors to a New Page or Directory

Let’s say you re-do your entire web site, renaming pages and directories. Visitors to the old pages will receive the 404 File Not Found error. You can solve this problem by redirecting calls to an old page to the new page. For example, if your old page was named oldpage.html and that page has been replaced by newpage.html, add this line to your .htaccess file:

Redirect permanent /oldpage.html http://www.mydomain.com/newpage.html

Of course, you want to replace mydomain.com with your actual domain name. Now, when the visitor types in http://www.mydomain.com/myoldpage.html, they will be automatically redirected to http://www.mydomain.com/mynewpage.html.

If you’ve renamed a directory, you can use one redirect line to affect all pages within the directory:

Redirect permanent /olddirectory http://www.mydomain.com/newdirectory/

Note that the old page or directory is specified using the system path relative to your www directory, while the new page or directory is specified by the absolute URL.

Prevent Hot Linking and Bandwidth Leeching

What if another web site owner is stealing your images and your bandwidth by linking directly to your image files from his/her web site? You can prevent this by adding this to your .htaccess file:

RewriteEngine on



RewriteCond %{HTTP_REFERER} !^$



RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com/.*$ [NC]



RewriteRule \.(gif|jpg)$ - [F]

Replace mydomain.com with your actual domain name. With this code in place, your images will only display when the visitor is browsing http://mydomain.com. Images linked from other domains will appear as broken images.

If you’re feeling particularly nasty, you can even provide an alternative image to display on the hot linked pages — for example, an image that says “Stealing is Bad … visit http://mydomain.com to see the real picture that belongs here.” Use this code to accomplish that:

RewriteEngine on



RewriteCond %{HTTP_REFERER} !^$



RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com/.*$ [NC]



RewriteRule \.(gif|jpg)$ http://www.mydomain.com/dontsteal.gif [R,L]

This time, replace mydomain.com with your domain name, and replace dontsteal.gif with the file name of the image you’ve created to discourage hot linking.

Prevent viewing of .htaccess or other files

To prevent visitors from seeing the contents of your .htaccess file, place the following code in the file:

<Files .htaccess>



order allow,deny



deny from all



</Files>

If you want to prevent visitors from seeing another file, just substitute that file’s name for .htaccess in the Files specification.

Eliminate Code Red and NIMDA Virus Attacks from your Access Log

Placing the below redirects in .htacess eliminates the logging problem without affecting your personalized error redirecting scripts.

redirect /scripts http://www.stoptheviruscold.invalid



redirect /MSADC http://www.stoptheviruscold.invalid



redirect /c http://www.stoptheviruscold.invalid



redirect /d http://www.stoptheviruscold.invalid



redirect /_mem_bin http://stoptheviruscold.invalid



redirect /msadc http://stoptheviruscold.invalid



RedirectMatch (.*)\cmd.exe$ http://stoptheviruscold.invalid$1

 

Access Control to your web files via .htaccess

 

Setting up access control using HTACCESS

There is an advantage to controlling access to certain parts of your domain. If, for instance, you wanted to make general information public, but only wanted to make specific information available to your customers you could use a feature of NCSA-based httpd servers commonly reffered to as HTACCESS.

Using this access control method you can limit access to certain branches of the directory tree. If you want to really understand how this works, nothing is better than reading the manual.

Basic Access Control

You can control access to your webpage two different ways, by host filtering or user authentication. But keep in mind that neither method is fullproof. This should be considered as secure as a courtesy lock on a restroom door; nice, but ultimately ineffective.

The default name of the access control file is .htaccess but that is not written in stone. In the server configuration overview we looked at a file called httpd.conf. This file had the following entry:

AccessFileName .htaccess

This is the default value, but any specified filename can be used. For the purposes of this tutorial I will refer to the .htaccess file by name, but your server may use a different file name.

The method of control is very simple. Place a correctly formated file called .htaccess in a directory and you can restrict access via the web to that directory. Here is a simple example of an .htacess file:

AuthUserFile /dev/null



AuthGroupFile /dev/null



AuthName "This is NOT a restricted directory"



AuthType Basic

<Limit GET>

order allow,deny

allow from all

</Limit>

The first two lines refer to files that contain lists of users and groups. I will cover the specific format of the files and their use later. The AuthName entry is displayed in the message box if the browser needs to request a username / password. AuthType is always Basic because the advanced authorization methods based on Kerberos or MD5 are detailed enough for books themselves.

The important parts for now are contained in the familiar looking
tag. GET is the only widely supported method. PUT was under developement to allow uploading and while POST is partially supported, its use is too complex for this document. Basically, to retrieve ANY document from this directory via the web, the web server will evaluate the .htaccess file and allow or deny access based on the outcome. The above example file is wide open and will allow anyone access. Let’s look at a more restrictive <Limit> rule.

<Limit GET>



order deny,allow



deny from all



allow from linuxweblog.com



</Limit>

This rule will cause everyone to be denied EXCEPT hosts from linuxweblog.com. The server processes the rules in order and the first exception case is returned. Here is another way to look at it.

<Limit GET>



order allow,deny



deny from linuxweblog.com



</Limit>

By changing the order to allow,deny and changing the allow entry to deny we have created a ban list. Everyone EXCEPT linuxweb.com hosts can get documents from the directory.

<Limit GET>



order deny,allow



allow from all



deny from linuxweblog.com 192.168.10.



</Limit>

This rule set is evaluated the same as the one above it, but includes an additional deny rule for the 192.168.10. domain. The drawback to using a DNS name can be illustrated if the web server can not resolve an IP address to a domain name. If you rely completely on DNS names and DNS ever fails, you may find yourself locked out of your own site!

Host access control is the simplest way to control access, but what if you have a different ip address every time you log in and you don’t want to allow everyone from your domain access to the directory tree? I’m glad I asked that.

User Based Access Control

The most effective method of access restriction is the use of a username and password. By using two additional files, people can be granted access either by username or group membership. These two files are conventionally called .htpasswd and .htgroup but they can be any name specified in the .htaccess file. I will refer to the conventional names, but feel free to change them on your site.

The .htpasswd file is a file that contains a list of usernames and encrypted passwords seperated by colons. Here is an example:

Bob:ZUvJgtVp77Vik



Ted:rBW8u1RJUr6eU



Carol:HwrJPys5u7NcM



Alice:UORwkyVbeWc6M

This is a list of a 4 user .htpasswd file. The format is similar to a standard Un*x /etc/passwd file and in fact the encryption method is compatible. So if you want, you can base the .htpasswd off of an actual modified Un*x /etc/passwd file. Here is an example of the .htgroup file:

Admin: Carol



Managers: Ted Carol



Staff: Bob Ted Carol Alice

The names of the groups are not special except as they are used. Using these files as examples, lets look at some new rule sets.

AuthUserFile /usr/local/etc/httpd/private/.htpasswd



AuthGroupFile /usr/local/etc/httpd/private/.htgroup



AuthName "This is a restricted directory"



AuthType Basic

<Limit GET>

order allow,deny

allow from all

require user Alice

require group Managers

satisfy any

</Limit>

In this case we have specified authorization user and group files and given a title to the message box. The rule will deny everyone EXCEPT Alice OR the group Managers. The satifisy element handles whether the rule is evalutated as a logical AND or OR. By default it is a logical AND. That means that without the “satisfy any” line it would assume “satisfy all” and require both user Alice and group Managers to access the directory. Since Alice is not a part of the Managers group NO ONE would have access to the directory. Let’s look at another one.

AuthUserFile /usr/local/etc/httpd/private/.htpasswd



AuthGroupFile /usr/local/etc/httpd/private/.htgroup



AuthName "This is a restricted directory"



AuthType Basic

<Limit GET>

order deny,allow

deny from all

allow from linuxweblog.com

require group Managers

satisfy all

</Limit>

This example combines both user and host validation. You have to supply a username that is in the Managers group AND be connecting from the linuxweblog.com domain.

 

Redirect browser to use SSL

You can redirect browser to use SSL secure port using .htaccess file with Rewrite Rules.

Create a .htaccess file with the below Rewrite rule.

Options +FollowSymLinks



RewriteEngine On



RewriteCond %{SERVER_PORT} !=443



RewriteRule ^ https://secure.yourdomain.com%{REQUEST_URI} [NS,R,L]

 

 

Redirecting Dynamic URL using mod_rewrite

What do you do when you need to move servers or web-files to a different domain or directory, especially if you need to be moving dynamic content. How would you prevent down-time? This is not an end all solution, but Apaches’ module mod_rewrite comes to the rescue of redirecting URLs.

Below are the steps that was taken to move web-files to a different servers.

1. Create a temporary unused sub-domain to point to the new servers IP address.

2. Allow for a day before you migrate your content to let the subdomain resolve.

3. Setup rewrite rule to redirect your current domain to the temporary domain after migrating content.

4. Change the Primary and Secondary NameServers for the domain to point to the new location.

5. Keep the redirection up for a while until the NameServers are fully resolved.

Below is an example of what was used:

# this tells the web server to allow rewriting for this directory



RewriteEngine On                                                                             

# check the hostname to apply the redirection to

RewriteCond %{HTTP_HOST} domain.com [OR]

RewriteCond %{HTTP_HOST} http://www.domain.com

 

# describe the pattern to look for, and how to rewrite it

RewriteRule ^(.*)$ http://temp.domain.com/$1 [R]

All rewrite rules are contained in the .htaccess file. The rewrite rules cover all the files in the directory that contains the .htaccess file.

In general, each RewriteRule line specifies a pattern to look for, and a replacement text. The patterns can be very complicated — the rules have the full power of Unix Regular Expressions (ie. grep), but the example shown above will serve most people.

The “[R]” in the rewrite rule shown above tells the web server to redirect the user’s browser to the new URL. This is useful because the browser will show the new URL, and saving a bookmark will always lead to the new location.

Leaving the [R] off the line will also display the new URL, but a bookmark saved from the resulting page will continue to use the original (non-rewritten) URL. This would be useful if you want to preserve an easy-to-remember URL, but also want the ability to change it in the future.

 

Watermark images with mod_rewrite

Below is how I have watermarked images excluding thumbnails with the text “.thumb.” and “.highlight.” in the name of the image files.

Contents of “.htaccess” :

RewriteEngine on



RewriteCond %{REQUEST_FILENAME} !\.thumb\.|\.highlight\.



RewriteRule ^.*[Jj][Pp][Gg]$|.*[Gg][Ii][Ff]$|.*[Pp][Nn][Gg]$ watermark.php?%{REQUEST_FILENAME}

Contents of “watermark.php” :

<?php

// watermark.gif should have a transparent background.

$watermark = “watermark.gif”;

$image = $QUERY_STRING;

 

if (empty($image)) die();

 

if (!file_exists($image)) {

   header(“404 Not Found”);

   echo “File Not Found.”; die();

}

 

$outputType = getFileType($image);

 

watermark($image, $watermark, $outputType);

 

/**

   Outputs the image $source with $watermark in the lower right corner.

   @param $source the source image

   @param $watermark the watermark to apply

   @param $outputType the type to output as (png, jpg, gif, etc.)

                      defaults to the image type of $source if left blank

*/

function watermark($source, $watermark, $outputType=”") {

   $sourceType = getFileType($source);

   $watermarkType = getFileType($watermark);

 

   if (empty($outputType)) $outputType = $sourceType;

   if ($outputType == “gif”) $outputType = “png”; // Okay to remove

   header(“Content-type:image/$outputType”);

 

   // Derive function names

   $createSource = “ImageCreateFrom”.strtoupper($sourceType);

   $showImage = “Image”.strtoupper($outputType);

   $createWatermark = “ImageCreateFrom”.strtoupper($watermarkType);

 

   // Load original and watermark to memory

   $output = $createSource($source);

   $logo = $createWatermark($watermark);

   ImageAlphaBlending($output, true);

 

   // Find proper coordinates so watermark will be in the lower right corner

   $x = ImageSX($output) – ImageSX($logo);

   $y = ImageSY($output) – ImageSY($logo);

 

   // Display

   ImageCopy($output, $logo, $x, $y, 0, 0, ImageSX($logo), ImageSY($logo));

   $showImage($output);

 

   // Purge

   ImageDestroy($output);

   ImageDestroy($logo);

}

 

function getFileType($string) {

   $type = strtolower(eregi_replace(“^(.*)\.”,”",$string));

   if ($type == “jpg”) $type = “jpeg”;

   return $type;

}

?>

 

 

h1

Server Security with Advanced Policy Firewall and Antidos

July 2, 2006

LinuxAPF is a policy based iptables firewall system designed for ease of use and configuration.  APF is ideal for deployment in many server environments based on Linux.

Below are notes on installing, configuring and running APF.

  1. Download the latest tarball via rfxnetworks.com
  2. Extract and install it:
    # tar -xvzf apf-current.tar.gz
    
    # cd apf*
    
    # ./install.sh
  3. Check the port that you need to protect with `ifconfig`. Usually it is “eth0″ but if it’s something else, change it in the “conf.apf” file or you’ll risk locking yourself from the server.
  4. Edit “/etc/apf/conf.apf” and enable D-Shield block list of top networks exhibiting suspicious activity, and activate Antidos also.
    USE_DS="1"
    
    USE_AD="1"
  5. Open the common inbound and outboud ports.
    IG_TCP_CPORTS="20,21,22,25,53,80,110,143,443"
    
    IG_UDP_CPORTS="53"EGF="1"
    
    EG_TCP_CPORTS="21,22,25,43,53,80,110,443"
    
    EG_UDP_CPORTS="20,21,53"
  6. Edit “/etc/apf/ad/conf.antidos”:
    LP_KLOG="1"USR_ALERT="1"
    
    USR="root"
  7. Add antidos to “/etc/crontab”:
    # Antidos
    
    */2 * * * * root /etc/apf/ad/antidos -a >> /dev/null 2>&1
  8. Star the firewall via `apf –s`.
  9. If you are not locked out of SSH, disable development mode in “conf.apf” file.
    DEVM="0"
  10. Restart with `apf -r` and verify that firewall is up and protecting the server using `iptables -L -n`.

Notes:

  • APF uses init files and is automatically set to startup at boot time. Check with `chkconfig –list apf`.
  • The apf and antidos logs are rotated via the conf files present in “/etc/logrotate.d”.
  • Remember to add your IP address in “/etc/apf/allow_hosts.rules” and “/etc/apf/ad/ignore.hosts” files to avoid being locked out of the server.

Follow

Get every new post delivered to your Inbox.