Web Security

greenpepperwhinnySecurity

Nov 3, 2013 (3 years and 8 months ago)

62 views

CSci 215


PHP Security

How would

you
completely
secure a
Website?


http://heykidscomics.com/1564web.jpg

A Security Mindset

“Security is not a feature… It must be
constantly part of the core design of the
application, and it is a never
-
ending effort,
even after the application is deployed.”



Welling & Thomson

Two Golden Rules

1.
FILTER all external input


Forms


Files


External databases


POST, GET, COOKIE, SERVER
, etc.


2.
ESCAPE output


Client browser


Database

Two Golden Rules

PHP Script


Filter



Escape


Forms

POST, GET, COOKIE, etc.

html

MYSQL

Files

Databases

Filtering


Process by which you
inspect

data to
prove

its validity


Adopt a whitelist approach if possible


assume the data is
invalid

unless you can prove otherwise


Methods of filtering


Check length


Cast or convert data types


Use functions and regular expressions

to check validity

What is the
difference
between a
"
whitelist
"
approach and a
"blacklist"
approach?

Filtering with ctype Functions

if (
ctype_alnum
($_POST[
'username
'
])) {


$
username

= $_POST[
'username'
];

}

if (
ctype_digit
($_POST[
'year
'
])) {


$
year
= $_POST[
'year'
];

}

if (
ctype_alpha
($_POST[
'name
'
])) {


$
name
= $_POST[
'name'
];

}



Filtering with filter_var

http://nettuts.com/tutorials/php/sanitize
-
and
-
validate
-
data
-
with
-
php
-
filters/#more
-
2595


if (
isset
($_POST['email'])) {


if
(
filter_var

($_POST['email']),





FILTER_VALIDATE_EMAIL
))


echo “Email is valid”;


else



echo
“Email is invalid";

}


if (
isset
($_POST['homepage'])) {


if
(
filter_var

($_POST['homepage']),




FILTER_VALIDATE_URL
))



echo
“URL is valid”;



else



echo
“Invalid URL";

}

More PHP Filters

ID

Name

FILTER_VALIDATE_BOOLEAN

boolean


FILTER_VALIDATE_EMAIL

validate_email


FILTER_VALIDATE_FLOAT

float

FILTER_VALIDATE_INT

int


FILTER_VALIDATE_IP

validate_ip


FILTER_VALIDATE_REGEXP

validate_regexp


FILTER_VALIDATE_URL

validate_url


http://php.net/manual/en/function.filter
-
var.php


http://www.php.net/manual/en/filter.filters.validate.php


Escaping Output


Process by which you escape characters that have a
special meaning on a remote system.


Two most common outputs


html to the browser


use
htmlentities
()


MySQL database


mysql_real_escape_string
()
escapes special characters


PDO
prepared statements

Escape example

$html
=
array
();

$html
[
'username'
] =



htmlentities
($
username
,
ENT_QUOTES
);

echo

"Welcome back,
{$html
[
'username
'
]}
!"
;

http://php.net/manual/en/function.htmlentities.php


Will convert both double

and single quotes to
entities version

Common Attack Methods


If you follow these rules religiously, you will
produce secure code that is hard to break.


Otherwise, you will be susceptible to

common attack methods:

1.
register_globals

2.
spoofed forms

3.
cross
-
site scripting

4.
SQL injection

5.
session fixation




1. register_globals


register_globals

is a PHP setting that makes global
variables available as ordinary variable names.


$_POST['name']

is available as
$name


$_COOKIE['age']

is available as
$age


register_globals

is turned
off
by default, but it is
sometimes turned back on


If it is turned on, make sure

your code is secure

Use
phpinfo
() to
check your settings.

http://ned.highline.edu/~tostrander/215/security/info.php

Try It

if (form submitted) {


validate username and password from form submission


if (password and username match a user's entry) {



$authorized = true;


}

}

if ($authorized) {


include '/highly/sensitive/
data.php
';

} else {


display log
-
in form

}

http://ned.highline.edu/~tostrander/215/security/example1.php


How could we get a value
into this variable?

How could we
prevent
this "hack"?

Register Globals: Solution


Turn
off
register_globals

if possible


If register
globals

is
on
, be aware that any user can inject a
variable of any name into your PHP scripts


$authorized = false;

if (form submitted) {


if (password and username match…)



$authorized = true;

}

if ($authorized)


include '/highly/sensitive/data.php';


ALWAYS
EXPLICITLY
INITIALIZE

YOUR OWN
VARIABLES!


2. Spoofed Forms


Be aware that anybody can write their own forms and
submit them to your PHP scripts.




Using a select, checkbox or radio button form input
does
not guarantee

that the data submitted will be one of
your

