/*
 * examples/SignatureGuardedService.java
 * =====================================
 *
 * A signature-protected component done CORRECTLY.
 *
 * WHAT THIS DEMONSTRATES
 *     Four layers of control, each of which covers a different failure of the
 *     others. Three of the four are in this file; the fourth is in the manifest
 *     beside it (signature-guarded-AndroidManifest.xml).
 *
 *       LAYER 1  android:permission="...READ_VAULT" at protectionLevel="signature"
 *                Covers: an attacker requesting the permission. They would need
 *                the private key.
 *
 *       LAYER 2  Every app in the suite declares that permission IDENTICALLY.
 *                Covers: the squatting window. A permission an app USES but
 *                does not DECLARE is unowned on any device where the declaring
 *                sibling is absent, and whoever declares it first owns the rule.
 *                Measured on Android 13 - see README.md section 3.6.
 *
 *       LAYER 3  enforceSameSignatureCaller() in onBind().
 *                Covers: a squatted or mis-resolved permission, and any route
 *                that reached the component with the manifest check satisfied
 *                for the wrong reason.
 *
 *       LAYER 4  enforceSameSignatureCaller() again inside EVERY Binder method.
 *                Covers: the fact that layers 1 and 3 are ENTRY-TIME checks. An
 *                IBinder handed to a caller at bind time is used many times
 *                afterwards, and Binder.getCallingUid() inside the method is the
 *                only thing that re-establishes who is asking on each call.
 *                This is the layer that gets left out.
 *
 * WHY checkSignatures RATHER THAN A PERMISSION
 *     A permission name is a string, and a string can be squatted. A signing
 *     certificate cannot. PackageManager.checkSignatures(int, int) compares the
 *     certificates of two UIDs directly. It does not go near the permission
 *     database, so nothing an attacker can install changes its answer.
 *
 * WHY UID RATHER THAN PACKAGE NAME
 *     getCallingPackage() returns the FIRST package name for the calling UID,
 *     which is ambiguous when apps share a UID via android:sharedUserId, and it
 *     returns null outside a Binder transaction. Binder.getCallingUid() returns
 *     the UID the binder driver stamped into the transaction, which no amount
 *     of user-space cleverness can forge. Where you need names, resolve them
 *     from the UID with getPackagesForUid() and check EVERY entry - it returns
 *     an array for exactly this reason.
 *
 * WHAT THIS DOES NOT DO
 *     - It does not authenticate a HUMAN. It authenticates a calling app. If
 *       the sibling app is compromised, this check passes.
 *     - It does not protect against a same-signature app that has itself been
 *       repackaged with a leaked key. Key hygiene is the precondition for the
 *       whole scheme; see README.md section 3.2.
 *     - It does not rate-limit, audit, or scope data per caller. The enterprise
 *       variant in README.md section 9.5 adds a package allow-list on top.
 *
 * BUILDING
 *     This file is illustrative source, not a project. It references an AIDL
 *     interface (IVaultService) that you would generate from a .aidl file in a
 *     real app. To compile it you need an Android project; the point of the
 *     file is the shape of the checks, and that shape is copy-pasteable into
 *     any Service.
 *
 * AUTHORISED TESTING ONLY.
 */

package com.example.vault;

