Archive for the ‘LAMP Server Setup’ Category

LAMP Server Maintenance

Sunday, August 16th, 2009

Optimize tables overnight

Graphs with free memory everyday (with gnuplot and/or Ganglia)

clever report of the most frequent Apache errors

Cronjob to check Apache and MySQL are up, otherwise start them

Cronjob to check the space left

Make sure you don’t use personal email addresses for the monitoring/alerts (ie. mike, dan) but use aliases like: admin, developers

APC - Installing It On CentOS

Friday, January 30th, 2009

yum install php-pear
yum install php-devel
yum install httpd-devel

Edit the file /usr/share/pear/pearcmd.php and add the following at the beginning:
@ini_set(’memory_limit’, ‘16M’);
otherwise you’ll probably get a fatal error whilst building the extension:
pecl install apc

Now configure PHP to use the new extension.
Create the file /etc/php.d/apc.ini and in that file put:
extension=apc.so

Now restart apache
sudo /etc/init.d/httpd greaceful

In the future, if new versions of APC are released, you can easily upgrade them using:
sudo pecl upgrade apc

Now, to configure APC there are two options: either edit php.ini, or add apc.ini to the php.d folder. Either way, I use the following:

extension = apc.so
apc.enabled = 1
apc.shm_size = 48
apc.include_once_override = 1
apc.mmap_file_mask = /tmp/apc.XXXXXX

It’s very important to choose the size of the cache (apc.shm_size) because when it gets full, APC empties it.

Finally I restart apache again (service httpd restart) and verify that php -v returns the same output. If I want to verify that apc is working, I locate apc.php on the server and then copy it to a web-accessible directory. Then I load that script in my browser, and if I can see pretty graphs, then it’s working.

APC works thanks to share memory (RAM).

apc.shm_size aside, it’s also important to set correctly the number of sectors and apc.stat that it’s about whether to check the timestamp of the files (before serving) to re-cache them (see documentation).

IMPORTANT! I had this problem: the cache was flushed completely after getting full. That was because I need to set:
apc.ttl and apc.user_ttl to a non-zero value (for example 7200). In your vim /etc/php.d/apc.ini:
apc.ttl=7200
apc.user_ttl=7200

Linux - Check Apache and MySQL Are Running, Otherwise Start Them

Wednesday, July 23rd, 2008

The file is also reachable through this link: lamp-guarddog

#!/bin/sh
# Check whether Apache or/and Mysql server are down. If so, it starts them.

SERVICE_HTTP=’/usr/sbin/httpd’
SERVICE_MYSQL=’/usr/libexec/mysqld’
ADMIN_EMAIL=’danieleocchipinti.it@gmail.com’

if ps ax | grep -v grep | grep $SERVICE_HTTP > /dev/null
then
#echo “$SERVICE_HTTP is running”
a=0
else
echo “$SERVICE_HTTP is not running”
echo “$SERVICE_HTTP is not running!” | mail -s “$SERVICE_HTTP down” $ADMIN_EMAIL
service httpd start
fi

if ps ax | grep -v grep | grep $SERVICE_MYSQL > /dev/null
then
#echo “$SERVICE_MYSQL is running”
a=0
else
echo “$SERVICE_MYSQL is not running”
echo “$SERVICE_MYSQL is not running!” | mail -s “$SERVICE_MYSQL down” $ADMIN_EMAIL
service mysqld start
fi

Fast LAMP Server - Debian Lenny

Tuesday, May 20th, 2008

apt-get install apache2 php5 libapache2-mod-php5
apt-get install php5-xsl php5-gd php5-cli
apt-get install mysql-server mysql-client php5-mysql

  • In order to enable the use of .htaccess, you need to edit this file:

    /etc/apache2/sites-available/default

    In the section <Directory /var/www/>, change to:

    AllowOverride all
  • In order to enable the Rewrite Module:

    ln -s /etc/apache2/mods-available/rewrite.load /etc/apache2/mods-enabled/rewrite.load
    /etc/init.d/apache2 reload

Secure PHP & Apache Configuration

Saturday, May 10th, 2008

PHP

  • Disable error messages
  • expose_php Off

    Check you can’t get info by doing telnet localhost 80 and then issueing: HEAD / HTTP/1.0

  • session.use_only_cookies = 1
  • allow_url_fopen Off

    [if you don’t really need the opposite]

  • register_globals = Off
  • magic_quotes_gpc = ???

    This directive was introduced for improving security preventing SQL Injections, and it does. But it’s much better to put it Off and take care of escaping characters by yourself inside the PHP code for two main reasons. It doesn’t use a native function for your database and adds a level of complexity (infact if one of your input data can contain some quotes you’d need to use the stripslashes function )

