// 73-Labs/examples/chain-target/src/com/pentest/ch73/chain/NotesProvider.java
//
// Lab 02's exported ContentProvider. DELIBERATELY INSECURE.
//
//   Finding 2  exported, no read permission, no write permission, no path
//              permission, and query() ignores the selection entirely and
//              returns every row. Any application on the device -- and the
//              `shell` user over adb -- can read it.
//
// This is the finding the chain is built around, because it is the one where
// the static read and the dynamic confirmation say slightly different things.
// Statically you can prove the provider is reachable. Only dynamically can you
// establish WHAT it hands over, and that difference is the entire severity
// argument in the report you write at the end of Lab 02.
//
// AUTHORISED TESTING ONLY.

package com.pentest.ch73.chain;

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

public class NotesProvider extends ContentProvider {

    private static final String TAG = "ch73chain";

    static final String AUTHORITY = "com.pentest.ch73.chain.notes";

    private static final String[] COLUMNS = {"_id", "title", "body"};

    // The rows. The second one is why this is a finding rather than an
    // observation: it is a bearer credential sitting in a table that anybody
    // can read.
    private static final Object[][] ROWS = {
        {1, "shopping", "milk, bread, a 16 KiB page size"},
        {2, "session", "Bearer ch73.eyJzdWIiOiJsYWItMDIifQ.not-a-real-token"},
        {3, "wrapped", VaultActivity.wrap("CH73{the-chain-is-the-lesson}")},
    };

    @Override
    public boolean onCreate() {
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        // Note what is NOT here: no getCallingPackage() check, no permission
        // check, and `selection` is accepted and then thrown away. A caller
        // asking for one row gets all three.
        Log.i(TAG, "query from uid " + android.os.Binder.getCallingUid()
                + " selection=" + selection);
        MatrixCursor cursor = new MatrixCursor(COLUMNS);
        for (Object[] row : ROWS) {
            cursor.addRow(row);
        }
        return cursor;
    }

    @Override
    public String getType(Uri uri) {
        return "vnd.android.cursor.dir/vnd.com.pentest.ch73.chain.note";
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        return null;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        return 0;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        return 0;
    }
}
