Web Security Model and JavaScript...
Transcript of Web Security Model and JavaScript...
Web Security Model and JavaScript Rootkits
Credits: slides adapted from Stanford and Cornell Tech
Yan Huang
BrowserandNetwork
Browser
•
NetworkOS
Hardware
websiterequest
reply
HTTP:HyperTextTransferProtocol
◆Usedtorequestandreturndata• Methods:GET,POST,HEAD,…
◆ Statelessrequest/responseprotocol• Eachrequestisindependentofpreviousrequests• Statelessnesshasasignificantimpactondesignandimplementationofapplications
◆ Evolution• HTTP1.0:simple• HTTP1.1:morecomplex
GET /default.asp HTTP/1.0 Accept: image/gif, image/x-bitmap, image/jpeg, */* Accept-Language: en User-Agent: Mozilla/1.22 (compatible; MSIE 2.0; Windows 95) Connection: Keep-Alive If-Modified-Since: Sunday, 17-Apr-96 04:32:58 GMT
HTTPRequest
Method File HTTP version Headers
Data – none for GETBlank line
HTTP/1.0 200 OK Date: Sun, 21 Apr 1996 02:20:42 GMT Server: Microsoft-Internet-Information-Server/5.0 Connection: keep-alive Content-Type: text/html Last-Modified: Thu, 18 Apr 1996 17:39:05 GMT Content-Length: 2543 <HTML> Some data... blah, blah, blah </HTML>
HTTPResponse
HTTP version Status code Reason phrase Headers
Data
WebsiteStoringInfoInBrowser
Acookieisafilecreatedbyawebsitetostoreinformationinthebrowser
Browser
•
Server
POST login.cgi username and pwd
Browser
•
Server
GET restricted.htmlCookie: NAME=VALUE
HTTP is a stateless protocol; cookies add state
•If expires = NULL, this session only
HTTP Header: Set-cookie: NAME=VALUE ; domain = (who can read) ; expires = (when expires) ; secure = (send only over HTTPS)
WhatAreCookiesUsedFor?
◆Authentication• Thecookieprovestothewebsitethattheclientpreviouslyauthenticatedcorrectly
◆ Personalization• Recognizetheuserfromapreviousvisitandcustomizethewebpages
◆ Tracking• Followtheuserfromsitetosite;learnhis/herbrowsingbehavior,preferences,andsoon
GoalsofWebSecurity
◆ BrowsetheWebSafely• Amaliciouswebsitecannotstealormodifyinformationfromlegitimatesitestoharmtheusers…
• …evenifvisitedconcurrentlywithalegitimatesite-inseparatebrowserwindows,tabs,oriframes
◆ SupportsecureWebapplications• ApplicationsdeliveredovertheWebshouldhavethesamesecuritypropertieswerequireforstandaloneapplications(whataretheseproperties?)
AllofTheseShouldBeSafe
◆ Safetovisitanevilwebsite
◆ Safetovisittwopagesatthesametime
◆ Safedelegation
TwoSidesofWebSecurity
◆Webbrowser• ResponsibleforsecurelyconfiningWebcontentpresentedbyvisitedwebsites
◆Webapplications• Onlinemerchants,banks,blogs,GoogleApps…• Mixofserver-sideandclient-sidecode
– Server-sidecodewritteninPHP,Ruby,ASP,JSP…runsontheWebserver
– Client-sidecodewritteninJavaScript…runsintheWebbrowser• Manypotentialbugs:XSS,XSRF,SQLinjection
WhereDoestheAttackerLive?
Browser
•
OS
Hardware
website
Web attacker
Network attacker
Malware attacker
WebAttacker
◆ Controlsamaliciouswebsite(attacker.com)• CanevenobtainanSSL/TLScertificateforhissite($0)
◆ Attractinguservisitstoattacker.com• Phishingemail,enticingcontent,searchresults,placedbyanadnetwork,blindluck…
• Attacker’sFacebookapp
◆ Attackerhasnootheraccesstousermachine!◆ Variation:“iframeattacker”
• Aniframewithmaliciouscontentincludedinanotherwisehonestwebpage– Syndicatedadvertising,mashups,etc.
DangerousWebsites
◆Microsoft’s2006“Webpatrol”studyidentifiedhundredsofURLsthatcouldsuccessfullyexploitunpatchedWindowsXPmachines• Manyinterlinkedbyredirectionandcontrolledbythesamemajorplayers
◆ “ButInevervisitriskywebsites”• 11exploitpagesareamongtop10,000mostvisited• Trick:putupapagewithpopularcontent,getintosearchengines,pagethenredirectstotheexploitsite– Oneofthemalicioussiteswasprovidingexploitsto75“innocuous”sitesfocusingon(1)celebrities,(2)songlyrics,(3)wallpapers,(4)videogamecheats,and(5)wrestling
OSvs.BrowserAnalogies
◆ Primitives• Systemcalls• Processes• Disk
◆ Principals:Users• Discretionaryaccesscontrol
◆ Vulnerabilities• Bufferoverflow• Rootexploit
◆ Primitives • Document object model • Frames • Cookies and localStorage
◆ Principals: “Origins” • Mandatory access control
◆ Vulnerabilities • Cross-site scripting • Universal scripting
Operating system Web browser
ActiveX
◆ ActiveX“controls”arecompiledbinariesthatresideontheclientmachine• Downloadedandinstalled,likeanyotherexecutable• ActivatedbyanHTMLobjecttagonthepage• Runasnativebinaries,notinterpretedbythebrowser
◆ Securitymodelreliesonthreecomponents• Digitalsignaturestoverifythesourceofthecontrol• Browserpolicycanrejectcontrolsfromnetworkzones• Controlscanbemarkedbyauthoras“safeforinitialization”or“safeforscripting”
Onceaccepted,installedandstarted,nocontroloverexecution!
InstallingActiveXControls
If you install and run, no further control over the code, same access as any other program you installed
ActiveXRisks
◆ FromMSDN:• “AnActiveXcontrolcanbeanextremelyinsecurewaytoprovidea
feature.BecauseitisaComponentObjectModel(COM)object,itcandoanythingtheusercandofromthatcomputer.Itcanreadfromandwritetotheregistry,andithasaccesstothelocalfilesystem.FromthemomentauserdownloadsanActiveXcontrol,thecontrolmaybevulnerabletoattackbecauseanyWebapplicationontheInternetcanrepurposeit,thatis,usethecontrolforitsownendswhethersincereormalicious.”
◆Howcanacontrolbe“repurposed?”• Onceacontrolisinstalled,anywebpagethatknowsthecontrol’sclassidentifier(CLSID)canaccessitusinganHTMLobjecttagembeddedinthepage
Browser:BasicExecutionModel
◆ Eachbrowserwindoworframe:• Loadscontent• Renders
– ProcessesHTMLandexecutesscriptstodisplaythepage– Mayinvolveimages,subframes,etc.
• Respondstoevents
◆ Events• Useractions:OnClick,OnMouseover• Rendering:OnLoad,OnUnload• Timing:setTimeout(),clearTimeout()
HTMLandScripts
<html>…<p>Thescriptonthispageaddstwonumbers<script> varnum1,num2,sum num1=prompt("Enterfirstnumber") num2=prompt("Entersecondnumber") sum=parseInt(num1)+parseInt(num2) alert("Sum="+sum)</script> …</html>
Browser receives content,
displays HTML and executes scripts
Event-DrivenScriptExecution
<script type="text/javascript"> function whichButton(event) { if (event.button==1) { alert("You clicked the left mouse button!") } else { alert("You clicked the right mouse button!") }} </script> … <body onmousedown="whichButton(event)"> … </body>
Function gets executed
when some event happens
Script defines a
page-specific function
JavaScript
◆ “Theworld’smostmisunderstoodprogramminglanguage”
◆ LanguageexecutedbytheWebbrowser• Scriptsareembeddedinwebpages• CanrunbeforeHTMLisloaded,beforepageisviewed,whileitisbeingviewed,orwhenleavingthepage
◆Usedtoimplement“active”webpagesandWebapplications
◆ Apotentiallymaliciouswebpagegetstoexecutesomecodeonuser’smachine
JavaScriptHistory
◆DevelopedbyBrendanEichatNetscape• ScriptinglanguageforNavigator2
◆ Laterstandardizedforbrowsercompatibility• ECMAScriptEdition3(akaJavaScript1.5)
◆ RelatedtoJavainnameonly• Namewaspartofamarketingdeal• “JavaistoJavaScriptascaristocarpet”
◆Variousimplementationsavailable• SpiderMonkey,RhinoJava,others
CommonUsesofJavaScript
◆ Pageembellishmentsandspecialeffects◆Dynamiccontentmanipulation◆ Formvalidation◆Navigationsystems◆Hundredsofapplications
• GoogleDocs,GoogleMaps,dashboardwidgetsinMacOSX,Philipsuniversalremotes…
JavaScriptinWebpages
◆ EmbeddedinHTMLasa<script>element• Writtendirectlyinsidea<script>element
– <script>alert("HelloWorld!")</script>• Inafilelinkedassrcattributeofa<script>element
<scripttype="text/JavaScript"src=“functions.js"></script>
◆ Eventhandlerattribute<ahref="http://www.yahoo.com"onmouseover="alert('hi');">
◆ Pseudo-URLreferencedbyalink<ahref=“JavaScript:alert(‘Youclicked’);”>Clickme</a>
DocumentObjectModel(DOM)
◆HTMLpageisstructureddata◆DOMisobject-orientedrepresentationofthehierarchicalHTMLstructure• Properties:document.alinkColor,document.URL,document.forms[],document.links[],…
• Methods:document.write(document.referrer)– Thesechangethecontentofthepage!
◆AlsoBrowserObjectModel(BOM)• Window,Document,Frames[],History,Location,Navigator(typeandversionofbrowser)
BrowserandDocumentStructure
W3C standard differs from models supported in existing browsers
ReadingPropertieswithJavaScript
Samplescript
• Example1returns"ul"• Example2returns"null"• Example3returns"li"• Example4returns"text"
– Atextnodebelowthe"li"whichholdstheactualtextdataasitsvalue• Example5returns"Item1"
1. document.getElementById('t1').nodeName 2. document.getElementById('t1').nodeValue 3. document.getElementById('t1').firstChild.nodeName 4. document.getElementById('t1').firstChild.firstChild.nodeName 5. document.getElementById('t1').firstChild.firstChild.nodeValue
<ul id="t1"> <li> Item 1 </li> </ul>
Sample HTML
PageManipulationwithJavaScript
◆ Somepossibilities• createElement(elementName)• createTextNode(text)• appendChild(newChild)• removeChild(node)
◆ Example:addanewlistitem
var list = document.getElementById('t1') var newitem = document.createElement('li') var newtext = document.createTextNode(text) list.appendChild(newitem) newitem.appendChild(newtext)
<ul id="t1"> <li> Item 1 </li> </ul>
Sample HTML
JavaScriptBookmarks(Favelets)
◆ Scriptstoredbythebrowserasabookmark◆ Executedinthecontextofthecurrentwebpage◆ Typicaluses:
• Submitthecurrentpagetoabloggingorbookmarkingservice
• Queryasearchenginewithhighlightedtext• Passwordmanagers
– One-clicksign-on– Automaticallygenerateastrongpassword– Synchronizepasswordsacrosssites
Must execute only inside the “right” page
Root-Kits
Arootkitmodifiestheuser-program-accessiblebehavioroftheoperatingsystemandescapesdetectionbyinterceptionoftheoperatingsystem’sreflectionAPIs– E.g.,removingitselffromtheoperatingsystem’slistofrunningprocesses
JavaScript Rootkits?
AJavaScript“Rootkit”[“Rootkits for JavaScript environments”]
A malicious webpage
JavaScript bookmark
if (window.location.host == "bank.com") doLogin(password);
Malicious page defines a global variable named “window” whose value is a fake “location” object var window = { location: { host: "bank.com" } };
Browsers let web pages override native objects to help with compatibility.
Let’sDetectFakeObjects[“Rootkits for JavaScript environments”]
A malicious webpage
JavaScript bookmark
window.location = “#”; If window.location is a native object, new value will be “https://bank.com/login#”
window.__defineGetter__("location", function () { return "https://bank.com/login#"; }); window.__defineSetter__("location", function (v) { });
Let’sDetectEmulation[“Rootkits for JavaScript environments”]
A malicious webpage
JavaScript bookmark
typeof obj.__lookupGetter__(propertyName) !== "undefined"
Attacker emulates reflection API itself! Object.prototype.__lookupGetter__ = function() { ... };
typeOf and !== avoid asking for the value of “undefined” (could be redefined by attacker!)
Use reflection API
DefensestoJavascriptRootkits
– StoreashortmastersecretinaSecurecookieforpwdmngr.com
– Thebookmarkletinitiatesanetworkrequesttohttps://pwdmngr.combyaddinga<script>tagtothecurrentpage
– Mustauthenticatethewebsitereceivingthepassword– ReferralheaderthroughHTTPS