LEMP 12.04 Functions

by obs
4 deployments · 0 still active · last rev. 3 years ago

This script does nothing on its own.

Compatible with: No distros currently supported
						#!/bin/bash
######
#LICENCE#
######
#Released under the BSD license http://www.opensource.org/licenses/bsd-license
#Copyright (c) 2011, Rowan Wookey <admin@rwky.net>
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
#1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
#2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
#3. Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
######
#Support
######
#For support please email admin@rwky.net
#Some functions are taken from http://www.linode.com/stackscripts/view/?StackScriptID=1 the license below applies to those
# Copyright (c) 2010 Linode LLC / Christopher S. Aker <caker@linode.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, 
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# * Neither the name of Linode LLC nor the names of its contributors may be
# used to endorse or promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGE.

function system_primary_ip {
	# returns the primary IP assigned to eth0
	if ifconfig | grep 'venet' > /dev/null
	then
		echo $(ifconfig "venet0:0" | awk -F: '/inet addr:/ {print $2}' | awk '{ print $1 }')
	else
		echo $(ifconfig eth0 | awk -F: '/inet addr:/ {print $2}' | awk '{ print $1 }')
	fi
}

function get_rdns {
	# calls host on an IP address and returns its reverse dns

	if [ ! -e /usr/bin/host ]; then
		aptitude -y install dnsutils > /dev/null
	fi
	echo $(host $1 | awk '/pointer/ {print $5}' | sed 's/\.$//')
}

function get_rdns_primary_ip {
	# returns the reverse dns of the primary IP assigned to this system
	echo $(get_rdns $(system_primary_ip))
}

function prep_system
{
#update system
#setup hostname
if [ -z "$HOSTNAME" ]
then
export HOSTNAME=$(get_rdns_primary_ip)
fi
HOST=$(echo $HOSTNAME | sed 's/\(\[a-z0-9\]\)*\..*/\1/')
echo "$HOST" >  /etc/hostname
echo "`system_primary_ip` $HOSTNAME $HOST" >> /etc/hosts
start hostname
echo "/usr/sbin/nologin" >> /etc/shells
locale-gen en_US en_US.UTF-8 en_GB.UTF-8 en_GB
dpkg-reconfigure locales
#set timezone to UTC
ln -s -f /usr/share/zoneinfo/UTC /etc/localtime
service cron stop
apt-get update
apt-get -y install aptitude
aptitude -y purge bind9 xinetd samba
aptitude -y safe-upgrade
if [ -f /etc/default/saslauthd ]
then
	service saslauthd stop
	sed -i 's/START=yes/START=no/' /etc/default/saslauthd
fi
aptitude -y install python-software-properties rsyslog
}

function install_nginx {
#add nginx ppa
if [ $NGINX_VERSION == "Yes" ]
then
add-apt-repository -y ppa:nginx/stable
aptitude update
fi
#Install nginx
aptitude -y install nginx
cat <<EOT > /etc/nginx/fastcgi_config
fastcgi_intercept_errors on;
fastcgi_ignore_client_abort on;
fastcgi_connect_timeout 60;
fastcgi_send_timeout 180;
fastcgi_read_timeout 180;
fastcgi_buffer_size 128k;
fastcgi_buffers 4 256k;
fastcgi_busy_buffers_size 256k;
fastcgi_temp_file_write_size 256k;
fastcgi_max_temp_file_size 0;
fastcgi_index index.php;
EOT
cat <<EOT > /etc/nginx/sites-available/nginx_status
server {
	listen 127.0.0.1:80;
	location /nginx_status {
    		stub_status on;
	    access_log off;
 	 }   
}
EOT
ln -sf /etc/nginx/sites-available/nginx_status /etc/nginx/sites-enabled/nginx_status
mkdir -p /etc/munin/plugins/
ln -sf /usr/share/munin/plugins/nginx_request /etc/munin/plugins/nginx_request
ln -sf /usr/share/munin/plugins/nginx_status /etc/munin/plugins/nginx_status
mkdir -p /etc/munin/plugin-conf.d/
cat <<EOT >> /etc/munin/plugin-conf.d/nginx
[nginx*]
env.url http://localhost/nginx_status
EOT
service nginx stop
sed -i 's/# gzip_types/gzip_types/' /etc/nginx/nginx.conf
sed -i 's/# gzip_vary/gzip_vary/' /etc/nginx/nginx.conf
}

