]>
git.saurik.com Git - apple/xnu.git/blob - tools/tests/darwintests/drop_priv.c
7bb499c530c4568a2b3e898badd650c073d9c837
1 #include <darwintest.h>
3 #include <TargetConditionals.h>
13 #include <sys/types.h>
14 #include <uuid/uuid.h>
18 #define INVOKER_UID "SUDO_UID"
19 #define INVOKER_GID "SUDO_GID"
20 #define ID_MAX (unsigned long)UINT_MAX
22 _get_sudo_invoker(const char *var
)
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
);
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
);
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
;
41 #endif /* TARGET_OS_OSX */
49 uid_t lower_uid
= _get_sudo_invoker(INVOKER_UID
);
50 gid_t lower_gid
= _get_sudo_invoker(INVOKER_GID
);
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
;
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
);