370 likes | 501 Views
CSci 215 PHP Security. How would you completely secure a Website?. http://heykidscomics.com/1564web.jpg. A Security Mindset.
E N D
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 • FILTER external input • Forms • Files • External databases • Other: $_SERVER, $_COOKIE, etc. • ESCAPE output • Client browser • Database
Two Golden Rules xhtml Cookie Files Filter Escape PHP Script Forms Databases MYSQL POST, GET, COOKIE, etc.
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 expressionsto 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 • 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"; • } http://nettuts.com/tutorials/php/sanitize-and-validate-data-with-php-filters/#more-2595
More PHP Filters http://www.php.net/manual/en/filter.filters.validate.php http://php.net/manual/en/function.filter-var.php
Escaping Output • Process by which you escape characters that have a special meaning on a remote system. • Two most common outputs • xhtml to the browser • use htmlentities() • MySQL database • mysql_real_escape_string() escapes special characters • mysql_query allows only a single query to execute
Escape example Will convert both double and single quotes to entities version $xhtml = array(); $xhtml['username'] = htmlentities($username, ENT_QUOTES); echo"Welcome back, {$xhtml['username']}."; http://php.net/manual/en/function.htmlentities.php
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: • register_globals • spoofed forms • session fixation • SQL injection • cross-site scripting
1. register_globals • If register_globals is turned on, superglobal variable array values are available as variable names. $_POST[‘name’] is available as $name $_COOKIE[‘age’] is available as $age • Most PHP installations have register_globals turned off • If it is turned on, make sure your code is secure Use phpinfo() to check your settings.
Try It if (form submitted) { if (password and username match an entry in users list) $authorized = true; } if ($authorized) include '/highly/sensitive/data.php'; else display log-in form How could we get a value into this variable? http://ned.highline.edu/~tostrander/215/security/example1.php
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 this be prevented?
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. • Check referrer If($_POST[‘format’] == ‘HTML’ OR $_POST[‘format’] == ‘Text’)
HTTP_REFERER • Yes, it’s misspelled! • $_SERVER[‘HTTP_REFERER’] 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. 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 (s/he 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!");
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. • Escape your data • For a MySQL db, use the function mysql_real_escape_string()
5. 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 xhtml… 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 included into your page. htmlentities will .convert "<script>" to "<script>". This prevents the code from running if you display it on your website.
Storing Credentials • Keep as much code as possible, including definition of passwords, in included files outside of web accessible directories.
Be vigilant, but don’t panic! Filter Input + Escape Output = Secure Code