poc2017 huiyu wu hybrid app security ... - power of community

54
标题文本 » 正文级别 1 正文级别 2 正文级别 3 正文级别 4 » 正文级别 5 HuiYu Wu @ Tencent Security Platform Department Hybrid App Security Attack and Defense

Upload: others

Post on 04-May-2022

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

标题文本

» 正文级别 1– 正文级别 2

•正文级别 3– 正文级别 4

» 正文级别 5

HuiYu Wu@TencentSecurityPlatformDepartment

HybridAppSecurityAttackandDefense

Page 2: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

AboutMe

• SecurityresearcheratTencentSecurityPlatformDepartment

• FocusonIoTsecurityandMobilesecurity

• BugHunter

• WinnerofGeekPwn 2015

• Blog:http://www.droidsec.cn

Page 3: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

AboutTencentSecurityPlatformDepartment

Establishedin2005,withover10yearsofexperienceincybersecurity,TencentSecurityPlatformDepartmenthasbeendedicatedtotheprotectionofQQ,WeChat,TencentGamesandothercriticalproducts.

Oursecurityresearchteamhasfound60+Google/Apple/Adobevulnerabilitiesinlastyears.

Page 4: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

AboutTSRC

TencentSecurityResponseCenter(TSRC),awebplatformfoundedbyus,pioneeredthevulnerabilityrewardprogramsinChina.WehopetoworkmorecloselywiththesecuritycommunitythroughTSRC.

Themaximumbonusforacriticalvulnerabilityisabout$75,000.

ToLearnmoreaboutourbugbountyprogramandsubmitvulnerabilityreports:

https://en.security.tencent.com

Page 5: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

Agenda• Whatishybridapp

• Hybridmobileappframework(ApacheCordova)

• Hybridappsecuritymodel

• Attacksurfaceofhybridapp

• Howtosecureyourhybridapp

• Conclusion

Page 6: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

Whatishybridapp?

Page 7: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

Whatishybridapp?

Page 8: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

AdvantagesofHybridApp

Page 9: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

HybridMobileAppFramework

Page 10: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

ApacheCordovaApacheCordova

Page 11: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

CordovaArchitecture

Page 12: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

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

}}

Page 13: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

CordovaExampleApp

Page 14: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

CordovaSecurityMechanism

Domainwhitelistingisasecuritymodelthatcontrolsaccesstoexternaldomainsoverwhichyourapplicationhasnocontrol.Cordovaprovidesaconfigurablesecuritypolicytodefinewhichexternalsitesmaybeaccessed.

Page 15: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

CordovaSecurityMechanism

Cordovawhitelistplugin1.NavigationWhitelistControlswhichURLstheWebViewitselfcanbenavigatedto.<allow-navigationhref="http://example.com/*"/>

2.IntentWhitelistControlswhichURLstheappisallowedtoaskthesystemtoopen.<allow-intenthref="http://*/*"/>

3.NetworkRequestWhitelistControlswhichnetworkrequestsareallowedtobemade.<accessorigin="http://google.com"/>

Page 16: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

WebSecurity(1)sameoriginpolicy(SOP)(2)ContentSecurityPolicy(CSP)

BridgeSecurity(1)OriginCheck

MobileSecurity(1)System PermissionManage

HybridAppSecurityModelWhitelist-basedsecurity

Page 17: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

Fromthesecurityperspective,thekeycomponentsofanyhybridframeworkarethebridge.In AndroidsystemWebView,developerscanusebridgemechanismtoimplementtheinteractionbetweenJavaScriptandNativeAPIs.

HybridAppSecurityModel

Page 18: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

AndroidWebViewBridges

JStoNative Bridge

(1)Interface-basedbridges

var result=window.jsbridge.getXX();

->

classJsObject {

@JavascriptInterface

publicStringgetXX(){return"injectedObject";}}

webView.addJavascriptInterface(newJsObject(),"jsbridge");

Page 19: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

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”)......

}

Page 20: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

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”)......}

Page 21: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

AndroidWebView Bridges