function notification_email {
#mail root to confirm installation
mail -s "Server "`cat /etc/hostname`" setup complete" root <<EOT
Your server setup is complete, if you encounter problems or would like commercial support email admin@rwky.net. Your server will reboot shortly after this email is sent.
EOT
$(shutdown -r +1) &
}

function install_php_fpm {
#Install PHP and common extensions
aptitude -y install php5-fpm php5-cli php5-curl php5-gd php5-mcrypt php5-mysql php5-sqlite php-apc
#configure php to run as fcgi under user www-data on port 8000 edit init script to change this
sed -i 's/short_open_tag = On/short_open_tag = Off/' /etc/php5/fpm/php.ini
sed -i 's/disable_functions =/disable_functions = dl/' /etc/php5/fpm/php.ini
sed -i 's/expose_php = On/expose_php = Off/' /etc/php5/fpm/php.ini
sed -i 's/memory_limit = 128M/memory_limit = 32M/' /etc/php5/fpm/php.ini
sed -i 's/;arg_separator.output/arg_separator.output/' /etc/php5/fpm/php.ini
sed -i 's/;date.timezone =/date.timezone = UTC/' /etc/php5/fpm/php.ini
sed -i 's/session.name = PHPSESSID/session.name = SESSID/' /etc/php5/fpm/php.ini
sed -i 's@;error_log = syslog@error_log = /var/log/php/error.log@' /etc/php5/fpm/php.ini
mkdir -p /var/log/php/
chown www-data /var/log/php/
sed -i 's/#/;/' /etc/php5/conf.d/mcrypt.ini
}

