// examples/inert-sample/SentinelService.java
//
// =========================================================================
// INERT TEACHING SAMPLE — chapter 69. THIS IS NOT MALWARE.
// The peer-restart call that makes a watchdog pair a watchdog pair has been
// REMOVED and replaced with a log line. Nothing here survives being killed,
// and nothing here restarts anything.
// =========================================================================
//
// WHAT A WATCHDOG PAIR IS, AND WHY IT EXISTS
//
// A single process is easy to stop. `am force-stop <pkg>` kills every process
// belonging to a package at once, and so does swiping the app away on many
// OEM builds. Two cooperating processes are only slightly harder — force-stop
// still gets both — but they defeat the *casual* kill: the task-manager
// swipe, the battery optimiser, the low-memory killer reclaiming one process
// under pressure, and a user who force-stops from Settings without also
// revoking the capabilities that let the app restart.
//
// The mechanism is simple and the shape is what you learn to recognise:
//
//   * Two components in two processes, declared with android:process=":name"
//     on one of them, so that the package occupies two entries in `ps`.
//   * Each holds a reference to the other — usually a hardcoded component
//     name, sometimes an alarm, sometimes a bound service connection whose
//     onServiceDisconnected() is the trigger.
//   * At least one is a foreground service, so the platform's background
//     execution limits (API 26+) do not apply to it.
//   * Often a third arm: a JobScheduler job or WorkManager worker with a
//     periodic schedule, which the system itself restarts after a reboot.
//
// The reason a pair is used rather than a single foreground service is that
// the foreground service is visible: it posts a notification the user can see
// and tap through to "app info". The second process is not visible anywhere
// a normal user looks. So the visible arm absorbs attention and the invisible
// arm restores it.
//
// HOW AN ANALYST DETECTS IT — this is the part that matters
//
// Statically:
//   * grep the manifest for android:process=":".  A benign app has zero or
//     one such component, usually a crash reporter or a media playback
//     service. A component whose only job is to name another component is
//     the signal.
//   * Look for a class in process A whose imports mention a class in process
//     B, with no data flowing between them. A supervisor references its
//     supervisee and asks it nothing.
//   * android:stopWithTask="false" on both. This attribute means "do not
//     stop me when the user swipes the task away". It is legitimate on a
//     music player. On a utility app with no user-visible long-running work,
//     on both halves of a pair, it is not.
//
// Dynamically (emulator only — see the isolation rules in README section 7):
//   * `adb shell ps -A | grep <pkg>` before and after killing one pid. If the
//     pid comes back with a new number and the other pid is unchanged, you
//     have watched the restart happen.
//   * `adb shell dumpsys activity services <pkg>` shows both services, their
//     process names, and whether each is foreground.
//   * The three-way kill test: kill A, kill B, then kill both within the same
//     second. A pair that survives the first two and dies on the third is a
//     pair; anything that survives all three has a mechanism you have not
//     found yet, and JobScheduler is the usual answer —
//     `adb shell dumpsys jobscheduler | grep -A 20 <pkg>`.
//
// This class implements the SHAPE and none of the FUNCTION. It logs the peer
// it would supervise; it never starts it.

package com.pentest.ch69.inert;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

public class SentinelService extends Service {

    /** The peer this service would supervise. Named, never started. */
    static final String PEER = "com.pentest.ch69.inert.GuardService";

    private static final String CHANNEL_ID = "ch69-inert";

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(BootstrapProvider.TAG, "SentinelService.onCreate  pid="
                + android.os.Process.myPid() + "  process=main");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(BootstrapProvider.TAG, "SentinelService.onStartCommand  peer=" + PEER);

        if (BootstrapProvider.INERT) {
            Log.i(BootstrapProvider.TAG,
                    "INERT=true: a live pair would (a) call startForeground() "
                    + "with a low-importance notification so the platform's "
                    + "background limits do not apply, and (b) bind to " + PEER
                    + " so that onServiceDisconnected fires when the peer dies. "
                    + "This build does neither.");
            // START_NOT_STICKY is deliberate: it is the OPPOSITE of what a
            // persistence mechanism wants. A live sample returns START_STICKY
            // so that the system itself recreates the service after a kill,
            // which is the cheapest watchdog of all and needs no second
            // process. Note the value when you decompile this: the constant is
            // visible in the DEX and is a one-glance triage signal.
            return START_NOT_STICKY;
        }

        // Unreachable. Kept as commentary so the reader can see the shape:
        //   startForeground(1, buildQuietNotification());
        //   bindService(new Intent(this, GuardService.class), conn, BIND_AUTO_CREATE);
        //   return START_STICKY;
        return START_NOT_STICKY;
    }

    /**
     * Not called. Present because the *notification channel importance* is
     * itself a triage signal and the reader should see what to look for.
     *
     * A foreground service must post a notification. Malware minimises how
     * visible that notification is: IMPORTANCE_MIN or IMPORTANCE_NONE on the
     * channel, setShowBadge(false), a generic title borrowed from a system
     * string, and on API 31+ FOREGROUND_SERVICE_DEFERRED behaviour so the
     * notification does not appear for the first ten seconds. Since API 33
     * POST_NOTIFICATIONS is a runtime permission, and a foreground service
     * whose notification the user denied still runs — the notification is
     * suppressed, not the service.
     */
    @SuppressWarnings("unused")
    private Notification buildQuietNotification() {
        NotificationManager nm =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && nm != null) {
            NotificationChannel ch = new NotificationChannel(
                    CHANNEL_ID, "Sync", NotificationManager.IMPORTANCE_MIN);
            ch.setShowBadge(false);
            nm.createNotificationChannel(ch);
        }
        Notification.Builder b;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            b = new Notification.Builder(this, CHANNEL_ID);
        } else {
            b = new Notification.Builder(this);
        }
        return b.setContentTitle("Sync")
                .setSmallIcon(android.R.drawable.stat_notify_sync)
                .build();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // Not bindable. Note for the reader: chapter 28 measured that
        // getCallingUid() inside onBind() returns the SERVICE's own uid, not
        // the caller's, because onBind is dispatched by the system. Any access
        // check placed here is checking the wrong identity.
        return null;
    }

    @Override
    public void onDestroy() {
        Log.i(BootstrapProvider.TAG, "SentinelService.onDestroy — and that is "
                + "the end of it. Nothing restarts this service.");
        super.onDestroy();
    }
}
