File: candy.c

package info (click to toggle)
ccstools 1.7.2-20100401-3
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 984 kB
  • ctags: 1,080
  • sloc: ansic: 20,286; sh: 890; makefile: 80
file content (80 lines) | stat: -rw-r--r-- 1,720 bytes parent folder | download
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
72
73
74
75
76
77
78
79
80
/*
 * candy.c
 *
 * An example program for CERBERUS.
 * ( http://sourceforge.jp/projects/tomoyo/document/winf2005-en.pdf )
 *
 * Copyright (C) 2005-2009  NTT DATA CORPORATION
 *
 * Version: 1.7.0   2009/09/03
 */
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <pwd.h>

static const char *get_shell(void)
{
	static char *shell = NULL;
	if (!shell) {
		struct passwd *pw = getpwuid(getuid());
		shell = pw ? pw->pw_shell : "/bin/sh";
	}
	return shell;
}

static int get_start_time(pid_t pid, unsigned long long *t)
{
	FILE *fp;
	int i;
	char *cp;
	char buffer[1024];
	memset(buffer, 0, sizeof(buffer));
	snprintf(buffer, sizeof(buffer) - 1, "/proc/%d/stat", pid);
	fp = fopen(buffer, "r");
	if (!fp)
		return EOF;
	fgets(buffer, sizeof(buffer) - 1, fp);
	fclose(fp);
	for (i = 0; i < 21; i++) {
		cp = strchr(buffer, ' ');
		if (!cp)
			return EOF;
		memmove(buffer, cp + 1, strlen(cp + 1) + 1);
	}
	cp = strchr(buffer, ' ');
	if (!cp)
		return EOF;
	*cp = '\0';
	if (sscanf(buffer, "%llu", t) != 1)
		return EOF;
	return 0;
}

int main(int argc, char *argv[])
{
	static char buffer[1024];
	static const char *passwd = "CERBERUS\n";
	int trial;
	const char *shell = get_shell();
	for (trial = 0; trial < 3; trial++) {
		memset(buffer, 0, sizeof(buffer));
		printf("Password: ");
		fgets(buffer, sizeof(buffer) - 1, stdin);
		if (shell && !strcmp(buffer, passwd)) {
			unsigned long long t0;
			unsigned long long t1;
			if (get_start_time(getppid(), &t0) == 0 &&
			    get_start_time(getpid(), &t1) == 0) {
				/* 10 sec */
				if ((t1 - t0) < 1000)
					execlp(shell, shell, NULL);
			}
		}
		sleep(3);
	}
	printf("Authentication Failure\n");
	return 0;
}