]> git.saurik.com Git - apple/xnu.git/blob - tools/tests/darwintests/drop_priv.c
7bb499c530c4568a2b3e898badd650c073d9c837
[apple/xnu.git] / tools / tests / darwintests / drop_priv.c
1 #include <darwintest.h>
2
3 #include <TargetConditionals.h>
4 #include <limits.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <sys/errno.h>
9 #include <unistd.h>
10
11 #if !TARGET_OS_OSX
12 #include <pwd.h>
13 #include <sys/types.h>
14 #include <uuid/uuid.h>
15 #endif
16
17 #if TARGET_OS_OSX
18 #define INVOKER_UID "SUDO_UID"
19 #define INVOKER_GID "SUDO_GID"
20 #define ID_MAX (unsigned long)UINT_MAX
21 static unsigned
22 _get_sudo_invoker(const char *var)
23 {
24 char *value_str = getenv(var);
25 T_QUIET; T_WITH_ERRNO; T_ASSERT_NOTNULL(value_str,
26 "Not running under sudo, getenv(\"%s\") failed", var);
27 T_QUIET; T_ASSERT_NE_CHAR(*value_str, '\0',
28 "getenv(\"%s\") returned an empty string", var);
29
30 char *endp;
31 unsigned long value = strtoul(value_str, &endp, 10);
32 T_QUIET; T_WITH_ERRNO; T_ASSERT_EQ_CHAR(*endp, '\0',
33 "strtoul(\"%s\") not called on a valid number", value_str);
34 T_QUIET; T_WITH_ERRNO; T_ASSERT_NE_ULONG(value, ULONG_MAX,
35 "strtoul(\"%s\") overflow", value_str);
36
37 T_QUIET; T_ASSERT_NE_ULONG(value, 0ul, "%s invalid", var);
38 T_QUIET; T_ASSERT_LT_ULONG(value, ID_MAX, "%s invalid", var);
39 return (unsigned)value;
40 }
41 #endif /* TARGET_OS_OSX */
42
43 void
44 drop_priv(void);
45 void
46 drop_priv(void)
47 {
48 #if TARGET_OS_OSX
49 uid_t lower_uid = _get_sudo_invoker(INVOKER_UID);
50 gid_t lower_gid = _get_sudo_invoker(INVOKER_GID);
51 #else
52 struct passwd *pw = getpwnam("mobile");
53 T_QUIET; T_WITH_ERRNO; T_ASSERT_NOTNULL(pw, "getpwnam(\"mobile\")");
54 uid_t lower_uid = pw->pw_uid;
55 gid_t lower_gid = pw->pw_gid;
56 #endif
57 T_ASSERT_POSIX_SUCCESS(setgid(lower_gid), "Change group to %u", lower_gid);
58 T_ASSERT_POSIX_SUCCESS(setuid(lower_uid), "Change user to %u", lower_uid);
59 }