Apache

  • ServerTokens ProductOnly
  • ServerSignature Off

Check you can’t get info by doing telnet localhost 80 and then issueing: HEAD / HTTP/1.0

In a shared environment you could use these directives as well (for PHP):

  • disable_functions
  • enable_dl
  • memory_limit
  • max filesize in uploading
  • safemode ON

LAMP on Ubuntu

Saturday, April 5th, 2008
apt-get install apache2
apt-get install php5 libapache2-mod-php5
apt-get install php5-xsl php5-gd
/etc/init.d/apache2 restart
apt-get install mysql-server
apt-get install libapache2-mod-auth-mysql php5-mysql phpmyadmin
apt-get install bind9
apt-get install php5-cli
ln -s /etc/apache2/mods-available/vhost_alias.load /etc/apache2/mods-enabled/vhost_alias.load
ln -s /etc/apache2/mods-available/rewrite.load /etc/apache2/mods-enabled/rewrite.load

Server Setup and LAMP Setup From Scratch with full UTF support (utf8)

Sunday, February 3rd, 2008

Set the clock
date MMDDhhmmYYYY
hwclock –systohc &

Where: M=month, D=day, h=hour, m=minute, Y=year
The latter command is essential: it copies the date into the BIOS and makes the change definitive

First steps
* echo “hostname_you_chose” > /etc/hostname
/bin/hostname -F /etc/hostname

Changing the hostname could be very different distro by distro.

* /etc/host.conf :
order hosts,bind
multi on
* /etc/hosts:
127.0.0.1 localhost.localdomain localhost
192.168.0.10 hostname_you_chose.localdomain hostname_you_chose
* Add these lines at the bottom of the file /etc/profile (or of the file .bashrc of an user - even root - whether you want these options applied just on a specific user):
alias ls=’ls –color’
alias rm=”rm -i”
alias halt=”echo command disabled by alias”
alias ifdown=”echo command disabled by alias”
alias iptables=”echo you’re working on the server!”
alias exit=”/etc/init.d/general_check.sh; exit”

where /etc/init.d/general_check.sh is a script that performs some important check (permission, file existance, …) to make sure you’re not ruining anything in your last session.

N.B.: in the above commands, it’s very important not to use extra spaces between words.

Cleaning up the system

* nmap server_ip_address [to find out the open ports]
* Disable portmap (if active). It should be binded to the port 111 and refers to the service rpcbind.
* Disable fingerd (if active)
* IMPORTANT: if you want to shutdown a service, it’s not sufficient you stop it but you must be sure there isn’t a symbolic link in /etc/rcX.d
* IMPORTANT: don’t uninstall at all the default MTA (for example exim4) because it could be essential for the local operations.

SSH e SCP

/etc/ssh/sshd_config: [both for improving security]
Port a_different_port_rather_than_the_default_one
PermitRootLogin no

Before restarting sshd, MAKE SURE there is a non-root user in your system who can connect via SSH (and test it in another terminal), otherwise you’re bust!!!!!!!!!!!!!!!!!!!!!!!!!!

useradd -g users -s /bin/bash daniele
passwd daniele

Apache

Change the default user and group owner of the apache processes. Let’s say, user: pippo and group: pippo.
groupadd pippo
useradd -g pippo -s /dev/null pippo

So in the configuration file:
User pippo
Group pippo
and through the command line:

In this way, the user pippo won’t be granted to login to the system and launch commands. These should increase the security.

Then, create a new user that will be the owner of all the web documents. It must belong to the group pippo so Apache can access the web documents as well.

useradd -g pippo -d /var/www/html/ -s /bin/bash dev

chown -R dev:pippo /var/www/html

chmod -R 770 /var/www/html

chown -R dev:pippo directory_that_contains_sessions_see_the_php_ini

Always in the configuration file, remember to disable potential directives for the generation of the log file for the rewrite module (unless you temporary need it for debugging) as it’s very computation intensive.

Always in the configuration file, check that DirectoryIndex directive contains:

index.html index.htm index.php

Remember to customize the error pages, for example:
ErrorDocument 404 /misc/error_pages/error_404.php
You can put it in the VirtualHost Section

MySQL

Set a (very hard to guess!) password for root
mysqladmin -u root password root_password_you_like
IMPORTANT: don’t use the same password as for the root user in Linux
You could need this for the changes to take effect:
mysqladmin -u root -p flush-privileges

MySQL allows anonymous login by default. To disable it, just Google on the MySQL documentation.

To access the server:
mysql -u root -p

IMPORTANT: take a look at the user table. Make sure any user has got a password and they can access the server only locally that is they have ‘localhost’ as host. You can modify this table through the GRANT command.