NativetoJS

(1)loadUrl

WebView.loadUrl("javascript:callFromJava('callfromjava')");

->

functioncallFromJava(str){console.log(str);}

Page 22: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

AndroidWebView Bridges

NativetoJS

(2)evaluateJavascript (Android4.4+)

WebView.evaluateJavascript("getGreetings()",newValueCallback<String>(){

@OverridepublicvoidonReceiveValue(Stringvalue){Log.i(LOGTAG,"onReceiveValue value="+value);

}}

->

functiongetGreetings(){return1;}

Page 23: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

HybridAppSecurityModel

Bridges

Illegalcalls

JavaScript

NativeAPIs

IsOriginURLinwhitelist?call InterceptRequest

NO

YES

InjectJScode?Originwhitelistbypass?

Exposedbridge?

Interceptallrequest?

Whitelist-basedsecurity

Page 24: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

l XSSVulnerability

l Man-in-the-MiddleAttack

l InsecureWhitelist

l ExportedJSBridge

l IncorrectURLinterception

AttackSurfaceofHybridApp

Page 25: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

XSSVulnerability

ifawebapplicationrunningwithinhybridmobileapplicationsuffersfromanXSSvulnerability,theattackerisabletoinvokeallexposedmethodsformaliciouspurposes.

Inotherwords,theattackerisabletoaccessthenativecapabilitiesandresourcesofthedeviceandcouldforexampleeasilystealcontactdetails,takepicturesorlocatethepositionofuser.

Page 26: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

Attacker

XSSVulnerability

Page 27: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

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

">

Page 28: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

InjectmaliciousJSPayload

IfanycontentfromawhitelistedoriginisretrievedoverHTTP(ornotproperlycheckSSLCertificates),aman-in-the-middleattacker—forexample,amaliciousWi-Fiaccesspoint—caninjectanattackscriptintoit.Thisscriptwillbetreatedbythebrowserasifitcamefromthewhitelistedorigin。

Man-in-the-MiddleAttack

Page 29: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

Man-in-the-MiddleAttack

UseBurpSuiteto intercepthttpResponseandInjectpayload

InjectmaliciousJSPayload toJSlibraryresources

Page 30: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

InsecureCordovaWhitelistConfig

1.<allow-navigationhref="*"/>AwildcardcanbeusedtowhitelisttheentirenetworkoverHTTP

andHTTPS.

2.<allow-intenthref="*"/>AllowallunrecognizedURLstoopeninstalledapps.

3.<accessorigin="*"/>Don'tblockanyrequests

InsecureWhitelist

Page 31: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

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

Page 32: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

InsecureURLcheck

ifurl.getHost().contains(“abc.com”)...

ifurl.getHost().startwith(“abc.com”)...->https://abc.com.evil.com

InsecureWhitelist

Page 33: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

Localfileinclusion+InsecureStorage

InsecureWhitelist

Page 34: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

AnyJavaScriptobjectaddedtotheembeddedbrowserbytheframework’sNativeAPIsviafunctionssuchas'addJavascriptInterface'inAndroid'sWebViewisavailablebydefaulttoJavaScriptinanyiframe,regardlessofitsorigin.

ExportedJSBridge

Page 35: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

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

Page 36: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

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

Page 37: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

IncorrectURLinterception

CVE-2014-3501

InordertoensurethataCordovaWebViewonlyallowsrequeststoURLsintheconfiguredwhitelist,theframeworkoverridesAndroid’sshouldInterceptRequest()method.

AsofAndroid4.4KitKat,theWebViewisrenderedbyChromiumandsupportsWebSocket protocol.An attackercanthereforemakeuseofaWebSocket connectiontobypasstheCordovawhitelistingmechanism.

newWebSocket(“ws://127.0.0.1/xxx”)

Page 38: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

AttackDemo

AttackhybridappbyaQRcode

Page 39: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

AttackDemo

Page 40: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

Howtosecureyourhybridapp

Page 41: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

HybridAppSecurityModel

Bridges

Illegalcalls

JavaScript

NativeAPIs

Check OriginURL &Tokencall InterceptRequest

NO

YES

InjectJScode?

Originwhitelistbypass?

Exposedbridge?

Interceptallrequest?

CSP

SessionToken SessionToken

Enhancedwhitelist-basedsecurity

Page 42: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

•useCSPto protectwebapp

•SSLCertificatePinning

•Usesessiontokentoprotectbridges

•Don'tuseiframe andeval()

•Updateyourhybridappframeworktothelastversion

•UsesystemWebView foroutsidelinks

•Validatealluserinput

•Removeunusedplugins

Howtosecureyourhybridapp

Page 43: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

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

Page 44: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

SSLCertificatePinningTheideahereisyoucansignificantlyreducethechancesofa

man-in-the-middleattackby"pinning"theallowedpubliccertificatesacceptedbyyourappwhenmakingtheconnectiontohighlytrusted,officialcertificateauthorities thatyouareactuallyusing.

TIPS : usingandroid:debuggable="true"intheCordovaapplicationmanifestwillpermitSSLerrorssuchascertificatechainvalidationerrorsonself-signedcerts.

Howtosecureyourhybridapp

Page 45: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

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

Page 46: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

(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

Page 47: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

Howtosecureyourhybridapp

Don'tuseiframe andeval()

Ifcontentisservedinaniframe fromawhitelisteddomain,thatdomainwillhaveaccesstothenativebridge.Thismeansthatifyouwhitelistathird-partyadvertisingnetworkandservethoseadsthroughaniframe,itispossiblethatamaliciousadwillbeabletobreakoutoftheiframe andperformmaliciousactions.

UseTheJavaScriptfunctioneval incorrectlycanopenyourcodeupforinjectionattacks.

Page 48: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

Howtosecureyourhybridapp

Updateyourhybridappframeworktothelastversion

13 CVE IDsfor ApacheCordova(PhoneGap)

Include8bridge/whitelistbypassvulnerabilities

BeginningJuly11,2016,GooglePlaywillblockpublishingofanynewappsor updatesthatusepre-4.1.1versionsofApacheCordova.

https://support.google.com/faqs/answer/6325474

Page 49: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

UsesystemWebView foroutsidelinks

UsethesystemWebView whenopeninglinkstoanyoutsidewebsite.Thisismuchsaferthanwhitelistingadomainnameandincludingthecontentdirectlyinyourapplication.

TheInAppBrowser pluginInCordovabehaveslikeastandardwebbrowser,andcan'taccessCordovaAPIs.Forthisreason,theInAppBrowser pluginisrecommendedifyouneedtoloadthird-party(untrusted)content,insteadofloadingthatintothemainCordovaWebView.

Howtosecureyourhybridapp

Page 50: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

Howtosecureyourhybridapp

Validatealluserinput

Alwaysvalidateanyandallinputthatyourapplicationaccepts.Thisincludesusernames,passwords,dates,uploadedmedia,etc.Thisvalidationshouldalsobeperformedonyourserver,especiallybeforehandingthedataofftoanybackendservice.

Othersourceswheredatashouldbevalidated:userdocuments,contacts,pushnotifications.

Page 51: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

Howtosecureyouhybridapp

Removeunusedplugins

ReducingtheattacksurfaceoftheapplicationisimportanttoreducetheimpactofvulnerabilitieslikeXSS,particularlypluginswithdangerousfunctionality,likefile,cameraandcontactaccess.

Page 52: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

Conclusion

• Hybridappisbecomingmoreandmorepopular.

• Thereisalargeattacksurfaceinhybridapp,includingmobilesecurityandwebsecurity.

• Wepresent somesuggestionstodeveloperstoensurethesecurityofhybrid mobile app.

Page 53: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

标题文本

» 正文级别 1– 正文级别 2

•正文级别 3– 正文级别 4

» 正文级别 5

ThankYou

[email protected]

Page 54: POC2017 HuiYu Wu Hybrid App Security ... - Power Of Community

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