Archive for July, 2006

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 to install CVS

July 21, 2006

Installation:

Compile it from source

Download from ftp://ftp.cvshome.org/pub/

$ gunzip cvs-x.x.tar.gz $ tar -xvf cvs-x.x.tar $ cd cvs-x.x/  $ ./configure $ ./make $ su -l (enter password)	#switch user to root # ./make install

check to make certain CVS is installed:

$ which cvs /usr/bin/cvs

Create the cvsroot for a user and master repository:

You can choose to place your cvsroot almost wherever you want. I’ve historically placed it in /home/ to make regular backups easier. You might have your own reasons to place it where you want.

$ su -l # adduser cvs # rm -rf /home/cvs # mkdir /home/cvs

It can be convenient to enable user permissions by creating a ‘cvs’ group in /etc/group, and then adding various users to that group. While adding permissions to the cvsroot directories to the group ‘cvs’.

Set a CVSROOT:

You need to set the environment variables, so that CVS knows where to find the root library.

$ export CVSROOT=/home/cvs/		#for bash users > setenv CVSROOT '/home/cvs'		#for csh, or tcsh users # this can also be added to /etc/profile for system-wide access

This can also be set automatically upon login by adding a line to your ~/.bashrc file (or whichever stores your shell environment variables).

Check to make sure that it’s set properly:

$ echo $CVSROOT /home/cvs/

As you may have noticed, the CVSROOT variable is set by the client, and not the server. This enables you to easily use multiple CVSROOTs, based on permissions, partitioning, etc.

Remote access:

The CVS slient can also be configured to use a cvsroot on a remote server, and to tunnel through SSH. The remote client needs to have these entered at the command line, or read in from the .bashrc file:

export CVSROOT="user@host.domain.tld:/pathto/cvsroot" export CVS_RSH="/usr/bin/ssh"

All commands should operate as usual, but each will require a password in order to proceed.

Bad CVSROOT error:

A common, and frustrating error to run into while using this method, because it’s not well documented.

cvs checkout: is set for a remote access method but your cvs checkout: CVS executable doesn't support it cvs [checkout aborted]: Bad CVSROOT.

Your problem most likely exists with the client version of the cvs binary. It’s probably version 1.11.1 or previous, upgrading to 1.11.2 should take care of this.

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

Linux or UNIX disable null passwords

July 4, 2006

Q. How do I disabling logins for user with null passwords?

A. PAM (pluggable authentication modules) is used by both Unixish (Solaris/BSD/AIX/HP-UX) oses and Linux for configuring authentication related services.

A null password allows users to log onto a system without having to supply a valid password. This is a security risk to the system. In case if you are wondering how to setup null password, try command usermod as follows:

# usermod -p “” username

The PAM configuration option that enables null passwords is the nullok module argument passed to pam_unix.so PAM module. You’ll want to remove this argument from any modules of auth type for services that allow login.

Debian Linux

Debian Linux use following two files:

  • /etc/pam/common-auth: authentication settings common to all services
  • /etc/pam.d/common-password: password-related modules common to all services

Caution: before modifying below mentioned PAM config files, make the backup of files using cp command.

a) Open /etc/pam/common-auth:

# cp /etc/pam/common-auth /etc/pam/common-auth.ORI
# vi /etc/pam/common-auth

Find out line that read as follows:

password required pam_unix.so nullok obscure min=4 max=8 md5

Remove nullok from above line so that it read as follows:

password required pam_unix.so obscure min=4 max=8 md5

b) Save the file and exit to shell prompt. Open file /etc/pam.d/common-password:

# cp /etc/pam.d/common-password /etc/pam.d/common-password.ORI
# vi /etc/pam.d/common-password

Find out line that read as follows:

auth required pam_unix.so nullok_secure

Remove nullok_secure from above line so that it read as follows:

auth required pam_unix.so

Save the file and exit to shell prompt. Now no one be able to login using null password.

Red Hat / Fedora Linux

