首页

关于android开发中如何正确使用Public Content Providers安全用法及代码示例

标签:android,Public Content Providers,安全     发布时间:2017-10-31   

一、前言

public Content provider可以被其他应用使用,在没有指定客户端的情况下,可能会受到攻击和恶意篡改。当我们使用非安卓操作系统提供的Public Content Provider时,需要注意请求的参数是不是由恶意软件伪装的,并发送了攻击内容数据。安卓操作系统提供的Contacts和MediaStore不能被恶意软件伪装。

注意事项

1、显示设置导出exported属性为真。@b@2、处理接收到的请求数据,确认真实性和可用性。@b@3、当返回结果时,不可以包含敏感数据。

二、原代码示例

1.AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>@b@<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.jssec.android.provider.publicprovider">@b@ @b@<application@b@    android:icon="@drawable/ic_launcher"@b@    android:label="@string/app_name" >@b@ @b@    <!-- *** POINT 1 *** Explicitly set the exported attribute to true. -->@b@        <provider@b@            android:name=".PublicProvider"@b@            android:authorities="org.jssec.android.provider.publicprovider"@b@            android:exported="true" />@b@    </application>@b@</manifest>

2.PublicProvider.java

package org.jssec.android.provider.publicprovider;@b@import android.content.ContentProvider;@b@import android.content.ContentUris;@b@import android.content.ContentValues;@b@import android.content.UriMatcher;@b@import android.database.Cursor;@b@import android.database.MatrixCursor;@b@import android.net.Uri;@b@ @b@public class PublicProvider extends ContentProvider {@b@ @b@    public static final String AUTHORITY = "org.jssec.android.provider.publicprovider";@b@    public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.org.jssec.contenttype";@b@    public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.org.jssec.contenttype";@b@ @b@    // Expose the interface that the Content Provider provides.@b@    public interface Download {@b@        public static final String PATH = "downloads";@b@        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + PATH);@b@    }@b@ @b@    public interface Address {@b@        public static final String PATH = "addresses";@b@        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + PATH);@b@    }@b@ @b@    // UriMatcher@b@    private static final int DOWNLOADS_CODE = 1;@b@    private static final int DOWNLOADS_ID_CODE = 2;@b@    private static final int ADDRESSES_CODE = 3;@b@    private static final int ADDRESSES_ID_CODE = 4;@b@    private static UriMatcher sUriMatcher;@b@    static {@b@        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);@b@        sUriMatcher.addURI(AUTHORITY, Download.PATH, DOWNLOADS_CODE);@b@        sUriMatcher.addURI(AUTHORITY, Download.PATH + "/#", DOWNLOADS_ID_CODE);@b@        sUriMatcher.addURI(AUTHORITY, Address.PATH, ADDRESSES_CODE);@b@        sUriMatcher.addURI(AUTHORITY, Address.PATH + "/#", ADDRESSES_ID_CODE);@b@    }@b@ @b@    // Since this is a sample program,@b@    // query method returns the following fixed result always without using database.@b@    private static MatrixCursor sAddressCursor = new MatrixCursor(new String[] { "_id", "city" });@b@    static {@b@        sAddressCursor.addRow(new String[] { "1", "New York" });@b@        sAddressCursor.addRow(new String[] { "2", "London" });@b@        sAddressCursor.addRow(new String[] { "3", "Paris" });@b@    }@b@    private static MatrixCursor sDownloadCursor = new MatrixCursor(new String[] { "_id", "path" });@b@    static {@b@        sDownloadCursor.addRow(new String[] { "1", "/sdcard/downloads/sample.jpg" });@b@        sDownloadCursor.addRow(new String[] { "2", "/sdcard/downloads/sample.txt" });@b@    }@b@ @b@    @Override@b@    public boolean onCreate() {@b@        return true;@b@    }@b@ @b@    @Override@b@    public String getType(Uri uri) {@b@ @b@        switch (sUriMatcher.match(uri)) {@b@        case DOWNLOADS_CODE:@b@        case ADDRESSES_CODE:@b@            return CONTENT_TYPE;@b@ @b@        case DOWNLOADS_ID_CODE:@b@        case ADDRESSES_ID_CODE:@b@            return CONTENT_ITEM_TYPE;@b@ @b@        default:@b@            throw new IllegalArgumentException("Invalid URI:" + uri);@b@        }@b@    }@b@ @b@    @Override@b@    public Cursor query(Uri uri, String[] projection, String selection,@b@        String[] selectionArgs, String sortOrder) {@b@ @b@        // *** POINT 2 *** Handle the received request data carefully and securely.@b@        // Here, whether uri is within expectations or not, is verified by UriMatcher#match() and switch case. // Checking for other parameters are omitted here, due to sample.@b@        // Refer to "3.2 Handle Input Data Carefully and Securely."@b@        // *** POINT 3 *** When returning a result, do not include sensitive information.@b@        // It depends on application whether the query result has sensitive meaning or not.@b@        // If no problem when the information is taken by malware, it can be returned as result.@b@        switch (sUriMatcher.match(uri)) {@b@        case DOWNLOADS_CODE:@b@        case DOWNLOADS_ID_CODE:@b@            return sDownloadCursor;@b@ @b@        case ADDRESSES_CODE:@b@        case ADDRESSES_ID_CODE:@b@            return sAddressCursor;@b@ @b@        default:@b@            throw new IllegalArgumentException("Invalid URI:" + uri);@b@        }@b@    }@b@ @b@    @Override@b@    public Uri insert(Uri uri, ContentValues values) {@b@ @b@        // *** POINT 2 *** Handle the received request data carefully and securely.@b@        // Here, whether uri is within expectations or not, is verified by UriMatcher#match() and switch case. // Checking for other parameters are omitted here, due to sample.@b@        // Refer to "3.2 Handle Input Data Carefully and Securely."@b@        // *** POINT 3 *** When returning a result, do not include sensitive information.@b@        // It depends on application whether the issued ID has sensitive meaning or not.@b@        // If no problem when the information is taken by malware, it can be returned as result.@b@        switch (sUriMatcher.match(uri)) {@b@        case DOWNLOADS_CODE:@b@            return ContentUris.withAppendedId(Download.CONTENT_URI, 3);@b@ @b@        case ADDRESSES_CODE:@b@            return ContentUris.withAppendedId(Address.CONTENT_URI, 4);@b@ @b@        default:@b@            throw new IllegalArgumentException("Invalid URI:" + uri);@b@        }@b@    }@b@ @b@    @Override@b@    public int update(Uri uri, ContentValues values, String selection,String[] selectionArgs) {@b@ @b@        // *** POINT 2 *** Handle the received request data carefully and securely.@b@        // Here, whether uri is within expectations or not, is verified by UriMatcher#match() and switch case. // Checking for other parameters are omitted here, due to sample.@b@        // Refer to "3.2 Handle Input Data Carefully and Securely."@b@ @b@ @b@       // *** POINT 3 *** When returning a result, do not include sensitive information.@b@        // It depends on application whether the number of updated records has sensitive meaning or not. // If no problem when the information is taken by malware, it can be returned as result.@b@        switch (sUriMatcher.match(uri)) {@b@        case DOWNLOADS_CODE:@b@            return 5; // Return number of updated records@b@ @b@        case DOWNLOADS_ID_CODE:@b@            return 1;@b@ @b@        case ADDRESSES_CODE:@b@            return 15;@b@ @b@        case ADDRESSES_ID_CODE:@b@            return 1;@b@ @b@        default:@b@            throw new IllegalArgumentException("Invalid URI:" + uri);@b@        }@b@    }@b@ @b@    @Override@b@    public int delete(Uri uri, String selection, String[] selectionArgs) {@b@ @b@        // *** POINT 2 *** Handle the received request data carefully and securely.@b@        // Here, whether uri is within expectations or not, is verified by UriMatcher#match() and switch case. // Checking for other parameters are omitted here, due to sample.@b@        // Refer to "3.2 Handle Input Data Carefully and Securely."@b@        // *** POINT 3 *** When returning a result, do not include sensitive information.@b@        // It depends on application whether the number of deleted records has sensitive meaning or not. // If no problem when the information is taken by malware, it can be returned as result.@b@        switch (sUriMatcher.match(uri)) {@b@        case DOWNLOADS_CODE:@b@            return 10; // Return number of deleted records@b@ @b@        case DOWNLOADS_ID_CODE:@b@            return 1;@b@ @b@        case ADDRESSES_CODE:@b@            return 20;@b@ @b@        case ADDRESSES_ID_CODE:@b@            return 1;@b@ @b@        default:@b@            throw new IllegalArgumentException("Invalid URI:" + uri);@b@        }@b@    }@b@}

3.安全使用PublicUserActivity.java - 不要发送敏感数据、当接收结果时,确认结果数据的正确性和安全性

package org.jssec.android.provider.publicuser;@b@ @b@import android.app.Activity;@b@import android.content.ContentValues;@b@import android.content.pm.ProviderInfo;@b@import android.database.Cursor;@b@import android.net.Uri;@b@import android.os.Bundle;@b@import android.view.View;@b@import android.widget.TextView;@b@ @b@public class PublicUserActivity extends Activity {@b@ @b@    // Target Content Provider Information@b@    private static final String AUTHORITY = "org.jssec.android.provider.publicprovider";@b@    private interface Address {@b@        public static final String PATH = "addresses";@b@        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + PATH);@b@}@b@ @b@        public void onQueryClick(View view) {@b@ @b@        logLine("[Query]");@b@ @b@        if (!providerExists(Address.CONTENT_URI)) {@b@ @b@            logLine(" Content Provider doesn't exist.");@b@            return;@b@        }@b@ @b@        Cursor cursor = null;@b@        try {@b@            // *** POINT 4 *** Do not send sensitive information.@b@            // since the target Content Provider may be malware.@b@            // If no problem when the information is taken by malware, it can be included in the request.@b@            cursor = getContentResolver().query(Address.CONTENT_URI, null, null, null, null);@b@ @b@            // *** POINT 5 *** When receiving a result, handle the result data carefully and securely.@b@            // Omitted, since this is a sample. Please refer to "3.2 Handling Input Data Carefully and Securely."@b@            if (cursor == null) {@b@                logLine(" null cursor");@b@            } else {@b@                boolean moved = cursor.moveToFirst();@b@                while (moved) {@b@                    logLine(String.format(" %d, %s", cursor.getInt(0), cursor.getString(1)));@b@                    moved = cursor.moveToNext();@b@                }@b@            }@b@        }@b@        finally {@b@        if (cursor != null) cursor.close();@b@        }@b@    }@b@    public void onInsertClick(View view) {@b@ @b@        logLine("[Insert]");@b@ @b@        if (!providerExists(Address.CONTENT_URI)) {@b@            logLine(" Content Provider doesn't exist.");@b@            return;@b@        }@b@ @b@        // *** POINT 4 *** Do not send sensitive information.@b@        // since the target Content Provider may be malware.@b@        // If no problem when the information is taken by malware, it can be included in the request.@b@        ContentValues values = new ContentValues();@b@        values.put("city", "Tokyo");@b@        Uri uri = getContentResolver().insert(Address.CONTENT_URI, values);@b@ @b@        // *** POINT 5 *** When receiving a result, handle the result data carefully and securely.@b@        // Omitted, since this is a sample. Please refer to "3.2 Handling Input Data Carefully and Securely."@b@        logLine(" uri:" + uri);@b@    }@b@ @b@    public void onUpdateClick(View view) {@b@ @b@        logLine("[Update]");@b@        if (!providerExists(Address.CONTENT_URI)) {@b@            logLine(" Content Provider doesn't exist.");@b@            return;@b@        }@b@ @b@        // *** POINT 4 *** Do not send sensitive information.@b@        // since the target Content Provider may be malware.@b@        // If no problem when the information is taken by malware, it can be included in the request.@b@        ContentValues values = new ContentValues();@b@        values.put("city", "Tokyo");@b@        String where = "_id = ?";@b@        String[] args = { "4" };@b@        int count = getContentResolver().update(Address.CONTENT_URI, values, where, args);@b@ @b@        // *** POINT 5 *** When receiving a result, handle the result data carefully and securely.@b@        // Omitted, since this is a sample. Please refer to "3.2 Handling Input Data Carefully and Securely."@b@        logLine(String.format(" %s records updated", count));@b@    }@b@ @b@    public void onDeleteClick(View view) {@b@ @b@        logLine("[Delete]");@b@ @b@        if (!providerExists(Address.CONTENT_URI)) {@b@            logLine(" Content Provider doesn't exist.");@b@            return;@b@        }@b@ @b@        // *** POINT 4 *** Do not send sensitive information.@b@        // since the target Content Provider may be malware.@b@        // If no problem when the information is taken by malware, it can be included in the request.@b@        int count = getContentResolver().delete(Address.CONTENT_URI, null, null);@b@        // *** POINT 5 *** When receiving a result, handle the result data carefully and securely.@b@        // Omitted, since this is a sample. Please refer to "3.2 Handling Input Data Carefully and Securely."@b@        logLine(String.format(" %s records deleted", count));@b@    }@b@ @b@    private boolean providerExists(Uri uri) {@b@        ProviderInfo pi = getPackageManager().resolveContentProvider(uri.getAuthority(), 0);@b@        return (pi != null);@b@    }@b@ @b@    private TextView mLogView;@b@ @b@    @Override@b@    public void onCreate(Bundle savedInstanceState) {@b@        super.onCreate(savedInstanceState);@b@        setContentView(R.layout.main);@b@        mLogView = (TextView)findViewById(R.id.logview);@b@    }@b@ @b@    private void logLine(String line) {@b@        mLogView.append(line);@b@        mLogView.append("¥n");@b@    }@b@}

三、安全代码示例

不要发送敏感数据,当接收结果时,确认结果数据的正确性和安全性。

PublicUserActivity.java@b@ @b@package org.jssec.android.provider.publicuser;@b@ @b@import android.app.Activity;@b@import android.content.ContentValues;@b@import android.content.pm.ProviderInfo;@b@import android.database.Cursor;@b@import android.net.Uri;@b@import android.os.Bundle;@b@import android.view.View;@b@import android.widget.TextView;@b@ @b@public class PublicUserActivity extends Activity {@b@ @b@    // Target Content Provider Information@b@    private static final String AUTHORITY = "org.jssec.android.provider.publicprovider";@b@    private interface Address {@b@        public static final String PATH = "addresses";@b@        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + PATH);@b@}@b@ @b@        public void onQueryClick(View view) {@b@ @b@        logLine("[Query]");@b@ @b@        if (!providerExists(Address.CONTENT_URI)) {@b@ @b@            logLine(" Content Provider doesn't exist.");@b@            return;@b@        }@b@ @b@        Cursor cursor = null;@b@        try {@b@            // *** POINT 4 *** Do not send sensitive information.@b@            // since the target Content Provider may be malware.@b@            // If no problem when the information is taken by malware, it can be included in the request.@b@            cursor = getContentResolver().query(Address.CONTENT_URI, null, null, null, null);@b@ @b@            // *** POINT 5 *** When receiving a result, handle the result data carefully and securely.@b@            // Omitted, since this is a sample. Please refer to "3.2 Handling Input Data Carefully and Securely."@b@            if (cursor == null) {@b@                logLine(" null cursor");@b@            } else {@b@                boolean moved = cursor.moveToFirst();@b@                while (moved) {@b@                    logLine(String.format(" %d, %s", cursor.getInt(0), cursor.getString(1)));@b@                    moved = cursor.moveToNext();@b@                }@b@            }@b@        }@b@        finally {@b@        if (cursor != null) cursor.close();@b@        }@b@    }@b@    public void onInsertClick(View view) {@b@ @b@        logLine("[Insert]");@b@ @b@        if (!providerExists(Address.CONTENT_URI)) {@b@            logLine(" Content Provider doesn't exist.");@b@            return;@b@        }@b@ @b@        // *** POINT 4 *** Do not send sensitive information.@b@        // since the target Content Provider may be malware.@b@        // If no problem when the information is taken by malware, it can be included in the request.@b@        ContentValues values = new ContentValues();@b@        values.put("city", "Tokyo");@b@        Uri uri = getContentResolver().insert(Address.CONTENT_URI, values);@b@ @b@        // *** POINT 5 *** When receiving a result, handle the result data carefully and securely.@b@        // Omitted, since this is a sample. Please refer to "3.2 Handling Input Data Carefully and Securely."@b@        logLine(" uri:" + uri);@b@    }@b@ @b@    public void onUpdateClick(View view) {@b@ @b@        logLine("[Update]");@b@        if (!providerExists(Address.CONTENT_URI)) {@b@            logLine(" Content Provider doesn't exist.");@b@            return;@b@        }@b@ @b@        // *** POINT 4 *** Do not send sensitive information.@b@        // since the target Content Provider may be malware.@b@        // If no problem when the information is taken by malware, it can be included in the request.@b@        ContentValues values = new ContentValues();@b@        values.put("city", "Tokyo");@b@        String where = "_id = ?";@b@        String[] args = { "4" };@b@        int count = getContentResolver().update(Address.CONTENT_URI, values, where, args);@b@ @b@        // *** POINT 5 *** When receiving a result, handle the result data carefully and securely.@b@        // Omitted, since this is a sample. Please refer to "3.2 Handling Input Data Carefully and Securely."@b@        logLine(String.format(" %s records updated", count));@b@    }@b@ @b@    public void onDeleteClick(View view) {@b@ @b@        logLine("[Delete]");@b@ @b@        if (!providerExists(Address.CONTENT_URI)) {@b@            logLine(" Content Provider doesn't exist.");@b@            return;@b@        }@b@ @b@        // *** POINT 4 *** Do not send sensitive information.@b@        // since the target Content Provider may be malware.@b@        // If no problem when the information is taken by malware, it can be included in the request.@b@        int count = getContentResolver().delete(Address.CONTENT_URI, null, null);@b@        // *** POINT 5 *** When receiving a result, handle the result data carefully and securely.@b@        // Omitted, since this is a sample. Please refer to "3.2 Handling Input Data Carefully and Securely."@b@        logLine(String.format(" %s records deleted", count));@b@    }@b@ @b@    private boolean providerExists(Uri uri) {@b@        ProviderInfo pi = getPackageManager().resolveContentProvider(uri.getAuthority(), 0);@b@        return (pi != null);@b@    }@b@ @b@    private TextView mLogView;@b@ @b@    @Override@b@    public void onCreate(Bundle savedInstanceState) {@b@        super.onCreate(savedInstanceState);@b@        setContentView(R.layout.main);@b@        mLogView = (TextView)findViewById(R.id.logview);@b@    }@b@ @b@    private void logLine(String line) {@b@        mLogView.append(line);@b@        mLogView.append("¥n");@b@    }@b@}