Datasets:
language large_stringclasses 1
value | page_id int64 87.2M 87.2M | page_url large_stringlengths 73 73 | chapter int64 2 2 | section int64 0 7 | rule_id large_stringlengths 7 7 | title large_stringlengths 32 81 | intro large_stringlengths 506 3.71k | noncompliant_code large_stringlengths 123 8.67k | compliant_solution large_stringlengths 63 1.81k ⌀ | risk_assessment large_stringlengths 116 318 ⌀ | breadcrumb large_stringclasses 8
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
android | 87,150,611 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87150611 | 2 | 3 | DRD02-J | Do not allow WebView to access sensitive local resource through file scheme | The
WebView
class displays web pages as part of an activity layout. The behavior of a
WebView
object can be customized using the
WebSettings
object, which can be obtained from
WebView.getSettings()
.
Major security concerns for
WebView
are about the
setJavaScriptEnabled()
,
setPluginState()
, and
setAllowFileAccess()
methods.
setJavaScriptEnabled()
The
setJavaScriptEnabled()
tells WebView to enable JavaScript execution. To set it true:
webview.getWebSettings().setJavaScriptEnabled(true);
The default is
false
.
setPluginState()
The
setPluginState()
method
tells the WebView to enable, disable, or have plugins enabled on demand.
ON
any object will be loaded even if a plugin does not exist to handle the content
ON_DEMAND
if there is a plugin that can handle the content, a placeholder is shown until the user clicks on the placeholder.
Once clicked, the plugin will be enabled on the page.
OFF
all plugins will be turned off and any fallback content will be used
The default is
OFF
.
setAllowFileAccess()
The
setAllowFileAccess()
method enables or disables file access within WebView.
The default is
true
.
setAllowContentAccess()
The
setAllowContentAccess()
method enables or disables content URL access within WebView. Content URL access allows WebView to load content from a content provider installed in the system.
The default is
true
.
setAllowFileAccessFromFileURLs()
Sets whether JavaScript running in the context of a file scheme URL should be allowed to access content from other file scheme URLs. To enable the most restrictive, and therefore secure policy, this setting should be disabled. Note that the value of this setting is ignored if the value of
getAllowUniversalAccessFromFileURLs()
is
true
.
The default value is
true
for API level
ICE_CREAM_SANDWICH_MR1
(API level 15) and below, and
false
for API level
JELLY_BEAN
(API level 16) and above.
setAllowUniversalAccessFromFileURLs()
Sets whether JavaScript running in the context of a file scheme URL should be allowed to access content from any origin. This includes acess to content from other file scheme URLs. To enable the most restrictive, and therefore secure policy, this setting should be disabled.
The default value is
true
for API level
ICE_CREAM_SANDWICH_MR1
(API level 15) and below, and
false
for API level
JELLY_BEAN
(API level 16) and above.
Security Concerns for
WebView
Class
When an activity has
WebView
embedded to display web pages, any application can create and send an
Intent
object with a given URI to the activity to request that a web page be displayed.
WebView
can recognize a variety of schemes, including the
file:
scheme. A malicious application may create and store a crafted content on its local storage area, make it accessible with
MODE_WORLD_READABLE
permission, and send the URI (using the
file:
scheme) of this content to a target activity. The target activity renders this content.
When the target activity (
webView
object) sets JavaScript enabled, it can be abused to access the target application’s resources.
Android 4.1 provides additional methods to control file scheme access:
WebSettings#setAllowFileAccessFromFileURLs
WebSettings#setAllowUniversalAccessFromFileURLs | 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 url = getIntent().getStringExtra("URL");
webView.loadUrl(url);
}
}
// Malicious application prepares some crafted HTML file,
// places it on a local storage, makes accessible from
// other applications. The following code sends an
// intent to a target application (jp.vulnerable.android.app)
// to make it access and process the malicious HTML file.
String pkg = "jp.vulnerable.android.app";
String cls = pkg + ".DummyLauncherActivity";
String uri = "file:///[crafted HTML file]";
Intent intent = new Intent();
intent.setClassName(pkg, cls);
intent.putExtra("url", uri);
this.startActivity(intent);
## Noncompliant Code Example
The following noncompliant code example uses the
WebView
component with JavaScript enabled and processes any URI passed through
Intent
without any validation:
#FFCCCC
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 url = getIntent().getStringExtra("URL");
webView.loadUrl(url);
}
}
Proof of Concept
This code shows how the vulnerability can be exploited:
// Malicious application prepares some crafted HTML file,
// places it on a local storage, makes accessible from
// other applications. The following code sends an
// intent to a target application (jp.vulnerable.android.app)
// to make it access and process the malicious HTML file.
String pkg = "jp.vulnerable.android.app";
String cls = pkg + ".DummyLauncherActivity";
String uri = "file:///[crafted HTML file]";
Intent intent = new Intent();
intent.setClassName(pkg, cls);
intent.putExtra("url", uri);
this.startActivity(intent); | 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);
String url = getIntent().getStringExtra("url");
if (!url.startsWith("http")) { /* Note: "https".startsWith("http") == true */
url = "about:blank";
}
webView.loadUrl(url);
}
}
## Compliant Solution
Any URI received via an
intent
from outside a trust-boundary should be validated before rendering it with
WebView
. For example, the following code checks a received URI and rejects the "
file:
" scheme URI. More generally, it allows only URIs that start with "http". (Note that "https" starts with "http".)
#CCCCFF
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);
String url = getIntent().getStringExtra("url");
if (!url.startsWith("http")) { /* Note: "https".startsWith("http") == true */
url = "about:blank";
}
webView.loadUrl(url);
}
}
Risk Assessment
Allowing
WebView
to access sensitive resources may result in information leaks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DRD02-J
medium
probable
No
No
P4
L3
Automated Detection
Automatic detection is not feasible.
Tool
Version
Checker
Description | null | Android Secure Coding Standard > 2 Rules > Rule 03. WebView (WBV) |
android | 87,150,605 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87150605 | 2 | 2 | DRD03-J | Do not broadcast sensitive information using an implicit intent | Android applications' core components such as activities, services, and broadcast receivers are activated through messages, called
intents
. Applications can use broadcast to send messages to multiple applications (i.e., notification of events to an indefinite number of apps). Also, an application can receive a broadcast intent sent by the system.
To broadcast an intent it is passed to
Context.sendBroadcast()
to be transmitted and interested receivers can receive the intent, dynamically registering themselves by calling
Context.registerReceiver()
with the specified
intentFilter
as an argument. Alternatively, receivers can be statically registered by defining the
<receiver>
tag in the
AndroidManifest.xml
file.
Chin, et al., [
Chin 2011
] say: "
Broadcasts can be vulnerable to passive eavesdropping or active denial of service attacks. ... Eavesdropping is a risk whenever an application sends a public broadcast. (A public broadcast is an implicit Intent that is not protected by a Signature or SignatureOrSystem permission.) A malicious Broadcast Receiver could eavesdrop on all public broadcasts from all applications by creating an Intent lter that lists all possible actions, data, and categories. There is no indication to the sender or user that the broadcast has been read. Sticky broadcasts are particularly at risk for eavesdropping because they persist and are re-broadcast to new Receivers; consequently, there is a large temporal window for a sticky broadcast Intent to be read. Additionally, sticky broadcasts cannot be protected by permissions.
"
Furthermore, if the broadcast is an ordered broadcast then a malicious app could register itself with a high priority so as to receive the broadcast first. Then, it could either cancel the broadcast preventing it from being propagated further, thereby causing a denial of service, or it could inject a malicious data result into the broadcast that is ultimately returned to the sender.
Chin, et al., [
Chin 2011
] also warn against activity and service hijacking resulting from implicit intents. A malicious activity or service can intercept an implicit intent and be started in place of the intended activity or service. This could result in the interception of data or in a denial of service.
When
sendBroadcast()
is used, normally any other application, including a malicious application, can receive the broadcast.
This facilitates
intent sniffing
, see [
viaForensics 2014
]
26. Android: avoid intent sniffing
.
Therefore, receivers of broadcast intents should be restricted. One way to restrict receivers is to use an explicit intent. An explicit intent can specify a component (using
setComponent(ComponentName)
) or a class (using
setClass(Context, Class)
) so that only the specified component or class can resolve the intent.
It is also possible to restrict the receivers of intents by using permissions, as described below. Alternatively, starting with the Android version ICE_CREAM_SANDWICH (Android API version 4.0), you can also safely restrict the broadcast to a single application by using Intent.setPackage().
Yet another approach is to use the LocalBroadcastManager class. Using this class, the intent broadcast never goes outside of the current process. According to the Android API Reference, LocalBroadcastManager has a number of advantages over Context.sendBroadcast(Intent):
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 these broadcasts 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 through the system. | public class ServerService extends Service {
// ...
private void d() {
// ...
Intent v1 = new Intent();
v1.setAction("com.sample.action.server_running");
v1.putExtra("local_ip", v0.h);
v1.putExtra("port", v0.i);
v1.putExtra("code", v0.g);
v1.putExtra("connected", v0.s);
v1.putExtra("pwd_predefined", v0.r);
if (!TextUtils.isEmpty(v0.t)) {
v1.putExtra("connected_usr", v0.t);
}
}
this.sendBroadcast(v1);
}
final class MyReceiver extends BroadcastReceiver {
public final void onReceive(Context context, Intent intent) {
if (intent != null && intent.getAction() != null) {
String s = intent.getAction();
if (s.equals("com.sample.action.server_running") {
String ip = intent.getStringExtra("local_ip");
String pwd = intent.getStringExtra("code");
String port = intent.getIntExtra("port", 8888);
boolean status = intent.getBooleanExtra("connected", false);
}
}
}
}
public class BcReceiv extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent){
String s = null;
if (intent.getAction().equals("com.sample.action.server_running")){
String pwd = intent.getStringExtra("connected");
s = "Airdroid => [" + pwd + "]/" + intent.getExtras();
}
Toast.makeText(context, String.format("%s Received", s),
Toast.LENGTH_SHORT).show();
}
}
## Noncompliant Code Example
This noncompliant code example shows an application (
com/sample/ServerService.java
) with a vulnerable method
d()
using an implicit intent
v1
as an argument to
this.sendBroadcast()
to broadcast the intent. The intent includes such sensitive information as the device's IP address (
local_ip
), the port number (
port
), and the password to connect to the device (
code
).
#FFCCCC
public class ServerService extends Service {
// ...
private void d() {
// ...
Intent v1 = new Intent();
v1.setAction("com.sample.action.server_running");
v1.putExtra("local_ip", v0.h);
v1.putExtra("port", v0.i);
v1.putExtra("code", v0.g);
v1.putExtra("connected", v0.s);
v1.putExtra("pwd_predefined", v0.r);
if (!TextUtils.isEmpty(v0.t)) {
v1.putExtra("connected_usr", v0.t);
}
}
this.sendBroadcast(v1);
}
An application could receive the broadcast message by using a broadcast receiver as follows:
java
final class MyReceiver extends BroadcastReceiver {
public final void onReceive(Context context, Intent intent) {
if (intent != null && intent.getAction() != null) {
String s = intent.getAction();
if (s.equals("com.sample.action.server_running") {
String ip = intent.getStringExtra("local_ip");
String pwd = intent.getStringExtra("code");
String port = intent.getIntExtra("port", 8888);
boolean status = intent.getBooleanExtra("connected", false);
}
}
}
}
Proof of Concept
An attacker can implement a broadcast receiver to receive the implicit intent sent by the vulnerable application:
java
public class BcReceiv extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent){
String s = null;
if (intent.getAction().equals("com.sample.action.server_running")){
String pwd = intent.getStringExtra("connected");
s = "Airdroid => [" + pwd + "]/" + intent.getExtras();
}
Toast.makeText(context, String.format("%s Received", s),
Toast.LENGTH_SHORT).show();
}
} | Intent intent = new Intent("my-sensitive-event");
intent.putExtra("event", "this is a test event");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
## Compliant Solution
If the intent is only broadcast/received in the same application,
LocalBroadcastManager
can be used so that, by design, other apps cannot received the broadcast message, which reduces the risk of leaking sensitive information.
Instead of using
Context.sendBroadcast()
, use
LocalBroadcastManager.sendBroadcast()
:
#CCCCFF
Intent intent = new Intent("my-sensitive-event");
intent.putExtra("event", "this is a test event");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent); | ## Risk Assessment
Using an implicit intent can leak sensitive information to malicious apps or result in denial of service.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DRD03-J
Medium
Probable
No
No
P4
L3 | Android Secure Coding Standard > 2 Rules > Rule 02. Intent (ITT) |
android | 87,150,665 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87150665 | 2 | 1 | DRD04-J | Do not log sensitive information | Android provides capabilities for an app to output logging information and obtain log output. Applications can send information to log output using the
android.util.Log
class. To obtain log output, applications can execute the
logcat
command.
## To log output
The
android.util.Log
class allows a number of possibilities:
Log.d
(Debug)
Log.e
(Error)
Log.i
(Info)
Log.v
(Verbose)
Log.w
(Warn)
Example:
java
Log.v("method", Login.TAG + ", account=" + str1);
Log.v("method", Login.TAG + ", password=" + str2);
To obtain log output
Declare
READ_LOGS
permission in the manifest file so that an app can read log output:
AndroidManifest.xml
:
<uses-permission android:name="android.permission.READ_LOGS"/>
Call
logcat
from an application:
#ccccff
java
Process mProc = Runtime.getRuntime().exec(
new String[]{"logcat", "-d", "method:V *:S$Bc`W^(B)"});
BufferedReader mReader = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
Prior to Android 4.0, any application with
READ_LOGS
permission could obtain all the other applications' log output. After Android 4.1, the specification of
READ_LOGS
permission has been changed. Even applications with
READ_LOGS
permission cannot obtain log output from other applications.
However, by connecting an Android device to a PC, log output from other applications can be obtained.
Therefore, it is important that applications do not send sensitive information to log output. | Log.d("Facebook-authorize", "Login Success! access_token="
+ getAccessToken() + " expires="
+ getAccessExpires());
final StringBuilder slog = new StringBuilder();
try {
Process mLogcatProc;
mLogcatProc = Runtime.getRuntime().exec(new String[]
{"logcat", "-d", "LoginAsyncTask:I APIClient:I method:V *:S" });
BufferedReader reader = new BufferedReader(new InputStreamReader(
mLogcatProc.getInputStream()));
String line;
String separator = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
slog.append(line);
slog.append(separator);
}
Toast.makeText(this, "Obtained log information", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// handle error
}
TextView tView = (TextView) findViewById(R.id.logView);
tView.setText(slog);
## Noncompliant Code Example
Facebook SDK for Android contained the following code which sends Facebook access tokens to log output in plain text format.
#ffcccc
java
Log.d("Facebook-authorize", "Login Success! access_token="
+ getAccessToken() + " expires="
+ getAccessExpires());
Source:
http://blog.parse.com/2012/04/10/discovering-a-major-security-hole-in-facebooks-android-sdk/
## Noncompliant Code Example
Here is another example. A weather report for Android sent a user's location data to the log output as follows:
I/MyWeatherReport( 6483): Re-use MyWeatherReport data
I/ ( 6483): GET JSON:
http://example.com/smart/repo_piece.cgi?arc=0&lat=26.209026&lon=127.650803&rad=50&dir=-999&lim=52&category=1000
If a user is using Android OS 4.0 or before, other applications with
READ_LOGS
permission can obtain the user's location information without declaring
ACCESS_FINE_LOCATION
permission in the manifest file.
Proof of Concept
Example code of obtaining log output from a vulnerable application is as follows:
#ccccff
java
final StringBuilder slog = new StringBuilder();
try {
Process mLogcatProc;
mLogcatProc = Runtime.getRuntime().exec(new String[]
{"logcat", "-d", "LoginAsyncTask:I APIClient:I method:V *:S" });
BufferedReader reader = new BufferedReader(new InputStreamReader(
mLogcatProc.getInputStream()));
String line;
String separator = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
slog.append(line);
slog.append(separator);
}
Toast.makeText(this, "Obtained log information", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// handle error
}
TextView tView = (TextView) findViewById(R.id.logView);
tView.setText(slog); | null | ## Risk Assessment
Logging sensitive information can leak sensitive information to malicious apps.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DRD04-J
Medium
Probable
No
No
P4
L3 | Android Secure Coding Standard > 2 Rules > Rule 01. File I/O and Logging (FIO) |
android | 87,150,608 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87150608 | 2 | 5 | DRD05-J | Do not grant URI permissions on implicit intents | (THIS CODING RULE OR GUIDELINE IS UNDER CONSTRUCTION)
Data stored in an application's service provider can be referenced by URIs that are included in intents. If the recipient of the intent does not have the required privileges to access the URI, the sender of the intent can set either of the flags
FLAG_GRANT_READ_URI_PERMISSION
or
FLAG_GRANT_WRITE_URI_PERMISSION
on the intent. If the provider has specified in the manifest that URI permissions may be granted then the recipient of the intent will be able to read or write (respectively) the data at the URI.
Chin, et al., [
Chin 2011
] points out that, if a malicious component is able to intercept the intent, then it can access the data at the URI. Implicit intents can be intercepted by any component so, if the data is intended to be private, any intent carrying data privileges must be explicitly addressed, rather than being implicit. (See
DRD03-J. Do not broadcast sensitive information using an implicit intent
for more information about the interception of implicit intents.) | TBD
## Noncompliant Code Example
## This noncompliant code example shows an application that grantsFLAG_GRANT_READ_URI_PERMISSIONon an implicit intent.
#FFCCCC
TBD
An application could intercept the implicit intent and access the data at the URI. | TBD
## Compliant Solution
## In this compliant solution the intent is made explicit so that it cannot be intercepted:
#CCCCFF
TBD | ## Risk Assessment
Granting URI permissions in implicit intents can leak sensitive information.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DRD05-J
High
Probable
Yes
No
P12
L1 | Android Secure Coding Standard > 2 Rules > Rule 05. Permission (PER) |
android | 87,150,610 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87150610 | 2 | 0 | DRD08-J | Always canonicalize a URL received by a content provider | By using the
ContentProvider.openFile()
method, you can provide a facility for another application to access your application data (file). Depending on the implementation of
ContentProvider
, use of the method can lead to a directory traversal vulnerability. Therefore, when exchanging a file through a content provider, the path should be canonicalized before it is used.
This rule is an Android specific instance of
IDS01-J. Normalize strings before validating them
) and
IDS02-J. Canonicalize path names before validating them
. | 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);
}
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);
}
PathSegments getPathSegments() {
if (pathSegments != null) {
return pathSegments;
}
String path = getEncoded();
if (path == null) {
return pathSegments = PathSegments.EMPTY;
}
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();
}
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);
}
String target = "content://com.example.android.sdk.imageprovider/data/" +
"..%2F..%2F..%2Fdata%2Fdata%2Fcom.example.android.app%2Fshared_prefs%2FExample.xml";
ContentResolver cr = this.getContentResolver();
FileInputStream fis = (FileInputStream)cr.openInputStream(Uri.parse(target));
byte[] buff = new byte[fis.available()];
in.read(buff);
String target = "content://com.example.android.sdk.imageprovider/data/" +
"%252E%252E%252F%252E%252E%252F%252E%252E%252Fdata%252Fdata%252Fcom.example.android.app%252Fshared_prefs%252FExample.xml";
ContentResolver cr = this.getContentResolver();
FileInputStream fis = (FileInputStream)cr.openInputStream(Uri.parse(target));
byte[] buff = new byte[fis.available()];
in.read(buff);
## Noncompliant Code Example 1
This noncompliant code example tries to retrieve the last segment from the path
paramUri
, which is supposed to denote a file name, by calling
android.net.Uri.getLastPathSegment()
. The file is accessed in the pre-configured parent directory
IMAGE_DIRECTORY
.
#FFCCCC
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);
}
However, when the path is URL encoded, it may denote a file in an unintended directory which is outside of the pre-configured parent directory.
From Android 4.3.0_r2.2, the method
Uri.getLastPathSegment()
calls
Uri.getPathSegments()
internally (see:
Cross Reference: Uri.java
):
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);
}
A part of the method
Uri.getPathSegments()
is as follows:
PathSegments getPathSegments() {
if (pathSegments != null) {
return pathSegments;
}
String path = getEncoded();
if (path == null) {
return pathSegments = PathSegments.EMPTY;
}
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();
}
The method
Uri.getPathSegments()
first acquires a path by calling
getEncoded()
, then divides the path into segments using "/" as a separator. Any segment that is encoded will be URL decoded by the
decode()
method.
If a path is URL encoded, the separator character will be "%2F" instead of "/" and
getLastPathSegment()
may not properly return the last segment of the path, which will be a surprise to the user of the method. Moreover, the design of this API directly enables a directory traversal vulnerability.
If the
Uri.getPathSegments()
method decoded a path before making it into segments, the URL encoded path could be properly processed. Unfortunately, this is not the case and users should not pass a path to
Uri.getLastPathSegment()
before decoding it.
## Noncompliant Code Example 2
This noncompliant code example attempts to fix the first noncompliant code example by calling
Uri.getLastPathSegment()
twice. The first call is intended for URL decoding and the second call is to obtain the string the developer wanted.
#FFCCCC
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);
}
For example, consider what happens when the following URL encoded strings is passed to the content provider:
..%2F..%2F..%2Fdata%2Fdata%2Fcom.example.android.app%2Fshared_prefs%2FExample.xml
The first call of
Uri.getLastPathSegment()
will return the following string:
../../../data/data/com.example.android.app/shared_prefs/Example.xml
The string is converted to a Uri object by
Uri.parse()
, which is passed to the second call of
Uri.getLastPathSegment()
. The resulting string will be:
Example.xml
The string is used to create a file object. However, if an attacker could supply a string which cannot be decoded by the first call of the
Uri.getLastPathSegment()
, the last path segment may not be retrieved. An attacker can create such a string by using the technique called double encoding:
Double Encoding
(See [
OWASP 2009
]
Double Encoding
for more information.)
For example, the following double encoded string will circumvent the fix.
%252E%252E%252F%252E%252E%252F%252E%252E%252Fdata%252Fdata%252Fcom.example.android.app%252Fshared_prefs%252FExample.xml
The first call of
Uri.getLastPathSegment()
will decode "%25" to "%" and return the string:
%2E%2E%2F%2E%2E%2F%2E%2E%2Fdata%2Fdata%2Fcom.example.android.app%2Fshared_prefs%2FExample.xml
When this string is passed to the second Uri.getLastPathSegment(), "%2E" and "%2F" will be decoded and the result will be:
../../../data/data/com.example.android.app/shared_prefs/Example.xml
which makes directory traversal possible.
As a mitigation to the directory traversal attack in this example, it is not enough to only decode the strings. The decoded path must be checked to make sure that the path is under the intended directory.
Proof of Concept
The following malicious code can exploit the vulnerable application that contains the first noncompliant code example:
String target = "content://com.example.android.sdk.imageprovider/data/" +
"..%2F..%2F..%2Fdata%2Fdata%2Fcom.example.android.app%2Fshared_prefs%2FExample.xml";
ContentResolver cr = this.getContentResolver();
FileInputStream fis = (FileInputStream)cr.openInputStream(Uri.parse(target));
byte[] buff = new byte[fis.available()];
in.read(buff);
Proof of Concept (Double Encoding)
The following malicious code can exploit the vulnerable application that contains the second noncompliant code example:
String target = "content://com.example.android.sdk.imageprovider/data/" +
"%252E%252E%252F%252E%252E%252F%252E%252E%252Fdata%252Fdata%252Fcom.example.android.app%252Fshared_prefs%252FExample.xml";
ContentResolver cr = this.getContentResolver();
FileInputStream fis = (FileInputStream)cr.openInputStream(Uri.parse(target));
byte[] buff = new byte[fis.available()];
in.read(buff); | 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);
}
## Compliant Solution
In the following compliant solution, a path is decoded by
Uri.decode()
before use. Also, after the File object is created, the path is canonicalized by calling
File.getCanonicalPath()
and checked that it is included in
IMAGE_DIRECTORY
.
By using the canonicalized path, directory traversal will be mitigated even when a doubly-encoded path is supplied.
#CCCCFF
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);
} | ## Risk Assessment
Failing to canonicalize a path received by a content provider may lead to a directory traversal vulnerability which could result in the release of sensitive data or in the malicious corruption of data.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DRD08-J
High
Probable
Yes
No
P12
L1 | Android Secure Coding Standard > 2 Rules > Rule 00. Component Security (CPS) |
android | 87,150,718 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87150718 | 2 | 5 | DRD14-J | Check that a calling app has appropriate permissions before responding | (THIS CODING RULE OR GUIDELINE IS UNDER CONSTRUCTION)
If an app is using a granted permission to respond to a calling app then it must check that the calling app has that permission as well. Otherwise, the responding app may be granting privileges to the calling app that it should not have. (This is sometimes called the "confused deputy" problem.)
The methods
Context.checkCallingPermission()
and
Context.enforceCallingPermission()
can be used to ensure that the calling app has the correct permissions. | TBD
## Noncompliant Code Example
This noncompliant code example shows an app responding to a calling app without first checking the permissions of the calling app.
#FFCCCC
TBD | TBD
## Compliant Solution
## In this compliant solution the permissions of the calling app are checked before the response is sent:
#CCCCFF
TBD | ## Risk Assessment
Responding to a calling app without checking that it has the appropriate permissions can leak sensitive information.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DRD14-J
High
Probable
No
No
P6
L2 | Android Secure Coding Standard > 2 Rules > Rule 05. Permission (PER) |
android | 87,150,714 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87150714 | 2 | 7 | DRD15-J | Consider privacy concerns when using Geolocation API | The
Geolocation API
, which is specified by W3C, enables web browsers to access geographical location information of a user's device.
In the specification, it is prohibited that user agents send location information to web sites without obtaining permission from the user:
4.1 Privacy considerations for implementers of the Geolocation API
User agents must not send location information to Web sites without the express permission of the user. User agents must acquire permission through a user interface, unless they have prearranged trust relationships with users, as described below. The user interface must include the host component of the document's URI [URI]. Those permissions that are acquired through the user interface and that are preserved beyond the current browsing session (i.e. beyond the time when the browsing context [BROWSINGCONTEXT] is navigated to another URL) must be revocable and user agents must respect revoked permissions.
Some user agents will have prearranged trust relationships that do not require such user interfaces. For example, while a Web browser will present a user interface when a Web site performs a geolocation request, a VOIP telephone may not present any user interface when using location information to perform an E911 function.
A conforming implementation must acquire permission through a user interface before sending the user's geolocation to the web site.
An example Javascript for using Geolocation API is as follows:
<script>
navigator.geolocation.getCurrentPosition(
function(position) {
alert(position.coords.latitude);
alert(position.coords.longitude);
},
function(){
// error
});
</script>
The Javascript above will show the location of the device on a screen.
To enable geolocation in an application using the
WebView
class, the following permissions and the use of the
webkit
package is necessary:
permissions
android.permission.ACCESS_FINE_LOCATION
android.permission.ACCESS_COARSE_LOCATION
android.permission.INTERNET
webkit
package
WebSettings#setGeolocationEnabled(true)
WebChromeClient#onGeolocationPermissionsShowPrompt()
implementation
Among these, implementing the
WebChromeClient#onGeolocationPermissionsShowPrompt()
method needs security consideration. There are vulnerable apps and code examples that override this method so that a user's geolocation information is sent to servers without the user's consent. With such an implementation, the user's geolocation location data will leak just by visiting malicious sites. | public void onGeolocationPermissionsShowPrompt(String origin, Callback callback){
super.onGeolocationPermissionsShowPrompt(origin, callback);
callback.invoke(origin, true, false);
}
## Noncompliant Code Example
This noncompliant code example sends the user's geolocation information without obtaining the user's permission upon request from a server.
#FFCCCC
public void onGeolocationPermissionsShowPrompt(String origin, Callback callback){
super.onGeolocationPermissionsShowPrompt(origin, callback);
callback.invoke(origin, true, false);
} | public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
super.onGeolocationPermissionsShowPrompt(origin, callback);
// Ask for user's permission
// When the user disallows, do not send the geolocation information
}
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions$Callback callback) {
super.onGeolocationPermissionsShowPrompt(origin, callback);
if(MyPreferences.getBoolean("SECURITY_ENABLE_GEOLOCATION_INFORMATION", true)) {
WebViewHolder.a(this.a).permissionShowPrompt(origin, callback);
}
else {
callback.invoke(origin, false, false);
}
}
## Compliant Solution #1
This compliant solution shows a UI to ask for the user's consent. Depending on the user's response, the application can control the transmission of the geolocation data.
#CCCCFF
public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
super.onGeolocationPermissionsShowPrompt(origin, callback);
// Ask for user's permission
// When the user disallows, do not send the geolocation information
}
## Compliant Solution #2
## The following compliant solution is from a real world fix of a previously vulnerable application.
#CCCCFF
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions$Callback callback) {
super.onGeolocationPermissionsShowPrompt(origin, callback);
if(MyPreferences.getBoolean("SECURITY_ENABLE_GEOLOCATION_INFORMATION", true)) {
WebViewHolder.a(this.a).permissionShowPrompt(origin, callback);
}
else {
callback.invoke(origin, false, false);
}
}
If the user setting of geolocation is enabled, the code will show a screen to ask for the user's permission. If the setting is disabled, it will not transmit the geolocation data. | ## Risk Assessment
Sending a user's geolocation information without asking the user's permission violates the security and privacy considerations of the Geolocation API and leaks the user's sensitive information.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DRD15-J
Low
Probable
No
No
P2
L3 | Android Secure Coding Standard > 2 Rules > Rule 07. Miscellaneous (MSC) |
android | 87,150,713 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87150713 | 2 | 6 | DRD17-J | Do not use the Android cryptographic security provider encryption default for AES | (THIS CODING RULE OR GUIDELINE IS UNDER CONSTRUCTION)
The predominant Android cryptographic security provider API defaults to using an insecure AES encryption method: ECB block cipher mode for AES encryption. Android's default cryptographic security provider (since version 2.1) is BouncyCastle.
NOTE: Java also chose ECB as a default value when only the AES encryption method is chosen. So, this rule also applies to Java, but for Java's different default cryptographic security provider. Oracle Java's default cryptographic security provider is SunJCE. | ## Noncompliant Code Example
## This noncompliant code example shows an application that ..., and hence not secure.
#FFCCCC | ## Compliant Solution
## In this compliant solution ...
#CCCCFF | ## Risk Assessment
If an insecure encryption method is used, then the encryption does not assure privacy, integrity, and authentication of the data.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DRD17-J
High
Likely
Yes
No
P18
L1 | Android Secure Coding Standard > 2 Rules > Rule 06. Cryptography (CRP) |
android | 87,150,609 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87150609 | 2 | 2 | DRD21-J | Always pass explicit intents to a PendingIntent | (THIS CODING RULE OR GUIDELINE IS UNDER CONSTRUCTION)
A
Pending Intent
is an intent that can be given to another application for it to use later, see: [
Android API 2013
]
class
PendingIntent
. The application receiving the pending intent can perform the operation(s) specified in the pending intent with the same permissions and the same identity as the application that produced the pending intent. Consequently, the pending intent should be built with care, and must always contain base intents that have the component name set explicitly to a component owned by the originating application. This ensures that the base intents are ultimately sent to appropriate locations and nowhere else. An implicit intent must never be included in a pending intent. | TBD
## Noncompliant Code Example
## This noncompliant code example shows an application that creates a pending intent containing an implicit intent.
#FFCCCC
TBD
An application could intercept the implicit intent and pass it on to an inappropriate location, while both the intent originator and the intent recipient would remain unaware that the intent had been intercepted. | TBD
## Compliant Solution
## In this compliant solution the pending intent contains an explicit intent that cannot be misdirected.
#CCCCFF
TBD | ## Risk Assessment
Failing to pass an explicit intent to a pending intent could allow the intent to be misdirected, thereby leaking sensitive information and/or altering the data flow within an app.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DRD21-J
Medium
Probable
Yes
No
P4
L3 | Android Secure Coding Standard > 2 Rules > Rule 02. Intent (ITT) |
android | 87,150,699 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87150699 | 2 | 4 | DRD23-J | Do not use loopback when handling sensitive data | Under Construction
This guideline is under construction.
Loopback, that is, connecting network communications to
localhost
ports, should not be used when handling sensitive data. The
localhost
ports are accessible by other applications on the device, so their use may result in sensitive data being revealed. Instead, a secure Android IPC mechanism should be used, such as the
HttpsURLConnection
class
or the
SSLSocket
class
.
Similarly, secure communications should never be bound to the
INADDR_ANY
port since this would result in the application being able to receive requests form anywhere.
For more information on these issues, see: [
Android Security
] section
Using Networking
. | TBD
## Noncompliant Code Example
## This noncompliant code example shows an application that binds to alocalhostnetwork port to send sensitive data.
#FFCCCC
TBD
Another application could intercept the communication and access the sensitive data | TBD
## Compliant Solution
## In this compliant solution the application uses a secure network connection.
#CCCCFF
TBD | ## Risk Assessment
Using
localhost
or the
INADDR_ANY
port when handling sensitive data could result in the data being revealed.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DRD23-J
Medium
Probable
No
No
P4
L3 | Android Secure Coding Standard > 2 Rules > Rule 04. Network - SSL/TLS (NET) |
android | 87,150,663 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87150663 | 2 | 7 | DRD26-J | For OAuth, use a secure Android method to deliver access tokens | This rule was developed in part by Rachel Xu and Zifei (FeiFei) Han at the October 20-22, 2017
OurCS Workshop
(
http://www.cs.cmu.edu/ourcs/register.html
).
For more information about this statement, see the
About the OurCS Workshop
page.
For OAuth, use a secure Android method to deliver access tokens. The method to do with mobile apps and their platforms is not specified in the OAuth 1.0 or OAuth 2.0 standards. Access tokens can be securely delivered if the service provider can identify recipients using a globally unique identifier.
Under Construction
This guideline is under construction. | TBD
## Noncompliant Code Example
## This noncompliant code example shows an application that
#FFCCCC
TBD
An Intent can securely send an access token to its intended mobile relying party app, using an explicit intent, because the relying party can be uniquely identified through its developer key hash. | TBD
## Compliant Solution
## In this compliant solution the application
#CCCCFF
TBD | ## Risk Assessment
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DRD26-J
Medium
Probable
No
No
P4
L3 | Android Secure Coding Standard > 2 Rules > Rule 07. Miscellaneous (MSC) |
android | 87,150,654 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87150654 | 2 | 7 | DRD27-J | For OAuth, use an explicit intent method to deliver access tokens | Start copying here:
This rule was developed in part by Zifei (FeiFei) Han and Rachel Xu at the October 20-22, 2017
OurCS Workshop
(
http://www.cs.cmu.edu/ourcs/register.html
).
For more information about this statement, see the
About the OurCS Workshop
page.
End copying here.
Under Construction
This guideline is under construction.
Explanation:
Explicit intent can protect user information, while implicit intent declares general actions that all applications can use. This way implicit intent may be harmful and release the user's action information.
On the other hand, Explicit intent sent access tokens by using specific components to personalize for specific applications. Specifically when sending access tokens to hosts we should use explicit intent rather than implicit. | protected void OnTokenAcquired(Bundle savedInstanceState) {
//[Code to construct an OAuth client request goes here]
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(request.getlocationUri() + "&response_type=code"));
startActivity(intent);
}
## Noncompliant Code Example
## This noncompliant code example shows an application that ...
#FFCCCC
protected void OnTokenAcquired(Bundle savedInstanceState) {
//[Code to construct an OAuth client request goes here]
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(request.getlocationUri() + "&response_type=code"));
startActivity(intent);
} | protected void OnTokenAcquired(Bundle savedInstanceState) {
//[Code to construct an OAuth client request goes here]
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(request.getlocationUri() + "&response_type=code"), this, [YOUR OAUTH ACTIVITY CLASS]);
startActivity(intent);
}
## Compliant Solution
## In this compliant solution ...:
#CCCCFF
protected void OnTokenAcquired(Bundle savedInstanceState) {
//[Code to construct an OAuth client request goes here]
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(request.getlocationUri() + "&response_type=code"), this, [YOUR OAUTH ACTIVITY CLASS]);
startActivity(intent);
} | ## Risk Assessment
## Summary of risk assessment.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DRD27-J
No
No | Android Secure Coding Standard > 2 Rules > Rule 07. Miscellaneous (MSC) |
Dataset Card for SEI CERT Android Secure Coding Standard (Wiki rules)
Structured export of the SEI CERT Android Secure Coding Standard from the SEI wiki.
Dataset Details
Dataset Description
Android-focused secure coding rules (Java / Android APIs) with descriptive text and examples as published by SEI CERT.
- Curated by: Derived from public SEI CERT wiki pages; packaged as CSV by the dataset maintainer.
- Funded by [optional]: [More Information Needed]
- Shared by [optional]: [More Information Needed]
- Language(s) (NLP): English (rule text and embedded code).
- License: Compilation distributed as
other; verify with CMU SEI for your use case.
Dataset Sources [optional]
- Repository: https://wiki.sei.cmu.edu/confluence/display/seccode/SEI+CERT+Coding+Standards
- Paper [optional]: SEI CERT Android Secure Coding Standard
- Demo [optional]: [More Information Needed]
Uses
Direct Use
Mobile security training, AppSec checklists, and ML datasets for Android guidance.
Out-of-Scope Use
Does not guarantee coverage of the latest Android platform changes.
Dataset Structure
All rows share the same columns (scraped from the SEI CERT Confluence wiki):
| Column | Description |
|---|---|
language |
Language identifier for the rule set |
page_id |
Confluence page id |
page_url |
Canonical wiki URL for the rule page |
chapter |
Chapter label when present |
section |
Section label when present |
rule_id |
Rule identifier (e.g. API00-C, CON50-J) |
title |
Short rule title |
intro |
Normative / explanatory text |
noncompliant_code |
Noncompliant example(s) when present |
compliant_solution |
Compliant example(s) when present |
risk_assessment |
Risk / severity notes when present |
breadcrumb |
Wiki breadcrumb trail when present |
Dataset Creation
Curation Rationale
Compact machine-readable export of Android CERT guidance.
Source Data
Data Collection and Processing
Scraped from the Android section of the SEI wiki using the shared CSV schema.
Who are the source data producers?
[More Information Needed]
Annotations [optional]
Annotation process
[More Information Needed]
Who are the annotators?
[More Information Needed]
Personal and Sensitive Information
[More Information Needed]
Bias, Risks, and Limitations
[More Information Needed]
Recommendations
Users should be made aware of the risks, biases and limitations of the dataset. More information needed for further recommendations.
Citation [optional]
BibTeX:
[More Information Needed]
APA:
[More Information Needed]
Glossary [optional]
[More Information Needed]
More Information [optional]
[More Information Needed]
Dataset Card Authors [optional]
[More Information Needed]
Dataset Card Contact
[More Information Needed]
- Downloads last month
- 12