/* * Copyright (C) 2026 SlopRoot Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "su.h" /* * The NDK headers route FD_SET and FD_ISSET through bionic fortify checks * that Android 2.2 does not export. Define the plain bit operations. */ #define SLOPROOT_FD_BITS(set) ((set)->fds_bits) #define SLOPROOT_FD_INDEX(fd) ((fd) / (int)(8 * sizeof(fd_mask))) #define SLOPROOT_FD_MASK(fd) ((fd_mask)1 << ((fd) % (int)(8 * sizeof(fd_mask)))) #undef FD_SET #undef FD_ISSET #undef FD_ZERO #define FD_SET(fd, set) (SLOPROOT_FD_BITS(set)[SLOPROOT_FD_INDEX(fd)] |= SLOPROOT_FD_MASK(fd)) #define FD_ISSET(fd, set) ((SLOPROOT_FD_BITS(set)[SLOPROOT_FD_INDEX(fd)] & SLOPROOT_FD_MASK(fd)) != 0) #define FD_ZERO(set) (memset((set), 0, sizeof(fd_set))) /* * Preserve caller environment for already-authorized root shells while * strictly sanitizing the environment passed to root-launched /system/bin/am * during interactive authorization prompts. */ static char **caller_envp = NULL; static char merged_path[512]; static char trusted_bootclasspath_env[2048]; static char trusted_ld_library_path_env[512]; static int env_has_prefix(const char *entry, const char *prefix) { while (*prefix) { if (*entry != *prefix) return 0; entry++; prefix++; } return 1; } static int is_safe_path_char(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '/' || c == '.' || c == '_' || c == '-'; } static int is_safe_colon_path_list(const char *val, const char *prefix1, const char *prefix2) { if (!val || val[0] == '\0') return 0; const char *p = val; while (*p) { const char *seg_start = p; while (*p && *p != ':') { if (!is_safe_path_char(*p)) return 0; p++; } size_t seg_len = (size_t)(p - seg_start); if (seg_len == 0) return 0; int ok_prefix = 0; if (prefix1) { size_t p1 = strlen(prefix1); if (seg_len >= p1 && strncmp(seg_start, prefix1, p1) == 0) ok_prefix = 1; } if (!ok_prefix && prefix2) { size_t p2 = strlen(prefix2); if (seg_len >= p2 && strncmp(seg_start, prefix2, p2) == 0) ok_prefix = 1; } if (!ok_prefix) return 0; /* Reject any ".." path traversal component */ for (size_t i = 0; i + 1 < seg_len; i++) { if (seg_start[i] == '.' && seg_start[i + 1] == '.') { return 0; } } if (*p == ':') { p++; if (*p == '\0') return 0; } } return 1; } static int read_init_export_from_file(const char *rc_path, const char *var_name, char *out, size_t out_len) { int fd = open(rc_path, O_RDONLY | O_NOFOLLOW); if (fd < 0) return -1; struct stat st; if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode) || st.st_uid != 0 || (st.st_mode & 0022) != 0) { close(fd); return -1; } char line[2048]; size_t line_len = 0; int line_overflow = 0; char chunk[512]; size_t var_len = strlen(var_name); int found = -1; for (;;) { ssize_t r = read(fd, chunk, sizeof(chunk)); if (r < 0) { if (errno == EINTR) continue; break; } if (r == 0) { /* Flush final line without trailing newline */ if (line_len > 0 && !line_overflow) { line[line_len] = '\0'; const char *p = line; while (*p == ' ' || *p == '\t') p++; if (strncmp(p, "export", 6) == 0 && (p[6] == ' ' || p[6] == '\t')) { p += 6; while (*p == ' ' || *p == '\t') p++; if (strncmp(p, var_name, var_len) == 0 && (p[var_len] == ' ' || p[var_len] == '\t')) { p += var_len; while (*p == ' ' || *p == '\t') p++; size_t vlen = strlen(p); while (vlen > 0 && (p[vlen - 1] == '\r' || p[vlen - 1] == ' ' || p[vlen - 1] == '\t')) { vlen--; } if (vlen > 0 && vlen < out_len) { memcpy(out, p, vlen); out[vlen] = '\0'; found = 0; } } } } break; } for (ssize_t i = 0; i < r; i++) { char c = chunk[i]; if (c == '\n') { if (!line_overflow) { line[line_len] = '\0'; const char *p = line; while (*p == ' ' || *p == '\t') p++; if (strncmp(p, "export", 6) == 0 && (p[6] == ' ' || p[6] == '\t')) { p += 6; while (*p == ' ' || *p == '\t') p++; if (strncmp(p, var_name, var_len) == 0 && (p[var_len] == ' ' || p[var_len] == '\t')) { p += var_len; while (*p == ' ' || *p == '\t') p++; size_t vlen = strlen(p); while (vlen > 0 && (p[vlen - 1] == '\r' || p[vlen - 1] == ' ' || p[vlen - 1] == '\t')) { vlen--; } if (vlen > 0 && vlen < out_len) { memcpy(out, p, vlen); out[vlen] = '\0'; found = 0; } } } } line_len = 0; line_overflow = 0; if (found == 0) break; } else if (!line_overflow) { if (line_len + 1 < sizeof(line)) { line[line_len++] = c; } else { line_overflow = 1; } } } if (found == 0) break; } close(fd); return found; } static int load_trusted_bootclasspath(char *out, size_t out_len) { char val[1920]; const char *rc_paths[] = { "/init.environ.rc", "/init.rc", NULL }; for (int i = 0; rc_paths[i] != NULL; i++) { if (read_init_export_from_file(rc_paths[i], "BOOTCLASSPATH", val, sizeof(val)) == 0 && is_safe_colon_path_list(val, "/system/framework/", "/apex/")) { int n = snprintf(out, out_len, "BOOTCLASSPATH=%s", val); if (n > 0 && (size_t)n < out_len) return 0; } } /* Fallback: assemble from root-owned standard AOSP framework jars present on disk */ static const char *fallback_jars[] = { "/system/framework/core-libart.jar", "/system/framework/core.jar", "/system/framework/conscrypt.jar", "/system/framework/okhttp.jar", "/system/framework/core-junit.jar", "/system/framework/bouncycastle.jar", "/system/framework/ext.jar", "/system/framework/framework.jar", "/system/framework/framework2.jar", "/system/framework/android.policy.jar", "/system/framework/services.jar", "/system/framework/apache-xml.jar", NULL }; size_t pos = (size_t)snprintf(out, out_len, "BOOTCLASSPATH="); int count = 0; for (int i = 0; fallback_jars[i] != NULL; i++) { struct stat st; if (lstat(fallback_jars[i], &st) == 0 && S_ISREG(st.st_mode) && st.st_uid == 0 && (st.st_mode & 0022) == 0) { size_t jlen = strlen(fallback_jars[i]); if (pos + (count > 0 ? 1 : 0) + jlen + 1 >= out_len) break; if (count > 0) out[pos++] = ':'; memcpy(out + pos, fallback_jars[i], jlen); pos += jlen; out[pos] = '\0'; count++; } } return count > 0 ? 0 : -1; } static int load_trusted_ld_library_path(char *out, size_t out_len) { char val[384]; const char *rc_paths[] = { "/init.environ.rc", "/init.rc", NULL }; for (int i = 0; rc_paths[i] != NULL; i++) { if (read_init_export_from_file(rc_paths[i], "LD_LIBRARY_PATH", val, sizeof(val)) == 0 && is_safe_colon_path_list(val, "/vendor/lib", "/system/lib")) { int n = snprintf(out, out_len, "LD_LIBRARY_PATH=%s", val); if (n > 0 && (size_t)n < out_len) return 0; } } return -1; } static int is_safe_locale_or_tz(const char *val) { if (!val || val[0] == '\0' || val[0] == '-') return 0; size_t len = 0; for (const char *p = val; *p; p++) { char c = *p; if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '_' || c == '-' || c == '+' || c == ':' || c == '/')) { return 0; } if (c == '.' && p[1] == '.') return 0; if (++len > 64) return 0; } return 1; } static int is_safe_property_workspace(const char *val, int caller_is_root) { if (!val || val[0] == '\0') return 0; const char *p = val; long fd_num = 0; int fd_digits = 0; while (*p >= '0' && *p <= '9') { fd_num = fd_num * 10 + (*p - '0'); if (++fd_digits > 4 || fd_num > 1023) return 0; p++; } if (fd_digits == 0 || *p != ',') return 0; p++; long size_num = 0; int size_digits = 0; while (*p >= '0' && *p <= '9') { size_num = size_num * 10 + (*p - '0'); if (++size_digits > 7 || size_num > 1048576) return 0; p++; } if (size_digits == 0 || *p != '\0') return 0; if (fd_num < 3 || size_num < 4096) return 0; if (caller_is_root) return 1; /* For untrusted callers, only permit an unlinked root-owned read-only regular file fd. */ struct stat st; if (fstat((int)fd_num, &st) != 0) return 0; if (!S_ISREG(st.st_mode) || st.st_uid != 0 || st.st_nlink != 0 || (st.st_mode & 0022) != 0) { return 0; } int flags = fcntl((int)fd_num, F_GETFL, 0); if (flags < 0 || (flags & O_ACCMODE) != O_RDONLY) return 0; return 1; } static char **build_am_env(char **buf, size_t max_entries, int caller_is_root) { size_t n = 0; int has_tz = 0; int has_lang = 0; int has_lc_all = 0; int has_lc_ctype = 0; int has_prop_ws = 0; if (n + 1 < max_entries) buf[n++] = "PATH=/system/bin:/system/xbin:/sbin:/vendor/bin"; if (n + 1 < max_entries) buf[n++] = "HOME=/"; if (n + 1 < max_entries) buf[n++] = "ANDROID_ROOT=/system"; if (n + 1 < max_entries) buf[n++] = "ANDROID_DATA=/data"; if (n + 1 < max_entries) buf[n++] = "ANDROID_ASSETS=/system/app"; if (n + 1 < max_entries) buf[n++] = "ANDROID_STORAGE=/storage"; if (n + 1 < max_entries) buf[n++] = "TERM=dumb"; if (load_trusted_bootclasspath(trusted_bootclasspath_env, sizeof(trusted_bootclasspath_env)) == 0 && n + 1 < max_entries) { buf[n++] = trusted_bootclasspath_env; } if (load_trusted_ld_library_path(trusted_ld_library_path_env, sizeof(trusted_ld_library_path_env)) == 0 && n + 1 < max_entries) { buf[n++] = trusted_ld_library_path_env; } /* Whitelist only strictly validated benign caller variables. Never forward * BOOTCLASSPATH, LD_LIBRARY_PATH, LD_PRELOAD, ENV, BASH_ENV, CLASSPATH, PATH, etc. */ if (caller_envp != NULL) { for (size_t i = 0; caller_envp[i] != NULL && n + 1 < max_entries; i++) { char *entry = caller_envp[i]; if (!has_tz && env_has_prefix(entry, "TZ=") && is_safe_locale_or_tz(entry + 3)) { buf[n++] = entry; has_tz = 1; } else if (!has_lang && env_has_prefix(entry, "LANG=") && is_safe_locale_or_tz(entry + 5)) { buf[n++] = entry; has_lang = 1; } else if (!has_lc_all && env_has_prefix(entry, "LC_ALL=") && is_safe_locale_or_tz(entry + 7)) { buf[n++] = entry; has_lc_all = 1; } else if (!has_lc_ctype && env_has_prefix(entry, "LC_CTYPE=") && is_safe_locale_or_tz(entry + 9)) { buf[n++] = entry; has_lc_ctype = 1; } else if (!has_prop_ws && env_has_prefix(entry, "ANDROID_PROPERTY_WORKSPACE=") && is_safe_property_workspace(entry + 27, caller_is_root)) { buf[n++] = entry; has_prop_ws = 1; } } } buf[n] = NULL; return buf; } static char **build_exec_env(char **buf, size_t max_entries) { size_t n = 0; int has_path = 0; int has_home = 0; int has_android_root = 0; int has_android_data = 0; int has_term = 0; if (caller_envp != NULL) { for (size_t i = 0; caller_envp[i] != NULL && n + 6 < max_entries; i++) { char *entry = caller_envp[i]; if (env_has_prefix(entry, "PATH=")) { if (entry[5] != '\0') { has_path = 1; if (strstr(entry, "/system/bin") != NULL && strstr(entry, "/system/xbin") != NULL) { buf[n++] = entry; } else { snprintf(merged_path, sizeof(merged_path), "PATH=/system/bin:/system/xbin:/sbin:/vendor/bin:%s", entry + 5); buf[n++] = merged_path; } } continue; } if (env_has_prefix(entry, "HOME=")) has_home = 1; else if (env_has_prefix(entry, "ANDROID_ROOT=")) has_android_root = 1; else if (env_has_prefix(entry, "ANDROID_DATA=")) has_android_data = 1; else if (env_has_prefix(entry, "TERM=")) has_term = 1; buf[n++] = entry; } } if (!has_path && n + 1 < max_entries) buf[n++] = "PATH=/system/bin:/system/xbin:/sbin:/vendor/bin"; if (!has_home && n + 1 < max_entries) buf[n++] = "HOME=/"; if (!has_android_root && n + 1 < max_entries) buf[n++] = "ANDROID_ROOT=/system"; if (!has_android_data && n + 1 < max_entries) buf[n++] = "ANDROID_DATA=/data"; if (!has_term && n + 1 < max_entries) buf[n++] = "TERM=dumb"; buf[n] = NULL; return buf; } static int write_exact(int fd, const void *buf, size_t len) { const unsigned char *ptr = (const unsigned char *)buf; size_t sent = 0; while (sent < len) { ssize_t w = write(fd, ptr + sent, len - sent); if (w < 0) { if (errno == EINTR) continue; return -1; } if (w == 0) return -1; sent += (size_t)w; } return 0; } static int write_token(int fd, const char *key, const char *val) { size_t klen_s = strlen(key); uint32_t klen = htonl((uint32_t)klen_s); if (write_exact(fd, &klen, sizeof(klen)) < 0) return -1; if (write_exact(fd, key, klen_s) < 0) return -1; size_t vlen_s = strlen(val); uint32_t vlen = htonl((uint32_t)vlen_s); if (write_exact(fd, &vlen, sizeof(vlen)) < 0) return -1; if (write_exact(fd, val, vlen_s) < 0) return -1; return 0; } static int generate_random_hex(char *out, size_t num_bytes) { static const char hex[] = "0123456789abcdef"; unsigned char raw[32]; if (num_bytes == 0 || num_bytes > sizeof(raw)) return -1; int fd = open("/dev/urandom", O_RDONLY); if (fd < 0) return -1; size_t got = 0; while (got < num_bytes) { ssize_t r = read(fd, raw + got, num_bytes - got); if (r < 0) { if (errno == EINTR) continue; close(fd); return -1; } if (r == 0) { close(fd); return -1; } got += (size_t)r; } close(fd); for (size_t i = 0; i < num_bytes; i++) { out[i * 2] = hex[(raw[i] >> 4) & 0x0f]; out[i * 2 + 1] = hex[raw[i] & 0x0f]; } out[num_bytes * 2] = '\0'; return 0; } static int const_time_eq(const char *a, const char *b) { size_t la = strlen(a); size_t lb = strlen(b); if (la != lb) return 0; unsigned char diff = 0; for (size_t i = 0; i < la; i++) { diff |= (unsigned char)(a[i] ^ b[i]); } return diff == 0; } static void set_cloexec(int fd) { if (fd >= 0) { int flags = fcntl(fd, F_GETFD, 0); if (flags >= 0) { fcntl(fd, F_SETFD, flags | FD_CLOEXEC); } } } static int get_manager_uid(uid_t *out_uid) { int has_pkg_uid = 0; uid_t pkg_uid = 0; int fd = open(PACKAGES_LIST_PATH, O_RDONLY | O_NOFOLLOW); if (fd >= 0) { struct stat st; if (fstat(fd, &st) == 0 && S_ISREG(st.st_mode) && (st.st_uid == 0 || st.st_uid == 1000) && (st.st_gid == 0 || st.st_gid == 1000) && (st.st_mode & 0002) == 0) { char line[512]; size_t line_len = 0; int overflow = 0; char chunk[512]; for (;;) { ssize_t r = read(fd, chunk, sizeof(chunk)); if (r < 0) { if (errno == EINTR) continue; break; } if (r == 0) { if (line_len > 0 && !overflow) { line[line_len] = '\0'; char pkg[128]; unsigned long uid_val = 0; if (sscanf(line, "%127s %lu", pkg, &uid_val) == 2 && strcmp(pkg, MANAGER_PACKAGE) == 0 && uid_val >= 10000UL) { pkg_uid = (uid_t)uid_val; has_pkg_uid = 1; } } break; } for (ssize_t i = 0; i < r; i++) { if (chunk[i] == '\n') { if (!overflow) { line[line_len] = '\0'; char pkg[128]; unsigned long uid_val = 0; if (sscanf(line, "%127s %lu", pkg, &uid_val) == 2 && strcmp(pkg, MANAGER_PACKAGE) == 0 && uid_val >= 10000UL) { pkg_uid = (uid_t)uid_val; has_pkg_uid = 1; } } line_len = 0; overflow = 0; if (has_pkg_uid) break; } else if (!overflow) { if (line_len + 1 < sizeof(line)) { line[line_len++] = chunk[i]; } else { overflow = 1; } } } if (has_pkg_uid) break; } } close(fd); } if (has_pkg_uid) { *out_uid = pkg_uid; return 0; } struct stat dst; if (lstat(MANAGER_DATA_DIR, &dst) == 0) { if (!S_ISDIR(dst.st_mode) || dst.st_uid < 10000 || (dst.st_mode & 0002) != 0) { return -1; } *out_uid = dst.st_uid; return 0; } if (has_pkg_uid && errno == ENOENT) { *out_uid = pkg_uid; return 0; } return -1; } static void get_process_name(pid_t pid, char *buf, size_t buf_len) { char path[64]; snprintf(path, sizeof(path), "/proc/%d/cmdline", (int)pid); int fd = open(path, O_RDONLY); if (fd < 0) { snprintf(buf, buf_len, "unknown"); return; } ssize_t rd = read(fd, buf, buf_len - 1); close(fd); if (rd <= 0) { snprintf(buf, buf_len, "unknown"); return; } buf[rd] = '\0'; } static void set_selinux_context(const char *ctx) { int fd = open("/proc/self/attr/exec", O_WRONLY); if (fd >= 0) { write(fd, ctx, strlen(ctx)); close(fd); } } static int parse_policy_line(const char *line, uid_t uid, time_t now, int *matched_uid, int *action) { if (line[0] == '#' || line[0] == '\n' || line[0] == '\r' || line[0] == '\0') return 0; long f_uid = -1; int f_action = 0; long long f_until = 0; if (sscanf(line, "%ld %d %lld", &f_uid, &f_action, &f_until) >= 2) { if (f_uid >= 0 && (uid_t)f_uid == uid) { *matched_uid = 1; if ((f_action == POLICY_ALLOW || f_action == POLICY_DENY) && (f_until == 0 || f_until > (long long)now)) { *action = f_action; } return 1; } } return 0; } static int check_policy_file(const char *path, uid_t uid, int has_manager_uid, uid_t manager_uid, int is_app_file) { int fd = open(path, O_RDONLY | O_NOFOLLOW); if (fd < 0) return -2; struct stat st; if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode) || (st.st_mode & 0002) != 0) { close(fd); return -2; } if (is_app_file) { if (!has_manager_uid || (st.st_uid != manager_uid && st.st_uid != 0)) { close(fd); return -2; } } else { if (st.st_uid != 0 && st.st_uid != 1000 && (!has_manager_uid || st.st_uid != manager_uid)) { close(fd); return -2; } } char line[256]; size_t line_len = 0; int overflow = 0; char chunk[512]; int action = -1; int matched = 0; time_t now = time(NULL); for (;;) { ssize_t r = read(fd, chunk, sizeof(chunk)); if (r < 0) { if (errno == EINTR) continue; break; } if (r == 0) { if (line_len > 0 && !overflow) { line[line_len] = '\0'; parse_policy_line(line, uid, now, &matched, &action); } break; } for (ssize_t i = 0; i < r; i++) { if (chunk[i] == '\n') { if (!overflow) { line[line_len] = '\0'; if (parse_policy_line(line, uid, now, &matched, &action)) { break; } } line_len = 0; overflow = 0; } else if (!overflow) { if (line_len + 1 < sizeof(line)) { line[line_len++] = chunk[i]; } else { overflow = 1; } } } if (matched) break; } close(fd); return action; } static int check_policy(uid_t uid) { if (uid == 0) return POLICY_ALLOW; uid_t manager_uid = 0; int has_manager_uid = (get_manager_uid(&manager_uid) == 0); /* Prefer SuManager's live policy file when present so revocations take effect immediately. */ int act = check_policy_file(POLICY_PATH_APP, uid, has_manager_uid, manager_uid, 1); if (act >= 0) return act; if (act == -1) return POLICY_INTERACTIVE; act = check_policy_file(POLICY_PATH_SYSTEM, uid, has_manager_uid, manager_uid, 0); if (act >= 0) return act; return POLICY_INTERACTIVE; } static int prompt_manager(const struct su_request *req) { uid_t manager_uid = 0; if (get_manager_uid(&manager_uid) < 0) { return POLICY_DENY; } char sock_id[REQ_TOKEN_HEX_LEN + 1]; char req_token[REQ_TOKEN_HEX_LEN + 1]; if (generate_random_hex(sock_id, REQ_TOKEN_BYTES) < 0 || generate_random_hex(req_token, REQ_TOKEN_BYTES) < 0) { return POLICY_DENY; } char sock_path[108]; snprintf(sock_path, sizeof(sock_path), "%s%s.sock", REQ_SOCKET_PREFIX, sock_id); unlink(sock_path); int sfd = socket(AF_UNIX, SOCK_STREAM, 0); if (sfd < 0) return POLICY_DENY; set_cloexec(sfd); struct sockaddr_un addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, sock_path, sizeof(addr.sun_path) - 1); mode_t old_umask = umask(0077); int bind_res = bind(sfd, (struct sockaddr *)&addr, sizeof(addr)); umask(old_umask); if (bind_res < 0) { close(sfd); return POLICY_DENY; } if (chown(sock_path, manager_uid, manager_uid) != 0 || chmod(sock_path, 0600) != 0) { close(sfd); unlink(sock_path); return POLICY_DENY; } if (listen(sfd, 4) < 0) { close(sfd); unlink(sock_path); return POLICY_DENY; } /* Launch RequestActivity via am start with a strictly sanitized environment */ pid_t am_pid = fork(); if (am_pid == 0) { int caller_is_root = (getuid() == 0); int devnull = open("/dev/null", O_RDWR); if (devnull >= 0) { dup2(devnull, 0); dup2(devnull, 1); dup2(devnull, 2); close(devnull); } close(sfd); setgroups(0, NULL); if (setgid(0) != 0 || setuid(0) != 0) { _exit(126); } char *env_buf[64]; char **exec_env = build_am_env(env_buf, 64, caller_is_root); char *am_argv[] = { "am", "start", "-n", MANAGER_REQUEST_ACTIVITY, "--es", "socket", sock_path, "--es", "token", req_token, (char *)NULL }; execve("/system/bin/am", am_argv, exec_env); /* Android 2.x /system/bin/am has no #! shebang, so fall back to /system/bin/sh. */ char *sh_am_argv[] = { "sh", "/system/bin/am", "start", "-n", MANAGER_REQUEST_ACTIVITY, "--es", "socket", sock_path, "--es", "token", req_token, (char *)NULL }; execve("/system/bin/sh", sh_am_argv, exec_env); _exit(127); } if (am_pid > 0) { waitpid(am_pid, NULL, 0); } /* Wait for verified SuManager peer connection with 20 second deadline */ time_t accept_deadline = time(NULL) + 20; int cfd = -1; while (cfd < 0) { time_t now = time(NULL); if (now >= accept_deadline) break; fd_set fds; FD_ZERO(&fds); FD_SET(sfd, &fds); struct timeval tv; tv.tv_sec = accept_deadline - now; tv.tv_usec = 0; int sel = select(sfd + 1, &fds, NULL, NULL, &tv); if (sel < 0) { if (errno == EINTR) continue; break; } if (sel == 0) break; int candidate = accept(sfd, NULL, NULL); if (candidate < 0) { if (errno == EINTR) continue; break; } struct ucred peer; socklen_t peer_len = sizeof(peer); if (getsockopt(candidate, SOL_SOCKET, SO_PEERCRED, &peer, &peer_len) < 0 || peer_len != sizeof(peer) || peer.uid != manager_uid || peer.pid <= 0) { close(candidate); continue; } /* Reject peers that send unsolicited data (or EOF) before receiving request tokens. */ fd_set peek_fds; FD_ZERO(&peek_fds); FD_SET(candidate, &peek_fds); struct timeval zero_tv; zero_tv.tv_sec = 0; zero_tv.tv_usec = 0; if (select(candidate + 1, &peek_fds, NULL, NULL, &zero_tv) > 0) { close(candidate); continue; } cfd = candidate; } close(sfd); unlink(sock_path); if (cfd < 0) return POLICY_DENY; /* Write request tokens including per-request authorization nonce */ char s_pid[16], s_uid[16], s_to[16]; snprintf(s_pid, sizeof(s_pid), "%d", (int)req->from_pid); snprintf(s_uid, sizeof(s_uid), "%d", (int)req->from_uid); snprintf(s_to, sizeof(s_to), "%d", (int)req->to_uid); if (write_token(cfd, "version", "1") < 0 || write_token(cfd, "binary.version", "1") < 0 || write_token(cfd, "pid", s_pid) < 0 || write_token(cfd, "from.uid", s_uid) < 0 || write_token(cfd, "to.uid", s_to) < 0 || write_token(cfd, "from.name", req->from_name) < 0 || write_token(cfd, "to.name", "root") < 0 || write_token(cfd, "command", req->command) < 0 || write_token(cfd, "token", req_token) < 0 || write_token(cfd, "eof", "1") < 0) { close(cfd); return POLICY_DENY; } /* Read response line with 25 second deadline */ char resp[128]; memset(resp, 0, sizeof(resp)); size_t resp_len = 0; time_t resp_deadline = time(NULL) + 25; while (resp_len + 1 < sizeof(resp)) { time_t now = time(NULL); if (now >= resp_deadline) break; fd_set rfds; FD_ZERO(&rfds); FD_SET(cfd, &rfds); struct timeval tv; tv.tv_sec = resp_deadline - now; tv.tv_usec = 0; int sel = select(cfd + 1, &rfds, NULL, NULL, &tv); if (sel < 0) { if (errno == EINTR) continue; break; } if (sel == 0) break; ssize_t r = read(cfd, resp + resp_len, sizeof(resp) - 1 - resp_len); if (r < 0) { if (errno == EINTR) continue; break; } if (r == 0) break; resp_len += (size_t)r; resp[resp_len] = '\0'; if (strstr(resp, "\n") != NULL) break; } close(cfd); while (resp_len > 0 && (resp[resp_len - 1] == '\n' || resp[resp_len - 1] == '\r')) { resp[--resp_len] = '\0'; } char expected_allow[128]; snprintf(expected_allow, sizeof(expected_allow), "socket:ALLOW:%s", req_token); if (resp_len > 0 && const_time_eq(resp, expected_allow)) { return POLICY_ALLOW; } return POLICY_DENY; } static void execute_shell(const struct su_request *req) { setgroups(0, NULL); if (setgid(req->to_uid) != 0) { perror("su: setgid"); exit(1); } if (setuid(req->to_uid) != 0) { perror("su: setuid"); exit(1); } set_selinux_context("u:r:su:s0"); char *env_buf[128]; char **exec_env = build_exec_env(env_buf, 128); const char *sh = req->shell[0] ? req->shell : "/system/bin/sh"; if (req->command[0]) { char *shell_argv[] = { "sh", "-c", (char *)req->command, (char *)NULL }; execve(sh, shell_argv, exec_env); } else { char *shell_argv[] = { "sh", "-", (char *)NULL }; execve(sh, shell_argv, exec_env); } perror("su: exec"); exit(1); } static int send_fds(int sock, int fd0, int fd1, int fd2) { char dummy = 'F'; struct iovec iov = { .iov_base = &dummy, .iov_len = 1 }; int fds[3] = { fd0, fd1, fd2 }; char cmsg_buf[CMSG_SPACE(sizeof(fds))]; struct msghdr msg; memset(&msg, 0, sizeof(msg)); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = cmsg_buf; msg.msg_controllen = sizeof(cmsg_buf); struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; cmsg->cmsg_len = CMSG_LEN(sizeof(fds)); memcpy(CMSG_DATA(cmsg), fds, sizeof(fds)); if (sendmsg(sock, &msg, 0) < 0) return -1; return 0; } static int recv_fds(int sock, int *fd0, int *fd1, int *fd2) { char dummy = 0; struct iovec iov = { .iov_base = &dummy, .iov_len = 1 }; char cmsg_buf[CMSG_SPACE(sizeof(int) * 3)]; struct msghdr msg; memset(&msg, 0, sizeof(msg)); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = cmsg_buf; msg.msg_controllen = sizeof(cmsg_buf); if (recvmsg(sock, &msg, 0) <= 0) return -1; struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); if (!cmsg || cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) { return -1; } int fds[3]; memcpy(fds, CMSG_DATA(cmsg), sizeof(fds)); *fd0 = fds[0]; *fd1 = fds[1]; *fd2 = fds[2]; return 0; } static int run_client(int argc, char **argv) { int sock = socket(AF_UNIX, SOCK_STREAM, 0); if (sock < 0) return -1; struct sockaddr_un addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; addr.sun_path[0] = '\0'; strncpy(addr.sun_path + 1, DAEMON_SOCKET_ABSTRACT, sizeof(addr.sun_path) - 2); if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { /* Try filesystem path */ memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, DAEMON_SOCKET_DEV, sizeof(addr.sun_path) - 1); if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { close(sock); return -1; } } /* Send standard file descriptors */ if (send_fds(sock, 0, 1, 2) < 0) { close(sock); return -1; } /* Send argc and argv */ uint32_t net_argc = htonl((uint32_t)argc); if (write(sock, &net_argc, sizeof(net_argc)) != sizeof(net_argc)) { close(sock); return -1; } for (int i = 0; i < argc; i++) { uint32_t len = (uint32_t)strlen(argv[i]); uint32_t net_len = htonl(len); write(sock, &net_len, sizeof(net_len)); write(sock, argv[i], len); } /* Read exit status */ int status = 1; if (read(sock, &status, sizeof(status)) != sizeof(status)) { status = 1; } close(sock); return status; } static int read_exact(int fd, void *buf, size_t len) { unsigned char *ptr = (unsigned char *)buf; size_t got = 0; while (got < len) { ssize_t r = read(fd, ptr + got, len - got); if (r <= 0) return -1; got += (size_t)r; } return 0; } static int run_daemon(void) { /* Daemonize */ if (fork() > 0) return 0; setsid(); struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = SIG_IGN; sigaction(SIGPIPE, &sa, NULL); unlink(DAEMON_SOCKET_DEV); /* Bind filesystem socket in /dev */ int sfd = socket(AF_UNIX, SOCK_STREAM, 0); if (sfd < 0) return 1; set_cloexec(sfd); struct sockaddr_un addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, DAEMON_SOCKET_DEV, sizeof(addr.sun_path) - 1); bind(sfd, (struct sockaddr *)&addr, sizeof(addr)); chmod(DAEMON_SOCKET_DEV, 0666); listen(sfd, 10); /* Bind abstract socket */ int asfd = socket(AF_UNIX, SOCK_STREAM, 0); if (asfd >= 0) { set_cloexec(asfd); memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; addr.sun_path[0] = '\0'; strncpy(addr.sun_path + 1, DAEMON_SOCKET_ABSTRACT, sizeof(addr.sun_path) - 2); bind(asfd, (struct sockaddr *)&addr, sizeof(addr)); listen(asfd, 10); } while (1) { fd_set rfds; FD_ZERO(&rfds); FD_SET(sfd, &rfds); int maxfd = sfd; if (asfd >= 0) { FD_SET(asfd, &rfds); if (asfd > maxfd) maxfd = asfd; } if (select(maxfd + 1, &rfds, NULL, NULL, NULL) <= 0) continue; int active_fd = FD_ISSET(sfd, &rfds) ? sfd : asfd; int client = accept(active_fd, NULL, NULL); if (client < 0) continue; set_cloexec(client); struct ucred cred; socklen_t cred_len = sizeof(cred); if (getsockopt(client, SOL_SOCKET, SO_PEERCRED, &cred, &cred_len) < 0) { close(client); continue; } int fd0 = -1, fd1 = -1, fd2 = -1; if (recv_fds(client, &fd0, &fd1, &fd2) < 0) { close(client); continue; } set_cloexec(fd0); set_cloexec(fd1); set_cloexec(fd2); /* Read argc and argv with bounds checks */ uint32_t net_argc = 0; if (read_exact(client, &net_argc, sizeof(net_argc)) < 0) { close(fd0); close(fd1); close(fd2); close(client); continue; } uint32_t c_argc_u = ntohl(net_argc); if (c_argc_u == 0 || c_argc_u > 64) { close(fd0); close(fd1); close(fd2); close(client); continue; } int c_argc = (int)c_argc_u; char **c_argv = calloc((size_t)c_argc + 1, sizeof(char *)); if (!c_argv) { close(fd0); close(fd1); close(fd2); close(client); continue; } int read_ok = 1; for (int i = 0; i < c_argc; i++) { uint32_t net_len = 0; if (read_exact(client, &net_len, sizeof(net_len)) < 0) { read_ok = 0; break; } uint32_t len = ntohl(net_len); if (len > 8192) { read_ok = 0; break; } c_argv[i] = malloc((size_t)len + 1); if (!c_argv[i] || (len > 0 && read_exact(client, c_argv[i], len) < 0)) { read_ok = 0; break; } c_argv[i][len] = '\0'; } if (!read_ok) { close(fd0); close(fd1); close(fd2); close(client); for (int i = 0; i < c_argc; i++) free(c_argv[i]); free(c_argv); continue; } struct su_request req; memset(&req, 0, sizeof(req)); req.from_pid = cred.pid; req.from_uid = cred.uid; req.to_uid = 0; get_process_name(cred.pid, req.from_name, sizeof(req.from_name)); strncpy(req.shell, "/system/bin/sh", sizeof(req.shell) - 1); for (int i = 1; i < c_argc; i++) { if ((strcmp(c_argv[i], "-c") == 0 || strcmp(c_argv[i], "--command") == 0) && i + 1 < c_argc) { strncpy(req.command, c_argv[i + 1], sizeof(req.command) - 1); i++; } else if ((strcmp(c_argv[i], "-s") == 0 || strcmp(c_argv[i], "--shell") == 0) && i + 1 < c_argc) { strncpy(req.shell, c_argv[i + 1], sizeof(req.shell) - 1); i++; } } int policy = check_policy(req.from_uid); if (policy == POLICY_INTERACTIVE) { policy = prompt_manager(&req); } if (policy != POLICY_ALLOW) { write(fd2, "Permission denied\n", 18); int exit_status = 1; write(client, &exit_status, sizeof(exit_status)); close(fd0); close(fd1); close(fd2); close(client); for (int i = 0; i < c_argc; i++) free(c_argv[i]); free(c_argv); continue; } pid_t child = fork(); if (child == 0) { dup2(fd0, 0); dup2(fd1, 1); dup2(fd2, 2); close(fd0); close(fd1); close(fd2); close(client); close(sfd); if (asfd >= 0) close(asfd); execute_shell(&req); _exit(127); } close(fd0); close(fd1); close(fd2); int status = 0; waitpid(child, &status, 0); int ret_code = WIFEXITED(status) ? WEXITSTATUS(status) : 1; write(client, &ret_code, sizeof(ret_code)); close(client); for (int i = 0; i < c_argc; i++) free(c_argv[i]); free(c_argv); } return 0; } int main(int argc, char **argv, char **envp) { caller_envp = envp; if (argc > 1 && strcmp(argv[1], "--daemon") == 0) { if (getuid() != 0) { fprintf(stderr, "Permission denied\n"); return 1; } return run_daemon(); } if (argc > 1 && (strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "-V") == 0 || strcmp(argv[1], "--version") == 0)) { printf("%s (%d)\n", SU_VERSION_NAME, SU_VERSION_CODE); return 0; } if (argc > 1 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)) { fprintf(stderr, "Usage: su [options] [-] [LOGIN] [--] [args...]\n\n" "Options:\n" " -c, --command COMMAND pass COMMAND to invoked shell\n" " -s, --shell SHELL run SHELL instead of default\n" " -v, --version display version and exit\n" " --daemon run su daemon\n" " -h, --help display this help\n"); return 0; } uid_t uid = getuid(); uid_t euid = geteuid(); /* If not running with setuid root privileges, attempt daemon connection */ if (euid != 0) { int client_ret = run_client(argc, argv); if (client_ret >= 0) { return client_ret; } fprintf(stderr, "su: not setuid and daemon unavailable\n"); return 1; } struct su_request req; memset(&req, 0, sizeof(req)); req.from_pid = getpid(); req.from_uid = uid; req.to_uid = 0; get_process_name(getpid(), req.from_name, sizeof(req.from_name)); strncpy(req.shell, "/system/bin/sh", sizeof(req.shell) - 1); for (int i = 1; i < argc; i++) { if ((strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--command") == 0) && i + 1 < argc) { strncpy(req.command, argv[i + 1], sizeof(req.command) - 1); i++; } else if ((strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--shell") == 0) && i + 1 < argc) { strncpy(req.shell, argv[i + 1], sizeof(req.shell) - 1); i++; } } int policy = check_policy(req.from_uid); if (policy == POLICY_INTERACTIVE) { policy = prompt_manager(&req); } if (policy != POLICY_ALLOW) { fprintf(stderr, "Permission denied\n"); return 1; } execute_shell(&req); return 0; }