Securing a LAMP Server

bewgrosseteteΛογισμικό & κατασκευή λογ/κού

13 Δεκ 2013 (πριν από 3 χρόνια και 6 μήνες)

108 εμφανίσεις

Securing a LAMP server
1








Securing a LAMP Server

Technical Report














By: Denis Kucinic

For:
Michael Williamsyeagers

Securing a LAMP server
2


LINUX

3

APACHE

4

ETC
/
APACHE
2/
CONF
.
D
/
SECURITY

4

ETC
/
APACHE
2/
SITES
-
ENABLED
/000
-
DEFAULT

5

/
ETC
/
APACHE
/
MODS
-
ENABLED

6

C
ONFIGURATION CHANGES

6

M
ODULE ADDITIONS

7

MYSQL

10

PHP

10

CONFIGURATION CHANGES

11

SUHOSIN

11

CODE CHANGES

11

BIBLIOGRAPHY

13



Securing a LAMP server
3


Securing a LAMP server is not an easy task. It requires fundamental knowledge
in each of the four components, which requires a lot of research. The first step is
securing the Linux installation and installing the required LAMP components. In this
case, I w
ill be working with an Ubuntu server.
I learned extremely a lot about security
procedures to undergo while setting up a server. Some procedures were overlooked by
me in the past while some of the config files for the components were left wide
-
open
with sec
urity gaps.


To install the LAMP components you run the following command.

Apt
-
get install
apache2 php5 libapache2
-
mod
-
php5 mysql
-
server mysql
-
client
php5
-
mysql phpmyadmin


Linux

Securing the Linux distribution is rather easy compared to the other
components.
There is not much to it, but once completed, it provides a great magnitude of security.
To begin, denying anyone the ability to attempt to login as root from a SSH sessions
must be implemented. Editing /etc/ssh/sshd_config and changing the Perm
itRootLogin
to no provides that ability. Doing so, nobody can attempt to bruteforce root through SSH
because all attempts are automatically denied. Even if you know the root password, no
access is granted. In order to gain root you must SSH with a regular
user account and
run the su command.

The next implementation to do is the configuration of Ubuntu’s Uncomplicated
Firewall (ufw). UFW is used to provide ease of use for iptables configurations.
To begin
I ran

the following commands.

Installing UFW.

apt
-
get

install ufw


Turning on logging.

ufw logging on

Set default mode to deny. Anything not in the allow list is denied.

ufw default deny

Set the allow ports. 80 for HTTP, 22 for SSH, 443 for SSL.

ufw allow 80

ufw allow 22

ufw allow 443

Securing a LAMP server
4


Finally, enable the UFW
.

ufw enable



Fail2ban is a log scanner that is used to ban IP address’ that make too many
password failures by updating the firewall rules to reject the IPs. Needless to say this is
rather useful in preventing any bruteforce attempts. To install
,

the fol
lowing commands
must be run.

apt
-
get install fail2ban

C
opy /etc/fail2ban/jail.conf to jail.local

cp /etc/jail2ban/jail.conf jail.local

E
dit ignoreip field to ignore your ip.

ignoreip 127.0.0.1

/etc/init.d/fail2ban restart

Apache

Fortunately, Apache 2.2.16 comes relatively secure out of the box. Apart from a few
module additions and configuration changes, Apache comes with a bare install to create
a maximum security web server. Efficiency implementations have also been
implemented
alongside
security. Below are the changes

implemented to fulfill security
and efficiency concerns.

Note that I chose not to use Chroot
-
jail
because the server is
standalone and not shared.


/
ETC
/
APACHE
2/
CONF
.
D
/
SECURITY



ServerSignature Off: Turning off the
ServerSignature prevents attackers from
gathering the version number of the apache server. The removal of this prevents
specific version exploits if for some reason the server is not up to date. In this
case, the default was set to off. However,
it has bee
n

noted it down just in case.

ServerSignature Off



ServerTokens Prod: Changing ServerTokens

