1 / 40

CSCI 2910 Client/Server-Side Programming

CSCI 2910 Client/Server-Side Programming. Topic: More Topics in PHP Reading: Williams & Lane pp. 377-397. Today's Goals. Server-side applications open up a number of possibilities for malicious attacks

darrelt
Download Presentation

CSCI 2910 Client/Server-Side Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSCI 2910 Client/Server-Side Programming Topic: More Topics in PHP Reading: Williams & Lane pp. 377-397

  2. 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.

  3. Problems with User Input • You have no control over what users input to a form. • Your scripts need to examine input in order to prevent • unintentional characters from causing erroneous execution • malicious input from breaching security • Typically, JavaScript on the client side is used for form validation, but we need to do more on the server-side.

  4. 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 process that automatically escapes incoming data.

  5. 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 outputis critical to security

  6. 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.

  7. 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} • 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.

  8. 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.

  9. Other Form Issues • You can check the method of a form checking the PHP superglobal variable • $_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. • 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.

  10. 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. • Since PHP sends output to the client in "real time", i.e., as the output occurs, and since headers must be sent before the HTML file itself, calls to the header() function must be made before the script outputs anything.

  11. HTTP Headers (continued) • 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 (…);}else{ echo "Unable to redirect you.";}

  12. HTTP Headers – Redirect • The most common example is used 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.

  13. 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 filled out prefilled in the new form. • Remember that form elements in HTML can have preset values. • For example:<input type="text" name="first_name" value="David" />

  14. 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 preselect an option in a select element • To preset the value of a textarea, place the value between the <textarea> ... </textarea> tags

  15. 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.

  16. 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 natural disaster

  17. 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)

  18. 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 TODAYSAN 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.

  19. 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."

  20. Inserting PHP Using Form Inputs • Forms with text input may be used to insert PHP code. • Example: <?php print "Welcome, {$_POST['first_name']}";?> • Client could attempt to insert PHP code by using a first name such as (quotations are to be included): "; print "Gotcha!

  21. Inserting PHP Using Form Inputs (continued) • The PHP code that would be executed would be: print "Welcome, "; print "Gotcha!"; • 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.

  22. 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)."

  23. 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: <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.

  24. 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.

  25. 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>

  26. 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);}?>

  27. 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’

  28. 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.

  29. 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.

  30. 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);

  31. 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."

  32. 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…"

  33. Function htmlspecialchars() (continued) Specifically, the function translate 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;'

  34. 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)

  35. 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.

  36. 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

  37. 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.

  38. 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.)

  39. 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.

  40. 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?

More Related