Skip to main content
Android Secure Coding
2015-07-17
Masaki Kubo, Yozo Toda
Vulnerability Analysis Team
JPCERT Coordination Center
Copyright©2015 JPCERT/CC All rights reserved.
© 2015 JPCERT Coordination Center
This material is distributed by JPCERT/CC to course attendees for
their own individual study.
This material SHALL NOT be reproduced or used in any other
manner without requesting formal permission from JPCERT/CC at
secure-coding@jpcert.or.jp.
THE MATERIAL IS PROVIDED ON AN “AS IS” BASIS, AND JPCERT
COORDINATION CENTER DISCLAIMS ANY AND ALL
WARRANTIES, IMPLIED OR OTHERWISE (INCLUDING, BUT NOT
LIMITED TO, WARRANTY OF FITNESS FOR A PARTICULAR
PURPOSE, RESULTS OBTAINED FROM USE OF THE MATERIAL,
MERCHANTABILITY, AND/OR NON-INFRINGEMENT).
2
Copyright©2015 JPCERT/CC All rights reserved.
Instructors
Yozo Toda
Lead Analysit
yozo.toda@jpcert.or.jp
Joined JPCERT in 2001. As a veteran analyst,
Yozo is serving as a technical advisor for
vulnerability handlingteam. As a secure
coding evangelist, Yozo is active in training
programmers, writing technical documents,
translating books, presenting in
conferences including JavaOne, JJUG, Open
Source Conference. GSSP-C certified
programmer.
Yozo receivedB.Sc. in Mathematics from
Tokyo Metropolitan University and M.Sc. in
Computer Science fromTokyo Institute of
Technology.
Masaki Kubo
VulnerabilityAnalysis Team Lead
masaki.kubo@jpcert.or.jp
Masaki is leading the vulnerability analysis
team and secure coding initiative at
JPCERT. He has taught over 4000
programmers in Japan and Asia-Pacific
regions since 2006. Expert of ISO/IEC SC27
WG4. Visiting lecturer at National Institute
of Informatics and Tokyo Denki Univ.
Masaki studied at Keio University (B.A. in
Environmental Information) and
Dartmouth College (A.M. in Electro-acoustic
Music).
3
Copyright©2015 JPCERT/CC All rights reserved.
Timetable
4
Time Agenda
09:00 – 09:30 Part 1. Introduction
09:30 – 12:00 Part 2. Secure Coding (including short break)
12:00 – 13:00 Lunch Break
13:00 – 14:30 Part 3. Exercise: Vulnerability Analysis
14:30 – 14:45 Break
14:45 – 16:45 Part 4. Exercise: Security Code Review
16:45 – 17:00 Q & A session. Feedback. Closing Remarks.
Copyright©2015 JPCERT/CC All rights reserved.
Goals
Study Android app vulnerabilities from the real-world
examples
Learn secure coding techniques to avoid these
vulnerabilities
5
Copyright©2015 JPCERT/CC All rights reserved.
Audience
App Developer
Auditor / QA
Vulnerability Researcher
6
Copyright©2015 JPCERT/CC All rights reserved.
Vulnerability Analysis Team at JPCERT/CC
Conduct root cause analysis of vulnerabilities
—Reproduce, reverse engineer, analyze source, review design,
etc
Talk to vendors to have the vulnerability fixed
Talk to developers on secure coding (C, C++, Java and
Android)
R&D
7
Copyright©2015 JPCERT/CC All rights reserved.8
Introduction
Part 1
Photo by Joi Ito
Copyright©2015 JPCERT/CC All rights reserved.
Android Users Grow in 2014
9
[Source] The Guardian(January
13, 2014)
“Smartphone explosion in
2014 will see ownership in
India pass US”
Copyright©2015 JPCERT/CC All rights reserved.
Android Security on News Headlines
10
http://securityintelligence.com/mobile-malware-threats-in-2015-fraudsters-are-still-two-steps-ahead/
http://securityintelligence.com/mazeltov-more-android-malware-coming-to-a-mobile-device-near-you/#.Vac5BBNCrfA
Copyright©2015 JPCERT/CC All rights reserved.
Android Security on News Headlines
11
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/
Copyright©2015 JPCERT/CC All rights reserved.
Categorization of Android App Security Issues
12
Viruses
(Malicious Apps)
Potentially
Unwanted
Apps
Vulnerable
Apps
Research  on  Android  App  Vulnerabilities,  Oct.  2013
http://www.sonydna.com/sdna/solution/android_̲vulnerability_̲report_̲201310.pdf
Copyright©2015 JPCERT/CC All rights reserved.
Categorization of Android App Security Issues
13
Viruses
(MaliciousApps)
Potentially
Unwanted
Apps
Vulnerable
Apps
Not much
developers can
do with
Yes, this is our concern.
The responsibility is on
App developers.
Copyright©2015 JPCERT/CC All rights reserved.
Easily  Mitigated
Virus
(Malicious Apps)
Potentially
Unwanted
Apps
Vulnerable
Apps
Category PotentialImpact Countermeasures
Distribute virus-infected apps
to end users
Scan apps with Anti-Virus
before releasing them
Distribute annoying apps to
end users, bringing bad
corporate reputation
Change the design so that it
will not collectuser’s sensitive
data unnecessarily. Prepare
and publish privacy policy of
the app.
End  usersʼ’  privacy get  
compromised.  Damages  
corporation  reputation  as  well.
App developers need to design
apps secure and code securely.
Impact and Countermeasures
14
Challenging
Copyright©2015 JPCERT/CC All rights reserved.
Secure Android App Development
15
Scan  with Anti-‐‑‒Virus  
before  releasing  apps
Design not to annoy
endusers
The focus of
this course
Virus
(Malicious Apps)
Potentially
Unwanted
Apps
Vulnerable
Apps
Copyright©2015 JPCERT/CC All rights reserved.
Android App Vulnerabilities Reported in Japan
16
http://www.ipa.go.jp/security/vuln/report/JVNiPedia2012q3.html
The year of Vulnerable App
Explosion of private report in 2012
Apps
#
The number of Android OS software vulnerability reported by the year
Copyright©2015 JPCERT/CC All rights reserved.
Survey of Android App Vulnerabilities
17
Survey of Vulnerabilities in Android Apps 2013
http://www.sonydna.com/sdna/solution/android_vulnerability_report_201310.pdf
96% of  the  Apps  in  the  market  are  vulnerable
Vulnerable
Almost all the android apps contain some vulnerability
Copyright©2015 JPCERT/CC All rights reserved.
The Same Mistakes are Repeated
Same easy mistakes are
repeated
—File permissions
—Logging
—Exported settings
All the app developer
should have:
—Android specific security
model
—Secure coding best
pracitce
18
http://www.ipa.go.jp/about/technicalwatch/pdf/120613
report.pdf
component
file
Improper
Access Controlothers
Android app vulnerabilities
reported to IPA
Vulnerability Trend
Copyright©2015 JPCERT/CC All rights reserved.
Android App Vuls JPCERT has coordinated
19
Etc.
Advisories  Published:    over  50  Apps
Under  Coordination:  200  Apps
Developers have been cooperative and
responsive for most of the cases
Developers have been cooperative and
responsive for most of the cases
Copyright©2015 JPCERT/CC All rights reserved.
Vulnerability Categories
20
App Component Exposure
1. Unintended Activity Exposure
2. Local Server Accessible from Other Apps
3. Unintended Content Provider Exposure
WebView
4. File scheme
5. addJavascriptInterface
6. Location Bar Spoofing
7. JavaScript execution context
App Data Leakage
8. Broadcasting sensitive information
9. Loging sensitive information
10. Storing sensitive data in SD card
11. Improper File Permissions
HTML 5
12. Geolocation API and Privacy Concern
‘Classic’ Errors
13. Cryptographic Issues
14. Path traversal
15. Unsafe Decompression of Zip Files
16. Improper Certificate Verification
Copyright©2015 JPCERT/CC All rights reserved.
‘Bugs’ and ‘Vulnerabilities’
21
Traditional
Bug Vulnerability
Intended
Behavior Actual Behavior
Whittaker and Thompson, 2003
Secure software does what it is supposed to do
and doesn’t do what is not expected to do.
Secure software does what it is supposed to do
and doesn’t do what is not expected to do.
Copyright©2015 JPCERT/CC All rights reserved.
Secure Coding
22
Coding Errors
Flaws, Bugs,
Defects
Vulnerabilities
Root Cause
Small set of
patterns
Secure coding
patterns
Copyright©2015 JPCERT/CC All rights reserved.
Android App Vulnerabilities
In Part 2, we will look at each real world
vulnerabilities and discuss:
► Nature of the vulnerability
► Root cause
► How to fix the vulnerability
► References
23
Copyright©2015 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.pdf
24
Updated in June 1st, 2015.
Intended to be copied and pasted for
commercialuse.
Sample code is under Apache License
version 2.0.
Copyright©2015 JPCERT/CC All rights reserved.
Reference for a Developer
www.droidsec.org
—One of the most exhaustive list of materials related to
Android security
Whitepapers
Tools
Exploits
Crack-Me
Books
Miscellaneous stuffs
25
Copyright©2015 JPCERT/CC All rights reserved.26
Secure Coding
Part 2
Photo by Breyten Ernsting
Copyright©2015 JPCERT/CC All rights reserved.27
App Component Exposure
1.Unintended Activity Exposure
2.Local Server Accessible from Other Apps
3.Unintended Content Provider Exposure
Copyright©2015 JPCERT/CC All rights reserved.28
Unintended Activity Exposure
CASE #1
Copyright©2015 JPCERT/CC All rights reserved.
3rd Party Twitter Client Improper Access Control to its
Components
29
Allows other application with no
network access permissions to upload
pictures
3rd party Twitter client for Android with
picture uploading capability
Malicious app could
impersonate the
user to tweet
https://play.google.com/store/apps/details?id=jp.r246.twicca
http://jvn.jp/en/jp/JVN31860555/
Copyright©2015 JPCERT/CC All rights reserved.
Attack Scenario – Private Data Disclosure
30
malware
Twitter
1. Malware generates the URL for a
picture in local storage (file://...)
2. Malware starts the picture-
uploading activity by passing the
URL
3. The vulnerable app tweets with
the specified picture
Private  data
disclosure
Personal information is
now made publicfile://sdcard/…/my-privacy.jpg
Copyright©2015 JPCERT/CC All rights reserved.
Attack Scenario – Impersonation
31
malware
Twitter
1. Malware generates the URL for
a malicious picture (file://...)
2. Malware starts the picture-
uploading activity by passing
the URL
3. The vulnerable app tweets with
the specified picture
Malicious picture is tweeted
from the user’s twitter account
file://mal/malpic.jpg
impersonation
悪
悪
悪
悪
Copyright©2015 JPCERT/CC All rights reserved.
Root Cause
32
malware
Startingthe picture
uploading activity
Intent
• Picture-uploading activity was intended to be used internally
• However the activity was exported (accessible from other apps)!
• Other apps could send intents (request actions) to this activity
Activity is
exported
Copyright©2015 JPCERT/CC All rights reserved.
Solution
33
malware
Declare the activity private explicitly by
android:exported=“false”
Declared as a
private activity
...
<activity
android:name=".PicUploadActivity"
...
android:exported="false" />
...
AndroidManifest.xml
Copyright©2015 JPCERT/CC All rights reserved.
JSSEC Secure Coding Guidebook
34
4.1.1.1. Creating/UsingPrivate Activities Guideline to define
privately used Activity
sample manifest
Sample java code
Seucre coding points
android:exported="false
"
Sample app that
demonstratedthe
implementation of
secure coding
points
Copyright©2015 JPCERT/CC All rights reserved.
How the App was Fixed
35
…
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 …
}
}
The added code checks if the package name of the calling code is
the same as its own package name.
this check
was added
The more appropriate fix is “exported  =  false”.
Copyright©2015 JPCERT/CC All rights reserved.36
Local Web Server
Accessible from Other Apps
CASE #2
Copyright©2015 JPCERT/CC All rights reserved.
About the App
ES File Explorer File Manager
—com.estrongs.android.pop
Feature
— File and application manager
Vulnerability
—Files store in the external media became accessible over the
network
37
Copyright©2015 JPCERT/CC All rights reserved.
HTTP Server Started in the App
When you play music files or videos using this app, the
app starts the HTTP Server in device which is remotely
accessible
38
Copyright©2015 JPCERT/CC All rights reserved.
Unrestricted Access
The HTTP Server allowed
unrestricted access
By accessing the HTTP
Server remotely, a list of
files on the external media
could be seen
—Attackers can download
those files
39
Copyright©2015 JPCERT/CC All rights reserved.
Attack Scenarios
Conditions
—An attacker can only exploit the vulnerability when media
files are played by the user of the app
Scenarios
—The user must be forced to play media files somehow
—An attacker needs to obtain the IP address of the device
—The device need to be remotely accessible
40
could be difficult to attack
Copyright©2015 JPCERT/CC All rights reserved.
Solution
Limit the accessibility to the local server
—user authentication by user id / password
—IP address restrictions
Things to Consider
—Any other apps need to access the local server ?
—Do you really need to launch a local web server ?
41
Copyright©2015 JPCERT/CC All rights reserved.42
Unintended Content Provider
Exposure
CASE #3
Copyright©2015 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
43
Copyright©2015 JPCERT/CC All rights reserved.
Case
Vulnerable app (has not been fixed yet)
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.
Vulnerability
—The Content Provider was made public. Other apps could
access the application data via Content Provider of the app.
44
Copyright©2015 JPCERT/CC All rights reserved.
Intention of the Developer
Designed the ContentProvider accessible from any apps to
share application data
45
App A
by the same developer
Vulnerable App
ContentProviderContentProvider
READ/WRITEREAD/WRITE
DatabaseDatabase
App B
by the same developer
Copyright©2015 JPCERT/CC All rights reserved.
Cannot Block Malicious Apps
Malicious apps can also access application data through
the Content Provider
46
Malicious App
retrieve/manipulateretrieve/manipulate
Vulnerable App
ContentProviderContentProvider
READ/WRITEREAD/WRITE
datadata
Copyright©2015 JPCERT/CC All rights reserved.
Details
The ContentProvider was designed to be used internally
as well as externally
Intended to be used by other apps developed by the same
company
47
Vulnerable  App
ContentProviderContentProvider
DatabaseDatabase
Calendar  
Activity
Calendar  
Activity
Memo
Activity
Memo
Activity
Photo  Memo
Activity
Photo  Memo
Activity
Voice Memo
Activity
Voice Memo
Activity
TODO
Activity
TODO
Activity
Direct  DB  
Access
Direct  DB  
Access
App A
the same developer
Malicious  App
No  Access  
Restriction
Any  App  can  
Access
No  Access  
Restriction
Any  App  can  
Access
Copyright©2015 JPCERT/CC All rights reserved.
Data Access/Manipulation
What can attacker do ?
Note memos, photos, TODO, Voice memos
—Retrieve and manipulate application data
48
final  String  CONTENT_URI  =  "content://jp.co.XXXX.XXXXXX";
ContentValues values  =  new  ContentValues();
values.put("filename",  "/data/data/jp.co.XXXX.XXXXXX/databases/xxx");
values.put("titlename",  "hogehoge");
getContentResolver().insert(Uri.parse(CONTENT_URI  +  "/textmemo"),  values);
Ex.  Malicious  code  to  add  data  to  a  memo
Copyright©2015 JPCERT/CC All rights reserved.
To Share Data
Consider:
Range of the apps that you want to share data with
—unspecified large number of apps?
—apps that have the same signature?
—apps that have a specific permission?
Contents of the data
—Safe data to be shared with other apps?
What do you want to allow?
—Only allow retrieving the data?
—Or allow to add, edit or delete data as well?
49
Copyright©2015 JPCERT/CC All rights reserved.
To Share Data #1
Share data with any apps (unlimited)
A ContentProvider used to be made public to other apps
by default (before API17)
After Android 4.2 (API17), a ContentProvider is private
unless you explicitly make it public
—To make it private, set android:minSdkVersion and
android:targetSdkVersion to 17 or later
50
<provider   android:name="SampleContentProvider"
android:authorities=“com.example.app.Provider”
android:exported="true"   />
AndroidManifest.xml
Copyright©2015 JPCERT/CC All rights reserved.
To Share Data #2
Share with apps that have the same
signature
51
<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>
AndroidManifest.xml
Copyright©2015 JPCERT/CC All rights reserved.
To Share Data #3
Share with apps that have a specific
permission
52
<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"  />
AndroidManifest.xml
The above example defines singleread-write provider-levelpermission.
Copyright©2015 JPCERT/CC All rights reserved.
Don’t Want to Share Data
Consider:
Is it necessary to use a ContentProvider?
—If not, don’t
Make your ContentProvider private
—by specifying "android:exported=false" attribute in the
manifest file
53
Copyright©2015 JPCERT/CC All rights reserved.
Don’t Want to Share Data #1
Don’t use ContentProvider
Use SQLiteDatabase class or SQLiteOpenHelper class
—So that other apps cannot access the database
54
SQLiteDatabase  db  =  SQLiteDatabase.openOrCreateDatabase(
new  File(
"/data/data/"  +  getContext().getPackageName()  +  "/databases/",
DATABASE),  null);
long  id  =  db.insert("items",  null,  values);
db.close();
Copyright©2015 JPCERT/CC All rights reserved.
Don’t Want to Share Data #2
Make ContentProvider private
Specify "android:exported" attribute in the manifest
—However, in Android 2.2(API8) or before, even if you
explicitly declare "android:exported=false",your Content
Provider is accessible from other apps
55
<provider  android:name="SampleContentProvider"
android:authorities=“com.example.app.Provider”
android:exported="false"  />
Copyright©2015 JPCERT/CC All rights reserved.
JSSEC Secure Coding Guidebook
56
Flowchartthat guides you to choose the
appropriate type of contentprovider
Copyright©2015 JPCERT/CC All rights reserved.
Summary
Really need to use ContentProvider ?
—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 your ContentProvider
57
Copyright©2015 JPCERT/CC All rights reserved.58
WebView
4. File Scheme
5. addJavascriptInterface
6. Location Bar Spoofing
7. JavaScript Execution Context
Copyright©2015 JPCERT/CC All rights reserved.59
File Scheme
CASE #4
Copyright©2015 JPCERT/CC All rights reserved.
Case
Yahoo! Japan Browser / Sleipnir Mobile
Feature
—Web Browser apps
Vulnerability
—WebView with JavaScript enabled
—WebView processes any URI passed through Intents without
any validation
The URI may point to an attacker’s HTML file with javascript
60
Copyright©2015 JPCERT/CC All rights reserved.
Typical Code (vulnerable)
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);
}
}
61
This activity could receive
an Intent that may contain
malicious data
Is it safe to processes any given URI ?
Copyright©2015 JPCERT/CC All rights reserved.
Activity that Implements WebView
62
アプリB
IntentURL
This Vulnerability is often
seen in the apps that
implement the WebView
App A
DB
・cookie
・cache
WebView
public Activitypublic Activity
・JavaScriptenabled
・any URI processed
・JavaScriptenabled
・any URI processed
Copyright©2015 JPCERT/CC All rights reserved.
Attack Scenario
63
Vulnerable App
DB
・cookie
・cache
WebView
public Activitypublic Activity
・Javascriptenabled
・any URI processed
・Javascriptenabled
・any URI processed
cookie
cache
Malicious App
Intent
Attacker prepares
a crafted HTML file
Attacker's
Server
Copyright©2015 JPCERT/CC All rights reserved.
Malicious app send an Intent
64
Vuln app
DB
・cookie
・cache
WebView
Activity  publicActivity  public
・enabled  Javascript
・any  URI  passed
・enabled  Javascript
・any  URI  passed
cookie
cache
Attacker  supplied
HTML/Javascript
Attacker's  
Server
Malicious app
Intent
String  pkg =  "jp.vulnerable.android.app";
String  cls =  pkg +  ".DummyLauncherActivity";
String  uri =  "file:///[Exploit  html  file]";
Intent  intent  =  new  Intent();
intent.setClassName(pkg,  cls);
intent.putExtra("url",  uri);
this.startActivity(intent);
Copyright©2015 JPCERT/CC All rights reserved.
Malicious app send an Intent
65
Vuln app
DB
・cookie
・cache
WebView
Activity  publicActivity  public
・enabled  Javascript
・any  URI  passed
・enabled  Javascript
・any  URI  passed
cookie
cache
Attacker  supplied
HTML/Javascript
Attacker's  
Server
Malicious  app
Intent
String  pkg =  "jp.vulnerable.android.app";
String  cls =  pkg +  ".DummyLauncherActivity";
String  uri =  "file:///[Exploit  html  file]";
Intent  intent  =  new  Intent();
intent.setClassName(pkg,  cls);
intent.putExtra("url",  uri);
this.startActivity(intent);
…
String  turl =  getIntent().getStringExtra("url");
webView.loadUrl(turl);
Copyright©2015 JPCERT/CC All rights reserved.
Open an exploit html file
66
Vuln app
DB
・cookie
・cache
WebView
Activity  publicActivity  public
・enabled  Javascript
・any  URI  passed
・enabled  Javascript
・any  URI  passed
cookie
cache
Attacker's  
Server
Malicious  app
Intent
…
String  turl =  getIntent().getStringExtra("url");
webView.loadUrl(turl);
Attacker  prepares
some  crafted  HTML  file
Copyright©2015 JPCERT/CC All rights reserved.
Open an exploit html file
67
Vuln app
DB
・cookie
・cache
WebView
Activity  publicActivity  public
・enabled  Javascript
・any  URI  passed
・enabled  Javascript
・any  URI  passed
cookie
cache
Attacker's  
Server
Malicious app
Intent
Attacker prepares
a crafted HTML file
<script>
var target  =  "file:///data/data/jp.vulnerable.android.app/databases/webview.db";
var xhr =  new  XMLHttpRequest();
xhr.overrideMimeType("text/plain;  charset=iso-­‐8859-­‐1");
xhr.open("GET",  target,  true);
xhr.onreadystatechange =  function()  {
var data  =  xhr.responseText;
...
Any  resource  of  the  vulnerable  
appʼ’s  could  be  stolen
Copyright©2015 JPCERT/CC All rights reserved.
Conditions to be Vulnerable
WebView is implemented. JavaScript is enabled
Activity is public, and it receives any URI from Intent
file scheme is enabled
68
User’s private data in the app may
be stolen
Copyright©2015 JPCERT/CC All rights reserved.
Solution
Validate the URI received via Intent to decline file
scheme
—do not load the page, disable JavaScript
69
String intentUrl = getIntent().getStringExtra(”url")
String loadUrl = "about:blank";
if (!intentUrl.startsWith("file:")) {
loadUrl = intentUrl;
}
Do  not  load  the  page
String intentUrl = getIntent().getStringExtra(”url”)
wSettings.setJavaScriptEnabled(false);
if (!intentUrl.startsWith("file:")) {
wSettings.setJavaScriptEnabled(true);
}
Disable  JavaScript
Copyright©2015 JPCERT/CC All rights reserved.
Android 4.1 or later
70
New methods are added:
—WebSettings#setAllowFileAccessFromFileURLs
—WebSettings#setAllowUniversalAccessFromFileURLs
http://developer.android.com/reference/android/webkit/WebSettings.html#setAllowFileAccessFromFileURLs(boolean)
Copyright©2015 JPCERT/CC All rights reserved.
JSSEC Secure Coding Guidebook
71
Copyright©2015 JPCERT/CC All rights reserved.72
addJavascriptInterface
CASE #5
Copyright©2015 JPCERT/CC All rights reserved.
Case
Cybozu KUNAI
—http://products.cybozu.co.jp/kunai/
Feature
—Client app to access corporate groupware
Vulnerability
—Contained a vulnerability that allows addJavascriptInterface
to be exploited
—When opening a specially crafted website,
an attacker could execute an
arbitrary Java method
73
Copyright©2015 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
74
http://developer.android.com/reference/android/webkit/WebView.html
webView.addJavascriptInterface(new  Object(),  "injectedObject");
webView.loadData("",  "text/html",  null);
webView.loadUrl("javascript:alert(injectedObject.toString())");
can be called by the global
variable “injectedObject”
Copyright©2015 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!
75
http://developer.android.com/guide/webapps/webview.html
Copyright©2015 JPCERT/CC All rights reserved.
Example: Access the Java method from Javascript
76
@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>
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);
}
Copyright©2015 JPCERT/CC All rights reserved.
Example: Access to the Java method from Javascript
77
@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>
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);
}
Bind the SmsJSInterface object to
WebView
access from Javascript
send to SMS
Copyright©2015 JPCERT/CC All rights reserved.
Conditions to be vulnerable
WebView is implemented. Javascript is enabled
Java objects is registered through addJavascriptInterface()
Vulnerable WebView receives input (javascript) from
untrusted source
78
Copyright©2015 JPCERT/CC All rights reserved.
Reference: risk of addJavascriptInterface
79
By using reflection
— An attacker can obtain Context
through Javascript
—Even more!
—Runtime.exec() to do anything
under the app’s priviledge
MWR InfoSecurity
WebView addJavascriptInterface Remote Code Execution
https://labs.mwrinfosecurity.com/blog/2013/09/24/webview-addjavascriptinterface-remote-code-execution/
Copyright©2015 JPCERT/CC All rights reserved.
Summary
80
Design so that you don’t need addJavascriptInterface
If you need to use…
—Use only trusted content
NEVER USE
WebView#addJavascriptInterface
Copyright©2015 JPCERT/CC All rights reserved.
Android 4.2 (API17) and later
81
class JsObject {
@JavascriptInterface
public String  toString()  {  
return  "injectedObject";  
}
}
webView.addJavascriptInterface(new JsObject(),  "injectedObject");
webView.loadData("",  "text/html",  null);  
webView.loadUrl("javascript:alert(injectedObject.toString())");
Only public methods annotated with
"JavascriptInterface" can be accessed from Javascript
http://developer.android.com/reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object,  
java.lang.String)
Copyright©2015 JPCERT/CC All rights reserved.
JSSEC Secure Coding Guidebook
82
Copyright©2015 JPCERT/CC All rights reserved.83
Location Bar Spoofing
CASE #6
Copyright©2015 JPCERT/CC All rights reserved.
An attacker may display a
different URL than that of page
contents
https://play.google.com/store/apps/details?id=jp.co.yahoo.android.ybrowser
https://jvn.jp/en/jp/JVN55074201/
Could be abused
for phishing…
Location Bar Spoofing Vulnerability in Android Web Browsers
84
Copyright©2015 JPCERT/CC All rights reserved.
Attack Scenario – Phishing
85
“Yahoo! Browser” contains a flaw in displaying URL,
which allows the location bar to be spoofed.
A user access a malicious page, www.example.jp
User
The server
responds with
the requested
contents
The location bar shows a URL which looks different from
the site beingaccessed
Copyright©2015 JPCERT/CC All rights reserved.
How the Flaw Could Be Exploited
86
“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
User
The server
responds with
the requested
contents
The location bar shows a URL which is different from the
site beingaccessed
<script>
function  spoof(){
var w  =  window.open(the   URL to spoof)
w.document.write(contents to be displayed)
}
</script>
Copyright©2015 JPCERT/CC All rights reserved.
The behavior of the Vulnerable App
87
Attack  Scenario  – Phishing  -‐‑‒
“Yahoo! Browser” contains an issue in displaying
URL, which may result in the address bar being
spoofed.
A user access a malicious page on
www.example.jp
User
responds with
the requested
contents
The addressbarshows some URL different from the actual
contents
<script>
function spoof(){
var w = window.open(URL of Trusted
Site)
w.document.write(actual contents)
}
</script>
<script>
function  spoof(){
var w  =  window.open(the  URL  to  spoof)
w.document.write(some  contents)
}
</script>
how is the javascript interpreted? (assumption)
•Open a new browser window
•Print the argument (URL) on the location bar
•Terminate the loading of the URL
•Writes ‘some contents’ to the window
Between those two statement,
location bar is not updated?
Copyright©2015 JPCERT/CC All rights reserved.
Root Cause (assumption)
88
Location Bar
Source of the content
(URI)
The two components failed to synchronize
each other
Browser window
Page contents
Not synchronized!
Copyright©2015 JPCERT/CC All rights reserved.
Solution?
89
Which is the expected behavior:
a. Display incorrect URL (yes spoofed!)
b. Leave loation bar blank
c. Ignore document.write()
Which is the desirable behavior?
Any alternatives?
Copyright©2015 JPCERT/CC All rights reserved.
Solution?
90
Which is the expected behavior:
a. Display incorrect URL (yes spoofed!)
b. Leave loation bar is blank
c. Ignore document.write()
Which is the desirable behavior?
Any alternatives?
Pro: Better than a. to avoid the mismatch
between the contents and the URL
Con: user can’t determine where the
contents came from
Copyright©2015 JPCERT/CC All rights reserved.
Solution?
91
Which is the expected behavior:
a. Display incorrect URL (yes spoofed!)
b. Leave loation bar is blank
c. Ignore document.write()
Which is the desirable behavior?
Any alternatives?
Pro: Better than a. to avoid the mismatch
between the contents and the URL
Con: the behavior may be different from
what the developer expects
Copyright©2015 JPCERT/CC All rights reserved.92
Javascript Execution Context
CASE #7
Copyright©2015 JPCERT/CC All rights reserved.
Case
Opera, Sleipnir
Feature
—Web browser apps
Problem
—Javascript is executed in
the context of the target
site
93
Copyright©2015 JPCERT/CC All rights reserved.
Attack Scenarios
Attacker sends multiple Intents
1. First send an Intent to display the target site
2. Then send Javascript a attacker want to be executed as
another Intent
Ex.
1. Send an Intent that loads www.google.com
2. Send JavaScript (show cookie) via Intent
By using Javascript Scheme
—javascript:alert(document.cookie)
94
Copyright©2015 JPCERT/CC All rights reserved.
Proof of Concept
95
String  pkg =  "jp.co.aaa.bbb.ccc";
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  {
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);
Send  the  URL  of  the  
target
Send  JavaScript  that  
an  attacker  want  to  
have  it  executed
Copyright©2015 JPCERT/CC All rights reserved.
PoC
96
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  {
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);
Javascript is executed in the
context of www.google.com
Copyright©2015 JPCERT/CC All rights reserved.
Solution
97
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 fixed
Copyright©2015 JPCERT/CC All rights reserved.98
App Data Leakage
8.Broadcasting sensitive information
9.Loging sensitive information
10.Storing sensitive data in SD card
11.Improper File Permissions
Copyright©2015 JPCERT/CC All rights reserved.99
Broadcasting Sensitive
Information
CASE #8
Copyright©2015 JPCERT/CC All rights reserved.
Intent
Intent
—A message object that is passed between components (such
as Activity, Service, Broadcast Receiver, Content Provider)
—Explicit Intent
package is specified
—Implicit Intent
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) and later
100