chosen options…

Spoofed Forms: Example

The form written by a web developer to be submitted to a page:

<form action="
process.php
" method="POST">


<select name="
color
">



<option value="red">red</option>



<option value="green">green</option>



<option value="blue">blue</option>


</select>


<input type="submit" />

</form>


The user writes their own form to submit
to the same page
:

<form action="http://example.org/
process.php
" method="POST">


<input type="text" name="
color
" value="black" />


<input type="submit" />

</form>


Try It


See if you can spoof the form at
http://ned.highline.edu/~tostrander/215/security/example2.php









How could we
prevent
this "hack"?

Spoofed Forms: Solution


Users can submit whatever they like to your PHP
page… and it will be accepted
as long as it conforms to
your

rules.


Verify all incoming values; don’t rely on a form to
exert rules for you.


Never assume that a form value will be what is expected.




If($_POST[‘format’] == ‘HTML’ OR $_POST[‘format’] == ‘Text’)

Spoofed Forms: Solution


Check the referrer, i.e. where the request is coming from


$_SERVER['HTTP_REFERER
'
]
(yes, it’s misspelled!)
contains the URL of the page that linked to this one


<?
php


/*
This is a form processing script */



//
Where did we come from?


echo
$_SERVER['HTTP_REFERER'];




//
Make sure we came from
ned


if
(!
strstr
($_SERVER['HTTP_REFERER
'],



"
ned.highline.edu"))


die
("GO AWAY HACKER!");



//
Process the form…

3. Cross Site Scripting (XSS)


A type of
malicious code
injection


Script is often embedded
in a comment or message
field


The script executes on
the client when the page
is accessed

Cross Site Scripting (XSS)


This is a good example of why you should always escape
all output, even for html…





echo

"<p>Welcome back,
{$_POST[
'name'
]}
.</p>"
;




echo

"<p>Welcome back,

<script>alert('ATTACK!')</script>
.</p>"
;



Name:

<script>alert
('ATTACK!')</
script>

XSS: The Solution


Filter input


Escape Output


Be especially careful if you are writing user input to a file,
which is later
include
d into your page.

This prevents the code from
running if you display it on
your website.

htmlentities

will
.convert
"<script>" to
"&
lt;script&gt
;".

4. SQL Injection


The goal of SQL injection is to
insert arbitrary data into a
database query.


SQL Injection: Example


Consider this query executed in PHP on a MySQL
db
,
where the email text has been submitted from the user:



"SELECT * FROM members


WHERE email = '
{$_POST[
'email'
]}
'"

SQL Injection: Example


The use of
$_POST[..]

in the query should
immediately raise warning flags!


Consider if a user submitted the following email:



Email:

dummy' OR 'x'='x



The query now becomes,

SELECT * FROM members

WHERE email = '
dummy' OR 'x'='x
'




What will result?

Try It


Visit
http://ned.highline.edu/~tostrand/215/security/

example4.php


See if you can demonstrate a SQL injection vulnerability

SQL Injection: Solution


Filter input data


Quote your data


If your database allows it (MySQL does), put single quotes
around all values in your SQL statements, regardless of the
data type.


SELECT * FROM customer WHERE
custID

= '3'


Escape your data


For a MySQL
db
, use the function
mysql_real_escape_string
()


Use PDO prepared statements

5. Session Fixation

1. The malicious user hosts a page with links to your site or
emails spam links to your site with a session ID
already
set
.

… <
a href=“http://example.com/index.php
?PHPSESSID=1234
” …

Session Fixation

2. A client follows the link and is directed to your site,
where they login.


3. Now, the malicious user knows the session ID (because
they set it!), and can ‘hijack’ the session by browsing to
your site using the same session id.


4. Malicious user is now logged in as one of your legitimate
clients.


Session Fixation: Solution


Regenerate the session identifier whenever there is a
change in privilege level


For example, after verifying username and password


PHP has a function that does all the work for you:



session_regenerate_id
()


Check

the

referrer


<?
php


//Start the session and regenerate the session ID


session_start
();




//Verify that username and password are valid, and then:


session_regenerate_id
();




//Make sure we came from
ned


if(!
strstr
($_SERVER['HTTP_REFERER'], "ned.highline.edu"))



die("GO AWAY HACKER!");

Filter Input

+

Escape Output

=

Secure Code

A Few More Things


Storing Credentials


Keep credentials (e.g. usernames and passwords) in included
files outside of web accessible directories.


Encrypt Sensitive Data


Passwords, credit card numbers, etc. should be encrypted in
the database


sha1 and md5 are one
-
way encryption functions


Use SSL (Secure Sockets Layer)


Requires a certificate


Provides encryption for data traveling to and from the website


Uses
https