projects/aports·blob v3.4.0_rc4 · refs

121 lines · 2.6 KiB

1/* abuild-sudo.c - limited root privileges for users in "abuild" group
2 *
3 * Copyright (C) 2012 Natanael Copa <[email protected]>
4 * All rights reserved.
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 as published
8 * by the Free Software Foundation. See http://www.gnu.org/ for details.
9 */
10
11#include <sys/types.h>
12
13#include <err.h>
14#include <grp.h>
15#include <pwd.h>
16#include <stdio.h>
17#include <stdlib.h>
18#include <string.h>
19#include <unistd.h>
20
21#ifndef ABUILD_GROUP
22#define ABUILD_GROUP "abuild"
23#endif
24
25static const char* valid_cmds[] = {
26 "/bin/adduser",
27 "/usr/sbin/adduser",
28 "/bin/addgroup",
29 "/usr/sbin/addgroup",
30 "/sbin/apk",
31 "/usr/bin/abuild-rmtemp",
32 NULL
33};
34
35const char *get_command_path(const char *cmd)
36{
37 const char *p;
38 int i;
39 for (i = 0; valid_cmds[i] != NULL; i++) {
40 if (access(valid_cmds[i], F_OK) == -1)
41 continue;
42 p = strrchr(valid_cmds[i], '/') + 1;
43 if (strcmp(p, cmd) == 0)
44 return valid_cmds[i];
45 }
46 return NULL;
47}
48
49int is_in_group(gid_t group)
50{
51 int ngroups_max = sysconf(_SC_NGROUPS_MAX) + 1;
52 gid_t *buf = malloc(ngroups_max * sizeof(gid_t));
53 int ngroups;
54 int i;
55 if (buf == NULL) {
56 perror("malloc");
57 return 0;
58 }
59 ngroups = getgroups(ngroups_max, buf);
60 for (i = 0; i < ngroups; i++) {
61 if (buf[i] == group)
62 break;
63 }
64 free(buf);
65 return i < ngroups;
66}
67
68int main(int argc, const char *argv[])
69{
70 struct group *grent;
71 const char *cmd;
72 const char *path;
73 int i;
74 struct passwd *pw;
75
76 grent = getgrnam(ABUILD_GROUP);
77 if (grent == NULL)
78 errx(1, "%s: Group not found", ABUILD_GROUP);
79
80 char *name = NULL;
81 pw = getpwuid(getuid());
82 if (pw)
83 name = pw->pw_name;
84
85 if (!is_in_group(grent->gr_gid)) {
86 errx(1, "User %s is not a member of group %s\n",
87 name ? name : "(unknown)", ABUILD_GROUP);
88 }
89
90 if (name == NULL)
91 warnx("Could not find username for uid %d\n", getuid());
92 setenv("USER", name ?: "", 1);
93
94 cmd = strrchr(argv[0], '/');
95 if (cmd)
96 cmd++;
97 else
98 cmd = argv[0];
99 cmd = strchr(cmd, '-');
100 if (cmd == NULL)
101 errx(1, "Calling command has no '-'");
102 cmd++;
103
104 path = get_command_path(cmd);
105 if (path == NULL)
106 errx(1, "%s: Not a valid subcommand", cmd);
107
108 /* we dont allow --allow-untrusted option */
109 for (i = 1; i < argc; i++)
110 if (strcmp(argv[i], "--allow-untrusted") == 0)
111 errx(1, "%s: not allowed option", "--allow-untrusted");
112
113 argv[0] = path;
114 /* set our uid to root so bbsuid --install works */
115 setuid(0);
116 /* set our gid to root so apk commit hooks run with the same gid as for "sudo apk add ..." */
117 setgid(0);
118 execv(path, (char * const*)argv);
119 perror(path);
120 return 1;
121}