You need to modify single file /etc/pam.d/system-auth:

# cp /etc/pam.d/system-auth /etc/pam.d/system-auth.ORI
# vi /etc/pam.d/system-auth

Find out line that read as follows:

auth sufficient /lib/security/pam_unix.so likeauth nullok

Remove nullok from above line so that it read as follows:

auth sufficient /lib/security/pam_unix.so likeauth

Save the file.

h1

Dynamic DNS Setup

July 2, 2006

Notes on setting up a dynamic dns for home with bind-9.x

  1. Generating Secure DNS Keys
  2. On the home/client machine:

    # mkdir /etc/bind/tsig
    
    # cd /etc/bind/tsig
    
    # dnssec-keygen -a HMAC-MD5 -b 128 -n HOST host.domain.tld.

    Note the “.” after the tld. This generates the public and the private keys.

  3. named.conf
  4. On the remote server:

    Edit “/etc/named.conf” and add the generated key to the conf. (Note the trailing dot):

    key host.domain.tld. {
    
    algorithm hmac-md5;
    
    secret "qUSfVtkYf7WLxiZaOTN3Ua==";
    
    };

  5. Grant Authority
  6. Still on the remote server:

    Edit the “/etc/bind/zone.domain.tld” file, and modify the current allow-update line to include the key.

    allow-update   { key "default_key."; key "host.domain.tld."; };

    This allows full authority to modify any record within the domain (Be Warned).

    Restart named and make sure nothing is broken.

  7. nsupdate
  8. Back to the client machine:

    Run nsupdate to test that the client can now make updates.

    # nsupdate -k /etc/bind/tsig/Khost.domain.tld.*.key
    
    > update delete host.domain.tld A
    
    > update add host.domain.tld. 600 A 1.2.3.4
    
    > send
    
    > quit

    It first deletes host.domain.tld if it already exists, then recreates it with the given TTL, type, and IP address. The TTL is the time-to-live, which is a value used by other DNS servers to determine how often they refresh the entry for this host. A smaller values means they’ll refresh more often, which is what you want for a dynamic entry. “send” tells nsupdate to send the updates to the server.

  9. Automate
  10. Create a script and put it in a 10 minute cron to check for changes in the wan ip address and run nsupdate automagically.

    # cat /etc/cron.d/ddns
    
    SHELL=/bin/sh
    
    */10 * * * * root /etc/bind/ddns

    Below is an example script that gets the info from a Belkin wireless router within the home lan.

    #!/bin/bash
    
    # ddnsHOSTNAME="host.domain.tld"
    
    KEYFILE="/etc/bind/tsig/Khost.domain.tld.*.key"
    
    TTL=600
    
    #LOG="/tmp/ddns_log"
    
    LOG="/dev/null"
    
    IP_FILE="/tmp/ddns_ip"
    
    NEW_IP=`wget -q -O - 192.168.2.1 | grep "Up.*dw" | tr "\n" " " | awk -F "'" '{print $12}'`
    
    function do_nsupdate {
    
    echo "New IP address (${NEW_IP}) found. Updating..." >> $LOG
    
    echo $NEW_IP > $IP_FILE
    
    nsupdate -k $KEYFILE >> $LOG << EOF
    
    update delete $HOSTNAME A
    
    update add $HOSTNAME $TTL A $NEW_IP
    
    send
    
    quit
    
    EOF
    
    }
    
    if [ ! -f $IP_FILE ]; then
    
    echo "Creating $IP_FILE..." >> $LOG
    
    do_nsupdate
    
    else
    
    OLD_IP=`cat $IP_FILE`
    
    if [ "$NEW_IP" = "$OLD_IP" ]; then
    
    echo "new and old IPs (${OLD_IP}) are same. Exiting..." >> $LOG
    
    exit 0
    
    else
    
    do_nsupdate
    
    fi
    
    fi
    
    exit 0
h1

Permanently add static IP and default gateway

July 2, 2006

