Sunday, May 5, 2013

Active Directory Integration CentOS6.3

While learning how to join a linux machine to an Active Directory domain with the ability to use single sign-on I developed this script to automate the process. My environment is completely virtual utilizing XenServer 6.2 and my domain controllers are Windows Server 2008R2. This script will work for both CentOS servers as well as Desktop editions. This tutorial contains three scripts one for initial setup one for Active Directory integration and the other is to reset the system back to original should the adjoin.sh script should fail.

The adjoin.sh script assumes that you have set your hostname with a single name EX: mymachine, you have added DNS entries on your domain controller for the new machine, you have installed Identity Management for UNIX role to AD, and you have setup a static IP and set PermitRootLogin yes in sshd_config. Also make sure that you have setup a user in Active Directory and have added it to the proper administrative groups the user should have. Also create a group that will have admin privileges on the Linux machines. 

Once you have your initial system setup ssh into the machine as root and create the bin directory in /root.
I prefer to use mremoteng which you can grab from http://www.mremoteng.org/ or you can use putty or any other method that you like. In the /root/bin directory create two files netjoin.sh and reset.sh

If you are using these scripts to create a template only run setup.sh on the server before converting to template. You will only have to run setup.sh on the template after that all new VM's created will only need to run adjoin.sh. I usually make a directory /root/bin and then place the three scripts in that directory since it is in roots path. Also I change the permissions to 700. 






#!/bin/bash
## setup.sh
## Server setup script for preparing VMWare template for Active Directory integration
## Author: Glenn Weber
## Email: engineering@bngsupport.com
## Date: 05/04/2013

## This script is free to use and modify as needed I cannot guarantee that this script will work
## with your setup. If the script should fail simply run the accompanying reset.sh script
## You must also run the accompanying adjoin.sh to join to domain and spacewalk
## I have tested this script on both centOS 6.3 and centOS 6.4
## Only run this script if you are setting up a new machine or if you are creating a template to use
## If you are creating a template this portion will be done and you can just run the other scripts
domain_division=                                #ie: corp
domain_name=                
top_domain= #ie: com, net, org                              
workgrp=                                        # NETBIOS NAME of Domain
group=    # ie: linuxadmins
adm_server=                                     # This is only needed if you have an admin server that will be used for nagios


## Converts variables to uppercase
DOMAIN_DIVISION=$(echo "$domain_division" | tr '[a-z]' '[A-Z]')
DOMAIN_NAME=$(echo "$domain_name" | tr '[a-z]' '[A-Z]')
TOP_DOMAIN=$(echo "$top_domain"  | tr '[a-z]' '[A-Z]')
WORKGRP=$(echo "$workgrp" | tr '[a-z]' '[A-Z]')

## Turns off Firewall
service iptables save
service iptables stop
chkconfig iptables off

## Disables selinux
setenforce 0
sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/sysconfig/selinux

##Comment this section out if this is the main nagios server or you do not want to use nagios
## Installs epel repository and installs nagios plugins
rpm -ivh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
yum install nrpe nagios-plugins-all openssl -y

## Installs base software for Active directory Integration and a few other useful packages
yum install nano wget ntp krb5-libs krb5-workstation krb5-server samba samba-client samba-winbind sudo bc -y



## Starts ntpd service and sets services to start at boot
service ntpd start
chkconfig ntpd on

## Edits /etc/krb5.conf
cp /etc/krb5.conf /etc/krb5.conf.bkp
sed -i "s/EXAMPLE.COM/$DOMAIN_DIVISION.$DOMAIN_NAME.$TOP_DOMAIN/g" /etc/krb5.conf
sed -i 's/false/true/g' /etc/krb5.conf
sed -i "s/kerberos.example.com/$domain_division.$domain_name.$top_domain/g" /etc/krb5.conf
sed -i "s/example.com/$domain_division.$domain_name.$top_domain/g" /etc/krb5.conf
sed -i "s/.example.com/.$domain_division.$domain_name.$top_domain/g" /etc/krb5.conf

## Creates backup of /etc/pam.d directory and rewrites system-auth-ac
 cp -R /etc/pam.d /etc/pam.d.bkp
 cat > /etc/pam.d/system-auth-ac <<EOF
 auth        required      pam_env.so
          auth        sufficient    pam_unix.so nullok try_first_pass
          auth        requisite     pam_succeed_if.so uid >= 500 quiet
          auth        sufficient    pam_winbind.so use_first_pass
          auth        required      pam_deny.so

          account     required      pam_unix.so broken_shadow
          account     sufficient    pam_succeed_if.so uid < 500 quiet
          account     [default=bad success=ok user_unknown=ignore] pam_winbind.so
          account     required      pam_permit.so

          password    requisite     pam_cracklib.so try_first_pass retry=3
          password    sufficient    pam_unix.so md5 shadow nullok try_first_pass
use_authtok
          password    sufficient    pam_winbind.so use_authtok
          password    required      pam_deny.so

          session     optional      pam_keyinit.so revoke
          session     optional      pam_mkhomedir.so skel=/etc/skel/ umask=0077
          session     required      pam_limits.so
          session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet
use_uid
          session     required      pam_unix.so
EOF

## Creates Backup copy of smb.conf
cp /etc/samba/smb.conf /etc/samba/smb.conf.bkp

## Runs authconfig and adds entries to /etc/samba/smb.conf winbind section
authconfig --krb5realm=$DOMAIN_DIVISION.$DOMAIN_NAME.$TOP_DOMAIN \
--enablewinbind --enablewinbindauth --smbsecurity=ads --smbrealm=$DOMAIN_DIVISION.$DOMAIN_NAME.$TOP_DOMAIN \
--smbidmapuid="16777216-33554431" --smbidmapgid="16777216-33554431" --winbindseparator="+" \
--winbindtemplateshell="/bin/bash" --enablewinbindusedefaultdomain --enablewinbindoffline \
--smbworkgroup=$WORKGRP \
--winbindtemplatehomedir="/home/%U" --enablemkhomedir --disablemd5 --updateall

## Creates backup of /etc/sudoers file and appends group to sudoers file
cp /etc/sudoers /etc/sudoers.bkp
echo "## Allows members of the $group group to run all commands" >> /etc/sudoers
echo  "   %$group  ALL=(ALL) ALL " >> /etc/sudoers

## Adds Spacewalk Repos and clients
## Comment the below section if you do not have a Spacewalk server
rpm -Uvh http://yum.spacewalkproject.org/2.0-client/RHEL/6/x86_64/spacewalk-client-repo-2.0-3.el6.noarch.rpm
yum install rhn-client-tools rhn-check rhn-setup rhnsd m2crypto yum-rhn-plugin osad -y

cd /usr/share/rhn
wget http://$adm_server.$domain_division.$domain_name.$top_domain/repo/RHN-ORG-TRUSTED-SSL-CERT

cd /tmp
wget http://$adm_server.$domain_division.$domain_name.$top_domain/repo/RPM-GPG-KEY-spacewalk-2012
rpm --import RPM-GPG-KEY-spacewalk-2012

cd /etc/sysconfig/rhn
mv osad.conf osad.conf.bkp
wget http://$adm_server.$domain_division. $domain_name.$top_domain/repo/osad.conf


yum clean all



#!/bin/bash
## Server Active Directory integration script
## adjoin.sh
## Author: Glenn Weber
## Email: engineering@bngsupport.com
## Date: 05/04/2013
domain_division=
domain_name=      
top_domain=                    
sw_server=                