to Prod from OS returns the least
amount of information when returning the Server HTTP Response Header. It is
always good practice to comment out the previous value instead of overwriting it.
The hash (#) will be seen below to denote a comment.

Securing a LAMP server
5


#ServerTok
ens Full

ServerTokens Prod




/
ETC
/
APACHE
2/
SITES
-
ENABLED
/000
-
DEFAULT


The default root directory for your web server is /var/www, so any changes to any
configuration Options pertaining to /var/www affect the overall functional
ity of the web
server. Before
I

begin showing new and old code, it would be a good idea to introduce
the di
fferent types of Options that I
’ll be investigating.




Indexes allow directory traversal. With this enabled, anyone can view
a
directory
listing of files thus uncovering
the

directory tree. An example would be traversing
through
a

image folder in a detailed listing.



FollowSymlinks map URLs to filesystem locations.



MultiView enables the server to find and use a similar file if the initial file doesn’t
exist. Ex. It’ll use ind
ex2.html if index.html doesn’t exist.



ExecCGI allows for the execution of CGI scripts through mod_cgi.



SymLinksIfOwnerMatch is a more secure way of using symlinks as it checks
whether the target file or directory is owned by the same user id as the symlink

itself.

Within the <Directory /var/www/> tag,
I decided to remove all of the options because
they were never to be used.


#Options Indexes FollowSymLinks MultiViews





Options None

Within <Directory />
I

removed the FollowSymLinks.

#Options FollowSy
mLinks





Options None

The directory labeled “/usr/lib/cgi
-
bin” has been completely commented out.
I

do not
Securing a LAMP server
6


require the execution of of CGI scripts. Note that the ScriptAlias has been
commented out as well.

#


ScriptAlias /cgi
-
bin/ /usr/lib/cgi
-
bin/

#


<Directory "/usr/lib/cgi
-
bin">

#


AllowOverride None

#


Options +ExecCGI
-
MultiViews +SymLinksIfOwnerMatch

#


Order allow,deny

#


Allow from all

#


</Directory>


/
ETC
/
APACHE
/
MODS
-
ENABLED

The section below explains the current modules enabled by default. Some of the
modules are not used and removed accordingly. Disabling modules is as simple as
running a2dismod in root and typing the module name. Enabling modules is done
through a2
enmod. Below is a brief explanation of many of the modules that have
configuration files and the changes
I’ve

done to them.



C
ONFIGURATION CHANGES



alias: Allows you to alias sub
-
directories on the web server without showing their
parents. An example can
be creating an alias for /var/www/img/main into
/mainimg/ where you can call /mainimg/ in the html instead of /img/main. Hiding
the directory tree prevents attackers
from knowing the workings of the

site. The
default /usr/share/apache2/icons was removed fr
om alias.conf as it was not
necessary.
I

did not completely remove this module because alias
can be used to
hide the directories holding
important code or images from outsiders.

#<Directory "/usr/share/apache2/icons">

#


Options Indexes MultiViews

#


A
llowOverride None

#


Order allow,deny

#


Allow from all

#</Directory>

Securing a LAMP server
7




autoindex: Provides pictures for icons when directory traversal is enabled.
Disabled the use of it as directory traversal is disabled.





root# a2dismod autoindex



dir
: Dir is used when the server receives a request for a directory without having
the trailing slash. Dir redirects the request to the directory instead of trying to
open a file. A redirect would occur if a request arrives for
http://server.com/img

instead of
http://
server.com
/img/
.

DirectoryIndex is the default file Dir looks for when redirected to a directory. If the
file does not exist, it will revea
l that the page is not found. I

replaced the default
values with index.php. Not necessarily a security risk, but it is unneces
sary to
have especially when I

know
I’m

only using php.

#DirectoryIndex index.html index.cgi index.pl index.php index.xhtml
index.htm

DirectoryIndex index.php


M
ODULE ADDITIONS


In this section I will discuss the modules I installed that did not come with the initial
install. Along with security, I decided to implement two efficiency modules to help speed
the server up.



deflate: Allows for faster website access b
y compressing server output prior to
being sent to the user.

Before deflate was enabled
:




After deflare was enabled


Securing a LAMP server
8




pagespeed: Mod_pagespeed is used to automatically optimize web
pages and
the resources on them
. The install was done as follows.

root# wget
https://dl
-
ssl.google.com/dl/linux/direct/mod
-
pagespeed
-
beta_current_i386.deb

root# dpkg
-
i mod
-
pagespeed
-
*.deb


Before pagespeed was enabled:


After pagespeed was enabled:



ssl: Provides SSL and TLS support to be used when transferring important
information from a user to
my

server. The install procedure is below.

root# mkdir /etc/apache2/ssl

root# openssl req
-
new
-
x509
-
days 365
-
nodes
-
out
/et
c/apache2/ssl/apache.pem
-
keyout /etc/apache2/ssl/apache.pem

root# a2enmod ssl


Now

I went

into /etc/apache2/sites
-
enabled and edit 000
-
default. Once there
I
duplicated the entire <VirtualHost *:80> directive below the original. Once
duplicated,
I
change
d

the port on the duplicated VirtualHost to 443 instead of 80.
This enabled the use of http and https access on the web server.


Before the closing of the 443 VirtualHost, the two lines below were added
:



SSLEngine on



SSLCertificateFile /etc/ap
ache2/ssl/apache.pem

</VirtualHost>

Securing a LAMP server
9




ModSecurity: ModSecurity is self
-
described as a Web Application Firewall. It
offers the ability to protect an Apache server from attacks via POST requests.
Without such a tool, these attacks go unnoticed and unlogged by
a standard
installation. To begin the installation a few more packages need to be installed.
Without these, the mod_security updater would not operate.


root# apt
-
get install libwww
-
perl libio
-
socket
-
ssl
-
perl libnet
-
ssleay
-
perl
libgnupg
-
perl

Once installed,
I ran

the following command to retrieve new rules.

./rules
-
updater.pl
-
rhttp://www.modsecurity.org/autoupdate/repository/
-
p


rules
-
Smodsecurity
-
crs

The rules were where
I

ran the command. In
my

case it was ~/rules.

Once in
~/rules,
I

ran the following commands.

root# cd modsecurity
-
crs

root# unzip modsecurity
-
crs_2.2.1.zip

root# mv modsecurity
-
src /etc/apache2/modsecurity
-
crs

root# cd /etc/apache2/modsecurity
-
crs

root# mv

modsecurity_crs_10_config.conf.example
modsecurity_crs_10_config.conf


At the end of modsecurity_crs_10_config.conf,
I

added the following lines
to prevent some xss, sql and other types of attacks.

SecRuleEngine On

SecDataDir /var/log/httpd/

SecDebugLog /
var/log/httpd/modsec
-
debug.log

SecDebugLogLevel 1

Below are the filters used to prevent
different

types of attacks. These
filters can be modified using regular expressions which allow for the
creation of any type of filter you wish to have implemented.

# P
revent OS specific keywords

SecFilter /etc/password

# Prevent path traversal (..) attacks

SecFilter "
\
.
\
./"

# Weaker XSS protection but allows common HTML tags

SecFilter "<( |
\
n)*script"