Red Hat Linux has made it fairly easy to set up network so that it will start automatically. There are a series of scripts in /etc/sysconfig/network-scripts that will do most of the work.

1. Binding IP address

In “/etc/sysconfig/network-scripts/ifcfg-eth0″, add your IPADDR (IP address), NETMASK, NETWORK and BROADCAST address

DEVICE=eth0

ONBOOT=yes

IPADDR=192.168.0.x

NETMASK=255.255.255.0

NETWORK=192.168.0.0

BROADCAST=192.168.0.255

2. Adding Default Gateway

In “/etc/sysconfig/network” add your default gateway.

GATEWAY=192.168.0.1

You can now restart your network:

#/etc/sysconfig/network-scripts/ifdown eth0

#/etc/sysconfig/network-scripts/ifup eth0
( please dont run the command remotely.. else you may have shutdown the interface and will be disconnected )

or in redhat:

#service network restart
or
# /etc/init.d/network restart

Check your “/sbin/route” (routing) to verify everything is in place and restarting your computer should hold your new settings.

h1

Linux jail

July 2, 2006

Introduction to Jail

Basic concepts and supported platforms

Introduction to Jail

Basic concepts and supported platforms

Jail Chroot Project is an attempt of write a tool that builds a chrooted environment. The main goal of Jail is to be as simple as possible, and highly portable. The most difficult step when building a chrooted environment is to set up the right libraries and files. Here, Jail comes to the rescue with a tool to automagically configures & builds all the required files, directories and libraries. Jail is licensed under the GNU General Public License.

Jail program has been written using C, and the setup script has been written using a bash script and perl. Jail has been tested under Linux (Debian 2.1 & 2.2, RedHat 6.1, 6.2 and 7.0 and Caldera Openlinux 7.0), Solaris (2.6), IRIX (6.5) and FreeBSD 4.3. Some people has contributed to jail with patches and ideas. Thanks to all of them.

Jail supports lots of interesting features:

  • Runs on Linux, Solaris, IRIX and freeBSD (tested) and should run in any of the flavours of these operating systems.
  • Modular design, so you can port Jail in an easy way.
  • Support for multiple users in a single chrooted environment.
  • Fully customizable user shell.
  • Support for multiple servers: telnetd, sshd, ftpd…
  • Easy to install thanks to the enviroment creation script.
  • Should work in any UNIX.
  • Ease of porting.
  • Allows run any kind of program as a shell.

An html version of the mailing list has been added to the web site. Now you can read all the user contributions, ideas and patches here.

How Jail works

Jail’s design

How Jail works

Jail’s design

Jail is a login tool. Jail works as a wrapper to the user shell, so when the user log in the machine Jail is launched, and the chrooted environment is activated. Then, Jail execs the real user shell, so he gets his session in the server.

The ’chrooted environment’ is a subtree of the full tree in the filesystem, and the top of this subtree is saw by the chrooted user as the root ’/’ entry of the tree. So Jail is so useful for isolate users from the main filesystem’s directory tree. As you can see in the diagram, the light-gray shaded boxes are the chrooted environment:

So any user configured to be chrooted using Jail (e.g. user3) when log into the machine, he will be changed to his home directory (light-grey shaded box labeled user3) and his ’root’ directory will be ’chroot’ that will be showed just like ’/’. That is, user3 only can see the files under the directory called ’chroot’.

Jail internals

How jail interacts with the login process

by Juan M. Casillas

created at 26/08/2003 17:10:48
last updated at 05/09/2003 23:08:47

Before configure Jail, we have to need how Jail works. As you can see in the following diagram, the first things that Jail does is get the user’s information from the non-chrooted /etc/passwd. In this file there are information about where jail is located (the shell entry of the password file for this user) and which directory will be chrooted (the home directory entry of the password file for this user).

After that, Jail changes to the user directory and then it calls chroot in this directory, creating the chrooted environment. After this call, Jail only can see the files under the chrooted directory. Now, Jail setups some environment variables (the HOME and the SHELL variable that will be used by the real shell).