## Joins machine to domain
net ads join -Uadministrator

## Restarts services
service winbind restart
chkconfig winbind on
service smb restart
chkconfig smb on

## Creates backup of /etc/sysconfig/network and sets long domain name
cp /etc/sysconfig/network /etc/sysconfig/network.bkp
## copies short hostname to reset.sh
cat >> /root/bin/reset.sh <<EOF
hostname $HOSTNAME
EOF
hostname $HOSTNAME.$domain_divsion.$domain_name.$top_domain
sed -i "s/HOSTNAME=$HOSTNAME/HOSTNAME=$HOSTNAME.$domain_division.$domain_name.$top_domain/g" /etc/sysconfig/network

service network restart
## Turns off Root ssh Login and restarts sshd service
sed -i "s/PermitRootLogin yes/PermitRootLogin no/g" /etc/ssh/sshd_config
service sshd restart
wbinfo -u
sleep 5

## Registers machine with Spacewalk server
## Comment the below section if you do not have a Spacewalk server
rhnreg_ks --serverUrl=http://$sw_server.$domain_division.$domain_name.$top_domain/XMLRPC --activationkey=1-7eb473722e68584b94a75196c2c4330a && sleep 90

chkconfig osad on && service osad restart
rhn-actions-control --enable-all





#!/bin/bash
## reset.sh
## Reset script should be run only after adjoin.sh has been run and only if the machine
## fails to join the domain
## Author: Glenn Weber
## Email: engineering@bngsupport.com
## Date: 05/04/2013
## Resets all files back to original state if setup.sh and netjoin.sh scripts are unsuccessful
cp /etc/krb5.conf.bkp /etc/krb5.conf
rm -f /etc/krb5.conf.bkp
cp /etc/samba/smb.conf.bkp /etc/samba/smb.conf
rm -f /etc/samba/smb.conf.bkp
cp -R /etc/pam.d.bkp /etc/pam.d
rm -rf /etc/pam.d.bkp
cp /etc/sudoers.bkp /etc/sudoers
rm -f /etc/sudoers.bkp
cp /etc/sysconfig/network.bkp /etc/sysconfig/network
rm -f /etc/sysconfig/network.bkp
rm -f /etc/sysconfig/rhn/osad.conf
mv /etc/sysconfig/rhn/osad.conf.bkp /etc/sysconfig/rhn/osad.conf
rm -f /usr/share/rhn/RHN-ORG-TRUSTED-SSL-CERT
rm -f /etc/yum.repos.d/spacewalk-client-nightly.repo
rm -f /etc/yum.repos.d/spacewalk-client.repo
cp /etc/resolv.conf.bkp /etc/resolv.conf
rm -f /etc/resolv.conf.bkp









Please feel free to leave comments if you have questions or issues getting these scripts to work for you.













Monday, January 28, 2013

Web Hosting Server setup on Ubuntu server 12.04 with ISPconfig3 /Apache/Bind/Postfix/Dovecot/Roundcube

By Glenn Weber



This guide was developed to help those of you who wish to get a better understanding of setting up a web hosting server in a Linux environment. Much of this guide is taken from the HowtoForge perfect server tutorial series. This particular tutorial covers installation for Ubuntu Server 12.04 LTS and comes from http://www.howtoforge.com/perfect-server-ubuntu-12.04-lts-apache2-bind-dovecot-ispconfig-3.
Before diving into the setup I would like to give special thanks to Falko Timme for developing these series of tutorials. By no means is this a replacement for his excellent work but it is rather meant to extend the capabilities and security of his setup and to consolidate the information into one location for those who have the desire to configure a similar server.
The server setup I am using for this tutorial is done in VMware ESXi 5 but can be performed on any physical machine capable of running the operating system. I also utilize two network adapters which I use for nic bonding which I will discuss in further detail.

Preliminary Notes:
1.       The first thing you will need to do is to download a copy of Ubuntu Server. You can get the 64bit version at http://www.ubuntu.com/download/server/thank-you?distro=server&bits=64&release=lts  and the 32 bit version from http://www.ubuntu.com/download/server/thank-you?distro=server&bits=32&release=lts.
2.       In this tutorial I use the hostname mail.example.com with the IP address 192.168.0.100 and the gateway 192.168.0.1. These settings might differ for you, so you have to replace them where appropriate.
3.       Determine the method of installing the base system. I am using VMware so I upload the downloaded iso to a datastore , if this is being done in virtualbox simply boot off of the iso. The other alternative if this will be installed directly to a physical machine is to burn it to cd/dvd and boot that media.
4.       The following ports must be forwarded in your router to the server which you are installing this: HTTP 80, HTTPS 443, FTP 20-21, SMTP ports 25, 465, 587, IMAP ports 585, 143, ISPconfig control panel 8080, VPN-PPTP 1723 for instructions on how to forward these ports see the manual or look online for your specific router.

Insert your Ubuntu install CD into your system and boot from it. Select your language:
Then select Install Ubuntu Server:
Choose your language again (?):
Then select your location:




If you've selected an uncommon combination of language and location (like English as the language and Germany as the location, as in my case), the installer might tell you that there is no locale defined for this combination; in this case you have to select the locale manually. I select en_US.UTF-8 here:
Choose a keyboard layout (you will be asked to press a few keys, and the installer will try to detect your keyboard layout based on the keys you pressed):


The installer checks the installation CD, your hardware, and configures the network with DHCP if there is a DHCP server in the network:


Enter the hostname. In this example, my system is called server1.example.com, so I enter server1:



Create a user, for example the user Administrator with the user name administrator (don't use the user name admin as it is a reserved name on Ubuntu 12.04):                







I don't need an encrypted private directory, so I choose No here:
Please check if the installer detected your time zone correctly. If so, select Yes, otherwise No:
Now you have to partition your hard disk. For simplicity's sake I select Guided - use entire disk and set up LVM - this will create one volume group with two logical volumes, one for the / file system and another one for swap (of course, the partitioning is totally up to you - if you know what you're doing, you can also set up your partitions manually).
Select the disk that you want to partition:
When you're asked Write the changes to disks and configure LVM?, select Yes:
If you have selected Guided - use entire disk and set up LVM, the partitioner will create one big volume group that uses all the disk space. You can now specify how much of that disk space should be used by the logical volumes for / and swap. It makes sense to leave some space unused so that you can later on expand your existing logical volumes or create new ones - this gives you more flexibility.
When you're finished, hit Yes when you're asked Write the changes to disks?:
Afterwards, your new partitions are being created and formatted:
Now the base system is being installed:
Next the package manager apt gets configured. Leave the HTTP proxy line empty unless you're using a proxy server to connect to the Internet:


I'm a little bit old-fashioned and like to update my servers manually to have more control, therefore I select No automatic updates. Of course, it's up to you what you select here:
We need a DNS, mail, and LAMP server, but nevertheless I don't select any of them now because I like to have full control over what gets installed on my system. We will install the needed packages manually later on. The only item I select here is OpenSSH server so that I can immediately connect to the system with an SSH client such asPuTTY after the installation has finished:
The installation continues:
The GRUB boot loader gets installed:
Select Yes when you are asked Install the GRUB boot loader to the master boot record?:
The base system installation is now finished. Remove the installation CD from the CD drive and hit Continue to reboot the system:

After the reboot you can login with your previously created username (e.g. administrator). Because we must run all the steps from this tutorial with root privileges, we can either prepend all commands in this tutorial with the string sudo, or we become root right now by typing
sudo su
7 Configure The Network
Because the Ubuntu installer has configured our system to get its network settings via DHCP, we have to change that now because a server should have a static IP address. Edit /etc/network/interfaces and adjust it to your needs (in this example setup I will use the IP address 192.168.0.100 and the DNS servers 8.8.8.8 and 8.8.4.4
nano /etc/network/interfaces
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto eth0
iface eth0 inet static
        address 192.168.0.100
        netmask 255.255.255.0
        network 192.168.0.0
        broadcast 192.168.0.255
        gateway 192.168.0.1
        dns-nameservers 8.8.8.8 8.8.4.4
Then restart your network:
/etc/init.d/networking restart
Then edit /etc/hosts. Make it look like this:
nano /etc/hosts
127.0.0.1       localhost.localdomain   localhost
192.168.0.100   server1.example.com     server1

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
Now run
echo server1.example.com > /etc/hostname
/etc/init.d/hostname restart
Afterwards, run
hostname
hostname -f
Both should show server1.example.com now.

8 Edit /etc/ssh/sshd_config
nano  /etc/ssh/sshd_config and change the port and disable root login
Port 22203
PermitRootLogin no
9 Change the Default Shell
/bin/sh is a symlink to /bin/dash, however we need /bin/bash, not /bin/dash. Therefore we do this:
dpkg-reconfigure dash
Use dash as the default system shell (/bin/sh)? <-- No
If you don't do this, the ISPConfig installation will fail.
10 Synchronize the System Clock
It is a good idea to synchronize the system clock with an NTP (network time protocol) server over the Internet. Simply run
apt-get install ntp ntpdate
and your system time will always be in sync.
11 Edit Update your system and reboot
apt-get update
to update the apt package database and
apt-get upgrade
to install the latest updates (if there are any). If you see that a new kernel gets installed as part of the updates, you should reboot the system afterwards:
reboot
After reboot you should now be able to login via ssh with Putty, which can be downloaded from  http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html . Remember to use the correct port that you configured in /etc/ssh/sshd_config
12 Disable AppArmor
AppArmor is a security extension (similar to SELinux) that should provide extended security. In my opinion you don't need it to configure a secure system, and it usually causes more problems than advantages (think of it after you have done a week of trouble-shooting because some service wasn't working as expected, and then you find out that everything was ok, only AppArmor was causing the problem). Therefore I disable it (this is a must if you want to install ISPConfig later on).
We can disable it like this:
/etc/init.d/apparmor stop
update-rc.d -f apparmor remove
apt-get remove apparmor apparmor-utils

