Σχόλια 0

Το κείμενο της παρουσίασης

PHPSecurityWorkshopChris ShiﬂettBrain BulbThe PHP Consultancychris@brainbulb.comWho Am I?(Why Listen to Me?)Author of PHP Security (O'Reilly) and HTTP Developer'sHandbook (Sams)Author of Security Corner (php|architect) and Guru Speak(PHP Magazine)Founder of PHP Security ConsortiumMember of Zend Advisory Board and an author of the ZendPHP CertiﬁcationFounder and President of Brain Bulb, The PHP ConsultancyTalk OutlineIntroductionSecurity PrinciplesTwo Best Programming PracticesCharacteristics of a Secure DesignCommon PHP VulnerabilitiesPHP Security Audit HOWTO (abridged)More InformationQuestions and AnswersSecurity PrinciplesSecurity is a subjective topic.Security is very important, but not always most important.Security must be balanced with expense.Security must be balanced with usability.Security PrinciplesDefense in DepthLeast PrivilegeKeep It SimpleMinimize ExposureTwo Best Practices(The Least You Can Do)Filter InputEscape OutputFilter Input:What Is Input?Most input is obvious - form data ($_GETand$_POST),cookies ($_COOKIES), RSS feeds, etc.Some data is harder to identify -$_SERVER, data fromdatabases, etc.Some data is frequently misunderstood -$_SESSION, etc.The key is to identify the origin of data. If it originates from anyexternal source, it is input and must be ﬁltered.Filter Input:What Is Filtering?Filtering is the process by which you inspect data to prove itsvalidity.When possible, use a whitelist approach - assume data to beinvalid unless you can prove otherwise.Filtering is useless if you can't keep up with what has beenﬁltered and what hasn't.Employ a strict naming convention that lets you easily andreliably distinguish between ﬁltered and tainted data.Filter Input:Show Me the Code!<?php$clean = array();switch($_POST['color']){case 'red':case 'green':case 'blue':$clean['color'] = $_POST['color'];break;}?>Filter Input:Show Me More Code!<?php$clean = array();if (ctype_alnum($_POST['username'])){$clean['username'] = $_POST['username'];}?>Escape Output:What Is Output?Most output is obvious (anything sent to the client is output) -HTML, JavaScript, etc.The client isn't the only external destination - databases,session data stores, RSS feeds, etc.The key is to identify the destination of data. If it is being sentto any external source, it is output and must be escaped.Escape Output:What Is Escaping?Escaping is the process by which you escape any characterthat has a special meaning in the external system for which itis destined.Unless you’re sending data somewhere unusual, there isprobably a function that performs the escaping for you.The two most common destinations are the client (usehtmlentities()) and MySQL (usemysql_real_escape_string()).If you must write your own, make sure you’re exhaustive -ﬁnd a reliable and complete list of all characters with specialmeaning.Escape Output:Show Me the Code!<?php$html = array();$html['name'] = htmlentities($clean['name'],ENT_QUOTES, 'UTF-8');echo "<p>Welcome back, {$html['name']}.</p>";?>Escape Output:Show Me More Code!<?php$mysql = array();$mysql['username'] =mysql_real_escape_string($clean['username']);$sql = "SELECT *FROM profileWHERE username = '{$mysql['username']}'";$result = mysql_query($sql);?>Characteristics of aSecure DesignEasy to reliably distinguish between ﬁltered and tainted data.Easy to identify input.Easy to ensure that input is always ﬁltered.Easy to identify output.Easy to ensure that output is always escaped.Common PHPVulnerabilitiesSQL InjectionCross-Site ScriptingCommand InjectionSession FixationSession HijackingCross-Site Request ForgeriesSQL Injection:What's the Problem?<?php$query = "SELECT *FROM profileWHERE username = '{$_POST['username']}'";$result = mysql_query($query);?>SQL Injection:What's the Problem?<?php$query = "SELECT *FROM profileWHERE username = 'myname' OR 'foo' = 'foo'";$result = mysql_query($query);?>SQL Injection:What's the Solution?Filter input.Escape output.Use an escaping function native to your database(mysql_real_escape_string()for MySQL)If there isn't one,addslashes()is a good last resort.Never enable magic quotes.Cross-Site Scripting:What's the Problem?<?phpecho "<p>Welcome back,{$_GET['username']}.</p>";?>Cross-Site Scripting:What's the Problem?<?phpecho "<p>Welcome back,<script> ... </script>.</p>";?>Cross-Site Scripting:What's the Solution?Filter input.Escape output.Usehtmlentities()for escaping.If you want to allow some HTML to be interpreted, you canconvert speciﬁc entities back to HTML (whitelist approach).BBCode offers no protection.Command Injection:What's the Problem?<?phpecho exec("quota{$_POST['username']}");?>Command Injection:What's the Problem?<?phpecho exec("quotamyname; rm -rf /usr/local/apache");?>Command Injection:What's the Solution?Filter input.Escape output.The escaping function for commands isescapeshellcmd().Theescapeshellarg()function is also useful. It ensures thatthe data it escapes is treated as a single argument.Session Fixation:What's the Problem?PHP uses any session identiﬁer provided by the client.An attacker can take advantage of this by providing links toyour application with an embedded session identiﬁer.Session Fixation:What's the Problem?<a href="http://host/login.php?PHPSESSID=1234">Link</a>Session Fixation:What's the Solution?Usesession_regenerate_id()whenever there is a change inthe level of privilege.Session hijacking is useless if the user is unprivileged.Session Hijacking:What's the Problem?An attacker can impersonate another user if that user'ssession identiﬁer is known by the attacker.There are numerous conditions under which a sessionidentiﬁer can be compromised.The session identiﬁer is necessarily exposed, because thebrowser must identify itself upon each request.Session Hijacking:What's the Solution?Protect the session identiﬁer from exposure, prediction, andﬁxation.Use SSL and propagate it in a cookie.Propagate an authentication token in the URL to strengthenthe identity of the client.The authentication token must also not be predictable.Cross-Site Request Forgeries:What's the Problem?An attacker can send arbitrary HTTP requests from a victim.Because the requests originate from the victim, they canpotentially bypass traditional safeguards, including ﬁrewallsand access control.Cross-Site Request Forgeries:What's the Problem?<img src="http://host/buy.php?isbn=1234&quantity=100" />Cross-Site Request Forgeries:What's the Solution?Use a unique token in every form that you send to the user.Whenever you receive a request from the user that representsa form submission, check for this unique token.Cross-Site Request Forgeries:What's the Solution?<?phpsession_start();$token = md5(uniqid(rand(), true));$_SESSION['token'] = $token;?><form ...><input type="hidden" name="token"value="<?php echo $token; ?>" />...</form>PHP Security Audits:OverviewFocus on failures to ﬁlter input or escape output.This is accomplished primarily by tracking data.If tracking data is difﬁcult for you, then it's also difﬁcult for thedevelopers.If distinguishing between tainted and ﬁltered data is difﬁcultfor you, then it's also difﬁcult for the developers.PHP Security Audits:GuidelinesAsk questions. No one knows an application as well as thedeveloper(s).Have the design explained to you, and identify designproblems before you review the code.Swallow your pride. Your purpose is not to impress anyone.Provide speciﬁc references to code. Genericrecommendations are not a security audit.Educate yourself. Web application security is a highlyspecialized discipline. The more you know, the better theaudit.More InformationPHP Security Consortiumhttp://phpsec.org/PHP Security Consortium Libraryhttp://phpsec.org/library/PHP Security Guidehttp://phpsec.org/projects/guide/My Personal Web Sitehttp://shiﬂett.org/My Business Web Sitehttp://brainbulb.com/Questions and AnswersNow it's your chance to really get your money's worth!(Hopefully there is plenty of time left.)Feel free to ask me questions anytime.Visitbrainbulb.comfor PHP security audits, training, etc.Thanks for listening.PHPSecurityWorkshopChris ShiﬂettBrain BulbThe PHP Consultancychris@brainbulb.com