/*
 * timecheck.c -- RDTSC timing anti-debug specimen
 *
 * CS 492/592 Malware Reverse Engineering, Week 7 in-class activity.
 * See ../anti_analysis_activity.md for the exercise this belongs to.
 *
 * This is a teaching specimen, not malware. It does nothing to the host: the
 * "payload" is an XOR-decoded string printed to stdout. What is faithful is
 * the SHAPE of the check -- two RDTSC reads bracketing a short operation, a
 * threshold comparison, and a silent benign-looking exit when the threshold
 * is exceeded. That shape is what you will meet in a real sample.
 *
 * The one thing here that no real sample would carry is the TIMECHECK_DEBUG
 * environment variable, which makes the program print its own measurement.
 * It exists so the activity can collect native-timing numbers without a
 * debugger attached. Everything else you learn here transfers; that does not.
 *
 * Build:  make
 * Run:    ./timecheck
 */

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

/*
 * The threshold, in CPU cycles. The guarded operation below costs a few
 * hundred cycles on any machine built this decade, so a normal run clears
 * this by a wide margin. A debugger that merely *runs* the program does not
 * trip it either -- what trips it is an analyst stopping inside the window,
 * which costs wall-clock seconds and therefore billions of cycles.
 *
 * Real samples use much tighter thresholds, often in the low thousands. This
 * one is deliberately loose so the activity's measurement step has a clean
 * margin to look at on any classroom machine.
 */
#define THRESHOLD 50000ULL

/*
 * always_inline overrides the -fno-inline in the Makefile for this function
 * only. The point is that both RDTSC instructions end up inside guarded(),
 * where the disassembly shows the pair and the subtraction between them --
 * which is what the pattern looks like in compiled malware. The rest of the
 * program keeps its function boundaries so there is something to break on.
 */
static inline __attribute__((always_inline)) uint64_t ticks(void)
{
	uint32_t lo, hi;

	/*
	 * RDTSC puts the 64-bit timestamp counter in EDX:EAX. It is not a
	 * serializing instruction, so the surrounding instructions can be
	 * reordered around it; RDTSCP (and CPUID+RDTSC before it) exists to
	 * close that gap. Malware authors mostly do not care, because they
	 * are looking for a difference of seconds, not of cycles.
	 */
	__asm__ __volatile__("rdtsc" : "=a"(lo), "=d"(hi));

	return ((uint64_t)hi << 32) | lo;
}

/*
 * The decoy. A sample that exits loudly when it detects analysis has told you
 * it detected analysis. This one reports a plausible, boring failure and
 * exits 0, which is what makes timing checks expensive to notice.
 */
static void evade(void)
{
	puts("timecheck: no configuration found, nothing to do");
}

/*
 * The payload. The string exists in cleartext only after this runs and only
 * in this process's memory -- the on-disk binary contains the XOR'd bytes.
 * That is the whole reason the check is worth bypassing rather than stepping
 * around: you want the program to reach this code with you watching.
 */
static void payload(void)
{
	static const unsigned char enc[] =
		"\x39\x68\x74\x3c\x36\x35\x2d\x77\x6d\x74\x2e\x33\x37\x3f\x39\x32"
		"\x3f\x39\x31\x74\x33\x34\x2c\x3b\x36\x33\x3e\x60\x62\x6e\x6e\x69";
	char out[sizeof(enc)];
	size_t i;

	for (i = 0; i < sizeof(enc) - 1; i++)
		out[i] = (char)(enc[i] ^ 0x5a);
	out[sizeof(enc) - 1] = '\0';

	printf("timecheck: stage 2 target is %s\n", out);
}

/*
 * The check itself. Returns 1 if the environment looks clean, 0 if it looks
 * like someone is watching.
 */
static int environment_is_clean(void)
{
	uint64_t t0, t1, delta;
	volatile uint32_t acc = 0;
	int i;

	t0 = ticks();

	/* Something short and real, so the compiler cannot delete the window. */
	for (i = 0; i < 64; i++)
		acc += (uint32_t)(i * i);

	t1 = ticks();
	(void)acc;

	delta = t1 - t0;

	if (getenv("TIMECHECK_DEBUG") != NULL)
		fprintf(stderr,
			"[debug] t0=%llu t1=%llu delta=%llu threshold=%llu\n",
			(unsigned long long)t0, (unsigned long long)t1,
			(unsigned long long)delta,
			(unsigned long long)THRESHOLD);

	if (delta > THRESHOLD)
		return 0;

	return 1;
}

int main(void)
{
	if (!environment_is_clean()) {
		evade();
		return 0;
	}

	payload();
	return 0;
}