Now, Jail gets the users’ information from the /etc/passwd file in the chrooted environment, and checks if the user home directory is the same that the user home directory information readed from the non-chrooted file. If they are the same, the HOME variable is set to / else, Jail changes to this directory, and changes the HOME variable to this one.

Last, Jail set up again enviroment variables, SHELL is set up with the information readed from the chrooted /etc/passwd file. Now Jail replaces itsef with the shell program stored in the SHELL variable, runing the shell.

Configuring Jail

Overview of the installation process

Jail is launched as a login shell for any of the servers that allows access to the machine from the net, e.g. sshd, telnetd, ftpd, etc. So Jail is the shell of the chrooted users. To build a chrooted user, four steps are required:

  • Build user’s passwd entries in the non-chrooted environment.
  • Setup chrooted environment.
  • Add the software to the chrooted environment.
  • Add the users to the chrooted environment.

The first one is required to allow the user launch jail when a login process is invoked. The second, three and four steps are required to built the chrooted enviroment (create the required directories, copying the library and binary files, changing chrooted /etc/passwd file, and so on).

So these are the required steps in order to setup jail:

  1. Setup Entries
  2. Create directories
  3. Adding users
  4. Adding software
  5.  

Configuring Jail entries

The non-chrooted /etc/passwd file

To build the user’s password entries we can use a user creation script (just one like adduser) or to add the entries by hand. I usually prefer the second way, but first is also fine. If you choose the first method, when the creation scripts ends its work, you have to edit the files by hand. Here, I will use the second. Our nick name for the test user used in the examples will be user3.

All the magic resides on the /etc/passwd file. We have to add a line in this file to create a user in this machine. You have to setup also /etc/group and /etc/shadow if you have shadow passwords installed. Note also that you have to fit the uid an gid fields password, etc.

  user3:x:101:101:Jail Test User:/var/chroot:/usr/local/bin/jail

Note the /var/chroot field. This is the root directory of the chroot environment for this user.

Creating the Jail environment

Or how to invoke mkjailenv

Creating the Jail environment

Or how to invoke mkjailenv

mkjailenv creates the directories, and generates the basic filesystem layout with the special devices. mkjailenv has been written in perl. This are the command line arguments:

mkjailenv chrootdir

Argument

Description

chrootdir

The directory where the chrooted environment will live. It its the home entry in the non-chrooted /etc/passwd file

Invocation example:

mkjailenv /home/chroot

This will create the chrooted enviroment under the directory /home/chroot.

 

Adding users to the Jail

Or how to invoke addjailuser

Adding users to the Jail

Or how to invoke addjailuser

addjailuser edit the chrooted /etc/passwd automatically, creates the user directories, addjailuser has been written in perl script. This are the command line arguments:

addjailuser chrootdir userdir usershell username

Argument

Description

chrootdir

The directory where the chrooted environment will live. It its the home entry in the non-chrooted /etc/passwd file

userdir

The directory inside the chrooted enviroment when the user will live, in our example, /home/user3.

usershell

The user’s shell full path (e.g. /bin/bash)

username

The user’s name. In our example, user3

Invocation example:

addjailuser /var/chroot /home/user3 /bin/bash user3

This will add a user under the directory /var/chroot setups the home directory of the user3 into /home/user3, and selects /bin/bash as default shell for user3. Also edits the chrooted /etc/passwd, /etc/group and /etc/shadow to configure propertly jail.

 

Adding software to Jail

Or how to invoke addjailsw

Adding software to Jail

Or how to invoke addjailsw

addjailsw will copy the programs and the dependencies (libraries, auxiliar files, special devices) into the right places in the chrooted environment. addjailsw has been written in perl script. This are the command line arguments:

addjailsw chrootdir [-D] [-P program args]

Argument

Description

chrootdir

The directory where the chrooted environment will live. It its the home entry in the non-chrooted /etc/passwd file

-P program args (optional)

