Transcript
Page 1: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 1 of 42CSCI 2910 – Client/Server-Side Programming

CSCI 2910 Client/Server-Side Programming

Topic: More Topics in PHP

Reading: Williams & Lane pp. 377-397

Page 2: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 2 of 42CSCI 2910 – Client/Server-Side Programming

Today's Goals

• Server-side applications open up a number of possibilities for malicious attacks

• This lecture provides an overview of security along with only a few of the measures that can be taken to guard against attacks.

• All responsible web programmers must continually familiarize themselves with both the modes of attack and the means by which to protect themselves and their data.

Page 3: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 3 of 42CSCI 2910 – Client/Server-Side Programming

Quick Facts• Randal Schwartz -- Barney the Dinosaur

• Complexity of browsers and servers have opened up a number of other opportunities, i.e., every new feature opens up new vulnerabilities

• Many blogs, forums, search engines, and e-businesses display other user's form input to third party clients.

• Scripts and get-method forms can be disguised as simple links making unsuspecting clients vulnerable.

Page 4: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 4 of 42CSCI 2910 – Client/Server-Side Programming

Problems with User Input• You have no control over a user's form input.• Scripts must examine all input to prevent

– unintentional characters from causing erroneous execution– malicious input from breaching security

• Always validate form input by:– cleaning it up to verify acceptable strings or– using it to drive assignment of hard-coded values.

• Typically, JavaScript on the client side is used for form validation, but we need to do more on the server-side.

• Attackers could create forms that simulate input from legitimate forms.

Page 5: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 5 of 42CSCI 2910 – Client/Server-Side Programming

Escape Characters• It's a good idea to use trim() to remove excess white

space from user input• Be sure to control the escape character '\' so

unwanted white space is removed • Remove unwanted double slashes with stripslashes();• Prevent PHP control characters from entering form

