poc2017 huiyu wu hybrid app security ... - power of community
TRANSCRIPT
标题文本
» 正文级别 1– 正文级别 2
•正文级别 3– 正文级别 4
» 正文级别 5
HuiYu Wu@TencentSecurityPlatformDepartment
HybridAppSecurityAttackandDefense
AboutMe
• SecurityresearcheratTencentSecurityPlatformDepartment
• FocusonIoTsecurityandMobilesecurity
• BugHunter
• WinnerofGeekPwn 2015
• Blog:http://www.droidsec.cn
AboutTencentSecurityPlatformDepartment
Establishedin2005,withover10yearsofexperienceincybersecurity,TencentSecurityPlatformDepartmenthasbeendedicatedtotheprotectionofQQ,WeChat,TencentGamesandothercriticalproducts.
Oursecurityresearchteamhasfound60+Google/Apple/Adobevulnerabilitiesinlastyears.
AboutTSRC
TencentSecurityResponseCenter(TSRC),awebplatformfoundedbyus,pioneeredthevulnerabilityrewardprogramsinChina.WehopetoworkmorecloselywiththesecuritycommunitythroughTSRC.
Themaximumbonusforacriticalvulnerabilityisabout$75,000.
ToLearnmoreaboutourbugbountyprogramandsubmitvulnerabilityreports:
https://en.security.tencent.com
Agenda• Whatishybridapp
• Hybridmobileappframework(ApacheCordova)
• Hybridappsecuritymodel
• Attacksurfaceofhybridapp
• Howtosecureyourhybridapp
• Conclusion
Whatishybridapp?
Whatishybridapp?
AdvantagesofHybridApp
HybridMobileAppFramework
ApacheCordovaApacheCordova
CordovaArchitecture
CordovaExampleAppfunctionshowPhoneNumber(name){var successCallback =function(contact){alert("Phonenumber:"+contacts.phone);
}var failureCallback =...cordova.exec(successCallback ,failureCallback ,"ContactsPlugin","find",[{"name":name}]);
}
classContactsPlugin extendsCordovaPlugin {boolean execute(Stringaction,CordovaArgs args,CallbackContext callbackContext){if("find".equals(action)){Stringname=args.get(0).name;find(name,callbackContext);}elseif("create".equals(action))...
}voidfind(Stringname,CallbackContext callbackContext){Contactcontact =query("SELECT...wherename="+name);callbackContext.success(contact);
}}
CordovaExampleApp
CordovaSecurityMechanism
Domainwhitelistingisasecuritymodelthatcontrolsaccesstoexternaldomainsoverwhichyourapplicationhasnocontrol.Cordovaprovidesaconfigurablesecuritypolicytodefinewhichexternalsitesmaybeaccessed.
CordovaSecurityMechanism
Cordovawhitelistplugin1.NavigationWhitelistControlswhichURLstheWebViewitselfcanbenavigatedto.<allow-navigationhref="http://example.com/*"/>
2.IntentWhitelistControlswhichURLstheappisallowedtoaskthesystemtoopen.<allow-intenthref="http://*/*"/>
3.NetworkRequestWhitelistControlswhichnetworkrequestsareallowedtobemade.<accessorigin="http://google.com"/>
WebSecurity(1)sameoriginpolicy(SOP)(2)ContentSecurityPolicy(CSP)
BridgeSecurity(1)OriginCheck
MobileSecurity(1)System PermissionManage
HybridAppSecurityModelWhitelist-basedsecurity
Fromthesecurityperspective,thekeycomponentsofanyhybridframeworkarethebridge.In AndroidsystemWebView,developerscanusebridgemechanismtoimplementtheinteractionbetweenJavaScriptandNativeAPIs.
HybridAppSecurityModel
AndroidWebViewBridges
JStoNative Bridge
(1)Interface-basedbridges
var result=window.jsbridge.getXX();
->
classJsObject {
@JavascriptInterface
publicStringgetXX(){return"injectedObject";}}
webView.addJavascriptInterface(newJsObject(),"jsbridge");
AndroidWebView Bridges
JStoNative Bridge(2)Event-basedbridges
var result=prompt('[]','jsbridge://method?parm')
->
publicboolean onJsPrompt(WebViewview,Stringurl,Stringmessage,StringdefaultValue,JsPromptResult result){
ifurl.getScheme.equals(“jsbridge”)......
}
AndroidWebView Bridges
JStoNative Bridge
(3)URLinterposition-basedbridges
window.location.href="jsbridge://method?parm";
<iframe src="jsbridge://method?parm";>
->
publicboolean shouldOverrideUrlLoading(WebViewview,Stringurl){ifurl.getScheme.equals(“jsbridge”)......}
publicWebResourceResponse shouldInterceptRequest(WebViewview,String url){ifurl.getScheme.equals(“jsbridge”)......}
AndroidWebView Bridges
NativetoJS
(1)loadUrl
WebView.loadUrl("javascript:callFromJava('callfromjava')");
->
functioncallFromJava(str){console.log(str);}
AndroidWebView Bridges
NativetoJS
(2)evaluateJavascript (Android4.4+)
WebView.evaluateJavascript("getGreetings()",newValueCallback<String>(){
@OverridepublicvoidonReceiveValue(Stringvalue){Log.i(LOGTAG,"onReceiveValue value="+value);
}}
->
functiongetGreetings(){return1;}
HybridAppSecurityModel
Bridges
Illegalcalls
JavaScript
NativeAPIs
IsOriginURLinwhitelist?call InterceptRequest
NO
YES
InjectJScode?Originwhitelistbypass?
Exposedbridge?
Interceptallrequest?
Whitelist-basedsecurity
l XSSVulnerability
l Man-in-the-MiddleAttack
l InsecureWhitelist
l ExportedJSBridge
l IncorrectURLinterception
AttackSurfaceofHybridApp
XSSVulnerability
ifawebapplicationrunningwithinhybridmobileapplicationsuffersfromanXSSvulnerability,theattackerisabletoinvokeallexposedmethodsformaliciouspurposes.
Inotherwords,theattackerisabletoaccessthenativecapabilitiesandresourcesofthedeviceandcouldforexampleeasilystealcontactdetails,takepicturesorlocatethepositionofuser.
Attacker
XSSVulnerability
XSSVulnerability
HowtouseaXSSvulnerabilitytostealcontacts
<img src=xonerror="navigator.contacts.find(['displayName','phoneNumbers'],function(c){r='';for(i=0;c[i];i++){if(c[i].phoneNumbers&&c[i].phoneNumbers.length){r+=c[i].displayName+c[i].phoneNumbers[0].value+'\n';
}}alert(r);
">
InjectmaliciousJSPayload
IfanycontentfromawhitelistedoriginisretrievedoverHTTP(ornotproperlycheckSSLCertificates),aman-in-the-middleattacker—forexample,amaliciousWi-Fiaccesspoint—caninjectanattackscriptintoit.Thisscriptwillbetreatedbythebrowserasifitcamefromthewhitelistedorigin。
Man-in-the-MiddleAttack
Man-in-the-MiddleAttack
UseBurpSuiteto intercepthttpResponseandInjectpayload
InjectmaliciousJSPayload toJSlibraryresources
InsecureCordovaWhitelistConfig
1.<allow-navigationhref="*"/>AwildcardcanbeusedtowhitelisttheentirenetworkoverHTTP
andHTTPS.
2.<allow-intenthref="*"/>AllowallunrecognizedURLstoopeninstalledapps.
3.<accessorigin="*"/>Don'tblockanyrequests
InsecureWhitelist
RegexBypass (CVE-2012-6637)
Notregistereddomains/ExpiredDomains/Specialsubdomain
(1)Pattern.compile("^https\\:\\/\\/.*[.]abc[.](com|net|cc|hk)$")->http://abc.cc
(2)Pattern.compile("ˆhttps?://(.*\\.)?"+abc.com))->https://abc.com.evil.com
InsecureWhitelist
InsecureURLcheck
ifurl.getHost().contains(“abc.com”)...
ifurl.getHost().startwith(“abc.com”)...->https://abc.com.evil.com
InsecureWhitelist
Localfileinclusion+InsecureStorage
InsecureWhitelist
AnyJavaScriptobjectaddedtotheembeddedbrowserbytheframework’sNativeAPIsviafunctionssuchas'addJavascriptInterface'inAndroid'sWebViewisavailablebydefaulttoJavaScriptinanyiframe,regardlessofitsorigin.
ExportedJSBridge
CVE-2012-6336
functionexecute(cmdArgs){for(var obj inwindow){if("getClass"inwindow[obj]){alert(obj);return
window[obj].getClass().forName("java.lang.Runtime").getMethod("getRuntime",null).invoke(null,null).exec(cmdArgs);
}}
}
ExportedJSBridge
IncorrectURLinterception
GET POST XMLHttp Iframe WebSocket
shouldOverrideUrlLoading YES NO NO NO NO
shouldInterceptRequest YES NO YES YES NO
postUrl NO YES NO NO NO
AndroidWebView allowsdeveloperstointerceptandpreventinsecurewebresourcesfrombeingloadedbyimplementingthecallbackfunctions.IfdevelopersuseaincorrectURL interceptionfunction,itcan
leadtoawhitelistbypasssecurityvulnerability.
URLinterceptioninAndroidWebView
IncorrectURLinterception
CVE-2014-3501
InordertoensurethataCordovaWebViewonlyallowsrequeststoURLsintheconfiguredwhitelist,theframeworkoverridesAndroid’sshouldInterceptRequest()method.
AsofAndroid4.4KitKat,theWebViewisrenderedbyChromiumandsupportsWebSocket protocol.An attackercanthereforemakeuseofaWebSocket connectiontobypasstheCordovawhitelistingmechanism.
newWebSocket(“ws://127.0.0.1/xxx”)
AttackDemo
AttackhybridappbyaQRcode
AttackDemo
Howtosecureyourhybridapp
HybridAppSecurityModel
Bridges
Illegalcalls
JavaScript
NativeAPIs
Check OriginURL &Tokencall InterceptRequest
NO
YES
InjectJScode?
Originwhitelistbypass?
Exposedbridge?
Interceptallrequest?
CSP
SessionToken SessionToken
Enhancedwhitelist-basedsecurity
•useCSPto protectwebapp
•SSLCertificatePinning
•Usesessiontokentoprotectbridges
•Don'tuseiframe andeval()
•Updateyourhybridappframeworktothelastversion
•UsesystemWebView foroutsidelinks
•Validatealluserinput
•Removeunusedplugins
Howtosecureyourhybridapp
useCSPtoprotectweb appOnAndroidandiOS,thenetworkrequestwhitelistisnot
abletofilteralltypesofrequests(e.g.<video>&WebSocketsarenotblocked).So,inadditiontothewhitelist,youshoulduseaContentSecurityPolicy<meta>tagonallofyourpages.
CSPGuide:http://www.html5rocks.com/en/tutorials/security/content-security-policy/
TIPS : Bydefault,applyingaCSPdisablesbotheval()andinlinescriptwhiletheCSPintheCordovatemplatedisablesinlinebutallowseval().
Howtosecureyourhybridapp
SSLCertificatePinningTheideahereisyoucansignificantlyreducethechancesofa
man-in-the-middleattackby"pinning"theallowedpubliccertificatesacceptedbyyourappwhenmakingtheconnectiontohighlytrusted,officialcertificateauthorities thatyouareactuallyusing.
TIPS : usingandroid:debuggable="true"intheCordovaapplicationmanifestwillpermitSSLerrorssuchascertificatechainvalidationerrorsonself-signedcerts.
Howtosecureyourhybridapp
Usesessiontokentoprotectbridgesusea"sessiontoken" canpreventunauthorizedaccessto interface
bridges.There isaexample “BridgeSecret”inCordova.
(1)Sessiontokenissetinmainframeoriginandonlyexposednativemethodisaninit method.TheSOPpreventsforeign-originfromaccessingthetoken.
int generateBridgeSecret(){SecureRandom randGen =newSecureRandom();expectedBridgeSecret =randGen.nextInt(Integer.MAX_VALUE);returnexpectedBridgeSecret;
}
Howtosecureyourhybridapp
(2)Ifinit methodiscalledwithcorrectsessiontoken,thenthebridgeexposesadditionalmethodsdynamically.
prompt(argsJson,'jsbridge:'+JSON.stringify([bridgeSecret,service,action,callbackId]));
->
privateboolean verifySecret(Stringaction,int bridgeSecret)throwsIllegalAccessException {......if(expectedBridgeSecret <0||bridgeSecret !=expectedBridgeSecret){
......}else{….}}
Howtosecureyourhybridapp
Howtosecureyourhybridapp
Don'tuseiframe andeval()
Ifcontentisservedinaniframe fromawhitelisteddomain,thatdomainwillhaveaccesstothenativebridge.Thismeansthatifyouwhitelistathird-partyadvertisingnetworkandservethoseadsthroughaniframe,itispossiblethatamaliciousadwillbeabletobreakoutoftheiframe andperformmaliciousactions.
UseTheJavaScriptfunctioneval incorrectlycanopenyourcodeupforinjectionattacks.
Howtosecureyourhybridapp
Updateyourhybridappframeworktothelastversion
13 CVE IDsfor ApacheCordova(PhoneGap)
Include8bridge/whitelistbypassvulnerabilities
BeginningJuly11,2016,GooglePlaywillblockpublishingofanynewappsor updatesthatusepre-4.1.1versionsofApacheCordova.
https://support.google.com/faqs/answer/6325474
UsesystemWebView foroutsidelinks
UsethesystemWebView whenopeninglinkstoanyoutsidewebsite.Thisismuchsaferthanwhitelistingadomainnameandincludingthecontentdirectlyinyourapplication.
TheInAppBrowser pluginInCordovabehaveslikeastandardwebbrowser,andcan'taccessCordovaAPIs.Forthisreason,theInAppBrowser pluginisrecommendedifyouneedtoloadthird-party(untrusted)content,insteadofloadingthatintothemainCordovaWebView.
Howtosecureyourhybridapp
Howtosecureyourhybridapp
Validatealluserinput
Alwaysvalidateanyandallinputthatyourapplicationaccepts.Thisincludesusernames,passwords,dates,uploadedmedia,etc.Thisvalidationshouldalsobeperformedonyourserver,especiallybeforehandingthedataofftoanybackendservice.
Othersourceswheredatashouldbevalidated:userdocuments,contacts,pushnotifications.
Howtosecureyouhybridapp
Removeunusedplugins
ReducingtheattacksurfaceoftheapplicationisimportanttoreducetheimpactofvulnerabilitieslikeXSS,particularlypluginswithdangerousfunctionality,likefile,cameraandcontactaccess.
Conclusion
• Hybridappisbecomingmoreandmorepopular.
• Thereisalargeattacksurfaceinhybridapp,includingmobilesecurityandwebsecurity.
• Wepresent somesuggestionstodeveloperstoensurethesecurityofhybrid mobile app.
1. https://cordova.apache.org/docs/en/latest/guide/appdev/security/index.html
2. https://packetstormsecurity.com/files/124954/apachecordovaphonegap-bypass.txt
3. http://taco.visualstudio.com/en-us/docs/cordova-security-platform/
4. https://www.cvedetails.com/vulnerability-list/vendor_id-45/product_id-27153/Apache-Cordova.html
5. https://labs.mwrinfosecurity.com/assets/BlogFiles/Fracking-With-Hybrid-Mobile-Applications.compressed.pdf
6. https://dl.acm.org/citation.cfm?id=2990915
7. https://www.blackhat.com/docs/asia-15/materials/asia-15-Grassi-The-Nightmare-Behind-The-Cross-Platform-Mobile-Apps-Dream.pdf
Reference