function install_mysql
{
#Install mysql
echo "mysql-server-5.5 mysql-server/root_password password $MYSQL_PASSWORD" | debconf-set-selections
echo "mysql-server-5.5 mysql-server/root_password_again password $MYSQL_PASSWORD" | debconf-set-selections
aptitude -y install mysql-server mysql-client
innodb_memory=$(awk '/MemTotal/ {print int($2/3072)}' /proc/meminfo)
cat <<EOT > /etc/mysql/conf.d/innodb.cnf
[mysqld]
innodb_file_per_table
innodb_buffer_pool_size=${innodb_memory}M
innodb_additional_mem_pool_size=8M
EOT
#set charset to utf8
cat <<EOT > /etc/mysql/conf.d/charset.cnf 
[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci
EOT
#enable slow query logging to table compatible with mysql workbench
cat <<EOT > /etc/mysql/conf.d/logging.cnf
[mysqld]
slow_query_log = 1
slow_query_log_file     = /var/log/mysql/mysql-slow.log
long_query_time = 1
log-queries-not-using-indexes
log-output=TABLE
EOT
#make pid file static name across installations
cat <<EOT > /etc/mysql/conf.d/pid.cnf
[mysqld]
pid-file = /var/lib/mysql/mysqld.pid
EOT
#limit number of simultanious connections to 20
cat <<EOT > /etc/mysql/conf.d/connections.cnf
[mysqld]
max_connections = 20
EOT
#drop myisam specific settings since I'm assuming you're using innodb
cat <<EOT > /etc/mysql/conf.d/myisam.cnf
[mysqld]
key_buffer_size = 256k
read_buffer_size = 256k
read_rnd_buffer_size = 256k
EOT
#add root password to .my.cnf to prevent prompting
cat <<EOT > /root/.my.cnf
[client]
user=root
password=$MYSQL_PASSWORD
EOT
chmod 0400 /root/.my.cnf
service mysql stop
}


function install_postfix
{
#Install postfix
echo "postfix postfix/main_mailer_type select Internet Site" | debconf-set-selections
echo "postfix postfix/mailname string $HOSTNAME" | debconf-set-selections
echo "postfix postfix/destinations string localhost.localdomain, localhost, $HOSTNAME" | debconf-set-selections
service sendmail stop
aptitude -y purge sendmail-base sendmail-bin sendmail-cf sendmail-doc
aptitude -y install postfix mailutils
/usr/sbin/postconf -e "inet_interfaces = loopback-only"
#configure root alias
echo "root: $ROOT_EMAIL" >> /etc/aliases
echo "$USER_NAME: root" >> /etc/aliases
echo $HOSTNAME > /etc/mailname
/usr/bin/newaliases
service postfix stop
}

function configure_ssh {
#setup ssh
#add ssh key
sudo -u $USER_NAME mkdir -p /home/$USER_NAME/.ssh
sudo -u $USER_NAME echo "${USER_SSHKEY}" >> /home/$USER_NAME/.ssh/authorized_keys
mkdir -p /root/.ssh/
echo "${USER_SSHKEY}" >> /root/.ssh/authorized_keys
chmod 0600 /home/$USER_NAME/.ssh/authorized_keys /root/.ssh/authorized_keys
chown $USER_NAME:$USER_NAME /home/$USER_NAME/.ssh/authorized_keys
sed -i "s/Port 22/Port $SSH_PORT/" /etc/ssh/sshd_config #set ssh port
#enable internal sftp for chrooting
sed -i 's@Subsystem sftp /usr/lib/openssh/sftp-server@Subsystem sftp internal-sftp@' /etc/ssh/sshd_config
if [[ "$SSH_ALLOW_USERS" != *root* ]]
then
sed -i 's/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
else
sed -i 's/PermitRootLogin yes/PermitRootLogin without-password/' /etc/ssh/sshd_config
fi
if [ "$USER_SSHKEY" != "" ]
then
sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config #disable ssh password auth if $USER_SSHKEY is not empty
fi
sed -i 's/X11Forwarding yes/X11Forwarding no/' /etc/ssh/sshd_config #disable xforwarding
echo "AllowUsers $USER_NAME $SSH_ALLOW_USERS" >> /etc/ssh/sshd_config #only allow access from $USER
}

function configure_user
{
#configure ssh/sudo 
useradd -m -s /bin/bash $USER_NAME #add user account 
echo "$USER_NAME:$USER_PASSWORD" | chpasswd #setpassword
#add user to sudoers
echo "$USER_NAME ALL=(ALL) ALL" >> /etc/sudoers
usermod -a -G adm $USER_NAME
#lock out root
passwd -l root
}

function install_shorewall
{
#sets up shorewall firewall
aptitude -y install shorewall shorewall6
cp /usr/share/doc/shorewall/examples/one-interface/* /etc/shorewall/
sed -i 's/BLACKLISTNEWONLY=Yes/BLACKLISTNEWONLY=No/' /etc/shorewall/shorewall.conf
sed -i 's/REJECT/DROP/' /etc/shorewall/policy
if [ "$WEBSERVER" != "None" ]
then
echo "#accept http/s" >> /etc/shorewall/rules
echo "ACCEPT		net		\$FW:`system_primary_ip`		tcp	80" >> /etc/shorewall/rules
echo "ACCEPT		net		\$FW:`system_primary_ip`		tcp	443" >> /etc/shorewall/rules
fi
echo '#accept ssh and ratelimit to 5 connections per miniute per ip' >> /etc/shorewall/rules
echo "ACCEPT		net		\$FW:`system_primary_ip`		tcp	$SSH_PORT	-		-		s:ssh:1/min:1" >> /etc/shorewall/rules
sed -i 's/STARTUP_ENABLED=No/STARTUP_ENABLED=Yes/' /etc/shorewall/shorewall.conf
sed -i 's/startup=0/startup=1/' /etc/default/shorewall

#disable ipv6 by default
cp /usr/share/doc/shorewall6/examples/one-interface/* /etc/shorewall6/
sed -i 's/BLACKLISTNEWONLY=Yes/BLACKLISTNEWONLY=No/' /etc/shorewall6/shorewall6.conf
sed -i 's/REJECT/DROP/' /etc/shorewall6/policy
sed -i 's/STARTUP_ENABLED=No/STARTUP_ENABLED=Yes/' /etc/shorewall6/shorewall6.conf
sed -i 's/startup=0/startup=1/' /etc/default/shorewall6


}

function install_monit
{
#install and enable monit
 aptitude -y install monit
 sed -i 's/startup=0/startup=1/' /etc/default/monit
 mkdir -p /etc/monit/conf.d/
 sed -i "s/# set daemon  120/set daemon 120/" /etc/monit/monitrc
 sed -i "s/#   with start delay 240/with start delay 240/" /etc/monit/monitrc
 sed -i "s/# set logfile syslog facility log_daemon/set logfile \/var\/log\/monit.log/" /etc/monit/monitrc
 sed -i "s/# set mailserver mail.bar.baz,/set mailserver localhost/" /etc/monit/monitrc
 sed -i "s/# set eventqueue/set eventqueue/" /etc/monit/monitrc
 sed -i "s/#     basedir \/var\/monit/basedir \/var\/monit/" /etc/monit/monitrc
 sed -i "s/#     slots 100 /slots 100/" /etc/monit/monitrc
 sed -i "s/# set alert sysadm@foo.bar/set alert root@localhost reminder 180/" /etc/monit/monitrc
 sed -i "s/# set httpd port 2812 and/ set httpd port 2812 and/" /etc/monit/monitrc
 sed -i "s/#    use address localhost/use address localhost/" /etc/monit/monitrc
 sed -i "s/#    allow localhost/allow localhost/" /etc/monit/monitrc
 sed -i "s/# set mail-format { from: monit@foo.bar }/set mail-format { from: monit@`hostname -f` }/" /etc/monit/monitrc
 service monit stop
}

function install_munin
{
#install munin
aptitude -y install munin munin-node libcache-cache-perl libdbd-mysql-perl
sed -i 's/host \*/host 127.0.0.1/' /etc/munin/munin-node.conf
sed -i "s/localhost.localdomain/`hostname -f`/" /etc/munin/munin.conf
echo "munin: root" >> /etc/aliases
sed -i "s#\[mysql\*\]#[mysql*]\nenv.mysqladmin /usr/bin/mysqladmin#" /etc/munin/plugin-conf.d/munin-node
rm -f /etc/munin/plugins/nfs*
ln -sf /usr/share/munin/plugins/postfix_mailstats /etc/munin/plugins/
ln -sf /usr/share/munin/plugins/netstat /etc/munin/plugins/
sed -i 's/log_level 4/log_level 2/' /etc/munin/munin-node.conf
sed -i 's/log_file .*/log_file Sys::Syslog/' /etc/munin/munin-node.conf
if [ -x /usr/bin/newaliases ]
then
/usr/bin/newaliases
fi
service munin-node stop
}

function install_security
{
#install chrootkit rkhunter logwatch
aptitude -y install chkrootkit rkhunter logwatch logcheck libsys-cpu-perl build-essential cpanminus
cpanm 'Sys::MemInfo'
sed -i 's/#ALLOWHIDDENDIR=\/dev\/.initramfs/ALLOWHIDDENDIR=\/dev\/.initramfs/' /etc/rkhunter.conf
sed -i 's/#ALLOWHIDDENDIR=\/dev\/.udev/ALLOWHIDDENDIR=\/dev\/.udev/' /etc/rkhunter.conf
sed -i 's/DISABLE_TESTS="suspscan hidden_procs deleted_files packet_cap_apps apps"/DISABLE_TESTS="suspscan hidden_procs deleted_files packet_cap_apps apps os_specific"/' /etc/rkhunter.conf
rkhunter --propupd
sed -i 's/--output mail/--output mail --detail 10 --range "since 1 days ago" --archives --numeric --service All/' /etc/cron.daily/00logwatch
}

function install_tools
{
#install full vim, nano, less, htop (nice version of top), iotop (top for disk io), logrotate (rotates logs..), lynx (text webbrowser), mytop (top for mysql), screen (terminal emulator), sqlite3 (command line interface for sqlite databases)
aptitude -y install vim nano less htop iotop logrotate lynx mytop nmap screen sqlite3 cron-apt ntp curl pflogsumm bar apt-show-versions iftop
echo 'SYSLOGON="always"' >> /etc/cron-apt/config
echo 'MAILON="upgrade"' >> /etc/cron-apt/config
}

function install_ubuntu_stock_kernel
{
#installs ubuntu virtual kernel which works best on linode
#sets console to hvc0 so you can access via lish
#turns off barrier which breaks booting with 3.2+ kernels
#switches to ext4 but retains backwards compatablity with ext3
aptitude -y install linux-virtual grub
update-grub -y
sed -i 's#kopt=root=.* ro#kopt=root=/dev/xvda ro#' /boot/grub/menu.lst
sed -i 's#groot=.*#groot=(hd0)#' /boot/grub/menu.lst
sed -i 's/defoptions=quiet splash/defoptions=quiet console=hvc0/' /boot/grub/menu.lst
sed -i 's/# indomU=detect/# indomU=true/' /boot/grub/menu.lst
sed -i 's/noatime/barrier=0,noatime/' /etc/fstab
sed -i 's/ext3/ext4/' /etc/fstab
update-grub -y
chmod 0600 /boot/grub/menu.lst
cat <<EOT >/etc/init/hvc0.conf
# hvc - getty
#
# This service maintains a getty on hvc0 from the point the system is
# started until it is shut down again.

start on stopped rc RUNLEVEL=[2345]
stop on runlevel [!2345]

respawn
exec /sbin/getty -8 38400 hvc0
EOT
}

function set_root_profile
{
#Black       0;30     Dark Gray     1;30
#Blue        0;34     Light Blue    1;34
#Green       0;32     Light Green   1;32
#Cyan        0;36     Light Cyan    1;36
#Red         0;31     Light Red     1;31
#Purple      0;35     Light Purple  1;35
#Brown       0;33     Yellow        1;33
#Light Gray  0;37     White         1;37
cat <<EOT >> /root/.profile
PS1='\[\033[0;33m\]root@'
#add hostname
PS1=\$PS1\$(hostname -f)'\n'
#add ipv4 addresses
PS1=\$PS1\$(ifconfig | grep -v '127.0.0.1' | awk -F: '/inet addr:/ {print \$2}' | awk '{ print \$1 }')
#add ipv6 addresses
PS1=\$PS1'\n'\$(ifconfig | grep 'Global' | awk -F /  '/inet6 addr: / {print \$1}' | awk '{ print \$3 }')
#add current working dir and close colours
PS1=\$PS1'\n\$PWD:\$\033[00m\]\n'
export PS1
EOT

}

function cleanup
{
#disable services not required
if [ -f /etc/init/atd.conf ]
then
stop atd
mv /etc/init/atd.conf /etc/init/atd.conf.noexec
fi
if [ -f /etc/default/whoopsie ]
then
sed -i 's/true/false/' /etc/default/whoopsie
fi
update-locale
#tweak min free kbytes to get around page allocation failures on newer kernels
echo "vm.min_free_kbytes=6144" > /etc/sysctl.d/60-page.conf 
}