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
|
// SPDX-License-Identifier: MIT
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <libHX/defs.h>
#include <libHX/option.h>
#include <libHX/proc.h>
#include "internal.h"
#if defined(HAVE_INITGROUPS)
static const struct HXoption options_table[] = {
{.sh = 'u', .type = HXTYPE_STRING},
{.sh = 'g', .type = HXTYPE_STRING},
HXOPT_TABLEEND,
};
static int runner(int argc, char **argv)
{
char *user_name = nullptr, *group_name = nullptr;
struct HXopt6_result result;
if (HX_getopt6(options_table, argc, argv, &result,
HXOPT_USAGEONERR | HXOPT_ITER_OPTS) != HXOPT_ERR_SUCCESS)
return EXIT_FAILURE;
for (int i = 0; i < result.nopts; ++i) {
if (result.desc[i]->sh == 'u') user_name = result.oarg[i];
if (result.desc[i]->sh == 'g') group_name = result.oarg[i];
}
const char *user = user_name != NULL ? user_name : "-";
const char *group = group_name != NULL ? group_name : "-";
switch (HXproc_switch_user(user_name, group_name)) {
case HXPROC_USER_NOT_FOUND:
if (user_name == NULL)
return EXIT_FAILURE; /* impossible outcomes */
printf("No such user \"%s\": %s\n", user_name, strerror(errno));
break;
case HXPROC_GROUP_NOT_FOUND:
if (group_name == NULL || *group_name == '\0')
return EXIT_FAILURE; /* impossible outcome */
printf("No such group \"%s\": %s\n", group_name, strerror(errno));
break;
case HXPROC_SETUID_FAILED:
printf("setuid %s: %s\n", user, strerror(errno));
break;
case HXPROC_SETGID_FAILED:
printf("setgid %s: %s\n", group, strerror(errno));
break;
case HXPROC_INITGROUPS_FAILED:
printf("initgroups for %s: %s\n", user, strerror(errno));
break;
case HXPROC_SU_NOOP:
printf("No action was performed./User identity already reached.\n");
/* fallthrough */
case HXPROC_SU_SUCCESS: {
gid_t list[64] = {-1};
int numgroups = getgroups(ARRAY_SIZE(list), list);
printf("Identity now: uid %lu euid %lu gid %lu egid %lu\n",
static_cast(unsigned long, getuid()),
static_cast(unsigned long, geteuid()),
static_cast(unsigned long, getgid()),
static_cast(unsigned long, getegid()));
printf("Secondary groups:");
for (int i = 0; i < numgroups; ++i)
printf(" %lu", static_cast(unsigned long, list[i]));
printf("\n");
break;
}
}
HX_getopt6_clean(&result);
return EXIT_SUCCESS;
}
int main(int argc, char **argv)
{
int ret = runner(argc, argv);
if (ret != EXIT_SUCCESS)
fprintf(stderr, "FAILED\n");
return ret;
}
#else
int main(void)
{
return EXIT_SUCCESS;
}
#endif
|