import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Binder;
import android.os.IBinder;
import android.os.Process;
import android.util.Log;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class SignatureGuardedService extends Service {

    private static final String TAG = "SignatureGuardedService";

    /**
     * Stand-in for whatever the service actually protects. In a real app this
     * would be backed by EncryptedSharedPreferences or the Android Keystore -
     * see 49-KeyStore.
     */
    private final Map<String, String> mVault = Collections.synchronizedMap(new HashMap<>());

    /**
     * The Binder interface. IVaultService.Stub is generated by the AIDL
     * compiler from IVaultService.aidl.
     */
    private final IVaultService.Stub mBinder = new IVaultService.Stub() {

        @Override
        public String readSecret(String key) {
            // LAYER 4. Yes, again. onBind() already checked, and the manifest
            // permission was checked before that.
            //
            // Both of those were ENTRY-TIME checks. This IBinder was handed to
            // a caller once and can be invoked a thousand times afterwards; if
            // the caller ever passes the reference on, or if a route exists to
            // this object that did not go through onBind, the entry checks
            // never run again. Binder.getCallingUid() here is evaluated per
            // call, against the identity the kernel stamped into THIS
            // transaction.
            enforceSameSignatureCaller();
            return mVault.get(key);
        }

        @Override
        public void writeSecret(String key, String value) {
            enforceSameSignatureCaller();

            // Note the asymmetry a developer would be tempted to introduce
            // here: "reads are sensitive, writes are harmless". They are not.
            // An attacker who can write into a store the app itself trusts has
            // a poisoning primitive, and in the provider case the same mistake
            // shows up as readPermission without writePermission. See
            // 27-ContentProviders.
            mVault.put(key, value);
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        // LAYER 3. The manifest permission has already been checked by the
        // platform at this point - checkComponentPermission ran in
        // system_server before this method was reached. This check exists
        // because that permission is a STRING, and a string can be owned by an
        // app that installed before ours.
        enforceSameSignatureCaller();
        return mBinder;
    }

    /**
     * Authorise the caller by an identity the attacker cannot supply.
     *
     * Throws SecurityException, which crosses the Binder boundary and surfaces
     * in the CALLER's process when the reply is unparcelled. Throwing is the
     * right choice over returning null: a null return is indistinguishable from
     * "no such key" and teaches the caller nothing, while a SecurityException is
     * unambiguous and shows up in logcat during development.
     */
    private void enforceSameSignatureCaller() {
        final int callingUid = Binder.getCallingUid();

        // Ourselves. Binder.getCallingUid() returns our own UID when there is
        // no transaction in progress - which happens whenever this object is
        // used from our own code, from a Handler, or from an Executor.
        //
        // This early return is the ONLY safe form of the "or self" idea. Note
        // what it is NOT: it is not Context.checkCallingOrSelfPermission(),
        // which asks "does the caller hold the permission - or, if there is no
        // caller, do I?". In a privileged app that method returns GRANTED for
        // everyone the moment the check runs off the Binder thread. See
        // README.md section 3.8.
        if (callingUid == Process.myUid()) {
            return;
        }

        final PackageManager pm = getPackageManager();

        // checkSignatures(int, int) compares the signing certificates of two
        // UIDs. It operates on UIDs rather than package names, so it is
        // unambiguous under sharedUserId, and it never consults the permission
        // database, so nothing an attacker installs can change its answer.
        final int result = pm.checkSignatures(Process.myUid(), callingUid);
        if (result != PackageManager.SIGNATURE_MATCH) {
            // Log the UID and the resolved package names, not just "denied".
            // On an incident review the UID is what ties this line to a process.
            final String[] pkgs = pm.getPackagesForUid(callingUid);
            Log.w(TAG, "rejected uid=" + callingUid
                    + " packages=" + (pkgs == null ? "<unknown>" : java.util.Arrays.toString(pkgs))
                    + " checkSignatures=" + result);
            throw new SecurityException(
                    "caller uid " + callingUid + " is not same-signature");
        }
    }

    /**
     * The stricter variant: same signature AND an explicit package allow-list.
     *
     * Use this where a compromised sibling in your own suite must still not
     * reach the interface. It is the enterprise pattern from README.md 9.5.
     *
     * Note the loop. getPackagesForUid() returns an ARRAY, because a UID can
     * map to several packages under sharedUserId. Checking only element zero -
     * which is effectively what getCallingPackage() gives you - is a real bug
     * and it is the reason getCallingPackage() should not be used for a
     * security decision.
     */
    @SuppressWarnings("unused")
    private void enforceAllowedCaller(java.util.Set<String> allowed) {
        enforceSameSignatureCaller();

        final int callingUid = Binder.getCallingUid();
        if (callingUid == Process.myUid()) {
            return;
        }
        final String[] pkgs = getPackageManager().getPackagesForUid(callingUid);
        if (pkgs == null) {
            throw new SecurityException("cannot resolve packages for uid " + callingUid);
        }
        for (String p : pkgs) {
            if (allowed.contains(p)) {
                return;
            }
        }
        throw new SecurityException("uid " + callingUid + " is not in the allow-list");
    }
}
