abuild-sudo.c 2.14 KB
Newer Older
1 2 3 4 5 6 7 8 9
/* abuild-sudo.c - limited root privileges for users in "abuild" group
 *
 * Copyright (C) 2012 Natanael Copa <ncopa@alpinelinux.org>
 * All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation. See http://www.gnu.org/ for details.
 */
Natanael Copa's avatar
Natanael Copa committed
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

#include <sys/types.h>

#include <err.h>
#include <grp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#ifndef ABUILD_GROUP
#define ABUILD_GROUP "abuild"
#endif

static const char* valid_cmds[] = {
	"/bin/adduser",
26
	"/usr/sbin/adduser",
Natanael Copa's avatar
Natanael Copa committed
27
	"/bin/addgroup",
28
	"/usr/sbin/addgroup",
Natanael Copa's avatar
Natanael Copa committed
29 30 31 32 33 34 35 36 37
	"/sbin/apk",
	NULL
};

const char *get_command_path(const char *cmd)
{
	const char *p;
	int i;
	for (i = 0; valid_cmds[i] != NULL; i++) {
38 39
		if (access(valid_cmds[i], F_OK) == -1)
			continue;
Natanael Copa's avatar
Natanael Copa committed
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
		p = strrchr(valid_cmds[i], '/') + 1;
		if (strcmp(p, cmd) == 0)
			return valid_cmds[i];
	}
	return NULL;
}

int is_in_group(gid_t group)
{
	int ngroups_max = sysconf(_SC_NGROUPS_MAX) + 1;
	gid_t *buf = malloc(ngroups_max * sizeof(gid_t));
	int ngroups, ret = 0;
	int i;
	if (buf == NULL) {
		perror("malloc");
		return 0;
	}
	ngroups = getgroups(ngroups_max, buf);
	for (i = 0; i < ngroups; i++) {
		if (buf[i] == group)
			break;
	}
	free(buf);
	return i < ngroups;
}

int main(int argc, const char *argv[])
{
	struct group *grent;
	const char *cmd;
	const char *path;
71
	int i;
Natanael Copa's avatar
Natanael Copa committed
72 73 74 75 76 77 78 79 80

	grent = getgrnam(ABUILD_GROUP);
	if (grent == NULL)
		errx(1, "%s: Group not found", ABUILD_GROUP);

	if (!is_in_group(grent->gr_gid))
		errx(1, "Not a member of group %s\n", ABUILD_GROUP);

	cmd = strrchr(argv[0], '-');
81
	if (cmd == NULL)
Natanael Copa's avatar
Natanael Copa committed
82 83 84 85 86 87 88
		errx(1, "Calling command has no '-'");
	cmd++;

	path = get_command_path(cmd);
	if (path == NULL)
		errx(1, "%s: Not a valid subcommand", cmd);

89 90 91 92 93
	/* we dont allow --allow-untrusted option */
	for (i = 1; i < argc; i++)
		if (strcmp(argv[i], "--allow-untrusted") == 0)
			errx(1, "%s: not allowed option", "--allow-untrusted");

Natanael Copa's avatar
Natanael Copa committed
94
	argv[0] = path;
95
	/* set our uid to root so bbsuid --install works */
Natanael Copa's avatar
Natanael Copa committed
96 97
	setuid(0);
	execv(path, (char * const*)argv);
98
	perror(path);
Natanael Copa's avatar
Natanael Copa committed
99 100
	return 1;
}