installs the specific program “program” into the chrooted environment. The script uses the “args” parameter to launch the program where doing the strace command, to allows the program exit nicely, so the strace can do its work. If this parameter isn’t specified, the standard programs included in the file will be installed. See addjailsw’s code for in-deep details.

Invocation examples:

addjailsw /var/chroot
addjailsw /var/chroot -D
addjailsw /var/chroot -P vi "-c q"

The first invocation will add the standard programs under the /var/choot directory. The second invocation will do the same that first’s but also will show what files are going to be copied in /var/chroot. Last, the third invocation will install only the program vi, and when launched in the strace call, the arguments “-c q” will be passed to it (so vi will exit inmediatly).

 

Jail install HOWTO

Installation quick guide

Jail install HOWTO

Installation quick guide

Index

  1. Compiling and installing
  2. Creating the chrooted environment
  3. Adding software into the chrooted environment
  4. Adding users into the chrooted environment
  5. Troubleshooting
  6. Porting, improvements and hacks
  7. Copyright

Compiling and installing

Just untar the package, cd to ./src and edit the makefile and do a ’make’. Now you can choose your architecture from Linux, FreeBSD, Solaris and IRIX. then configure the installation directory (default /usr/local) and you’re ready !. Perhaps you need to tune some of the compiler directives, if you are in a different platform than these ones supported by Jail. After a while, you will have the jail binary created. Then, issue a ’make install’, to do this, you have to be root (the default path to install is /usr/local). Now you are ready to play with jail.

Creating the chrooted environment

Now choose where directory will be your chroot environment. In my example, I choose /var/chroot for the chrooted environment. Now become root, and launch the mkjailenv command:

/usr/local/bin/mkjailenv /var/chroot

The output should look like this:

                mkjailenv
                A component of Jail
                http://www.gsyc.inf.uc3m.es/~assman/jail/
                Juan M. Casillas
 
                Making chrooted environment into /var/chroot
                        Doing preinstall()
                        Doing special_devices()
                        Doing gen_template_password()
                        Doing postinstall()
                Done.
 

After that, you will have the basic chrooted environment installed under /var/chroot.

Adding software into the chrooted environment

After the chrooted environment has been created, we have to add some software inside it. To do this, we will use addjailsw. This scripts, if called without -P argument, will install a default set of programs into the chrooted environment. First of all, were are going to install the basic set of programs, an then we will install the less command.

To install the basic set of programs, we will issue the following command:

/usr/local/bin/addjailsw /var/chroot

The output of the program should look like this:

 
  addjailsw
  A component of Jail
  http://www.gsyc.inf.uc3m.es/~assman/jail/
  Juan M. Casillas
 
  Guessing head args()
  Guessing bash args()
  Guessing cat args()
  Guessing pwd args()
  Guessing ln args()
  Guessing mkdir args()
  Guessing rmdir args()
  Guessing ls args()
  Guessing sh args()
  Guessing mv args()
  Guessing rm args()
  Guessing more args()
  Guessing grep args()
  Guessing vi args()
  Guessing id args()
  Guessing cp args()
  Guessing tail args()
  Guessing touch args()
  creating /var/chroot//bin/ln
  creating /var/chroot//etc/nsswitch.conf
  creating /var/chroot//var/tmp/vi.recover/vi.wTrhwB
  creating /var/chroot//etc/group
  Warning: not allowed to overwrite /var/chroot/etc/group
  creating /var/chroot//lib/libncurses.so.5
  creating /var/chroot//bin/ls
  creating /var/chroot//etc/mtab
  creating /var/chroot//bin/mkdir
  creating /var/chroot//bin/rmdir
  creating /var/chroot//bin/bash
  creating /var/chroot//bin/sh
  creating /var/chroot//etc/passwd
  Warning: not allowed to overwrite /var/chroot/etc/passwd
  creating /var/chroot//tmp/vi.UrdLM7
  creating /var/chroot//bin/mv
  creating /var/chroot//etc/ld.so.cache
  creating /var/chroot//etc/terminfo/x/xterm
  creating /var/chroot//bin/rm
  creating /var/chroot//usr/bin/vi
  creating /var/chroot//lib/libdl.so.2
  creating /var/chroot//usr/bin/id
  creating /var/chroot//lib/ld-linux.so.2
  creating /var/chroot//usr/bin/tail
  creating /var/chroot//bin/cp
  creating /var/chroot//lib/libc.so.6
  creating /var/chroot//usr/bin/head
  creating /var/chroot//bin/cat
  creating /var/chroot//lib/libnsl.so.1
  creating /var/chroot//bin/touch
  creating /var/chroot//lib/libnss_compat.so.2
  creating /var/chroot//bin/pwd
  creating /var/chroot//bin/more
  creating /var/chroot//bin/grep
  creating /var/chroot//proc/meminfo
  creating /var/chroot/null:c:1:3
  creating /var/chroot/tty:c:5:0
 
  Done.
 