data using addslashes().• addslashes() escapes single quote ('), double quote

("), backslash (\) and NULL.• addslashes() works the same as Magic Quotes, a

process that automatically escapes incoming data.

Page 6: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 6 of 42CSCI 2910 – Client/Server-Side Programming

Validating Form Data• Although the HTML form might have JavaScript

used at the form to validate data, it is a good idea to validate form data at the server side too.

• Validating HTML form data:– prevents erroneous output– is critical to security– is not to be trusted entirely

• To eliminate confusion, all forms should indicate to user which fields are required and, where applicable, the format and type of information a field is expecting.

Page 7: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 7 of 42CSCI 2910 – Client/Server-Side Programming

Methods to Validate Form Data

• isset() tests if a variable has a value.

if (isset($var)) {

// $var has a value.}else{

// $var does not have a value.}

• Unfortunately, isset() will return a true if the variable is set to an empty string.

Page 8: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 8 of 42CSCI 2910 – Client/Server-Side Programming

Methods to Validate Form Data (continued)

• To avoid empty strings, use the string function strlen().

$input = stripslashes($_POST['name']);if (strlen($input) > 0) {

// User input a value.}else {

// User did not input a value}

Page 9: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 9 of 42CSCI 2910 – Client/Server-Side Programming

Did the User Input a Number?

• To test if a submitted value is a number, use the is_numeric() function.

• is_numeric() returns a boolean true if the value is a number.

Page 10: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 10 of 42CSCI 2910 – Client/Server-Side Programming

Hidden Form Elements

• Hidden form elements can be used to pass data to a PHP script without allowing the user to see it.

• This can be used to identify the form that requested the page or passing other constants to the server side script.

• Never use hidden elements to store secure information as the HTML can be viewed by the client.

Page 11: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 11 of 42CSCI 2910 – Client/Server-Side Programming

Verifying the Client• $_SERVER['HTTP_REFERER'] returns the

address of the page that referred the user to this script.

• $_SERVER['REQUEST_METHOD'] returns the method of the form used to refer the user to this script.

• $_SERVER['REMOTE_ADDR'] returns the IP address of machine originating request. Can use this to limit which machines have access to your PHP script.

Page 12: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 12 of 42CSCI 2910 – Client/Server-Side Programming

HTTP Headers

• HyperText Transfer Protocol (HTTP) is the protocol that defines how servers and clients communicate.

• When a browser requests a Web page, it receives a series of HTTP headers containing information about the transaction.

• PHP's built-in function header() allows a server-side script to provide a custom header.

• These headers can be used for authentication

Page 13: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 13 of 42CSCI 2910 – Client/Server-Side Programming

HTTP Headers (continued)• Since PHP sends output to the client as it is generated,

and since headers must be sent before the HTML file itself, the header() function must be executed before the script outputs anything.

• Failure to do this results in an error message to the user.

• To avoid this, use the headers_sent() function, which checks whether or not data has been sent to the Web browser.

if (!headers_sent()) header ("Location: http://www.url.com/a.php"); else echo "Unable to redirect you.";

Page 14: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 14 of 42CSCI 2910 – Client/Server-Side Programming

HTTP Headers – Redirect• The most common example of headers is to

redirect the browser from the current page to another.

• Example: header ("Location: http://www.url.com/page.php");

• A redirect should be the last thing to occur on the current page since the browser will soon be leaving it.

• Therefore, this line should be followed by a call to the exit() function in order to stop execution of the script.

Page 15: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 15 of 42CSCI 2910 – Client/Server-Side Programming

Sticky Forms• If a user needs to be returned to a form, e.g.,

they have forgotten to input required data, it's nice to have the fields that they have already entered pre-filled for the new form.

• Remember that form elements in HTML can have preset values.

• For example:<input type="text" name="first_name" value="David" />

Page 16: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 16 of 42CSCI 2910 – Client/Server-Side Programming

Sticky Forms (continued)

• Use the valid values returned in $_GET and $_POST to preset those values.

• For example:<input type="text" name="first_name" value="<?php print $_POST['first_name'] ?>" />

• Presetting other form elements:– Use checked="checked" to preset a checkbox– Use selected="selected" to pre-select an option in a select

element– To preset the value of a textarea, place the value between

the <textarea> ... </textarea> tags

Page 17: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 17 of 42CSCI 2910 – Client/Server-Side Programming

Security Issues

• Allowing the client to execute scripts and access databases on a server opens up vulnerabilities not inherent in client-side applications.

• Security has become the most important design issue in web application development. It must be addressed in your designs.

Page 18: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 18 of 42CSCI 2910 – Client/Server-Side Programming

Identifying the Threats(Source: Laws, Michaele, Course Notes – PHP4/ PHP Part4_lecture.doc)

• Four types of threats to server side applications– Access to or modification of sensitive data

• User permissions (who sees what)• What to store, what not to store• Encoding data sent to server using SSL

– Loss or destruction of data• Deleting a table• Loss of a server due to a destructive event, e.g.,

natural disaster

Page 19: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 19 of 42CSCI 2910 – Client/Server-Side Programming

Identifying the Threats (continued)(Source: Laws, Michaele, Course Notes – PHP4/ PHP Part4_lecture.doc)

– Denial of Service• Crashing the computer• Filling up HDD• Generating multiple processes, using up memory• Causing hardware failure on server by manipulating

device drivers• Flooding network with traffic

– Malicious Code Injection• SQL Injection• Cross Site Scripting (XSS)

Page 20: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 20 of 42CSCI 2910 – Client/Server-Side Programming

You Don't Want to Become the Reason for Articles Like This…

(Source: Swartz, Jon, USA Today, Posted 2/18/2003 5:07 PM)

Hackers Get Credit Card Numbers

By Jon Swartz, USA TODAY

SAN FRANCISCO — Intruders broke into a computer system and accessed more than 5.6 million credit card account numbers from Visa, MasterCard and American Express in what is believed to be the largest security breach of its kind.

The suspected hackers cracked the security of a company that processes transactions for merchants, the credit card associations said Tuesday. They wouldn't identify the company attacked or say when or how the hackers got to the accounts, which includes about 3.4 million from Visa and 2.2 million from MasterCard.

Page 21: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 21 of 42CSCI 2910 – Client/Server-Side Programming

Warning(Source: Laws, Michaele, Course Notes – PHP4/ PHP Part4_lecture.doc)

"The following information is never to be used with malicious intent, or to “show off”. It is understood that to write secure code, one must comprehend what makes code insecure and how or why it is insecure. Use of techniques discussed in class without prior approval of all parties involved will result in termination from the CS department, and possible discipline measures from the university and/or local authorities."

Page 22: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 22 of 42CSCI 2910 – Client/Server-Side Programming

Inserting PHP Using Form Inputs

• Forms with text input may be used to insert PHP code.• Example:

<?phpprint "Welcome, {$_POST['first_name']}";

?>

• Client could attempt to insert a script using a first name such as:

<script>confirm("Gotcha!");</script>

Page 23: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 23 of 42CSCI 2910 – Client/Server-Side Programming

Inserting PHP Using Form Inputs (continued)

• On a poorly configured server, the PHP code that would be executed would allow the pop-up:

• Okay, so this may not be that malicious, but there are other things a hacker could do.

• For example, a hacker could use this method to insert JavaScript code to access server or client data.

Page 24: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 24 of 42CSCI 2910 – Client/Server-Side Programming

Cross Site Scripting (Source: Laws, Michaele, Course Notes – PHP4/ PHP Part4_lecture.doc)

"[Cross Site Scripting] is when a web site displays user input in the browser that has not been properly sanitized. Cross site scripting can be used to steal cookies, compromise data integrity and trick users into submitting information to a hacker. An unauthorized user can modify data in the URL string to insert damaging HTML into the processing script, and send the user to a bogus site (cross site)."

Page 25: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 25 of 42CSCI 2910 – Client/Server-Side Programming

Cross Site Scripting (continued)• Basically, the problem occurs when a hacker manages to trick a

client into clicking on a link that has a URL modified to insert malicious code into the processing script.

• For example, if the first_name element of the preceding form and associated script were set to:

<script language=\'JavaScript\'>alert(document.cookie)</script>

then a JavaScript function would be executed.• While an alert box is not that malicious, giving a hacker the

ability to insert JavaScript into a client's page puts the clients cookies and other information at risk of being sent to the hacker through what might appear to be an innocent link.

Page 26: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 26 of 42CSCI 2910 – Client/Server-Side Programming

SQL Injection

• Many database queries require user input to identify records.

• In particular, user names and passwords can be exploited to gain access to other data.

• SQL injection inserts PHP SQL functions through form inputs to gain unauthorized access to protected information.

Page 27: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 27 of 42CSCI 2910 – Client/Server-Side Programming

Sample HTML Login Form<form method="post" action="processlogin.php">

userid: <input size = "10" type=”text” name="userid"><br />

password: <input size = "10" type="text" name="pwd"><br />

<input type="submit" value="Click to login" name="loginbutton"></form>

Page 28: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 28 of 42CSCI 2910 – Client/Server-Side Programming

Sample PHP Login Script<?phpheader("Cache-Control: no-cache, must-revalidate");if (isset($_POST['loginbutton'])){

$connection = mysql_connect('localhost','db2910','12345');if (!$connection){

echo 'error connecting to mysql';exit();

}mysql_select_db ('userdb',$connection);$result = mysql_query,("select * from users where username='" .$_POST['userid']. "' and password =

'" .$_POST['pwd']."'"$db);if ($result){ header("Location:

http://www.url.com/websecurity/login_success.htm"); exit;}else

echo("<h1>Invalid userid or password.</h1>");mysql_close($db);

}?>

Page 29: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 29 of 42CSCI 2910 – Client/Server-Side Programming

Valid Operation

• If the user were to enter a user name of "abcde" and password of "12345", the PHP script would perform the following SQL query:

Select * from members where username='abcde’ and password=’12345’

Page 30: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 30 of 42CSCI 2910 – Client/Server-Side Programming

Malicious Operation• If the user entered a user name of ‘ or ‘’ = ‘

(including the single quotation marks) and a password of ‘ or ‘’ = ‘ (including the single quotation marks), the PHP script would perform the following SQL query:

Select * from members where username=’’ or ‘’ = ‘’ and password = ‘’ or ‘’ = ‘’

• This will return all records, and the user will be allowed access to the system.

Page 31: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 31 of 42CSCI 2910 – Client/Server-Side Programming

Options

• One option to solve this problem is to create a function that will strip characters that could be used by hackers.

• It is important when enrolling valid users to include this code to properly format a user's name for use in the database.

• It might also be beneficial to use this function to limit the length of the client's input.

Page 32: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 32 of 42CSCI 2910 – Client/Server-Side Programming

Function clean()

function clean($input, $maxlength){

$input = substr($input,0,$maxlength);

$input = EscapeShellCmd($input);$input =htmlspecialchars($input,ENT_QUOTES);return $input;

}

$userid = clean($_POST['userid'],10);$pwd = clean($_POST ['pwd'],15);

Page 33: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 33 of 42CSCI 2910 – Client/Server-Side Programming

Function escapeshellcmd()(Source:

http://us3.php.net/manual/en/function.escapeshellcmd.php)

"escapeshellcmd() escapes any characters in a string that might be used to trick a shell command into executing arbitrary commands. This function should be used to make sure that any data coming from user input is escaped before this data is passed to the exec() or system() functions, or to the backtick operator.

Following characters are preceded by a backslash: #&;`|*?~<>^()[]{}$\, \x0A and \xFF. ' and " are escaped only if they are not paired. In Windows, all these characters plus % are replaced by a space instead."

Page 34: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 34 of 42CSCI 2910 – Client/Server-Side Programming

Function htmlspecialchars()(Source:

http://us3.php.net/manual/en/function.htmlspecialchars.php)

"Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming…"

Page 35: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 35 of 42CSCI 2910 – Client/Server-Side Programming

Function htmlspecialchars() (continued)

Specifically, the function translates the following characters:– '&' (ampersand) becomes '&amp;' – " (double quote) becomes '&quot;' when

ENT_NOQUOTES is not set. – ' (single quote) becomes '&#039;' only when

ENT_QUOTES is set. – '<' (less than) becomes '&lt;' – '>' (greater than) becomes '&gt;'

Page 36: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 36 of 42CSCI 2910 – Client/Server-Side Programming

Do Not Trust User Input• There are other steps you can take to verify the

integrity of user input.• Be sure to typecast all user data to the expected

type, e.g., int, float, string, etc.• Send values through conditional statements to

check that they are within the expected ranges.• Escape all HTML characters• Use the extension *.php for all files containing

PHP scripts. (This is most important when it comes to include files.)

• Use mysql_num_rows() to verify that only one result is returned when only one is expected. (Especially important for username/password)

Page 37: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 37 of 42CSCI 2910 – Client/Server-Side Programming

Encrypting Passwords in Database

• If a hacker gains access to a database, all passwords stored as plain text are at risk.

• One-way encryption involves receiving a password, then passing it through an encryption algorithm before storing it in the database.

• The original password cannot be deciphered from the encrypted one.

• Later, when the user enters their password for access, the same encryption algorithm is used to generate the encrypted version. This encrypted version can then be compared with the version stored in the database.

Page 38: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 38 of 42CSCI 2910 – Client/Server-Side Programming

One-Way Encryption in PHP• PHP provides two functions that can be used for one-

way encryption of passwords.• string crypt (string str [, string salt]) – returns an

encrypted string using a system defined algorithm.– The argument str is the string to be encrypted and salt is a

string to drive the encryption.– The salt argument is a two character string.– If the salt argument is not provided, crypt generates one

randomly. – Randomly generated salt will be returned as the first two

characters of the return value.– Randomly generated salt will need to be stored so encrypted

string can be regenerated.– crypt() only encrypts first 8 characters of string

Page 39: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 39 of 42CSCI 2910 – Client/Server-Side Programming

One-Way Encryption in PHP (continued)

• string md5 ( string str [, bool raw_output] ) – calculates the MD5 hash of str using the RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns the resulting hash.

• The hash is a 32-character hexadecimal number.

• This algorithm does not use a salt.

Page 40: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 40 of 42CSCI 2910 – Client/Server-Side Programming

crypt() Versus md5()

• md5( ) works with strings of any length while crypt() only uses first 8 characters, i.e., results of crypt() would be the same for "abcdefgh5" and "abcdefgh6".

• crypt( ) uses a salt to calculate the encrypted string while md5() does not. (Note: If the script concatenated a salt with the string to be encrypted before sending it to md5(), it would be the same as using a salt.)

Page 41: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 41 of 42CSCI 2910 – Client/Server-Side Programming

Denial of Service Attacks• There are a number of ways that a hacker can

bring down a server.• Examples:

– If there is no limit on the length of a form input, a hacker could enter a very large message and fill the database.

– In an alternate effort to fill a database, a hacker could create a automated process to enter a large quantity of messages in a short time

• Prevention measures include:– limiting the size of data coming from a form– limiting the number of messages submitted from one or

more IP addresses over a 24 hour period. – $_SERVER['REMOTE_ADDR'] can be used to prevent

access by certain client machines.

Page 42: CSCI 2910  Client/Server-Side Programming

Security Basics in PHP – Page 42 of 42CSCI 2910 – Client/Server-Side Programming

Designing in Security

• Make a discussion of security issues part of every design.

• Be sure to address concerns such as:– What is an appropriate use of script features?– How could those features be compromised?