# Prevent XSS atacks (HTML/Javascript injection)

SecFilter "<(.|
\
n)+>
"

# Very crude filters to prevent SQL injection attacks

SecFilter "delete[[:space:]]+from"

Securing a LAMP server
10


SecFilter "insert[[:space:]]+into"

SecFilter "select.+from"

# Prevent shell command execution

SecFilterSelective ARGS "bin/"

#Accept almost all byte values

SecFilterForceByteRange 1 255

#Scan post body payload

SecFilterScanPOST On

#Turn off unicode ecoding validations as we don't use utf

SecFilterCheckUnicodeEncoding Off


Finally restart

apache by issuing /etc/init.d/apache2 restart.



Evasive: Mod_evasive is a
n evasive maneuvers module for Apache that prevents
attacks such as HTTP DDoS or bruteforces. It does so by denying any user the
ability to request the same page more than a few times a second by temporarily
banning them.
I

enabled it by installing libapac
he2
-
mod
-
evasive.



Important change to note from Apache 2.0 to Apache 2.2:

o

Mod_userdir: Has been removed from the mods
-
enabled default list. This
feature when enabled gives the local machine users the ability to publish
content under their home directory.

MySQL

MySQL comes pre
-
installed with mysql_secure_installation which helps secure
MySQL by removing anonymous user accounts, disabling root access from anyone not
on localhost, and removing of test databases. It’s as simple as typing
mysql_secure_installat
ion in a console and following the steps given.

Surprisingly, that is all there is to securing MySQL on Ubuntu. However, there
are a few security precautions in the PHP section which will explain how to secure your
PHP code against any SQL vulnerabilities.

