/*
 * examples/tamper_check.c
 * ---------------------------------------------------------------------------
 * PURPOSE
 *   The native tier of the chapter 38 detector: anti-analysis that runs inside
 *   JNI_OnLoad, before the Java class that triggered System.loadLibrary() has
 *   finished its static initialiser, and therefore before any of the app's own
 *   logic has had a chance to be hooked at the Java level.
 *
 *   Six checks, each of which reports rather than decides:
 *
 *     N1  TracerPid          is somebody ptrace-attached right now
 *     N2  ptrace self-attach  claim the tracer slot so nobody else can
 *     N3  maps scan           is an instrumentation library mapped in
 *     N4  Frida default port  is something listening on 127.0.0.1:27042
 *     N5  self .text digest   has my own code been patched on disk
 *     N6  timing              did the checks take absurdly long
 *
 *   It also ships a `__attribute__((constructor))` function to demonstrate the
 *   tier BELOW JNI_OnLoad: ELF constructors run inside dlopen(), before
 *   JNI_OnLoad, before anything. 17-Libraries owns the mechanism; this file
 *   shows what a check looks like when it lives there, and prints the ordering
 *   so you can watch it for yourself.
 *
 * BUILD (out of tree - never leave a .so in the repository)
 *   # host, one architecture
 *   NDK=$ANDROID_HOME/ndk/25.2.9519653
 *   TC=$NDK/toolchains/llvm/prebuilt/<host>/bin
 *   $TC/aarch64-linux-android21-clang -shared -fPIC -O2 -Wall -Wextra \
 *       -o /tmp/libch38.so tamper_check.c -llog
 *
 *   # host, syntax-only check with no NDK (works with any clang/gcc):
 *   #   this file guards every Android-specific include, so a plain
 *   #   `cc -fsyntax-only tamper_check.c` succeeds off-device too.
 *
 * WHAT THIS WILL *NOT* TELL YOU
 *   * It will NOT stop a determined analyst. Every check here is defeated in
 *     chapter 67's methodology, and several are defeated by a one-line Frida
 *     script in README section 6.6. Its value is that it forces the attacker
 *     to work at the NATIVE tier and to be attached EARLY, which is a real cost
 *     increase over a Java-only design and no more than that.
 *   * It will NOT detect root. Chapter 37 owns that.
 *   * N5 will NOT catch an in-memory patch. It digests the file on disk. An
 *     attacker who patches the mapped pages after the check has run leaves the
 *     file untouched and the digest correct -- which is exactly the lesson
 *     18-ARM records from the other side.
 *   * N2 is a one-shot. PTRACE_TRACEME succeeds once per process. If your app
 *     calls it twice, the second call fails and you will detect yourself.
 *
 * AUTHORISED TESTING ONLY.
 * ---------------------------------------------------------------------------
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#if defined(__ANDROID__) || defined(__linux__)
#  include <unistd.h>
#  include <fcntl.h>
#  include <errno.h>
#  include <sys/ptrace.h>
#  include <sys/socket.h>
#  include <netinet/in.h>
#  include <arpa/inet.h>
#  include <dlfcn.h>
#  define CH38_HAVE_POSIX 1
#endif

#ifdef __ANDROID__
#  include <jni.h>
#  include <android/log.h>
#  define LOGI(...) __android_log_print(ANDROID_LOG_INFO, "CH38N", __VA_ARGS__)
#else
/* Building off-device for a syntax check: fall back to stdout so the file is
 * still compilable and still readable as ordinary C. */
#  define LOGI(...) do { printf("[CH38N] "); printf(__VA_ARGS__); printf("\n"); } while (0)
#endif

/* --------------------------------------------------------------------------
 * Reporting model
 *
 * Same decision as the Java tier: return evidence, not a boolean. A single
 * `int is_tampered()` is one branch, and one branch in a native library is
 * eight bytes to overwrite. Reporting each check separately is better for the
 * learner AND marginally better for the defender, because the attacker now has
 * six sites to find rather than one.
 * -------------------------------------------------------------------------- */

typedef enum { CH38_PASS = 0, CH38_FAIL = 1, CH38_UNKNOWN = 2 } ch38_verdict;

static const char *verdict_name(ch38_verdict v)
{
    switch (v) {
    case CH38_PASS:    return "PASS";
    case CH38_FAIL:    return "FAIL";
    default:           return "UNKNOWN";
    }
}

static void report(const char *id, const char *name, ch38_verdict v, const char *evidence)
{
    LOGI("%s %-22s %-7s | %s", id, name, verdict_name(v), evidence);
}

/* --------------------------------------------------------------------------
 * N1 - TracerPid
 *
 * /proc/self/status is generated by the kernel when it is read
 * (fs/proc/array.c). The TracerPid line carries the PID of the process that is
 * ptrace-attached, or 0.
 *
 * Deliberately implemented with open/read rather than fopen/fgets. It is not
 * meaningfully harder to hook, but it does mean that hooking fopen alone -- the
 * first thing most people try -- misses it, and watching that happen is
 * instructive.
 * -------------------------------------------------------------------------- */

static ch38_verdict check_tracer_pid(char *ev, size_t evlen)
{
#ifdef CH38_HAVE_POSIX
    int fd = open("/proc/self/status", O_RDONLY);
    if (fd < 0) {
        snprintf(ev, evlen, "open(/proc/self/status) failed: %s", strerror(errno));
        return CH38_UNKNOWN;
    }

    char buf[4096];
    ssize_t n = read(fd, buf, sizeof(buf) - 1);
    close(fd);
    if (n <= 0) {
        snprintf(ev, evlen, "read failed");
        return CH38_UNKNOWN;
    }
    buf[n] = '\0';

    const char *p = strstr(buf, "TracerPid:");
    if (p == NULL) {
        snprintf(ev, evlen, "no TracerPid line");
        return CH38_UNKNOWN;
    }

    long pid = strtol(p + 10, NULL, 10);
    snprintf(ev, evlen, "TracerPid=%ld", pid);
    return (pid == 0) ? CH38_PASS : CH38_FAIL;
#else
    (void)evlen;
    snprintf(ev, 32, "not a Linux host");
    return CH38_UNKNOWN;
#endif
}

/* --------------------------------------------------------------------------
 * N2 - ptrace self-attach
 *
 * PTRACE_TRACEME asks the kernel to make the CALLER's parent its tracer. A
 * process may have at most one tracer, so after this succeeds, any later
 * PTRACE_ATTACH from a debugger or from frida-server returns EPERM.
 *
 * Three things people get wrong about this, all worth stating plainly:
 *
 *   1. It is NOT a detection on its own. It is a DENIAL. It stops an attach; it
 *      does not tell you one was attempted.
 *   2. Calling it twice is how you turn it into a detection: the second call
 *      fails with EPERM if -- and only if -- somebody is already tracing. That
 *      also means an app must never call it twice by accident.
 *   3. It costs nothing to defeat if the attacker was attached first. Spawn the
 *      process under Frida and the tracer slot is taken before your library
 *      ever loads.
 * -------------------------------------------------------------------------- */

static ch38_verdict check_ptrace_traceme(char *ev, size_t evlen)
{
#ifdef CH38_HAVE_POSIX
    errno = 0;
    long r = ptrace(PTRACE_TRACEME, 0, NULL, NULL);
    if (r == 0) {
        snprintf(ev, evlen, "PTRACE_TRACEME succeeded; the tracer slot is now ours");
        return CH38_PASS;
    }
    snprintf(ev, evlen, "PTRACE_TRACEME failed: %s (errno=%d) - somebody else "
                        "is already tracing this process", strerror(errno), errno);
    return CH38_FAIL;
#else
    (void)evlen;
    snprintf(ev, 32, "not a Linux host");
    return CH38_UNKNOWN;
#endif
}

/* --------------------------------------------------------------------------
 * N3 - address-space scan
 *
 * Read /proc/self/maps and look for the names instrumentation frameworks leave
 * behind. This is the most useful check in the file and also the one whose
 * limits are easiest to state: it finds artefacts that are NAMED. Rename the
 * agent, load it from memory, or hook the read, and it sees nothing.
 * -------------------------------------------------------------------------- */

static const char *MAP_NEEDLES[] = {
    "frida", "gum-js-loop", "linjector", "gadget", "libriru", "lspd", NULL
};

static ch38_verdict check_maps(char *ev, size_t evlen)
{
#ifdef CH38_HAVE_POSIX
    FILE *f = fopen("/proc/self/maps", "r");
    if (f == NULL) {
        snprintf(ev, evlen, "fopen(/proc/self/maps) failed");
        return CH38_UNKNOWN;
    }

    char line[512];
    int lines = 0;
    const char *hit = NULL;

    while (fgets(line, sizeof(line), f) != NULL) {
        lines++;
        for (int i = 0; MAP_NEEDLES[i] != NULL && hit == NULL; i++) {
            if (strstr(line, MAP_NEEDLES[i]) != NULL) {
                hit = MAP_NEEDLES[i];
            }
        }
        if (hit != NULL) {
            break;
        }
    }
    fclose(f);

    if (hit != NULL) {
        snprintf(ev, evlen, "%d mappings scanned, matched \"%s\"", lines, hit);
        return CH38_FAIL;
    }
    snprintf(ev, evlen, "%d mappings scanned, no match", lines);
    return CH38_PASS;
#else
    (void)evlen;
    snprintf(ev, 32, "not a Linux host");
    return CH38_UNKNOWN;
#endif
}

/* --------------------------------------------------------------------------
 * N4 - Frida default port
 *
 * A non-blocking connect to 127.0.0.1:27042. frida-server binds it by default;
 * `frida-server -l 127.0.0.1:1337` does not. So this check costs the attacker
 * one flag. It is here to be understood and then dismissed, which is a more
 * useful outcome than never seeing it.
 * -------------------------------------------------------------------------- */

static ch38_verdict check_frida_port(char *ev, size_t evlen)
{
#ifdef CH38_HAVE_POSIX
    int s = socket(AF_INET, SOCK_STREAM, 0);
    if (s < 0) {
        snprintf(ev, evlen, "socket() failed");
        return CH38_UNKNOWN;
    }

    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(27042);
    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);

    int r = connect(s, (struct sockaddr *)&addr, sizeof(addr));
    int e = errno;
    close(s);

    if (r == 0) {
        snprintf(ev, evlen, "connected to 127.0.0.1:27042");
        return CH38_FAIL;
    }
    snprintf(ev, evlen, "127.0.0.1:27042 refused (%s)", strerror(e));
    return CH38_PASS;
#else
    (void)evlen;
    snprintf(ev, 32, "not a Linux host");
    return CH38_UNKNOWN;
#endif
}

/* --------------------------------------------------------------------------
 * N5 - digest of our own file on disk
 *
 * dladdr() on a function inside this library gives us the path the linker
 * loaded it from. We then read that file and produce a cheap checksum of it.
 *
 * A real implementation would hash only the .text section, with a SHA-256, and
 * compare against a value stored somewhere the hash does not cover. This one
 * deliberately uses a simple additive checksum and PRINTS it rather than
 * comparing, for the same bootstrap reason the Java tier does not hardcode a
 * DEX CRC: you cannot compile the digest of a file into that file.
 *
 * The honest limitation, stated once and loudly: THIS CHECKS THE FILE, NOT THE
 * MEMORY. An attacker who lets the library load cleanly and then patches the
 * mapped pages -- which is what every hooking framework does -- passes this
 * check every time.
 * -------------------------------------------------------------------------- */

static ch38_verdict check_self_file(char *ev, size_t evlen)
{
#ifdef CH38_HAVE_POSIX
    Dl_info info;
    memset(&info, 0, sizeof(info));
    if (dladdr((void *)(uintptr_t)&check_self_file, &info) == 0 || info.dli_fname == NULL) {
        snprintf(ev, evlen, "dladdr() could not name our own object");
        return CH38_UNKNOWN;
    }

    FILE *f = fopen(info.dli_fname, "rb");
    if (f == NULL) {
        /* On modern Android an .so inside an APK with extractNativeLibs=false
         * is not a standalone file at all: dli_fname is the APK path with the
         * entry appended, e.g. /data/app/.../base.apk!/lib/arm64-v8a/libx.so,
         * which fopen cannot open. This is not a failure of the idea, it is a
         * fact about packaging, and returning UNKNOWN is the honest answer. */
        snprintf(ev, evlen, "cannot open \"%s\" (uncompressed-in-APK library?)",
                 info.dli_fname);
        return CH38_UNKNOWN;
    }

    unsigned long sum = 0;
    unsigned long bytes = 0;
    unsigned char buf[4096];
    size_t n;
    while ((n = fread(buf, 1, sizeof(buf), f)) > 0) {
        for (size_t i = 0; i < n; i++) {
            sum = (sum * 31u + buf[i]) & 0xffffffffu;
        }
        bytes += (unsigned long)n;
    }
    fclose(f);

    snprintf(ev, evlen, "%s: %lu bytes, checksum 0x%08lx (reported, not compared)",
             info.dli_fname, bytes, sum);
    return CH38_UNKNOWN;
#else
    (void)evlen;
    snprintf(ev, 32, "not a Linux host");
    return CH38_UNKNOWN;
#endif
}

/* --------------------------------------------------------------------------
 * N6 - timing
 *
 * Instrumentation costs time. A hooked function is a jump into a trampoline,
 * into an interpreter, and back. Measuring how long our own checks took and
 * comparing against a threshold is the cheapest anti-hook signal there is.
 *
 * It is also the most false-positive-prone thing in the file, and any honest
 * treatment has to say so: a cold-start app on a loaded phone, a big GC pause,
 * or a low-end device at minimum CPU frequency will blow past any threshold you
 * pick. Ship this as a signal you LOG, never as one you act on.
 * -------------------------------------------------------------------------- */

static ch38_verdict check_timing(long elapsed_us, char *ev, size_t evlen)
{
    const long THRESHOLD_US = 250000; /* 250 ms - deliberately generous */
    snprintf(ev, evlen, "checks took %ld us (threshold %ld us) - LOG THIS, "
                        "DO NOT ACT ON IT", elapsed_us, THRESHOLD_US);
    return (elapsed_us > THRESHOLD_US) ? CH38_FAIL : CH38_PASS;
}

/* --------------------------------------------------------------------------
 * The tier below JNI_OnLoad
 *
 * A function marked constructor is placed in .init_array, and the dynamic
 * linker calls everything in .init_array as part of dlopen(), BEFORE dlopen()
 * returns and therefore before System.loadLibrary() returns and therefore
 * before JNI_OnLoad. Watch the log ordering: this line always precedes the
 * JNI_OnLoad line.
 *
 * 17-Libraries owns the linker mechanism and ships its own .init_array lab.
 * What belongs HERE is the security consequence: a check placed in a
 * constructor runs earlier than any Java-level hook can possibly be installed
 * by a script that waits for Java.perform.
 * -------------------------------------------------------------------------- */

__attribute__((constructor))
static void ch38_early(void)
{
    char ev[256];
    ch38_verdict v = check_tracer_pid(ev, sizeof(ev));
    LOGI("E0 .init_array constructor  %-7s | %s", verdict_name(v), ev);
    LOGI("E0 ^ this ran INSIDE dlopen(), before JNI_OnLoad and before any app "
         "Java code. If you are reading this line in logcat but your Frida "
         "script printed nothing yet, you were too late.");
}

/* --------------------------------------------------------------------------
 * JNI_OnLoad
 *
 * Called by ART once, when System.loadLibrary() maps this object. Its return
 * value is the JNI version the library requires; returning JNI_ERR makes
 * loadLibrary throw UnsatisfiedLinkError, which is the most brutal thing a
 * native tamper check can do and is a genuinely bad idea in production because
 * it is indistinguishable from a packaging bug.
 * -------------------------------------------------------------------------- */

static long now_us(void)
{
    struct timespec ts;
#if defined(CLOCK_MONOTONIC)
    if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
        return (long)ts.tv_sec * 1000000L + ts.tv_nsec / 1000L;
    }
#endif
    return 0;
}

void ch38_run_all(void)
{
    char ev[512];
    long t0 = now_us();

    report("N1", "TracerPid",     check_tracer_pid(ev, sizeof(ev)), ev);
    report("N2", "ptrace TRACEME", check_ptrace_traceme(ev, sizeof(ev)), ev);
    report("N3", "maps scan",     check_maps(ev, sizeof(ev)), ev);
    report("N4", "frida port",    check_frida_port(ev, sizeof(ev)), ev);
    report("N5", "self file",     check_self_file(ev, sizeof(ev)), ev);

    long elapsed = now_us() - t0;
    report("N6", "timing",        check_timing(elapsed, ev, sizeof(ev)), ev);
}

#ifdef __ANDROID__
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
{
    (void)reserved;

    LOGI("JNI_OnLoad entered - running native tier before any app Java code");
    ch38_run_all();

    JNIEnv *env = NULL;
    if ((*vm)->GetEnv(vm, (void **)&env, JNI_VERSION_1_6) != JNI_OK) {
        return JNI_ERR;
    }

    /* A production library would return JNI_ERR here on a FAIL verdict. This
     * one does not, deliberately: the labs need the app to keep running so the
     * reader can see the whole report. Failing closed is discussed in README
     * 5.9 and it is the right choice in production for exactly the reasons it
     * is the wrong choice in a lab. */
    return JNI_VERSION_1_6;
}
#else
int main(void)
{
    LOGI("host build - running the checks outside Android");
    ch38_run_all();
    return 0;
}
#endif