As you can see in the output there are some temporal files, and also, there are some files that are begin overwritten, and other that are not allowed to be overwritted. This files are the passwd, group and shadow files of the chrooted environment. When the scripts ends, it cleans all the temporal directories in the chrooted environment.

Now, we are going to install the ’awk’ program into the chrooted environment. We need to call the addjailsw script with the -P argument:

/usr/local/bin/addjailsw /var/chroot -P awk

The output for the script will be something like this:

 
  addjailsw
  A component of Jail
  http://www.gsyc.inf.uc3m.es/~assman/jail/
  Juan M. Casillas
 
  Guessing awk args(0)
  creating /var/chroot//lib/libc.so.6
  Warning: file /var/chroot/lib/libc.so.6 exists.
  Overwritting it
  creating /var/chroot//usr/bin/awk
  creating /var/chroot//etc/ld.so.cache
  Warning: file /var/chroot/etc/ld.so.cache exists.
  Overwritting it
  creating /var/chroot//lib/libm.so.6
  creating /var/chroot//lib/ld-linux.so.2
  Warning: file /var/chroot/lib/ld-linux.so.2 exists.
  Overwritting it
 
  Done.
 

Now, you have awk installed into the chroot environment. You should use this script to install all the software into the chrooted environment

Adding users into the chrooted environment

Now, it is time to add some users into the chroot environment. First of all we need to have the users created in the system, so you can add them by hand, or using adduser. For this example, I will create a new user called chroottest with adduser To do this:

/usr/local/bin/addjailuser /var/chroot /home/chroottest /bin/bash chroottest