IMPORTANT: Set utf8_general_ci as the server default collation

IMPORTANT: The databases are stored in /var/lib/mysql

touch /var/log/mysqld_slow_queries.log
chown mysql:mysql /var/log/mysqld_slow_queries.log
chmod 640 /var/log/mysqld_slow_queries.log
In the my.cnf
log-slow-queries = /var/log/mysqld_slow_queries.log
long_query_time = 1
The above will log queries taking longer than one second to the specified log file.

PHP

If you’re confident no malicious scripts will be running, increase
max_execution_time
memory_limit

Make the services start at the boot

This is achieved by symbolic links in the directory related to the runlevels.

Make everything UTF8

  • httpd.conf:
    AddCharset UTF-8 .utf8
    AddDefaultCharset UTF-8
  • php.ini
    default_charset = “utf-8″
  • my.cnf
    character-set-server=utf8
    default-collation=utf8_unicode_ci

    Then, if you’re writing PHP scripts, soon after opening your connection to mysql, issue one of the following:
    SET NAMES ‘utf8′;
    OR, if you are running the mysqli extension:
    mysqli_set_charset(’utf8′);

  • Last suggestions

    * Make sure you gave the minimal permission to any file added or modified in the server
    * Set a cron job for backups
    * Make sure the log for cron is active. There should be a line to uncomment in the file /etc/syslog.conf or something similar. The log file should be /var/log/cron.log. Then restart the cron service.
    * Keep your system updated with security patches and new versions of the installed software.

LAMP Backup Script

Monday, January 28th, 2008

#!/bin/bash
#
# my_backup.sh V1.0
#
# An useful script that performs a variety of operations in order to backup different data.
# It’s a good starting point for your bespoke one

# Creating all the definitions
datestamp=$(date +’%Y%m%d%H%M%S’)
tarname=my_backup-$datestamp”.tgz”
tempdir_base=tmpbckdir$datestamp
tempdir=*/var/tmp_backups/*$tempdir_base
tempdir_db=$tempdir”/db”

# Creating the directories for the operations
mkdir $tempdir
mkdir $tempdir_db

# Backuping databases
mysqldump -u *superuser* -p*superuser_psw* *database1* | gzip –best > $tempdir_db/*database1*.sql.gz
mysqldump -u *superuser* -p*superuser_psw* *database2* | gzip –best > $tempdir_db/*database2*.sql.gz
mysqldump -u *superuser* -p*superuser_psw* *database3* | gzip –best > $tempdir_db/*database3*.sql.gz

# Backuping databases - There are a lot of databases called like this: user_user1, user_user2,…
cd /var/lib/mysql/
for i in $( echo user_* ); do
mysqldump -u *superuser* -p*superuser_psw* $i > $tempdir_db/$i.sql
done

# Backuping files
cp -ra *dir1* $tempdir/*dir1*
cp -ra *dir2* $tempdir/*dir2*

# Sending a mail with the content of a log file
mutt -s “log file” -a *file_path* *mail address* < *file_path*
# truncating the file
echo “” > *file_path*

# Storing the compressed backup in a local disk
mount /dev/hdc1 /mnt
cd /etc/sm_it
tar czf /mnt/$tarname $tempdir_base
umount /mnt

# Deleting the temp files
rm -r $tempdir

LAMP Backup Script

SELinux

Wednesday, January 9th, 2008

A good resource is:

http://www.crypt.gen.nz/selinux/faq.html

There, the most important thing is this.

It is important that server daemons are started within the correct context, if they are not then they will probably not run properly.

For Fedora and RedHat Enterprise Linux, use the normal command,

service (name) start/stop

For Debian and Gentoo, use the run_init command to run scripts in /etc/init.d within the correct context, for example sshd:

run_init /etc/init.d/sshd start

which starts up the sshd daemon. Note that run_init will prompt the user for their password before performing the function: this is to prevent unauthorised acces to the functionality such as being executed by a trojan program.

To know if selinux is installed

rpm -qa | grep selinux

To know if it is enabled

/usr/sbin/getenforce

Server: Setting a Firewall With Iptables

Sunday, January 6th, 2008
  • Copy the file iptables.sh in the directory /etc/init.d with these rules (but obviously you need to customize them).
  • Make the file executable.
  • Assuming the current run level is the second one:ln -s /etc/init.d/iptables.sh /etc/rc2.d/S97iptables
    Actually you should link the script in any runlevel to cover the case you change runlevel, even temporary.

******************************************************************

iptables script

******************************************************************

Useful Commands:
List of active rules:
iptables -L
Removes all the rules
iptables -F