13 Install Postfix, Dovecot, MySQL, phpMyAdmin, rkhunter, binutils
We can install Postfix, Dovecot, MySQL, rkhunter, and binutils with a single command:
apt-get install postfix postfix-mysql postfix-doc mysql-client mysql-server openssl getmail4 rkhunter binutils dovecot-imapd dovecot-pop3d dovecot-mysql dovecot-sieve sudo
You will be asked the following questions:
New password for the MySQL "root" user: <-- yourrootsqlpassword
Repeat password for the MySQL "root" user: <-- yourrootsqlpassword
General type of mail configuration: <-- Internet Site
System mail name: <-- server1.example.com
Next open the TLS/SSL and submission ports in Postfix:
nano /etc/postfix/master.cf
Uncomment the submission and smtps sections (leave -o milter_macro_daemon_name=ORIGINATING as we don't need it):
[...]
submission inet n       -       -       -       -       smtpd
  -o syslog_name=postfix/submission
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
smtps     inet  n       -       -       -       -       smtpd
  -o syslog_name=postfix/smtps
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
[...]
Restart Postfix afterwards:
/etc/init.d/postfix restart
We want MySQL to listen on all interfaces, not just localhost, therefore we edit /etc/mysql/my.cnf and comment out the line bind-address = 127.0.0.1:
vi /etc/mysql/my.cnf
[...]
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
#bind-address           = 127.0.0.1
[...]
Then we restart MySQL:
/etc/init.d/mysql restart
Now check that networking is enabled. Run
netstat -tap | grep mysql
The output should look like this:
root@server1:~# netstat -tap | grep mysql
tcp        0      0 *:mysql                 *:*                     LISTEN      21298/mysqld
root@server1:~#

14 Install Amavisd-new, SpamAssassin, And Clamav
To install amavisd-new, SpamAssassin, and ClamAV, we run
apt-get install amavisd-new spamassassin clamav clamav-daemon zoo unzip bzip2 arj nomarch lzop cabextract apt-listchanges libnet-ldap-perl libauthen-sasl-perl clamav-docs daemon libio-string-perl libio-socket-ssl-perl libnet-ident-perl zip libnet-dns-perl
The ISPConfig 3 setup uses amavisd which loads the SpamAssassin filter library internally, so we can stop SpamAssassin to free up some RAM:
/etc/init.d/spamassassin stop
update-rc.d -f spamassassin remove

15 Install Apache2, PHP5, phpMyAdmin, FCGI, suExec, Pear, And mcrypt
Apache2, PHP5, phpMyAdmin, FCGI, suExec, Pear, and mcrypt can be installed as follows:
apt-get install apache2 apache2.2-common apache2-doc apache2-mpm-prefork apache2-utils libexpat1 ssl-cert libapache2-mod-php5 php5 php5-common php5-gd php5-mysql php5-imap phpmyadmin php5-cli php5-cgi libapache2-mod-fcgid apache2-suexec php-pear php-auth php5-curl php5-mcrypt mcrypt php5-imagick imagemagick libapache2-mod-suphp libruby libapache2-mod-ruby libapache2-mod-python libapache2-mod-perl2
You will see the following question:
Web server to reconfigure automatically: <-- apache2
Configure database for phpmyadmin with dbconfig-common? <-- No
Then run the following command to enable the Apache modules suexecrewritesslactions, and include (plus davdav_fs, and auth_digest if you want to use WebDAV):
a2enmod suexec rewrite ssl actions include
a2enmod dav_fs dav auth_digest
Restart Apache afterwards:
/etc/init.d/apache2 restart

15.1Xcache
Xcache is a free and open PHP opcode cacher for caching and optimizing PHP intermediate code. It's similar to other PHP opcode cachers, such as eAccelerator and APC. It is strongly recommended to have one of these installed to speed up your PHP page.
Xcache can be installed as follows:
apt-get install php5-xcache
Now restart Apache:
/etc/init.d/apache2 restart

15.2 PHP-FPM
Starting with the upcoming ISPConfig 3.0.5, there will be an additional PHP mode that you can select for usage with Apache: PHP-FPM. If you plan to use this PHP mode, it makes sense to configure your system for it now so that later on when you upgrade to ISPConfig 3.0.5, your system is prepared (the latest ISPConfig version at the time of this writing is ISPConfig 3.0.4.4).
To use PHP-FPM with Apache, we need the mod_fastcgi Apache module (please don't mix this up with mod_fcgid - they are very similar, but you cannot use PHP-FPM with mod_fcgid). We can install PHP-FPM and mod_fastcgi as follows:
apt-get install libapache2-mod-fastcgi php5-fpm
Make sure you enable the module and restart Apache:
a2enmod actions fastcgi alias
/etc/init.d/apache2 restart

16 Install PureFTPd And Quota
PureFTPd and quota can be installed with the following command:
apt-get install pure-ftpd-common pure-ftpd-mysql quota quotatool
Edit the file /etc/default/pure-ftpd-common...
nano /etc/default/pure-ftpd-common
... and make sure that the start mode is set to standalone and set VIRTUALCHROOT=true:
[...]
STANDALONE_OR_INETD=standalone
[...]
VIRTUALCHROOT=true
[...]
Now we configure PureFTPd to allow FTP and TLS sessions. FTP is a very insecure protocol because all passwords and all data are transferred in clear text. By using TLS, the whole communication can be encrypted, thus making FTP much more secure.
If you want to allow FTP and TLS sessions, run
echo 1 > /etc/pure-ftpd/conf/TLS
In order to use TLS, we must create an SSL certificate. I create it in /etc/ssl/private/, therefore I create that directory first:
mkdir -p /etc/ssl/private/
Afterwards, we can generate the SSL certificate as follows:
openssl req -x509 -nodes -days 7300 -newkey rsa:2048 -keyout /etc/ssl/private/pure-ftpd.pem -out /etc/ssl/private/pure-ftpd.pem
Country Name (2 letter code) [AU]: <-- Enter your Country Name (e.g., "DE").
State or Province Name (full name) [Some-State]: 
<-- Enter your State or Province Name.
Locality Name (eg, city) []: 
<-- Enter your City.
Organization Name (eg, company) [Internet Widgits Pty Ltd]: 
<-- Enter your Organization Name (e.g., the name of your company).
Organizational Unit Name (eg, section) []: 
<-- Enter your Organizational Unit Name (e.g. "IT Department").
Common Name (eg, YOUR name) []: 
<-- Enter the Fully Qualified Domain Name of the system (e.g. "server1.example.com").
Email Address []: 
<-- Enter your Email Address.
Change the permissions of the SSL certificate:
chmod 600 /etc/ssl/private/pure-ftpd.pem
Then restart PureFTPd:
/etc/init.d/pure-ftpd-mysql restart
Edit /etc/fstab. Mine looks like this (I added ,usrjquota=quota.user,grpjquota=quota.group,jqfmt=vfsv0 to the partition with the mount point /):
nano /etc/fstab
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
proc            /proc           proc    nodev,noexec,nosuid 0       0
/dev/mapper/server1-root /               ext4    errors=remount-ro,usrjquota=quota.user,grpjquota=quota.group,jqfmt=vfsv0 0       1
# /boot was on /dev/sda1 during installation
UUID=4b58d345-1c55-4ac5-940e-7245938656a6 /boot           ext2    defaults        0       2
/dev/mapper/server1-swap_1 none            swap    sw              0       0
/dev/fd0        /media/floppy0  auto    rw,user,noauto,exec,utf8 0       0
To enable quota, run these commands:
mount -o remount /
quotacheck -avugm
quotaon -avug

17 Install BIND DNS Server
BIND can be installed as follows:
apt-get install bind9 dnsutils

18 Install Vlogger, Webalizer, And AWstats
Vlogger, webalizer, and AWstats can be installed as follows:
apt-get install vlogger webalizer awstats geoip-database libclass-dbi-mysql-perl
Open /etc/cron.d/awstats afterwards...
nano /etc/cron.d/awstats
... and comment out everything in that file:
#MAILTO=root
#*/10 * * * * www-data [ -x /usr/share/awstats/tools/update.sh ] && /usr/share/awstats/tools/update.sh
# Generate static reports:
#10 03 * * * www-data [ -x /usr/share/awstats/tools/buildstatic.sh ] && /usr/share/awstats/tools/buildstatic.sh

19 Install Jailkit
Jailkit is needed only if you want to chroot SSH users. It can be installed as follows (important: Jailkit must be installed before ISPConfig - it cannot be installed afterwards!):
apt-get install build-essential autoconf automake1.9 libtool flex bison debhelper binutils-gold
cd /tmp
wget http://olivier.sessink.nl/jailkit/jailkit-2.14.tar.gz
tar xvfz jailkit-2.14.tar.gz
cd jailkit-2.14
./debian/rules binary
You can now install the Jailkit .deb package as follows:
cd ..
dpkg -i jailkit_2.14-1_*.deb
rm -rf jailkit-2.14*

20 Install fail2ban
This is optional but recommended, because the ISPConfig monitor tries to show the log:
apt-get install fail2ban
To make fail2ban monitor PureFTPd and Dovecot, create the file /etc/fail2ban/jail.local:
nano /etc/fail2ban/jail.local
[pureftpd]
enabled  = true
port     = ftp
filter   = pureftpd
logpath  = /var/log/syslog
maxretry = 3

[dovecot-pop3imap]
enabled = true
filter = dovecot-pop3imap
action = iptables-multiport[name=dovecot-pop3imap, port="pop3,pop3s,imap,imaps", protocol=tcp]
logpath = /var/log/mail.log
maxretry = 5
Then create the following two filter files:
nano /etc/fail2ban/filter.d/pureftpd.conf
[Definition]
failregex = .*pure-ftpd: \(.*@<HOST>\) \[WARNING\] Authentication failed for user.*
ignoreregex =
nano /etc/fail2ban/filter.d/dovecot-pop3imap.conf
[Definition]
failregex = (?: pop3-login|imap-login): .*(?:Authentication failure|Aborted login \(auth failed|Aborted login \(tried to use disabled|Disconnected \(auth failed|Aborted login \(\d+ authentication attempts).*rip=(?P<host>\S*),.*
ignoreregex =
Restart fail2ban afterwards:
/etc/init.d/fail2ban restart
21 Install ISPConfig 3
To install ISPConfig 3 from the latest released version, do this:
cd /tmp
wget http://www.ispconfig.org/downloads/ISPConfig-3-stable.tar.gz
tar xfz ISPConfig-3-stable.tar.gz
cd ispconfig3_install/install/
The next step is to run
php -q install.php
This will start the ISPConfig 3 installer. The installer will configure all services like Postfix, Dovecot, etc. for you. A manual setup as required for ISPConfig 2 (perfect setup guides) is not necessary.
root@server1:/tmp/ispconfig3_install/install# php -q install.php


--------------------------------------------------------------------------------
 _____ ___________   _____              __ _         ____
|_   _/  ___| ___ \ /  __ \            / _(_)       /__  \
  | | \ `--.| |_/ / | /  \/ ___  _ __ | |_ _  __ _    _/ /
  | |  `--. \  __/  | |    / _ \| '_ \|  _| |/ _` |  |_ |
 _| |_/\__/ / |     | \__/\ (_) | | | | | | | (_| | ___\ \
 \___/\____/\_|      \____/\___/|_| |_|_| |_|\__, | \____/
                                              __/ |
                                             |___/
--------------------------------------------------------------------------------


>> Initial configuration

Operating System: Debian or compatible, unknown version.

    Following will be a few questions for primary configuration so be careful.
    Default values are in [brackets] and can be accepted with <ENTER>.
    Tap in "quit" (without the quotes) to stop the installer.


Select language (en,de) [en]:
 <-- ENTER
Installation mode (standard,expert) [standard]: <-- ENTER
Full qualified hostname (FQDN) of the server, eg server1.domain.tld  [server1.example.com]: <-- ENTER
MySQL server hostname [localhost]: <-- ENTER
MySQL root username [root]: <-- ENTER
MySQL root password []: <-- yourrootsqlpassword
MySQL database to create [dbispconfig]: <-- ENTER
MySQL charset [utf8]: <-- ENTER
Generating a 2048 bit RSA private key
...........+++
.....................+++
writing new private key to 'smtpd.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:
 <-- ENTER
State or Province Name (full name) [Some-State]: <-- ENTER
Locality Name (eg, city) []: <-- ENTER
Organization Name (eg, company) [Internet Widgits Pty Ltd]: <-- ENTER
Organizational Unit Name (eg, section) []: <-- ENTER
Common Name (e.g. server FQDN or YOUR name) []: <-- ENTER
Email Address []: <-- ENTER
Configuring Jailkit
Configuring Dovecot
Configuring Spamassassin
Configuring Amavisd
Configuring Getmail
Configuring Pureftpd
Configuring BIND
Configuring Apache
Configuring Vlogger
Configuring Apps vhost
Configuring Bastille Firewall
Configuring Fail2ban
Installing ISPConfig
ISPConfig Port [8080]:
 <-- ENTER
Do you want a secure (SSL) connection to the ISPConfig web interface (y,n) [y]: <-- ENTER
Generating RSA private key, 4096 bit long modulus
.......++
.........................................................++
e is 65537 (0x10001)
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:
 <-- ENTER
State or Province Name (full name) [Some-State]: <-- ENTER
Locality Name (eg, city) []: <-- ENTER
Organization Name (eg, company) [Internet Widgits Pty Ltd]: <-- ENTER
Organizational Unit Name (eg, section) []: <-- ENTER
Common Name (e.g. server FQDN or YOUR name) []: <-- ENTER
Email Address []: <-- ENTER
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
 <-- ENTER
An optional company name []: <-- ENTER
writing RSA key
Configuring DBServer
Installing ISPConfig crontab
no crontab for root
no crontab for getmail
Restarting services ...
Rather than invoking init scripts through /etc/init.d, use the service(8)
utility, e.g. service mysql restart

Since the script you are attempting to invoke has been converted to an
Upstart job, you may also use the stop(8) and then start(8) utilities,
e.g. stop mysql ; start mysql. The restart(8) utility is also available.
mysql stop/waiting
mysql start/running, process 2543
 * Stopping Postfix Mail Transport Agent postfix
/usr/sbin/postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
   ...done.
 * Starting Postfix Mail Transport Agent postfix
postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
/usr/sbin/postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
/usr/sbin/postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
/usr/sbin/postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
/usr/sbin/postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
/usr/sbin/postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
/usr/sbin/postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
/usr/sbin/postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
/usr/sbin/postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
/usr/sbin/postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
/usr/sbin/postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
/usr/sbin/postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
/usr/sbin/postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
/usr/sbin/postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
/usr/sbin/postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
/usr/sbin/postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
/usr/sbin/postconf: warning: /etc/postfix/master.cf: unused parameter: smtpd_bind_address=127.0.0.1
   ...done.
Stopping amavisd: (not running).
The amavisd daemon is already running, PID: [1126]
Starting amavisd: (failed).
 * Stopping ClamAV daemon clamd
   ...done.
 * Starting ClamAV daemon clamd
   ...done.
Rather than invoking init scripts through /etc/init.d, use the service(8)
utility, e.g. service dovecot restart

Since the script you are attempting to invoke has been converted to an
Upstart job, you may also use the stop(8) and then start(8) utilities,
e.g. stop dovecot ; start dovecot. The restart(8) utility is also available.
dovecot stop/waiting
dovecot start/running, process 3668
 * Restarting Mailman master qrunner mailmanctl
 * Waiting...
   ...done.
   ...done.
 * Restarting web server apache2
 ... waiting .   ...done.
Restarting ftp server: Running: /usr/sbin/pure-ftpd-mysql-virtualchroot -l mysql:/etc/pure-ftpd/db/mysql.conf -l pam -E -H -Y 1 -O clf:/var/log/pure-ftpd/transfer.log -8 UTF-8 -b -D -A -u 1000 -B
Installation completed.
root@server1:/tmp/ispconfig3_install/install#
The installer automatically configures all underlying services, so no manual configuration is needed.
You now also have the possibility to let the installer create an SSL vhost for the ISPConfig control panel, so that ISPConfig can be accessed using https:// instead ofhttp://. To achieve this, just press ENTER when you see this question: Do you want a secure (SSL) connection to the ISPConfig web interface (y,n) [y]:.
Afterwards you can access ISPConfig 3 under http(s)://server1.example.com:8080/ or http(s)://192.168.0.100:8080/ ( http or https depends on what you chose during installation). Log in with the username admin and the password admin (you should change the default password after your first login):


The system is now ready to be used.
 22 Install Roundcube webmail
22.1 Download and extract RoundCube
First we make a folder for the webmail and change directory:
mkdir /var/www/webmail/
cd /var/www/
Then we download the latest stable version of RoundCube from http://www.roundcube.net/download and extract it:
wget http://sourceforge.net/projects/roundcubemail/files/roundcubemail/0.8.4/roundcubemail-0.8.4.tar.gz
tar xfz roundcubemail-0.8.4.tar.gz
mv roundcubemail-0.8.4/* webmail
rm roundcubemail-0.8.4.tar.gz
rm -rf roundcubemail-0.8.4
Then we change directory and give some permissions to the /logs and /temp directories:
cd webmail
chown -R www-data:www-data temp/ logs/

22.2 Prepare the database
Now we want to add a user and database for our RoundCube installation. With MySQL you can set up the database by issuing the following commands:
CREATE DATABASE roundcubemail;
GRANT ALL PRIVILEGES ON roundcubemail.* TO roundcubeuser@localhost IDENTIFIED BY 'password';
(Of course, you have to replace the database, username and password accordingly.)
Then we want to flush the users privileges or you will get a database connection error:
FLUSH PRIVILEGES;

22.3 Configuring RoundCube
Now point your browser to http://url-to-roundcube/installer/ and follow the instructions to start the installation of RoundCube. The first page shows the requirements, if everything is okay click "START INSTALLATION". The installer checks if everything is there. In case you see some red NOT OK messages, you need to install or enable something. Follow the links to see what has to be done.
If everything checks out fine you are ready to create the configuration files, click "NEXT" to get there. Get through the form and change the settings according to your needs. Do not forget to enter the database setting that we made earlier within the "Database Setup" section.
If there are red Not OK messages then you will need to configure them before you can proceed with the configuration. Most likely the NOT OK messages will pertain to issues with php. You will need to edit /etc/php5/apache2/php.ini and make the necessary changes. One common NOT OK message that may show up pertains to date.timezone. in /etc/php5/apache2/php.ini you will have to uncomment this line and set it similar but with your timezone.
nano /etc/php5/apache2/php.ini
date.timezone ='America/New_York'
After all necessary changes are made restart apache /etc/init.d/apache2 restart and then reload the roundcube configuration page. If all problems are resolved it will show no red NOT OK messages.
When you are finished hit the "CREATE CONFIG" button and you will get two text boxes with the information for main.inc.php and db.inc.php that you must create in your/config directory.
Finally click "CONTINUE" and get to the last step of the installation process. Your configuration will now be verified and tested against your webserver. Click "Initialize database" to create the necessary tables in your database.
If there are no red NOT OK messages, you can also try to send a mail in order to test the SMTP settings.
Last but not least you have to remove the whole installer directory from the webserver. If this remains active it can expose the configuration including passwords. We do this with the following command:
rm -rf /var/www/webmail/installer

22.4 Adding aliases
For everyone to be able to access his webmail (under his domain name) you have to create or edit the file /etc/apache2/conf.d/roundcube.conf and add the alias "/webmail" and some more information about the directories:
In my case, I have only made this with a redirect to the default domain of the ISPConfig 3 installation with SSL for security and valid verifications
nano /etc/apache2/conf.d/roundcube.conf
# RoundCube alias and redirect functions
Alias /webmail /var/www/webmail
<Directory /var/www/webmail>
  Options +FollowSymLinks
  # This is needed to parse /var/www/webmail/.htaccess. See its
  # content before setting AllowOverride to None.
  AllowOverride All
  order allow,deny
  allow from all
</Directory>
# Protecting basic directories:
<Directory /var/www/webmail/config>
        Options -FollowSymLinks
        AllowOverride None
</Directory>
<Directory /var/www/webmail/temp>
        Options -FollowSymLinks
        AllowOverride None
        Order allow,deny
        Deny from all
</Directory>
<Directory /var/www/webmail/logs>
        Options -FollowSymLinks
        AllowOverride None
        Order allow,deny
        Deny from all
</Directory>
<IfModule mod_rewrite.c>
  <IfModule mod_ssl.c>
    <Location /webmail>
      RewriteEngine on
      RewriteCond %{HTTPS} !^on$ [NC]
      RewriteRule . https://www.yourdomain.com:8080/webmail/  [L]
    </Location>
  </IfModule>
</IfModule>
If you want to access the webmail with every domain without SSL you can just remove/comment out the mod_rewrite section. This might give you some errors, please look the following page (troubleshooting) for possible solutions http://trac.roundcube.net/wiki/Howto_Install

22.5 Final tweaks
We want to make some final tweeks in RoundCube by changing the following lines in main.inc.php:
nano /var/www/webmail/config/main.inc.php
[...]
$rcmail_config['message_cache_lifetime'] = '10d';
[...]
$rcmail_config['default_host'] = '';
[...]
$rcmail_config['smtp_server'] = '';
[...]
$rcmail_config['session_lifetime'] = 10;
[...]
$rcmail_config['create_default_folders'] = FALSE;
[...]
to:
[...]
$rcmail_config['message_cache_lifetime'] = '30m';
[...]
$rcmail_config['default_host'] = 'localhost';
[...]
$rcmail_config['smtp_server'] = '%h';
[...]
$rcmail_config['session_lifetime'] = 30;
[...]
$rcmail_config['create_default_folders'] = TRUE;
[...]
Now go to http://www.yourdomain.com/webmail to access the newly created webmail interface.
 22.6 Installing and configuring the password plugin
Installing the password plugin allows the users to change their password within the roundcube web email interface.
1. enable it (plugin password)
 cd /var/www/roundcube/config
 nano main.inc.php

[...]

$rcmail_config['plugins'] = array('password');
[...]


2. Configure it
The database, username, and password that needs to be entered into the $rcmail_config[‘password_db_dsn’] line can be located in /usr/local/ispconfig/interface/lib/config.inc.php
 cd /var/www/roundcube/plugins/password
 cp config.inc.php.dist config.inc.php
 vim config.inc.php

[...]
$rcmail_config['password_driver'] = 'sql';
$rcmail_config['password_db_dsn'] = 'mysql://ispconfig:$PASSWORD@localhost/dbispconfig';
[...]
$rcmail_config['password_query'] = 'UPDATE mail_user SET password=%c WHERE email=%u LIMIT 1';
[...]

3. Restart apache
/etc/init.d/apache2 restart
After restarting apache login to the roundcube web email and click on settings. You should now see Password listed on the left. Click password and you will be taken to a page that asks for current password and then you must enter new password twice click save. It should say that the save was successful. This has been tested with roundcube-0.8.4 and confirmed to work. I have also tested it with roundcube-0.8.5 and currently is this setup is not working correctly.

23 Securing our Ubuntu Server
 23.1 Secure shared memory.
·         /dev/shm can be used in an attack against a running service, such as httpd. Modify /etc/fstab to make it more secure.
·         Open a Terminal Window and enter the following :
sudo nano /etc/fstab
·         Add the following line and save. You will need to reboot for this setting to take effect :
tmpfs     /dev/shm     tmpfs     defaults,noexec,nosuid     0     0

23.2 Protect su by limiting access only to admin group.
·         To limit the use of su by admin users only we need to create an admin group, then add users and limit the use of su to the admin group.
·         Add a admin group to the system and add your own admin username to the group by replacing <YOUR ADMIN USERNAME> below with your admin username.
·         Open a terminal window and enter:
sudo groupadd admin
sudo usermod -a -G admin <YOUR ADMIN USERNAME>
sudo dpkg-statoverride --update --add root admin 4750 /bin/su

23.3 Harden network with sysctl settings.
sudo nano  /etc/sysctl.conf
·         Edit the /etc/sysctl.conf file to read as follows :
#
# /etc/sysctl.conf - Configuration file for setting system variables
# See /etc/sysctl.d/ for additional system variables
# See sysctl.conf (5) for information.
#

#kernel.domainname = example.com

# Uncomment the following to stop low-level messages on console
#kernel.printk = 3 4 1 3

##############################################################3
# Functions previously found in netbase
#

# Uncomment the next two lines to enable Spoof protection (reverse-path filter)
# Turn on Source Address Verification in all interfaces to
# prevent some spoofing attacks
net.ipv4.conf.default.rp_filter=1
net.ipv4.conf.all.rp_filter=1

# Uncomment the next line to enable TCP/IP SYN cookies
# See http://lwn.net/Articles/277146/
# Note: This may impact IPv6 TCP sessions too
net.ipv4.tcp_syncookies=1
net.ipv4.tcp_max_syn_backlog = 2048
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 5

# Uncomment the next line to enable packet forwarding for IPv4
net.ipv4.ip_forward=1
# Uncomment the next line to enable packet forwarding for IPv6
#  Enabling this option disables Stateless Address Autoconfiguration
#  based on Router Advertisements for this host
#net.ipv6.conf.all.forwarding=1


###################################################################
# Additional settings - these settings can improve the network
# security of the host and prevent against some network attacks
# including spoofing attacks and man in the middle attacks through
# redirection. Some network environments, however, require that these
# settings are disabled so review and enable them as needed.
#
# Do not accept ICMP redirects (prevent MITM attacks)
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0
# _or_
# Accept ICMP redirects only for gateways listed in our default
# gateway list (enabled by default)
# net.ipv4.conf.all.secure_redirects = 1
#
# Do not send ICMP redirects (we are not a router)
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
#
# Do not accept IP source route packets (we are not a router)
net.ipv4.conf.all.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv6.conf.default.accept_source_route = 0
#
# Log Martian Packets
net.ipv4.conf.all.log_martians = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
#
·         To reload sysctl with the latest changes, enter:
sudo sysctl -p

23.4 Disable Open DNS Recursion – BIND DNS Server.
·         Open a Terminal and enter the following :
sudo nano /etc/bind/named.conf.options
·         Add the following to the Options section :
recursion no;
·         Restart BIND DNS server. Open a Terminal and enter the following :
sudo /etc/init.d/bind9 restart

23.5 Prevent IP Spoofing
·         Open a Terminal and enter the following :
sudo nano /etc/host.conf
·         Add or edit the following lines :
order bind,hosts
nospoof on

23.6 Harden PHP for security
·         Edit the php.ini file :
sudo nano /etc/php5/apache2/php.ini
·         Add or edit the following lines :
disable_functions = exec,system,shell_exec,passthru
register_globals = Off
expose_php = Off
magic_quotes_gpc = On

23.7 Web Application Firewall-ModSecurity and ModEvasive
1. Install ModSecurity on your server.
·         Install the dependencies. Open the Terminal Window and enter :
sudo apt-get install libxml2 libxml2-dev libxml2-utils
sudo apt-get install libaprutil1 libaprutil1-dev
·         64bit users please note - Because of this bug you need to create a symbolic link to libxml2.so.2 or the installation will report the file missing and fail.
ln -s /usr/lib/x86_64-linux-gnu/libxml2.so.2 /usr/lib/libxml2.so.2
·         Now install ModSecurity
sudo apt-get install libapache-mod-security
2. Configure ModSecurity rules.
·         Activate the recommended default rules to get things going. Configure as needed.
sudo mv /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf
·         The default folder for ModSecurity rules is /etc/modsecurity/ . All .conf files will be included and need to be configured as required.
·         We need to activate all the base rules and make sure they also get loaded. 
·         You might want to edit the SecRequestBodyLimit option in the modsecurity.conf file.
·         SecRequestBodyLimit limits the page request size and limits file uploads to 128 KB by default. Change this to the size of files you would accept uploaded to the server.
·         This settings is very important as it limits the size of all files that can be uploaded to the server. For CMS sites using Drupal or Wordpress this setting is the source of much pain. 
·         Open the Terminal Window and enter :
sudo nano /etc/modsecurity/modsecurity.conf
·         First activate the rules by editing the SecRuleEngine option and set to On.
SecRuleEngine On
·         Edit the following to option to increase the request limit to 16 MB and save the file :
SecRequestBodyLimit 16384000
SecRequestBodyInMemoryLimit 16384000
3. Download and install the latest OWASP Core Rule Set.
·         We need to download and install the latest OWASP ModSecurity Core Rule Set from the project website
·         We will also activate the default CRS config file modsecurity_crs_10_setup.conf.example
·         Open the Terminal Window and enter :
cd /tmp
sudo wget http://downloads.sourceforge.net/project/mod-security/modsecurity-crs/0-CURRENT/modsecurity-crs_2.2.5.tar.gz
sudo tar -zxvf modsecurity-crs_2.2.5.tar.gz
sudo cp -R modsecurity-crs_2.2.5/* /etc/modsecurity/
sudo rm modsecurity-crs_2.2.5.tar.gz
sudo rm -R modsecurity-crs_2.2.5
sudo mv /etc/modsecurity/modsecurity_crs_10_setup.conf.example  /etc/modsecurity/modsecurity_crs_10_setup.conf
·         Now we create symbolic links to all activated base rules. Open a terminal window and enter :
cd /etc/modsecurity/base_rules
for f in * ; do sudo ln -s /etc/modsecurity/base_rules/$f /etc/modsecurity/activated_rules/$f ; done
cd /etc/modsecurity/optional_rules
for f in * ; do sudo ln -s /etc/modsecurity/optional_rules/$f /etc/modsecurity/activated_rules/$f ; done 
·         Now add these rules to Apache2. Open a terminal window and enter:
sudo nano /etc/apache2/mods-available/mod-security.conf
·         Add the following to towards the end of the file with other includes  and save the file :
Include "/etc/modsecurity/activated_rules/*.conf"
4. Check if ModSecurity is enabled and restart Apache.
·         Before restarting Apache2 check if the modules has been loaded.
·         Open the Terminal Window and enter :
sudo a2enmod headers
sudo a2enmod mod-security
·         Then restart the Apache2 webserver :
sudo /etc/init.d apache2 restart
·         OR
service apache2 restart
5. Install ModEvasive.
·         Open the Terminal Window and enter :
sudo apt-get install libapache2-mod-evasive
6. Create log file directory for mod_evasive.
·         Open the Terminal Window and enter :
sudo mkdir /var/log/mod_evasive
·         Change the log folder permissions :
sudo chown www-data:www-data /var/log/mod_evasive/
7. Create mod-evasive.conf file and configure ModEvasive.
·         Open the Terminal Window and enter :
sudo nano /etc/apache2/mods-available/mod-evasive.conf
·         and add the following, changing the email value, and other options below as required :
<ifmodule mod_evasive20.c>
   DOSHashTableSize 3097
   DOSPageCount  2
   DOSSiteCount  50
   DOSPageInterval 1
   DOSSiteInterval  1
   DOSBlockingPeriod  10
   DOSLogDir   /var/log/mod_evasive
   DOSEmailNotify  EMAIL@DOMAIN.com
   DOSWhitelist   127.0.0.1
</ifmodule>
8. Check if ModEvasive is enabled and restart Apache.
·         Before restarting Apache2 check if the module has been loaded.
·         Open the Terminal Window and enter :
sudo a2enmod mod-evasive
·         Then restart the Apache2 webserver :
sudo /etc/init.d/apache2 restart

There is one exception that needs to be made as modsecurity will cause phpmyadmin to fail with different tasks such as logging in. There may be another more secure workaround for this but it was the only way that I could find that would allow phpmyadmin to work correctly. If anyone has the correct fix for this please post a comment on this matter.
Edit /etc/apache2/conf.d/phpmyadmin.conf
nano /etc/apache2/conf.d/phpmyadmin.conf
You will need to add SecRuleEngine Off to the first directory section as follows:
<Directory /usr/share/phpmyadmin>
        Options FollowSymLinks
        DirectoryIndex index.php
        SecRuleEngine Off
        <IfModule mod_php5.c>
                AddType application/x-httpd-php .php

                php_flag magic_quotes_gpc Off
                php_flag track_vars On
                php_flag register_globals Off
                php_admin_flag allow_url_fopen Off
                php_value include_path .
                php_admin_value upload_tmp_dir /var/lib/phpmyadmin/tmp
                php_admin_value open_basedir /usr/share/phpmyadmin/:/etc/phpmyadmi$
        </IfModule>

</Directory>


24 Configuring daily/weekly/monthly server backups with Rsync
For my setup I have a 2TB external USB hard drive formatted as ext4. The reason behind this is that Rsync will not be able to preserve permissions, symbolic links or owners for files or directories if it is not backed up to a ext4 partition. You could backup to an NTFS drive but you would lose all permissions, symbolic links and owners for files and directories.
If you have an external USB hard drive the easiest way to format it from a windows machine is to use MiniTool Partition Wizard, which can be downloaded at http://download.cnet.com/MiniTool-Partition-Wizard-Home-Edition/3001-2094_4-10962200.html?spi=109ba3d834f92183390798338fec097d It is fairly easy to use and self-explanatory. If you have any questions please leave a comment and I will give you further instructions on how to use it to format the external drive.
Once you have a formatted USB drive we need to mount it so that it can be utilized.
We can check to see if it is mounted by running the command fdisk –l on my system it shows up as /dev/sdb1
I then run the command : df –h which shows me the partition tables and I can see that /dev/sdb1 is correct and showing the correct amount of space.
# df -h
Filesystem             Size  Used Avail Use% Mounted on
/dev/mapper/mail-root  1.4T  2.5G  1.3T   1% /
udev                   6.9G  4.0K  6.9G   1% /dev
tmpfs                  2.8G  352K  2.8G   1% /run
none                   5.0M     0  5.0M   0% /run/lock
tmpfs                  6.9G     0  6.9G   0% /run/shm
/dev/sdb1              1.8T  2.1G  1.7T   1% /mnt
/dev/sda1              228M   47M  169M  22% /boot
When all of that is in place you will need to create some directories for backing up to.

Run the command:  mkdir /mnt/Backups

Then you will need to edit  /etc/fstab
nano /etc/fstab
add the entry   /dev/sdb1  /mnt/Backups    auto
save the file and then run mount  -a

Next we need to create a few more directories since this drive will be used for server backups as well as database backups
mkdir /mnt/Backups/server_backups/daily
mkdir /mnt/Backups/server_backups/weekly
mkdir /mnt/Backups/server_backups/monthly
mkdir /mnt/Backups/mysql_backups
You are now ready to schedule the backups through cron so they can run automated.
Run the following command:  crontab –e make a choice of editor you wish to use. I prefer nano.

Warning: When using the –delete flag be sure to check your command twice. If you reverse the source with the destination you will sync your data with an empty folder. You will be left with two empty folders! The –delete flag helps to insure that files that don’t exist either on the source or in the backups get removed.
An example is $ rsync –av /path/to/source  /mnt/Backups/server_backups/daily
The following is a breakdown of the scheduling for those of you who are not familiar with cron.
*    *    *    *    *  command to be executed
┬    ┬    ┬    ┬    ┬
│    │    │    │    │
│    │    │    │    │
│    │    │    │    └───── day of week (0 - 7) (0 or 7 are Sunday, or use names)
│    │    │    └────────── month (1 - 12)
│    │    └─────────────── day of month (1 - 31)
│    └──────────────────── hour (0 - 23)
└───────────────────────── min (0 - 59)
I use the --exclude flag to keep from backing up unnecessary directories. Note: you must add an --exclude for each directory you choose to exclude from the backup


For the daily backup:
00 23 * * * rsync -av --delete --exclude=/mnt --exclude=/proc --exclude=/dev --exclude=/sys --exclude=/tmp --exclude=/media / /mnt/Backups/server_backups/daily

For the Weekly backup:
00 3  * * 7 rysnc -av --delete /mnt/Backups/server_backups/daily /mnt/Backups/server_backups/weekly

For the Monthly backup:
00 6  1 * * rysnc tar -cvjf /mnt/Backups/server_backups/monthly/monthly_$(date +%Y%m%d).tar.bz2 /mnt/Backups/server_backups/daily

The monthly backup is compressed with bzip and created with the date so that the file will not be overwritten when the next monthly backup runs.

25 Configuring Automysqlbackup
1. Install AutoMySQLBackup:
 apt-get install automysqlbackup
2. Configure AutoMySQLBackup:
nano /etc/default/automysqlbackup
3. See the configuration below: the only thing I change in this file is the backup directory.
I set it to /mnt/Backups/mysql_backups which is the directory I created earlier when setting up my server backups
[...]
# Host name (or IP address) of MySQL server e.g localhost
#For remote database, fill the domain or ip address
DBHOST=localhost
[...]
# List of DBNAMES for Daily/Weekly Backup e.g. “DB1 DB2 DB3″
# The following is a quick hack that will find the names of the databases by
# reading the mysql folder content. Feel free to replace by something else.
#DBNAMES=”db_ispconfig web1 web2 web3″
DBNAMES=`find /var/lib/mysql -mindepth 1 -maxdepth 1 -type d | cut -d’/’ -f5 | grep -v ^mysql\$ | tr \\\r\\\n ,\ `
[...]
# Backup directory location e.g /
backups
# Folders inside this one will be created (daily, weekly, etc.), and the
# subfolders will be database names.
BACKUPDIR=”/
mnt/Backups/mysql_backups#BACKUPDIR=”/path/to/backup/folder/”
[...]
# Email Address to send mail to? (user@domain.com)
MAILADDR=”user@domain.com”
[...]
4. Run AutoMySQLBackup:
4. Run AutoMySQLBackup:
automysqlbackup
5. Open the backup folder (/mnt/Backups/mysql_backups)
ls -l /mnt/Backups/mysql_backups
6. You will see the backup files. It will create directories for daily/weekly/monthly automatically

7. Add it to cron to run it automatically.
crontab –e   00 22 * * * automysqlbackup save and exit


26 Nic Bonding with ifenslave
This setup is assuming you have two network cards installed in your system. If you don’t you can skip this section.
Bonding is a method of grouping or aggregating Ethernet interfaces to provide higher throughput and/or fault tolerance. To use bonding in Linux, you’ll need to install the ‘ifenslave’ package. In Ubuntu you’d run:
sudo apt-get install ifenslave
With the package installed, you can being creating your bond interface. In the following example, two NICs are aggregated and as a bonus, we create virtual interface for an additional IP address:
auto eth0
iface eth0 inet manual
bond-master bond0
auto eth1
iface eth1 inet manual
bond-master bond0
auto bond0
iface bond0 inet static
mtu 9000
address 192.168.0.1
netmask 255.255.255.0
network 192.168.0.0
broadcast 192.168.0.255
gateway 192.168.0.254
dns-nameservers 192.168.0.254
bond-miimon 50
bond-mode balance-rr
bond-slaves none
auto bond0:1
iface bond0:1 inet static
address 192.168.0.2
netmask 255.255.255.0
network 192.168.0.0
broadcast 192.168.0.255
gateway 192.168.0.254
dns-nameservers 192.168.0.254
Youcan can also set a high MTU if your NIC supports it. Linux bonding supports seven modes:
·         Mode 0 (balance-rr)
·         Mode 1 (active-backup)
·         Mode 2 (balance-xor)
·         Mode 3 (broadcast)
·         Mode 4 (802.3ad)
·         Mode 5 (balance-tlb)
·         Mode 6 (balance-alb)
Some modes require configuration on the switch as well, particularly for Mode 4. Modes 0 and 1 should provide fault tolerance and load balancing to suit most applications.


27 Installing webmin
Webmin is a web-based interface for system administration for Unix. Using any modern web browserhttp://images.intellitxt.com/ast/adTypes/icon1.png, you can setup user accounts, Apache, DNS, file sharing and much more. Webmin removes the need to manually edit Unix configuration files like /etc/passwd, and lets you manage a system from the console or remotely.
Preparing your system
Open the terminal and run the following command
sudo apt-get install perl libnet-ssleay-perl openssl libauthen-pam-perl libpam-runtime libio-pty-perl apt-show-versions python
Now you need to dpwnload webmin deb package using the following command
wget http://sourceforge.net/projects/webadmin/files/webmin/1.610/webmin_1.610_all.deb
Install downloaded package using the following command
sudo dpkg -i webmin_1.610_all.deb
This will install webmin now you need to access https://ubuntu-serverip:10000
Ubuntu in particular don't allow logins by the root user by default. However, the user created at system installation time can use sudo to switch to root. Webmin will allow any user who has this sudo capability to login with full root privileges.
Once you logged in you should see similar to the following screen


References: