summaryrefslogtreecommitdiffstats
path: root/knock-knock-token.c
blob: 617202ff2555420e4c602989e24efc9c258b6037 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
 * Knock-Knock Token
 * by zx2c4
 * Jason@zx2c4.com
 *
 * Someone about to steal your laptop and you have sensitive things open on it?
 * With Knock-Knock Token, you specify a block device that belongs to removable
 * storage such as a USB flash drive. When the flash drive is removed from the
 * USB port, and the block device disappears as a consequence, your computer
 * immediately turns off. So, as the thief is snatching your laptop from you,
 * simply snatch the USB key, and your data is saved. The program automatically
 * daemonizes.
 *
 * $ sudo ./knock-knock-token /dev/sdc1
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/inotify.h>
#include <sys/reboot.h>

int main(int argc, char *argv[])
{
	int inotify, device_monitor;
	struct stat file_info;

	if (argc < 2) {
		fprintf(stderr, "Usage: %s BLOCK_DEVICE\n", argv[0]);
		return EXIT_FAILURE;
	}

	if (getuid()) {
		fprintf(stderr, "You must be root to run this program.\n");
		return EXIT_FAILURE;
	}

	if (stat(argv[1], &file_info) < 0) {
		perror("stat");
		return EXIT_FAILURE;
	}
	if (!S_ISBLK(file_info.st_mode))
		fprintf(stderr, "Warning: %s is not a block device. Are you sure you meant to monitor it?\n", argv[1]);

	inotify = inotify_init();
	if (inotify < 0) {
		perror("inotify_init");
		return EXIT_FAILURE;
	}
	device_monitor = inotify_add_watch(inotify, argv[1], IN_DELETE_SELF);
	if (device_monitor < 0) {
		perror("inotify_add_watch");
		return EXIT_FAILURE;
	}

	fprintf(stderr, "Daemonizing...\n");
	if (daemon(0, 0) < 0)
		perror("daemon");

	device_monitor = read(inotify, NULL, 0);

	//TODO: securely wipe memory

	sync();
	reboot(RB_ENABLE_CAD);
	reboot(RB_POWER_OFF);
	reboot(RB_HALT_SYSTEM);
	
	return EXIT_SUCCESS;
}