// examples/inert-sample/BootstrapProvider.java
//
// =========================================================================
// INERT TEACHING SAMPLE — chapter 69. THIS IS NOT MALWARE.
// No payload, no C2, no exfiltration, no evasion. Every method below logs
// and returns. All embedded indicators resolve to RFC 2606 `.invalid`
// names, which can never be registered or resolved by anybody.
// =========================================================================
//
// WHY A PROVIDER, AND NOT AN Application SUBCLASS
//
// This class exists to demonstrate the single most important persistence and
// early-execution primitive on Android, and to give the triage tool in
// ../../scripts/apk-triage.py something genuine to detect.
//
// When the system starts a process for an app, ActivityThread runs
// handleBindApplication(). Inside it, in this order:
//
//   1. the ClassLoader is built and the Instrumentation is created
//   2. Application is INSTANTIATED (its constructor and attachBaseContext run)
//   3. installContentProviders() runs — every non-multiprocess provider
//      declared for this process is instantiated and its onCreate() called
//   4. THEN mInstrumentation.callApplicationOnCreate(app) runs, which is
//      Application.onCreate()
//
// So provider onCreate() precedes Application.onCreate(). Chapter 09 measured
// this on a device with a Frida hook that timestamps both; see
// ../../../09-Android-App-Internals/README.md section 3 and its section 7.3
// script. Three consequences follow, and all three are why malware likes it:
//
//   * A library that ships a provider executes inside every host app that
//     depends on it, with the host's UID and permissions, before the host's
//     own initialisation code has run. androidx.startup is this mechanism
//     used deliberately and benignly; a hostile SDK is the same mechanism.
//   * Any integrity or anti-tamper check the app performs in
//     Application.onCreate() has already been preceded by the provider.
//   * The provider does not need to be exported, does not need an
//     intent-filter, and does not appear in any list of "entry points" that a
//     reader assembles by looking for Activities.
//
// WHAT A HOSTILE VERSION WOULD DO HERE, AND WHY THIS ONE DOES NOT
//
// A real dropper's provider onCreate() typically: reads an encrypted config
// from assets, decrypts it, decides whether the environment is a real user
// device, and schedules a second stage. This class performs step one only —
// it locates the config assets and reports their SIZE, without decrypting
// them and without acting on them. Decryption is done OFFLINE by the analyst,
// with ../../scripts/config-decrypt.py, which is where it belongs: the
// analyst's job is to read the config, not to execute it.

package com.pentest.ch69.inert;

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

import java.io.IOException;
import java.io.InputStream;

public class BootstrapProvider extends ContentProvider {

    static final String TAG = "CH69-INERT";

    /**
     * The whole sample is gated on this. It is `true`, it is `final`, and
     * nothing sets it to anything else. Every branch guarded by it is the
     * branch that does nothing.
     *
     * Deliberately a plain `static final boolean` rather than a
     * BuildConfig field, so that it survives into the DEX as a constant the
     * reader can see: javac folds `if (INERT)` and leaves the dead branch
     * out, which is itself a useful thing to observe in JADX. Compare what
     * jadx shows for this class against the source and note what is missing.
     */
    public static final boolean INERT = true;

    /** Set by onCreate so the rest of the sample can prove the ordering. */
    static volatile long providerOnCreateNanos = 0L;

    @Override
    public boolean onCreate() {
        providerOnCreateNanos = System.nanoTime();

        Log.i(TAG, "BootstrapProvider.onCreate  pid=" + android.os.Process.myPid()
                + "  t=" + providerOnCreateNanos
                + "  (this runs BEFORE Application.onCreate)");

        // Stage-one reconnaissance, in the only form this sample performs it:
        // measure the config blobs and print their length. No decryption
        // happens on-device. No network call happens anywhere.
        reportAssetSize("cfg-xor.bin");
        reportAssetSize("cfg-aes.bin");

        if (INERT) {
            Log.i(TAG, "INERT=true: no stage two is scheduled, no config is "
                    + "decrypted, no socket is opened.");
            return true;
        }

        // Unreachable. Present so the reader can see the SHAPE of the branch a
        // hostile provider takes, written as comments rather than as code.
        //
        //   1. decrypt assets/cfg-aes.bin with the key embedded in this DEX
        //   2. read the "gate" URL and the "poll" interval from the plaintext
        //   3. start SentinelService in the foreground so the process survives
        //   4. schedule GuardService in a second process to restart it
        //
        // Steps 1 and 2 are what config-decrypt.py reproduces offline. Steps 3
        // and 4 are what the watchdog pair models, with the restart removed.
        return true;
    }

    private void reportAssetSize(String name) {
        Context ctx = getContext();
        if (ctx == null) {
            Log.w(TAG, "no context in onCreate — cannot stat " + name);
            return;
        }
        InputStream in = null;
        try {
            in = ctx.getAssets().open(name);
            int total = 0;
            byte[] buf = new byte[4096];
            int n;
            while ((n = in.read(buf)) > 0) {
                total += n;
            }
            Log.i(TAG, "asset " + name + " is " + total + " bytes "
                    + "(NOT decrypted on device — use config-decrypt.py)");
        } catch (IOException e) {
            Log.w(TAG, "asset " + name + " missing: " + e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ignored) {
                    // nothing to do
                }
            }
        }
    }

    // ------------------------------------------------------------------ //
    // The ContentProvider contract. This provider serves no data. It is
    // android:exported="false" and every method refuses. A provider used
    // purely as an execution hook usually looks exactly like this, and that
    // is a recognisable triage pattern in its own right: a provider whose
    // query/insert/update/delete all return null or 0, whose getType()
    // returns null, and whose onCreate() is the only method with a body.
    // ------------------------------------------------------------------ //

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        return null;
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @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;
    }
}