After answer all the questions and set the user password, we are ready to add this users to the chrooted environment. This program accepts some parameters:

  1. the first parameter is the full path to the chrooted environment (in my example, is /var/chroot)
  2. the full path of the directory under the user will live. This path will be created under the chrooted environment, and when the user logs into, it will see it as the full path. (e.g, in our example, /home/chroottest is the home directory. addjailuser will create /var/chroot/home/chrootest, and when the user logs into, he will see /home/chroottest. Because it lives under the chrooted environment, he will see a ’virtual’ home directory).
  3. The full path to the shell that the user will use. (e.g, I like to use bash, so I use the /bin/bash parameter. NOTE: if you want yo use some other shell (or program) you will need to add it to the list of the installed programs (see section 2 to see how to do that).
  4. The name of the user, in my example, chroottest

After that, we are ready to launch the program (always as root):

   /usr/local/bin/addjailuser
   /var/chroot
   /home/chroottest
   /bin/bash
   chroottest

The inverted slashes are to allow us insert carriage returns because the line is too long to type it in a single shell line. After launch the command, the output should look like this:

  addjailuser
  A component of Jail
  http://www.gsyc.inf.uc3m.es/~assman/jail/
  Juan M. Casillas
 
  Adding user pruebas in  chrooted environment /var/chroot
  Done.

That’s all. You have the user added into the chrooted environment. Now is time to try it:

su - chroottest

As you can see, you are in the new created chrooted environment, Congratulations !

Troubleshooting

Setting up SSH & scp

Now jail support terminal handling and parameter-passing, so configure ssh & scp now is possible. You only have to install a standard chrooted environment (just as described in this section) and then, install the two programs with the addjailsw script. First of all, install ssh:

/usr/local/bin/addjailsw /var/chroot -P ssh --version

To finish, install scp in the same way:

/usr/local/bin/addjailsw /var/chroot -P scp --version

Now you have the two programs installed in the chrooted environment; you can test it doing a ssh form in and out the chrooted environment, and a scp.

Well, there are not troubleshooting section :( Im writting some documentation, and improving the code for jail, mkjailenv, addjailsw and addjailuser. Also we have a mailinglist with some of the tricks and recipes to have jail working:

Jail mail archive

Also, you can generate some log files and send them back to me, so I will try to manage them and find an answer for your problems. I usually need a log for mkenv.pl, addjailuser.pl, addjailsw.pl and the output for a login session into a chrooted account.

Porting, improvements and hacks

If you tailor mkenv.pl for your platform, please send me the new mkenv.pl, so I can put it into the distribution, also, send me patches if you write any of them for jail.

Copyright

This program, the web site, all the documentation an the scripts has been written by Juan M. Casillas . All the source code, web pages, documentation and scripts has been released using the GNU Public License, version 2.0 or above (you can find the complete GPL text in a file called GPL, in the root file of jail’s distribution). Also, this program has been done and improved thanks to the help of lot of people arround the world. Thanks to all for your work, your test-drives, and your improvements & ideas.

 

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

KOOL tips

July 2, 2006

Some frequently used MySQL commands for reference…

 
# Create User



CREATE USER user [IDENTIFIED BY [PASSWORD] 'password'];

# Create Database

$ mysqladmin -u <username> -p create <nameOfDatabase>

 

# Drop/Delete Database

$ mysqladmin -u <username> -p drop <nameOfDatabase>

 

# Check Process List

$ mysqladmin -u root -p proc

 

# Check Status at 5 seconds interval

$ mysqladmin -u root -p -i 5 status

 

# Dump Database

$ mysqldump –opt -u <username> -h <hostname> <nameOfDatabase> -p > /path/to/file   

 

$ mysqldump –opt -u <username> -h <hostname> –all-databases -p > /path/to/file

 

# Import Database

$ mysql -h <host> -u <username> <nameOfDatabase> -p < /path/to/file

 

GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER ON <dbname>.* TO <dbuser@localhost> [IDENTIFIED BY '<password>'];

 

REVOKE ALL ON <dbname> FROM <dbuser@localhost>;

 

CREATE DATABASE <dbname>;

 

DROP DATABASE <dbname>;

 

DROP TABLE <tablename1[, table2, table3...]>;

 

# To activate new permissions

FLUSH PRIVILEGES;

 

USE <nameOfDatabase>;

 

SHOW DATABASES;

 

# show tables begining with the prefix

SHOW TABLES LIKE ‘prefix%’;

 

SELECT * FROM <nameOfTable>;

 

DESCRIBE <nameOfTable>;

 

INSERT INTO <table> <username, password, name1, name2, …> VALUES (‘user’, password(‘pass’), ‘value1′, ‘value2′ …);

 

CREATE TABLE <newtable> AS SELECT DISTINCT <field> FROM <oldtable>;

 

INSERT INTO <database.table> SELECT * FROM <database.table> WHERE <field> = <value>;

 

ALTER TABLE <tableOldName> RENAME <tableNewName>;

 

UPDATE <tableName> SET <field1> = <newValue> [WHERE <field2> = <currentValue>];

 

Optimize MySQL Tables

OPTIMIZE TABLE should be used if you have deleted a large part of a table or if you have made many changes to a table with variable-length rows (tables that have VARCHAR, BLOB, or TEXT columns). Deleted records are maintained in a linked list and subsequent INSERT operations reuse old record positions. You can use OPTIMIZE TABLE to reclaim the unused space and to defragment the data file.

OPTIMIZE TABLE tbl_name[,tbl_name]...

Remember to do this periodically and after every upgrade.

mysqlcheck -o -u root -p --all-databases

OPTIMIZE TABLE for MyISAM tables is equivalent of running:

$ myisamchk --quick --check-only-changed --sort-index --analyze *.MYI

 

MySQL Database Repair

  CHECK TABLE <tableName>

  REPAIR TABLE <tableName>

  myisamchk -e *.MYI

  myisamchk -r -q <tableName> (-r -q means `quick recovery mode’)

 

 

Tuning/Optimizing my.cnf file for MySQL

Had to do some fine tuning of MySQL 4.1.9 and here is what my.cnf file looks like for a 2GHz machine with 1GB of memory.

[mysqld]



socket=/path/to/mysql.sock



datadir=/var/lib/mysql



skip-locking



skip-innodb



# MySQL 4.x has query caching available.



# Enable it for vast improvement and it may be all you need to tweak.



query_cache_type=1



query_cache_limit=1M



query_cache_size=32M



# max_connections=500



# Reduced to 200 as memory will not be enough for 500 connections.



# memory=key_buffer+(sort_buffer_size+read_buffer_size)*max_connections



# which is now: 64 + (1 + 1) * 200 = 464 MB

 

 

Sorting VARCHAR data in mysql

Here’s a quick tip at sorting VARCHAR type data in mysql database with values in a column.

With the default sort, it would look something like below:

mysql> SELECT column FROM table_name ORDER BY column; 

column

======

100

1000

10000

200

2000

20000

Now with “… ORDER BY column+0″, I get it sorted right:

mysql> SELECT column FROM table_name ORDER BY column+0; 

column

======

100

200

1000

2000

10000

20000

This is a quick fix instead of sorting to CAST operator.

 

root login email alert on linux systems…

echo <<EOF >>~/.bash_profile



# Send email notification of root login



echo 'ALERT - Root Shell Access:' `who` | mail -s "Alert: Root Access from `who | awk '{print $6}'`" offsite@email.tld



EOF

You may also benefit from jailing your system if you have shell users.

 

Fried your Master Boot Record?

No worries! You are using GRUB (GRand Unified Bootloader) aren’t you?

You should atleast know where your “/boot” partition is installed.

  1. Here is my drive setup and “/boot” is setup in “hda3″.
2.           # df -h



3.           Filesystem            Size  Used Avail Use% Mounted on



4.           /dev/mapper/VolGroup00-LogVol00



5.                                  18G  4.3G   13G  26% /



6.           /dev/hda3              99M   19M   76M  20% /boot



7.           none                  506M     0  506M   0% /dev/shm
8.           # fdisk -l

9.           Disk /dev/hda: 60.0 GB, 60011642880 bytes

10.       255 heads, 63 sectors/track, 7296 cylinders

Units = cylinders of 16065 * 512 = 8225280 bytes

 

   Device Boot      Start         End      Blocks   Id  System

/dev/hda1               1        1044     8385898+   7  HPFS/NTFS

/dev/hda2            1045        4699    29358787+  83  Linux

/dev/hda3            4700        4712      104422+  83  Linux

/dev/hda4            4713        7296    20755980    5  Extended

/dev/hda5            4713        7296    20755948+  8e  Linux LVM

  1. Boot up your handy knoppix and run the below commands [ notes ].
12.       # su -                    [ root shell ]



13.       # grub                    [ grub shell ]



14.       grub> root (hd0,2)        [ specify where /boot partition resides ]



15.                                 [ 3rd primary partition of the 1st HDD ]



16.                                 [ hint: start count from 0 ]



17.       grub> setup (hd0)         [ install grub in MBR ]



18.       grub> quit                [ exit the grub shell ]



19.       # shutdown -r now
  1. Here’s a one line that will do the same automatically.
21.       # grub-install hd0

You should now have a shiny new MBR.

 

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.