summaryrefslogtreecommitdiff
path: root/check/check.c
blob: 38a016470ce5ec3802ded14d58775d2d0aae3ca1 (plain)
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#define _XOPEN_SOURCE 700
#include <errno.h>
#include <grp.h>
#include <locale.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <pwd.h>
#include <unistd.h>

#include "check.h"

static char *progname = NULL;

void fatal(int include_errno, char *fmt, ...)
{
	fprintf(stderr, "%s: ", progname);
	va_list ap;
	va_start(ap, fmt);
	vfprintf(stderr, fmt, ap);
	va_end(ap);
	if (include_errno) {
		fprintf(stderr, ": %s", strerror(errno));
	}
	fputc('\n', stderr);
	exit(EXIT_FAILURE);
}

static char *get_username(void)
{
	struct passwd *pwd = getpwuid(getuid());
	if (pwd == NULL) {
		fatal(1, "unable to determine user name");
	}
	return pwd->pw_name;
}

static char *get_groupname(void)
{
	struct group *grp = getgrgid(getgid());
	if (grp == NULL) {
		fatal(1, "unable to determine group name");
	}
	return grp->gr_name;
}

static char *get_command(int argc, char *argv[])
{
	if (argc < 2) {
		fatal(1, "missing operands");
	}

	return argv[1];
}

int main(int argc, char *argv[])
{
	setlocale(LC_ALL, "");
	progname = argv[0];

	char *cmd = get_command(argc, argv);
	char *user = get_username();
	char *group = get_groupname();

	openlog(PRIVEXEC_LOG_ID, LOG_PID, LOG_AUTH);
	syslog(LOG_INFO, "checking %s:%s for permission to run %s",
		user, group, cmd);

	switch (get_permission(user, group, cmd)) {
	case AUTHENTICATE:
		syslog(LOG_INFO, "%s:%s requires authentication to run %s",
			user, group, cmd);
		if (authenticate(user) != 0) {
			syslog(LOG_NOTICE, "%s:%s failed authentication for %s",
				user, group, cmd);
			fatal(0, "bad authentication");
		}
		/* FALLTHRU */
	case AUTHORIZED:
		syslog(LOG_INFO, "%s:%s authorized to run %s",
			user, group, cmd);
		return 0;

	case DENIED:
		syslog(LOG_NOTICE,
			"%s:%s explicitly denied permission to run %s",
			user, group, cmd);
		fatal(0, "explicitly denied");
		return 1;
	
	case UNKNOWN:
	default:
		syslog(LOG_NOTICE,
			"%s:%s denied permission to run %s by default",
			user, group, cmd);
		fatal(0, "denied by default");
	}

	return 1;
}