PHP

Securing PHP requires not only configuration changes, but code changes as
well. Considering the use of MySQL, the need for preventing SQL injection attacks must
be prevented. Mod_security does prevent such from happening, but it is always a good
Securing a LAMP server
11


idea
to patch the code too. But, before I get into the code patching, I’ll take a closer look
at some php configuration changes that need to be changed.

CONFIGURATION CHANGES

The default configuration
file

has some needed security measures in place, but
not all.
The configuration file is located in /etc/php5/apache2/php.ini. To start, I took a
look at register_globals to make sure it was set to off. This is a humongous security risk
if set to on. It allows
for all EGPCS (Environment, GET, POST, Cookie, Server)
variables to be set as global variables.



Expose_php:
In order to hide PHP’s version
from being appended to Apache’s
signature or from HTTP header requests, make sure expose_php is set to off.



Allow_u
rl_fopen: Considering I won’t be doing any fopen, or including any other
files that are not local, this option is useless to have enabled. This prevents the
possibility of a Remote File Inclusion attack. I turned it off.



Display_errors: Self
-
explanatory, I

turned it off. Nobody needs to see any errors
in my php code.

SUHOSIN


Suhosin is mandatory when using PHP. It is used to protect servers from flaws in
PHP applications and PHP core. A full list of what it protects can be found at
Suhosin
Features List
. I did not find anything within the suhosin configuration that needed
changing so I left all the values default. To view the configuration values, you can simply
create a file on your we
bserver and add <?php phpinfo(); ?> within it. This will populate
a list of everything PHP has enabled. However, be sure to remove it once you are done
viewing it as it is something you do not want intruders seeing.


CODE CHANGES

Mysql_real_escape_string

is vital in ensuring that the data being sent it safe. It will
prevent the use
of special characters such as
\
x00,
\
n,
\
r,
\
,’,”,
\
x1a by escaping them.

Below is an example of how to use mysql_real_escape_string
.


In this example, you’ll notice a select for a username where the prod_id matches the
one of the get variable. Once one is found it will be saved in the $winner variable as
Securing a LAMP server
12


denoted on line 3. Then the winner is submitted into another table. This is an examp
le
not using mysql_real_escape_string and leaves the code vulnerable.

1

$query = mysql_query("SELECT username F
ROM answers WHERE prod_id='".
$_GET['prodid']

. "' ORDER BY RAND() LIMIT 1");

2

$result = mysql_fetch_assoc($query);

3

$winner = $result[
'username'];

4

mysql_query("INSERT INTO winners (prod_id, username) VALUES ('".$_GET['prodid']."',
'$winner')");


In this segment of code you’ll notice the user of mysql_real_escape_string around each
of the received and sent variables. Use mysql_real_esca
pe_string wherever you send
any variables to the database.

1

$query = mysql_query("SELECT username FROM answers WHERE prod_id='".
mysql_real_escape_string($_GET['prodid']) . "' ORDER BY RAND() LIMIT 1");

2

$result = mysql_fetch_assoc($query);

3

$winner =
mysql_real_escape_string($result['username']);

4

mysql_query("INSERT INTO winners (prod_id, username) VALUES (".
mysql_real_escape_string($_GET['prodid']) ."', '$winner')");








Securing a LAMP server
13


Bibliography

April 26
th
, 2011. Uncomplicated Firewall


UFW.
Retrieved from
https://help.ubuntu.com/community/UFW
.


Apache Core Features. Retrieved from
http://httpd.apache.org/docs/2.2/m
od/core.html#options
.


Apache Module mod_deflate. Retrieved from

http://httpd.apache.org/docs/2.2/mod/mod_deflate.html
.


Mod_pagespeed overview. Retrived from

http://code.google.com/speed/page
-
speed/docs/module.html
.


Apache Module mod_ssl. Retrieved from

http://httpd.apache.or
g/docs/2.2/mod/mod_ssl.html
.


July 19
th
, 2011. Sourceforge.net: Reference Manual


mod
-
security. Retrieved from

http://sourceforge.net/apps/mediawiki/mod
-
se
curity/index.php?title=Reference_Manual

http://library.linode.com/lamp
-
guides/ubuntu
-
10.10
-
maverick