feat: experimental native userland that runs the Linux side without proot

This commit is contained in:
Kurt Himebauch committed 2026-11-08 14:53:52 -05:00
1 parent 3bb279f635
commit 70c33fc039
45 files changed
+10132 -8

No files matched your search

+114
View File
@@ -0,0 +1,114 @@
// Part of libddnatv-hook.so, included by ddnatv-hook.c (one translation unit, so the
// parts share their static functions and are built with the same command as before).
//
// xz and zstd limited to one thread (threads of forked dpkg-deb children fail on Android).
#ifndef DDNATV_HOST_TEST
// Hook lzma multi-threaded routines to enforce single-threaded execution
// This prevents clone/pthread_create failures in forked dpkg-deb child processes on Android
typedef struct {
const uint8_t *next_in;
size_t avail_in;
uint64_t total_in;
uint8_t *next_out;
size_t avail_out;
uint64_t total_out;
const void *allocator;
void *internal;
void *reserved_ptr1;
void *reserved_ptr2;
void *reserved_ptr3;
void *reserved_ptr4;
uint64_t reserved_int1;
uint64_t reserved_int2;
size_t reserved_int3;
size_t reserved_int4;
uint32_t reserved_enum1;
uint32_t reserved_enum2;
} ddnatv_lzma_stream;
typedef struct {
uint32_t flags;
uint32_t threads;
uint64_t block_size;
uint32_t timeout;
uint32_t preset;
const void *filters;
int check;
uint64_t memlimit_threading;
uint64_t memlimit_stop;
} ddnatv_lzma_mt;
int lzma_stream_decoder_mt(ddnatv_lzma_stream *strm, const ddnatv_lzma_mt *options) {
static int (*orig_decoder)(ddnatv_lzma_stream *, uint64_t, uint32_t) = NULL;
if (!orig_decoder) {
orig_decoder = (int (*)(ddnatv_lzma_stream *, uint64_t, uint32_t))dlsym(RTLD_DEFAULT, "lzma_stream_decoder");
if (!orig_decoder) {
orig_decoder = (int (*)(ddnatv_lzma_stream *, uint64_t, uint32_t))dlsym(RTLD_NEXT, "lzma_stream_decoder");
}
}
uint64_t memlimit = (options && options->memlimit_threading > 0) ? options->memlimit_threading : UINT64_MAX;
uint32_t flags = options ? options->flags : 0;
if (orig_decoder) {
return orig_decoder(strm, memlimit, flags);
}
static int (*orig_mt)(ddnatv_lzma_stream *, const ddnatv_lzma_mt *) = NULL;
if (!orig_mt) {
orig_mt = (int (*)(ddnatv_lzma_stream *, const ddnatv_lzma_mt *))dlsym(RTLD_NEXT, "lzma_stream_decoder_mt");
}
return orig_mt ? orig_mt(strm, options) : -1;
}
int lzma_stream_encoder_mt(ddnatv_lzma_stream *strm, const ddnatv_lzma_mt *options) {
// The native userland encodes on one thread. The single-thread encoders take the same settings: xz passes its
// compression level as a filter chain (its preset field is unused), other programs a preset.
// Honouring only the preset made `xz -T4 -9` (and -T0) compress like `xz -0`.
if (options && options->filters) {
static int (*orig_stream)(ddnatv_lzma_stream *, const void *, int) = NULL;
if (!orig_stream) {
orig_stream = (int (*)(ddnatv_lzma_stream *, const void *, int))dlsym(RTLD_DEFAULT, "lzma_stream_encoder");
if (!orig_stream) {
orig_stream = (int (*)(ddnatv_lzma_stream *, const void *, int))dlsym(RTLD_NEXT, "lzma_stream_encoder");
}
}
if (orig_stream) return orig_stream(strm, options->filters, options->check);
}
static int (*orig_easy)(ddnatv_lzma_stream *, uint32_t, int) = NULL;
if (!orig_easy) {
orig_easy = (int (*)(ddnatv_lzma_stream *, uint32_t, int))dlsym(RTLD_DEFAULT, "lzma_easy_encoder");
if (!orig_easy) {
orig_easy = (int (*)(ddnatv_lzma_stream *, uint32_t, int))dlsym(RTLD_NEXT, "lzma_easy_encoder");
}
}
if (orig_easy) {
uint32_t preset = options ? options->preset : 6;
int check = options ? options->check : 4; // LZMA_CHECK_CRC64
return orig_easy(strm, preset, check);
}
static int (*orig_mt)(ddnatv_lzma_stream *, const ddnatv_lzma_mt *) = NULL;
if (!orig_mt) {
orig_mt = (int (*)(ddnatv_lzma_stream *, const ddnatv_lzma_mt *))dlsym(RTLD_NEXT, "lzma_stream_encoder_mt");
}
return orig_mt ? orig_mt(strm, options) : -1;
}
uint32_t lzma_cputhreads(void) {
return 1;
}
int ZSTD_CCtx_setParameter(void *cctx, int param, int value) {
static int (*orig_param)(void *, int, int) = NULL;
if (!orig_param) {
orig_param = (int (*)(void *, int, int))dlsym(RTLD_DEFAULT, "ZSTD_CCtx_setParameter");
if (!orig_param) {
orig_param = (int (*)(void *, int, int))dlsym(RTLD_NEXT, "ZSTD_CCtx_setParameter");
}
}
if (param == 400 /* ZSTD_c_nbWorkers */ && value > 1) {
value = 1;
}
return orig_param ? orig_param(cctx, param, value) : -1;
}
#endif /* !DDNATV_HOST_TEST */
Binary file not shown.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+671
View File
@@ -0,0 +1,671 @@
// Part of libddnatv-hook.so, included by ddnatv-hook.c (one translation unit, so the
// parts share their static functions and are built with the same command as before).
//
// Other file operations: access, chmod, unlink, mkdir, rename, readlink, extended attributes,
// links, times, truncate, statfs, the working directory, realpath and scandir.
#ifndef DDNATV_HOST_TEST
// Hook faccessat
int faccessat(int dirfd, const char *pathname, int mode, int flags) {
init_ddnatv_hook();
if (!pathname) {
errno = EFAULT;
return -1;
}
struct stat st;
int stat_flags = (flags & AT_SYMLINK_NOFOLLOW) ? AT_SYMLINK_NOFOLLOW : 0;
if (fstatat(dirfd, pathname, &st, stat_flags) != 0) {
return -1;
}
if (mode == F_OK) {
return 0;
}
if (mode & X_OK) {
if (S_ISDIR(st.st_mode)) return 0;
if ((st.st_mode & 0111) != 0) return 0;
if (strstr(pathname, "/bin/") || strstr(pathname, "/sbin/")) return 0;
errno = EACCES;
return -1;
}
return 0;
}
int faccessat2(int dirfd, const char *pathname, int mode, int flags) {
return faccessat(dirfd, pathname, mode, flags);
}
// Hook access
int access(const char *pathname, int mode) {
return faccessat(AT_FDCWD, pathname, mode, 0);
}
// Hook euidaccess and eaccess
int euidaccess(const char *pathname, int mode) {
return faccessat(AT_FDCWD, pathname, mode, AT_EACCESS);
}
int eaccess(const char *pathname, int mode) {
return faccessat(AT_FDCWD, pathname, mode, AT_EACCESS);
}
// Hook chmod
int chmod(const char *pathname, mode_t mode) {
static int (*orig_chmod)(const char *, mode_t) = NULL;
if (!orig_chmod) orig_chmod = (int (*)(const char *, mode_t))dlsym(RTLD_NEXT, "chmod");
if (!orig_chmod) return -1;
char buf[PATH_MAX];
const char *target = rewrite_path(pathname, buf, sizeof(buf));
int ret = orig_chmod(target, mode);
if (ret != 0 && ((mode & 06000) != 0 || errno == EPERM || errno == EACCES || errno == ENOSYS)) {
ret = orig_chmod(target, mode & 01777);
}
if (ret != 0 && (errno == EPERM || errno == EACCES)) {
errno = 0;
return 0;
}
return ret;
}
// Hook fchmod
int fchmod(int fd, mode_t mode) {
static int (*orig_fchmod)(int, mode_t) = NULL;
if (!orig_fchmod) orig_fchmod = (int (*)(int, mode_t))dlsym(RTLD_NEXT, "fchmod");
if (!orig_fchmod) return -1;
int ret = orig_fchmod(fd, mode);
if (ret != 0 && ((mode & 06000) != 0 || errno == EPERM || errno == EACCES || errno == ENOSYS)) {
ret = orig_fchmod(fd, mode & 01777);
}
if (ret != 0 && (errno == EPERM || errno == EACCES)) {
errno = 0;
return 0;
}
return ret;
}
// Hook fchmodat
int fchmodat(int dirfd, const char *pathname, mode_t mode, int flags) {
static int (*orig_fchmodat)(int, const char *, mode_t, int) = NULL;
if (!orig_fchmodat) orig_fchmodat = (int (*)(int, const char *, mode_t, int))dlsym(RTLD_NEXT, "fchmodat");
if (!orig_fchmodat) return -1;
char buf[PATH_MAX];
const char *target = (pathname && pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname;
int ret = orig_fchmodat(dirfd, target, mode, flags);
if (ret != 0 && ((mode & 06000) != 0 || errno == EPERM || errno == EACCES || errno == ENOSYS)) {
ret = orig_fchmodat(dirfd, target, mode & 01777, flags);
}
if (ret != 0 && (errno == EPERM || errno == EACCES)) {
errno = 0;
return 0;
}
return ret;
}
// Hook unlink
int unlink(const char *pathname) {
static int (*orig_unlink)(const char *) = NULL;
if (!orig_unlink) orig_unlink = (int (*)(const char *))dlsym(RTLD_NEXT, "unlink");
char buf[PATH_MAX];
const char *target = rewrite_path(pathname, buf, sizeof(buf));
unlink_mapped_unix_socket(target);
dev_t hl_dev = 0;
ino_t hl_ino = 0;
int hardlinked = lookup_emulated_hardlink_at(AT_FDCWD, target, &hl_dev, &hl_ino);
int ret = orig_unlink(target);
if (ret != 0 && refused_in_repaired_dir(AT_FDCWD, target)) {
// The name could not be looked up while its directory was closed
hardlinked = lookup_emulated_hardlink_at(AT_FDCWD, target, &hl_dev, &hl_ino);
ret = orig_unlink(target);
}
if (ret == 0 && hardlinked) unregister_emulated_hardlink(hl_dev, hl_ino);
return ret;
}
// Hook unlinkat
int unlinkat(int dirfd, const char *pathname, int flags) {
static int (*orig_unlinkat)(int, const char *, int) = NULL;
if (!orig_unlinkat) orig_unlinkat = (int (*)(int, const char *, int))dlsym(RTLD_NEXT, "unlinkat");
char buf[PATH_MAX];
const char *target = (pathname && pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname;
dev_t hl_dev = 0;
ino_t hl_ino = 0;
int hardlinked = 0;
if (target) {
unlink_mapped_unix_socket(target);
hardlinked = lookup_emulated_hardlink_at(dirfd, target, &hl_dev, &hl_ino);
}
int ret = orig_unlinkat ? orig_unlinkat(dirfd, target, flags) : -1;
if (ret != 0 && orig_unlinkat && refused_in_repaired_dir(dirfd, target)) {
hardlinked = target ? lookup_emulated_hardlink_at(dirfd, target, &hl_dev, &hl_ino) : 0;
ret = orig_unlinkat(dirfd, target, flags);
}
if (ret == 0 && hardlinked) unregister_emulated_hardlink(hl_dev, hl_ino);
return ret;
}
// Hook rmdir
int rmdir(const char *pathname) {
static int (*orig_rmdir)(const char *) = NULL;
if (!orig_rmdir) orig_rmdir = (int (*)(const char *))dlsym(RTLD_NEXT, "rmdir");
char buf[PATH_MAX];
const char *target = rewrite_path(pathname, buf, sizeof(buf));
int ret = orig_rmdir(target);
if (ret != 0 && refused_in_repaired_dir(AT_FDCWD, target)) ret = orig_rmdir(target);
return ret;
}
// The app is root for the programs it runs, and root enters and writes every directory whatever its
// mode; the app does not. dpkg makes each new directory with mode 0 and sets the mode a moment later,
// and a chmod that fails is reported as done (see chmod), which left directories nobody could put a
// file in: "Permission denied" in /usr/share/applications and others (#44). So a directory always
// keeps its owner's read, write and search rights.
#define NEW_DIR_OWNER_RIGHTS S_IRWXU
// Hook mkdir
int mkdir(const char *pathname, mode_t mode) {
static int (*orig_mkdir)(const char *, mode_t) = NULL;
if (!orig_mkdir) orig_mkdir = (int (*)(const char *, mode_t))dlsym(RTLD_NEXT, "mkdir");
char buf[PATH_MAX];
const char *target = rewrite_path(pathname, buf, sizeof(buf));
int ret = orig_mkdir(target, mode | NEW_DIR_OWNER_RIGHTS);
if (ret != 0 && refused_in_repaired_dir(AT_FDCWD, target)) ret = orig_mkdir(target, mode | NEW_DIR_OWNER_RIGHTS);
return ret;
}
// Hook mkdirat
int mkdirat(int dirfd, const char *pathname, mode_t mode) {
static int (*orig_mkdirat)(int, const char *, mode_t) = NULL;
if (!orig_mkdirat) orig_mkdirat = (int (*)(int, const char *, mode_t))dlsym(RTLD_NEXT, "mkdirat");
char buf[PATH_MAX];
const char *target = (pathname && pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname;
int ret = orig_mkdirat(dirfd, target, mode | NEW_DIR_OWNER_RIGHTS);
if (ret != 0 && refused_in_repaired_dir(dirfd, target)) ret = orig_mkdirat(dirfd, target, mode | NEW_DIR_OWNER_RIGHTS);
return ret;
}
static void ensure_dir_exists(const char *path) {
if (!path || path[0] == '\0') return;
char tmp[PATH_MAX];
strncpy(tmp, path, sizeof(tmp) - 1);
tmp[sizeof(tmp) - 1] = '\0';
for (char *p = tmp + 1; *p; p++) {
if (*p == '/') {
*p = '\0';
mkdir(tmp, 0755);
*p = '/';
}
}
mkdir(tmp, 0755);
}
// Hook inotify_add_watch
int inotify_add_watch(int fd, const char *pathname, uint32_t mask) {
static int (*orig_inotify_add_watch)(int, const char *, uint32_t) = NULL;
if (!orig_inotify_add_watch) orig_inotify_add_watch = (int (*)(int, const char *, uint32_t))dlsym(RTLD_NEXT, "inotify_add_watch");
if (!pathname) return -1;
char buf[PATH_MAX];
const char *target = rewrite_path(pathname, buf, sizeof(buf));
if (target && access(target, F_OK) != 0) {
ensure_dir_exists(target);
}
return orig_inotify_add_watch ? orig_inotify_add_watch(fd, target, mask) : -1;
}
// Hook rename
int rename(const char *oldpath, const char *newpath) {
static int (*orig_rename)(const char *, const char *) = NULL;
if (!orig_rename) orig_rename = (int (*)(const char *, const char *))dlsym(RTLD_NEXT, "rename");
char buf1[PATH_MAX];
char buf2[PATH_MAX];
const char *target_old = rewrite_path(oldpath, buf1, sizeof(buf1));
const char *target_new = rewrite_path(newpath, buf2, sizeof(buf2));
dev_t hl_dev = 0;
ino_t hl_ino = 0;
int hardlinked = lookup_emulated_hardlink_at(AT_FDCWD, target_new, &hl_dev, &hl_ino);
int ret = orig_rename(target_old, target_new);
if (ret != 0 && errno == EACCES) {
// Both directories: the old name is taken out of one, the new put in the other
int refused = errno;
int fixed_old = refused_in_repaired_dir(AT_FDCWD, target_old);
errno = refused;
int fixed_new = refused_in_repaired_dir(AT_FDCWD, target_new);
if (fixed_old || fixed_new) {
hardlinked = lookup_emulated_hardlink_at(AT_FDCWD, target_new, &hl_dev, &hl_ino);
ret = orig_rename(target_old, target_new);
}
}
if (ret == 0 && hardlinked) unregister_emulated_hardlink(hl_dev, hl_ino);
return ret;
}
// Hook renameat
int renameat(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
static int (*orig_renameat)(int, const char *, int, const char *) = NULL;
if (!orig_renameat) orig_renameat = (int (*)(int, const char *, int, const char *))dlsym(RTLD_NEXT, "renameat");
char buf1[PATH_MAX];
char buf2[PATH_MAX];
const char *target_old = (oldpath && oldpath[0] == '/') ? rewrite_path(oldpath, buf1, sizeof(buf1)) : oldpath;
const char *target_new = (newpath && newpath[0] == '/') ? rewrite_path(newpath, buf2, sizeof(buf2)) : newpath;
dev_t hl_dev = 0;
ino_t hl_ino = 0;
int hardlinked = lookup_emulated_hardlink_at(newdirfd, target_new, &hl_dev, &hl_ino);
int ret = orig_renameat(olddirfd, target_old, newdirfd, target_new);
if (ret != 0 && errno == EACCES) {
int refused = errno;
int fixed_old = refused_in_repaired_dir(olddirfd, target_old);
errno = refused;
int fixed_new = refused_in_repaired_dir(newdirfd, target_new);
if (fixed_old || fixed_new) {
hardlinked = lookup_emulated_hardlink_at(newdirfd, target_new, &hl_dev, &hl_ino);
ret = orig_renameat(olddirfd, target_old, newdirfd, target_new);
}
}
if (ret == 0 && hardlinked) unregister_emulated_hardlink(hl_dev, hl_ino);
return ret;
}
// Hook renameat2
int renameat2(int olddirfd, const char *oldpath, int newdirfd, const char *newpath, unsigned int flags) {
static int (*orig_renameat2)(int, const char *, int, const char *, unsigned int) = NULL;
if (!orig_renameat2) {
orig_renameat2 = (int (*)(int, const char *, int, const char *, unsigned int))dlsym(RTLD_NEXT, "renameat2");
if (!orig_renameat2) return renameat(olddirfd, oldpath, newdirfd, newpath);
}
char buf1[PATH_MAX];
char buf2[PATH_MAX];
const char *target_old = (oldpath && oldpath[0] == '/') ? rewrite_path(oldpath, buf1, sizeof(buf1)) : oldpath;
const char *target_new = (newpath && newpath[0] == '/') ? rewrite_path(newpath, buf2, sizeof(buf2)) : newpath;
dev_t hl_dev = 0;
ino_t hl_ino = 0;
// RENAME_EXCHANGE keeps both files, so nothing is replaced.
int hardlinked = !(flags & RENAME_EXCHANGE) && lookup_emulated_hardlink_at(newdirfd, target_new, &hl_dev, &hl_ino);
int ret = orig_renameat2(olddirfd, target_old, newdirfd, target_new, flags);
if (ret != 0 && errno == EACCES) {
int refused = errno;
int fixed_old = refused_in_repaired_dir(olddirfd, target_old);
errno = refused;
int fixed_new = refused_in_repaired_dir(newdirfd, target_new);
if (fixed_old || fixed_new) {
hardlinked = !(flags & RENAME_EXCHANGE) && lookup_emulated_hardlink_at(newdirfd, target_new, &hl_dev, &hl_ino);
ret = orig_renameat2(olddirfd, target_old, newdirfd, target_new, flags);
}
}
if (ret == 0 && hardlinked) unregister_emulated_hardlink(hl_dev, hl_ino);
return ret;
}
// Hook readlink
ssize_t readlink(const char *pathname, char *buf, size_t bufsiz) {
if (is_proc_self_exe(pathname)) {
ssize_t exe_len = handle_proc_self_exe(buf, bufsiz);
if (exe_len >= 0) return exe_len;
}
static ssize_t (*orig_readlink)(const char *, char *, size_t) = NULL;
if (!orig_readlink) orig_readlink = (ssize_t (*)(const char *, char *, size_t))dlsym(RTLD_NEXT, "readlink");
char pbuf[PATH_MAX];
const char *target = rewrite_path(pathname, pbuf, sizeof(pbuf));
ssize_t ret = orig_readlink ? orig_readlink(target, buf, bufsiz) : -1;
if (ret < 0 && errno == ENOENT) {
char alt[PATH_MAX];
const char *retry = usrmerge_retry_path(target, alt, sizeof(alt));
if (retry) ret = orig_readlink(retry, buf, bufsiz);
}
return postprocess_readlink(pathname, buf, ret, bufsiz);
}
// Hook readlinkat
ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) {
if (is_proc_self_exe(pathname)) {
ssize_t exe_len = handle_proc_self_exe(buf, bufsiz);
if (exe_len >= 0) return exe_len;
}
static ssize_t (*orig_readlinkat)(int, const char *, char *, size_t) = NULL;
if (!orig_readlinkat) orig_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat");
char pbuf[PATH_MAX];
const char *target = (pathname && pathname[0] == '/') ? rewrite_path(pathname, pbuf, sizeof(pbuf)) : pathname;
ssize_t ret = orig_readlinkat ? orig_readlinkat(dirfd, target, buf, bufsiz) : -1;
if (ret < 0 && errno == ENOENT && pathname && pathname[0] == '/') {
char alt[PATH_MAX];
const char *retry = usrmerge_retry_path(target, alt, sizeof(alt));
if (retry) ret = orig_readlinkat(dirfd, retry, buf, bufsiz);
}
return postprocess_readlink(pathname, buf, ret, bufsiz);
}
// Fortified readlink variants used by dpkg / update-alternatives
ssize_t __readlink_chk(const char *pathname, char *buf, size_t bufsiz, size_t buflen) {
return readlink(pathname, buf, bufsiz);
}
ssize_t __readlinkat_chk(int dirfd, const char *pathname, char *buf, size_t bufsiz, size_t buflen) {
return readlinkat(dirfd, pathname, buf, bufsiz);
}
// Ubuntu's programs find Android's SELinux (enforcing) through libselinux and then ask its policy
// questions it has no answers for. The one that mattered: PAM's pam_rootok, which lets root
// change its own entries, asks "may this user be root" and was refused, so chfn, chsh and
// `adduser --gecos` (the installation of PostgreSQL) failed with "PAM: Authentication failure".
// Ubuntu does not use SELinux, so for its programs it is off, as its labels are hidden below.
int is_selinux_enabled(void) { return 0; }
// Extended attributes take the same paths as stat(). Without these hooks coreutils read
// security.selinux with the Ubuntu path itself: `ls -l` printed an error line for every file
// Android lacks (/etc/os-release) and showed Android's own label for the ones it has
// (/etc/passwd). Ubuntu does not use SELinux, so its label is hidden altogether: `ls -l` looks as
// on Ubuntu and cp/tar/rsync do not try to copy Android's labels.
ssize_t getxattr(const char *path, const char *name, void *value, size_t size) {
static ssize_t (*orig_getxattr)(const char *, const char *, void *, size_t) = NULL;
if (!orig_getxattr) orig_getxattr = (ssize_t (*)(const char *, const char *, void *, size_t))dlsym(RTLD_NEXT, "getxattr");
if (is_selinux_xattr(name)) {
errno = ENODATA;
return -1;
}
char pbuf[PATH_MAX];
return orig_getxattr ? orig_getxattr(rewrite_path(path, pbuf, sizeof(pbuf)), name, value, size) : -1;
}
ssize_t lgetxattr(const char *path, const char *name, void *value, size_t size) {
static ssize_t (*orig_lgetxattr)(const char *, const char *, void *, size_t) = NULL;
if (!orig_lgetxattr) orig_lgetxattr = (ssize_t (*)(const char *, const char *, void *, size_t))dlsym(RTLD_NEXT, "lgetxattr");
if (is_selinux_xattr(name)) {
errno = ENODATA;
return -1;
}
char pbuf[PATH_MAX];
return orig_lgetxattr ? orig_lgetxattr(rewrite_path(path, pbuf, sizeof(pbuf)), name, value, size) : -1;
}
ssize_t listxattr(const char *path, char *list, size_t size) {
static ssize_t (*orig_listxattr)(const char *, char *, size_t) = NULL;
if (!orig_listxattr) orig_listxattr = (ssize_t (*)(const char *, char *, size_t))dlsym(RTLD_NEXT, "listxattr");
char pbuf[PATH_MAX];
ssize_t ret = orig_listxattr ? orig_listxattr(rewrite_path(path, pbuf, sizeof(pbuf)), list, size) : -1;
return size > 0 ? drop_selinux_xattr(list, ret) : ret;
}
ssize_t llistxattr(const char *path, char *list, size_t size) {
static ssize_t (*orig_llistxattr)(const char *, char *, size_t) = NULL;
if (!orig_llistxattr) orig_llistxattr = (ssize_t (*)(const char *, char *, size_t))dlsym(RTLD_NEXT, "llistxattr");
char pbuf[PATH_MAX];
ssize_t ret = orig_llistxattr ? orig_llistxattr(rewrite_path(path, pbuf, sizeof(pbuf)), list, size) : -1;
return size > 0 ? drop_selinux_xattr(list, ret) : ret;
}
ssize_t fgetxattr(int fd, const char *name, void *value, size_t size) {
static ssize_t (*orig_fgetxattr)(int, const char *, void *, size_t) = NULL;
if (!orig_fgetxattr) orig_fgetxattr = (ssize_t (*)(int, const char *, void *, size_t))dlsym(RTLD_NEXT, "fgetxattr");
if (is_selinux_xattr(name)) {
errno = ENODATA;
return -1;
}
return orig_fgetxattr ? orig_fgetxattr(fd, name, value, size) : -1;
}
ssize_t flistxattr(int fd, char *list, size_t size) {
static ssize_t (*orig_flistxattr)(int, char *, size_t) = NULL;
if (!orig_flistxattr) orig_flistxattr = (ssize_t (*)(int, char *, size_t))dlsym(RTLD_NEXT, "flistxattr");
ssize_t ret = orig_flistxattr ? orig_flistxattr(fd, list, size) : -1;
return size > 0 ? drop_selinux_xattr(list, ret) : ret;
}
int setxattr(const char *path, const char *name, const void *value, size_t size, int flags) {
static int (*orig_setxattr)(const char *, const char *, const void *, size_t, int) = NULL;
if (!orig_setxattr) orig_setxattr = (int (*)(const char *, const char *, const void *, size_t, int))dlsym(RTLD_NEXT, "setxattr");
char pbuf[PATH_MAX];
return orig_setxattr ? orig_setxattr(rewrite_path(path, pbuf, sizeof(pbuf)), name, value, size, flags) : -1;
}
int lsetxattr(const char *path, const char *name, const void *value, size_t size, int flags) {
static int (*orig_lsetxattr)(const char *, const char *, const void *, size_t, int) = NULL;
if (!orig_lsetxattr) orig_lsetxattr = (int (*)(const char *, const char *, const void *, size_t, int))dlsym(RTLD_NEXT, "lsetxattr");
char pbuf[PATH_MAX];
return orig_lsetxattr ? orig_lsetxattr(rewrite_path(path, pbuf, sizeof(pbuf)), name, value, size, flags) : -1;
}
int removexattr(const char *path, const char *name) {
static int (*orig_removexattr)(const char *, const char *) = NULL;
if (!orig_removexattr) orig_removexattr = (int (*)(const char *, const char *))dlsym(RTLD_NEXT, "removexattr");
char pbuf[PATH_MAX];
return orig_removexattr ? orig_removexattr(rewrite_path(path, pbuf, sizeof(pbuf)), name) : -1;
}
int lremovexattr(const char *path, const char *name) {
static int (*orig_lremovexattr)(const char *, const char *) = NULL;
if (!orig_lremovexattr) orig_lremovexattr = (int (*)(const char *, const char *))dlsym(RTLD_NEXT, "lremovexattr");
char pbuf[PATH_MAX];
return orig_lremovexattr ? orig_lremovexattr(rewrite_path(path, pbuf, sizeof(pbuf)), name) : -1;
}
// Hook symlink
int symlink(const char *target, const char *linkpath) {
static int (*orig_symlink)(const char *, const char *) = NULL;
if (!orig_symlink) orig_symlink = (int (*)(const char *, const char *))dlsym(RTLD_NEXT, "symlink");
char pbuf[PATH_MAX], tbuf[PATH_MAX];
const char *newlink = rewrite_path(linkpath, pbuf, sizeof(pbuf));
const char *newtarget = (target && target[0] == '/') ? rewrite_path(target, tbuf, sizeof(tbuf)) : target;
int ret = orig_symlink ? orig_symlink(newtarget, newlink) : -1;
if (ret != 0 && orig_symlink && refused_in_repaired_dir(AT_FDCWD, newlink)) ret = orig_symlink(newtarget, newlink);
return ret;
}
// Hook symlinkat
int symlinkat(const char *target, int newdirfd, const char *linkpath) {
static int (*orig_symlinkat)(const char *, int, const char *) = NULL;
if (!orig_symlinkat) orig_symlinkat = (int (*)(const char *, int, const char *))dlsym(RTLD_NEXT, "symlinkat");
char pbuf[PATH_MAX], tbuf[PATH_MAX];
const char *newlink = (linkpath && linkpath[0] == '/') ? rewrite_path(linkpath, pbuf, sizeof(pbuf)) : linkpath;
const char *newtarget = (target && target[0] == '/') ? rewrite_path(target, tbuf, sizeof(tbuf)) : target;
int ret = orig_symlinkat ? orig_symlinkat(newtarget, newdirfd, newlink) : -1;
if (ret != 0 && orig_symlinkat && refused_in_repaired_dir(newdirfd, newlink)) ret = orig_symlinkat(newtarget, newdirfd, newlink);
return ret;
}
// Hook linkat
int linkat(int olddirfd, const char *oldpath, int newdirfd, const char *newpath, int flags) {
static int (*orig_linkat)(int, const char *, int, const char *, int) = NULL;
if (!orig_linkat) orig_linkat = (int (*)(int, const char *, int, const char *, int))dlsym(RTLD_NEXT, "linkat");
char obuf[PATH_MAX], nbuf[PATH_MAX];
const char *rold = (oldpath && oldpath[0] == '/') ? rewrite_path(oldpath, obuf, sizeof(obuf)) : oldpath;
const char *rnew = (newpath && newpath[0] == '/') ? rewrite_path(newpath, nbuf, sizeof(nbuf)) : newpath;
int ret = orig_linkat ? orig_linkat(olddirfd, rold, newdirfd, rnew, flags) : -1;
if (ret != 0 && orig_linkat && refused_in_repaired_dir(newdirfd, rnew)) ret = orig_linkat(olddirfd, rold, newdirfd, rnew, flags);
if (ret != 0 && (errno == EXDEV || errno == EPERM || errno == EACCES || errno == ENOTSUP || errno == ENOSYS)) {
ret = ddnatv_emulate_hardlinkat(olddirfd, rold, newdirfd, rnew);
}
return ret;
}
// Hook link
int link(const char *oldpath, const char *newpath) {
return linkat(AT_FDCWD, oldpath, AT_FDCWD, newpath, 0);
}
// Hook utime / utimes / lutimes / futimesat / utimensat
int utime(const char *filename, const struct utimbuf *times) {
static int (*orig_utime)(const char *, const struct utimbuf *) = NULL;
if (!orig_utime) orig_utime = (int (*)(const char *, const struct utimbuf *))dlsym(RTLD_NEXT, "utime");
char buf[PATH_MAX];
const char *target = rewrite_path(filename, buf, sizeof(buf));
return orig_utime ? orig_utime(target, times) : -1;
}
int utimes(const char *filename, const struct timeval times[2]) {
static int (*orig_utimes)(const char *, const struct timeval[2]) = NULL;
if (!orig_utimes) orig_utimes = (int (*)(const char *, const struct timeval[2]))dlsym(RTLD_NEXT, "utimes");
char buf[PATH_MAX];
const char *target = rewrite_path(filename, buf, sizeof(buf));
return orig_utimes ? orig_utimes(target, times) : -1;
}
int lutimes(const char *filename, const struct timeval times[2]) {
static int (*orig_lutimes)(const char *, const struct timeval[2]) = NULL;
if (!orig_lutimes) orig_lutimes = (int (*)(const char *, const struct timeval[2]))dlsym(RTLD_NEXT, "lutimes");
char buf[PATH_MAX];
const char *target = rewrite_path(filename, buf, sizeof(buf));
return orig_lutimes ? orig_lutimes(target, times) : -1;
}
int futimesat(int dirfd, const char *pathname, const struct timeval times[2]) {
static int (*orig_futimesat)(int, const char *, const struct timeval[2]) = NULL;
if (!orig_futimesat) orig_futimesat = (int (*)(int, const char *, const struct timeval[2]))dlsym(RTLD_NEXT, "futimesat");
char buf[PATH_MAX];
const char *target = (pathname && pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname;
return orig_futimesat ? orig_futimesat(dirfd, target, times) : -1;
}
int utimensat(int dirfd, const char *pathname, const struct timespec times[2], int flags) {
static int (*orig_utimensat)(int, const char *, const struct timespec[2], int) = NULL;
if (!orig_utimensat) orig_utimensat = (int (*)(int, const char *, const struct timespec[2], int))dlsym(RTLD_NEXT, "utimensat");
char buf[PATH_MAX];
const char *target = (pathname && pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname;
return orig_utimensat ? orig_utimensat(dirfd, target, times, flags) : -1;
}
// Hook truncate
int truncate(const char *path, off_t length) {
static int (*orig_truncate)(const char *, off_t) = NULL;
if (!orig_truncate) orig_truncate = (int (*)(const char *, off_t))dlsym(RTLD_NEXT, "truncate");
char buf[PATH_MAX];
const char *target = rewrite_path(path, buf, sizeof(buf));
return orig_truncate(target, length);
}
// Hook statfs / statfs64 / statvfs / statvfs64
int statfs(const char *path, struct statfs *buf) {
static int (*orig_statfs)(const char *, struct statfs *) = NULL;
if (!orig_statfs) orig_statfs = (int (*)(const char *, struct statfs *))dlsym(RTLD_NEXT, "statfs");
char pbuf[PATH_MAX];
const char *target = rewrite_path(path, pbuf, sizeof(pbuf));
return orig_statfs ? orig_statfs(target, buf) : -1;
}
int statvfs(const char *path, struct statvfs *buf) {
static int (*orig_statvfs)(const char *, struct statvfs *) = NULL;
if (!orig_statvfs) orig_statvfs = (int (*)(const char *, struct statvfs *))dlsym(RTLD_NEXT, "statvfs");
char pbuf[PATH_MAX];
const char *target = rewrite_path(path, pbuf, sizeof(pbuf));
return orig_statvfs ? orig_statvfs(target, buf) : -1;
}
// Hook chdir
int chdir(const char *path) {
static int (*orig_chdir)(const char *) = NULL;
if (!orig_chdir) orig_chdir = (int (*)(const char *))dlsym(RTLD_NEXT, "chdir");
char buf[PATH_MAX];
const char *target = rewrite_path(path, buf, sizeof(buf));
return orig_chdir ? orig_chdir(target) : -1;
}
// Hook fchdir
int fchdir(int fd) {
static int (*orig_fchdir)(int) = NULL;
if (!orig_fchdir) orig_fchdir = (int (*)(int))dlsym(RTLD_NEXT, "fchdir");
return orig_fchdir ? orig_fchdir(fd) : -1;
}
// Hook getcwd
char *getcwd(char *buf, size_t size) {
static char *(*orig_getcwd)(char *, size_t) = NULL;
if (!orig_getcwd) orig_getcwd = (char *(*)(char *, size_t))dlsym(RTLD_NEXT, "getcwd");
return orig_getcwd ? orig_getcwd(buf, size) : NULL;
}
char *__getcwd_chk(char *buf, size_t size, size_t buflen) {
return getcwd(buf, size);
}
// Hook realpath and canonicalize_file_name
char *realpath(const char *path, char *resolved_path) {
static char *(*orig_realpath)(const char *, char *) = NULL;
if (!orig_realpath) orig_realpath = (char *(*)(const char *, char *))dlsym(RTLD_NEXT, "realpath");
if (!path) {
errno = EINVAL;
return NULL;
}
init_ddnatv_hook();
if (is_proc_self_exe(path)) {
char tmp[PATH_MAX];
ssize_t n = handle_proc_self_exe(tmp, sizeof(tmp) - 1);
if (n > 0) {
tmp[n] = '\0';
if (resolved_path) {
strncpy(resolved_path, tmp, PATH_MAX - 1);
resolved_path[PATH_MAX - 1] = '\0';
return resolved_path;
} else {
return strdup(tmp);
}
}
}
char pbuf[PATH_MAX];
const char *target = rewrite_path(path, pbuf, sizeof(pbuf));
char *res = orig_realpath ? orig_realpath(target, resolved_path) : NULL;
if (res && g_ddnatv_root[0] != '\0') {
size_t rlen = g_ddnatv_root_len;
if (strncmp(res, g_ddnatv_root, rlen) == 0 && (res[rlen] == '/' || res[rlen] == '\0')) {
size_t rem_len = strlen(res + rlen);
if (rem_len == 0) {
res[0] = '/';
res[1] = '\0';
} else {
memmove(res, res + rlen, rem_len + 1);
}
}
}
return res;
}
char *__realpath_chk(const char *path, char *resolved_path, size_t resolved_len) {
return realpath(path, resolved_path);
}
char *canonicalize_file_name(const char *path) {
return realpath(path, NULL);
}
// Hook scandir and scandir64
int scandir(const char *dirp, struct dirent ***namelist,
int (*filter)(const struct dirent *),
int (*compar)(const struct dirent **, const struct dirent **)) {
static int (*orig_scandir)(const char *, struct dirent ***,
int (*)(const struct dirent *),
int (*)(const struct dirent **, const struct dirent **)) = NULL;
if (!orig_scandir) orig_scandir = (int (*)(const char *, struct dirent ***,
int (*)(const struct dirent *),
int (*)(const struct dirent **, const struct dirent **)))dlsym(RTLD_NEXT, "scandir");
char buf[PATH_MAX];
const char *target = rewrite_path(dirp, buf, sizeof(buf));
return orig_scandir ? orig_scandir(target, namelist, filter, compar) : -1;
}
#if defined(__LP64__)
// Export 64-bit Large File Support (LFS) symbol aliases on 64-bit platforms so that
// calls from libraries compiled with LFS (such as libstdc++ calling fopen64) are intercepted.
__asm__(
".globl open64\n" ".set open64, open\n"
".globl openat64\n" ".set openat64, openat\n"
".globl __open64_2\n" ".set __open64_2, __open_2\n"
".globl __openat64_2\n" ".set __openat64_2, __openat_2\n"
".globl creat64\n" ".set creat64, creat\n"
".globl fopen64\n" ".set fopen64, fopen\n"
".globl freopen64\n" ".set freopen64, freopen\n"
".globl stat64\n" ".set stat64, stat\n"
".globl lstat64\n" ".set lstat64, lstat\n"
".globl fstatat64\n" ".set fstatat64, fstatat\n"
".globl truncate64\n" ".set truncate64, truncate\n"
".globl statfs64\n" ".set statfs64, statfs\n"
".globl statvfs64\n" ".set statvfs64, statvfs\n"
".globl scandir64\n" ".set scandir64, scandir\n"
".globl mkstemp64\n" ".set mkstemp64, mkstemp\n"
".globl mkostemp64\n" ".set mkostemp64, mkostemp\n"
".globl mkstemps64\n" ".set mkstemps64, mkstemps\n"
".globl mkostemps64\n" ".set mkostemps64, mkostemps\n"
".globl tmpfile64\n" ".set tmpfile64, tmpfile\n"
);
#endif
#endif /* !DDNATV_HOST_TEST */
+650
View File
@@ -0,0 +1,650 @@
// Part of libddnatv-hook.so, included by ddnatv-hook.c (one translation unit, so the
// parts share their static functions and are built with the same command as before).
//
// Opening, creating and inspecting files: open, fopen, temporary files, directories, the stat family.
#ifndef DDNATV_HOST_TEST
#ifndef O_TMPFILE
#define O_TMPFILE (020000000 | 00200000)
#endif
static inline int open_needs_mode(int flags) {
#ifdef O_TMPFILE
return ((flags & O_CREAT) != 0) || ((flags & O_TMPFILE) == O_TMPFILE);
#else
return (flags & O_CREAT) != 0;
#endif
}
// The app is root for the programs it runs, and root puts names in every directory and takes them out
// whatever the mode of the directory; the app does not. A directory that is the app's own can have lost
// its owner's rights: an earlier version left the directories dpkg makes (with mode 0) at mode 0 when the
// chmod that follows did not take effect, and a package can ship a read-only one (#44). When a call that
// makes or removes a name is refused in such a directory, the directory is given its owner's rights and the
// call is made once more. Returns 1 when the directory was repaired (the call can be made again).
static int give_dir_owner_rights(int dirfd, const char *name) {
static int (*orig_fchmodat)(int, const char *, mode_t, int) = NULL;
if (!name || !*name) return 0;
char parent[PATH_MAX];
size_t len = strlen(name);
if (len >= sizeof(parent)) return 0;
memcpy(parent, name, len + 1);
while (len > 1 && parent[len - 1] == '/') parent[--len] = '\0';
char *slash = strrchr(parent, '/');
if (!slash) {
strcpy(parent, ".");
} else if (slash == parent) {
parent[1] = '\0';
} else {
*slash = '\0';
}
struct stat st;
if (real_fstatat(dirfd, parent, &st, 0) != 0 || !S_ISDIR(st.st_mode)) return 0;
if (__atomic_load_n(&g_app_uid, __ATOMIC_RELAXED) == (uid_t)-1) load_app_ids();
if (st.st_uid != __atomic_load_n(&g_app_uid, __ATOMIC_RELAXED)) return 0;
if ((st.st_mode & 0700) == 0700) return 0;
if (!orig_fchmodat) orig_fchmodat = (int (*)(int, const char *, mode_t, int))dlsym(RTLD_NEXT, "fchmodat");
return orig_fchmodat && orig_fchmodat(dirfd, parent, (st.st_mode | 0700) & 07777, 0) == 0;
}
// For the calls that were refused (EACCES): whether the directory of `name` was repaired, so that the call
// can be made again. errno stays what the call left when it was not.
static int refused_in_repaired_dir(int dirfd, const char *name) {
if (errno != EACCES) return 0;
int saved = errno;
int fixed = give_dir_owner_rights(dirfd, name);
if (!fixed) errno = saved;
return fixed;
}
static int dlopen_preload_deps(const char *path, void *(*orig_dlopen)(const char *, int), int depth);
// Hook dlopen and dlmopen
void *dlopen(const char *filename, int flags) {
static void *(*orig_dlopen)(const char *, int) = NULL;
if (!orig_dlopen) orig_dlopen = (void *(*)(const char *, int))dlsym(RTLD_NEXT, "dlopen");
if (!filename) return orig_dlopen ? orig_dlopen(NULL, flags) : NULL;
if (!orig_dlopen) return NULL;
char buf[PATH_MAX];
const char *target = rewrite_path(filename, buf, sizeof(buf));
void *handle = orig_dlopen(target, flags);
if (!handle && target[0] == '/' && !(flags & RTLD_NOLOAD)) {
// Its dependencies may be in its RUNPATH, which ld.so looked for outside the rootfs
int saved = errno;
if (dlopen_preload_deps(target, orig_dlopen, 0) > 0) handle = orig_dlopen(target, flags);
if (!handle) errno = saved;
}
return handle;
}
void *dlmopen(Lmid_t lmid, const char *filename, int flags) {
static void *(*orig_dlmopen)(Lmid_t, const char *, int) = NULL;
if (!orig_dlmopen) orig_dlmopen = (void *(*)(Lmid_t, const char *, int))dlsym(RTLD_NEXT, "dlmopen");
if (!filename) return orig_dlmopen ? orig_dlmopen(lmid, NULL, flags) : NULL;
char buf[PATH_MAX];
const char *target = rewrite_path(filename, buf, sizeof(buf));
return orig_dlmopen ? orig_dlmopen(lmid, target, flags) : NULL;
}
// Hook open
int open(const char *pathname, int flags, ...) {
static int (*orig_open)(const char *, int, ...) = NULL;
if (!orig_open) orig_open = (int (*)(const char *, int, ...))dlsym(RTLD_NEXT, "open");
init_ddnatv_hook();
char exe_buf[PATH_MAX];
if (is_proc_self_exe(pathname)) {
if (g_real_exe[0] != '\0') {
pathname = g_real_exe;
} else if (handle_proc_self_exe(exe_buf, sizeof(exe_buf)) > 0) {
pathname = exe_buf;
}
}
char buf[PATH_MAX];
const char *target = rewrite_path(pathname, buf, sizeof(buf));
if (open_needs_mode(flags)) {
va_list args;
va_start(args, flags);
mode_t mode = va_arg(args, mode_t);
va_end(args);
int fd = orig_open(target, flags, mode);
if (fd < 0 && (flags & O_CREAT) && refused_in_repaired_dir(AT_FDCWD, target)) fd = orig_open(target, flags, mode);
return fd;
}
return orig_open(target, flags);
}
// Hook openat
int openat(int dirfd, const char *pathname, int flags, ...) {
static int (*orig_openat)(int, const char *, int, ...) = NULL;
if (!orig_openat) orig_openat = (int (*)(int, const char *, int, ...))dlsym(RTLD_NEXT, "openat");
init_ddnatv_hook();
char exe_buf[PATH_MAX];
if (is_proc_self_exe(pathname)) {
if (g_real_exe[0] != '\0') {
pathname = g_real_exe;
} else if (handle_proc_self_exe(exe_buf, sizeof(exe_buf)) > 0) {
pathname = exe_buf;
}
}
char buf[PATH_MAX];
const char *target = (pathname && pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname;
if (open_needs_mode(flags)) {
va_list args;
va_start(args, flags);
mode_t mode = va_arg(args, mode_t);
va_end(args);
int fd = orig_openat(dirfd, target, flags, mode);
if (fd < 0 && (flags & O_CREAT) && refused_in_repaired_dir(dirfd, target)) fd = orig_openat(dirfd, target, flags, mode);
return fd;
}
return orig_openat(dirfd, target, flags);
}
// Hook creat
int creat(const char *pathname, mode_t mode) {
return open(pathname, O_CREAT | O_WRONLY | O_TRUNC, mode);
}
// Fortified open variants used by GNU tar and other coreutils compiled with _FORTIFY_SOURCE=2/3
int __open_2(const char *pathname, int flags) {
return open(pathname, flags);
}
int __openat_2(int dirfd, const char *pathname, int flags) {
return openat(dirfd, pathname, flags);
}
// openat2/open_how local definition: avoids depending on <linux/openat2.h>,
// which old NDK/cross headers may lack. Layout matches UAPI ver0
// (flags, mode, resolve = 3 x __u64); extra fields are never read here.
struct ddnatv_open_how {
uint64_t flags;
uint64_t mode;
uint64_t resolve;
};
#ifndef RESOLVE_BENEATH
#define RESOLVE_BENEATH 0x08
#endif
#ifndef __NR_openat2
#define __NR_openat2 437
#endif
#ifndef __NR_fchmodat2
#define __NR_fchmodat2 452
#endif
static long call_orig_syscall(long number, unsigned long a1, unsigned long a2, unsigned long a3, unsigned long a4, unsigned long a5, unsigned long a6) {
static long (*orig_syscall)(long, unsigned long, unsigned long, unsigned long, unsigned long, unsigned long, unsigned long) = NULL;
if (!orig_syscall) {
orig_syscall = (long (*)(long, unsigned long, unsigned long, unsigned long, unsigned long, unsigned long, unsigned long))dlsym(RTLD_NEXT, "syscall");
}
return orig_syscall ? orig_syscall(number, a1, a2, a3, a4, a5, a6) : syscall(number, a1, a2, a3, a4, a5, a6);
}
// Hook openat2 (used by GNU tar 1.35+/gnulib for RESOLVE_BENEATH traversal).
// Rewrites absolute paths like openat, then delegates; on ENOSYS (kernels
// without openat2, e.g. Android < 5.6) emulates with plain openat instead of
// trusting every caller to implement the fallback itself.
int openat2(int dirfd, const char *pathname, struct ddnatv_open_how *how, size_t usize) {
static int (*orig_openat2)(int, const char *, struct ddnatv_open_how *, size_t) = NULL;
if (!orig_openat2) orig_openat2 = (int (*)(int, const char *, struct ddnatv_open_how *, size_t))dlsym(RTLD_NEXT, "openat2");
if (!pathname) {
errno = EFAULT;
return -1;
}
char exe_buf[PATH_MAX];
if (is_proc_self_exe(pathname)) {
if (g_real_exe[0] != '\0') {
pathname = g_real_exe;
} else if (handle_proc_self_exe(exe_buf, sizeof(exe_buf)) > 0) {
pathname = exe_buf;
}
}
char buf[PATH_MAX];
const char *target = (pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname;
if (orig_openat2) {
int ret = orig_openat2(dirfd, target, how, usize);
if (ret >= 0 || errno != ENOSYS) return ret;
}
#ifdef __NR_openat2
long sret = call_orig_syscall(__NR_openat2, (unsigned long)dirfd, (unsigned long)target, (unsigned long)how, (unsigned long)usize, 0, 0);
if (sret >= 0 || errno != ENOSYS) {
return (int)sret;
}
#endif
if (!how || usize < 16) {
errno = EINVAL;
return -1;
}
int flags = (int)(how->flags & 0xffffffffu);
mode_t mode = (mode_t)(how->mode & 07777u);
// RESOLVE_BENEATH, RESOLVE_NO_SYMLINKS and the other resolve flags restrict every component of
// the path, which a plain openat() cannot do (a symlink in the middle would still be followed).
// Say so: callers such as gnulib's openat2 (GNU tar) then walk the path safely themselves.
if (how->resolve != 0) {
errno = ENOSYS;
return -1;
}
if (open_needs_mode(flags)) {
return openat(dirfd, target, flags, mode);
}
return openat(dirfd, target, flags);
}
// Hook fchmodat2 (used by GNU tar for lchmod-style symlink chmod).
// Delegates when the libc symbol exists, otherwise emulates: symlinks cannot
// be chmod'ed without kernel support, so skip them (return 0) like gnulib,
// and route everything else through fchmodat.
int fchmodat2(int dirfd, const char *pathname, mode_t mode, int flags) {
static int (*orig_fchmodat2)(int, const char *, mode_t, int) = NULL;
if (!orig_fchmodat2) orig_fchmodat2 = (int (*)(int, const char *, mode_t, int))dlsym(RTLD_NEXT, "fchmodat2");
if (!pathname) {
errno = EFAULT;
return -1;
}
char buf[PATH_MAX];
const char *target = (pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname;
if (orig_fchmodat2) {
int ret = orig_fchmodat2(dirfd, target, mode, flags);
if (ret == 0 || errno != ENOSYS) return ret;
}
if ((flags & AT_SYMLINK_NOFOLLOW) != 0) {
struct stat st;
if (fstatat(dirfd, target, &st, AT_SYMLINK_NOFOLLOW) == 0 && S_ISLNK(st.st_mode)) {
return 0;
}
}
return fchmodat(dirfd, target, mode, 0);
}
// Hook fopen
FILE *fopen(const char *pathname, const char *mode) {
static FILE *(*orig_fopen)(const char *, const char *) = NULL;
if (!orig_fopen) orig_fopen = (FILE *(*)(const char *, const char *))dlsym(RTLD_NEXT, "fopen");
char buf[PATH_MAX];
const char *target = rewrite_path(pathname, buf, sizeof(buf));
return orig_fopen(target, mode);
}
// Hook freopen
FILE *freopen(const char *pathname, const char *mode, FILE *stream) {
static FILE *(*orig_freopen)(const char *, const char *, FILE *) = NULL;
if (!orig_freopen) orig_freopen = (FILE *(*)(const char *, const char *, FILE *))dlsym(RTLD_NEXT, "freopen");
char buf[PATH_MAX];
const char *target = rewrite_path(pathname, buf, sizeof(buf));
return orig_freopen(target, mode, stream);
}
// Hook write
ssize_t write(int fd, const void *buf, size_t count) {
static ssize_t (*orig_write)(int, const void *, size_t) = NULL;
if (!orig_write) orig_write = (ssize_t (*)(int, const void *, size_t))dlsym(RTLD_NEXT, "write");
return orig_write ? orig_write(fd, buf, count) : -1;
}
// Hook mkstemp
int mkstemp(char *template) {
static int (*orig_mkstemp)(char *) = NULL;
if (!orig_mkstemp) orig_mkstemp = (int (*)(char *))dlsym(RTLD_NEXT, "mkstemp");
if (!template) { errno = EINVAL; return -1; }
char buf[PATH_MAX];
const char *target = rewrite_path(template, buf, sizeof(buf));
if (target == template) {
return orig_mkstemp ? orig_mkstemp(template) : -1;
}
char tmp_buf[PATH_MAX];
strncpy(tmp_buf, target, sizeof(tmp_buf) - 1);
tmp_buf[sizeof(tmp_buf) - 1] = '\0';
int fd = orig_mkstemp ? orig_mkstemp(tmp_buf) : -1;
if (fd >= 0) {
size_t orig_len = strlen(template);
size_t tmp_len = strlen(tmp_buf);
if (orig_len >= 6 && tmp_len >= 6) {
memcpy(template + orig_len - 6, tmp_buf + tmp_len - 6, 6);
}
}
return fd;
}
// Hook mkostemp
int mkostemp(char *template, int flags) {
static int (*orig_mkostemp)(char *, int) = NULL;
if (!orig_mkostemp) orig_mkostemp = (int (*)(char *, int))dlsym(RTLD_NEXT, "mkostemp");
if (!template) { errno = EINVAL; return -1; }
char buf[PATH_MAX];
const char *target = rewrite_path(template, buf, sizeof(buf));
if (target == template) {
return orig_mkostemp ? orig_mkostemp(template, flags) : -1;
}
char tmp_buf[PATH_MAX];
strncpy(tmp_buf, target, sizeof(tmp_buf) - 1);
tmp_buf[sizeof(tmp_buf) - 1] = '\0';
int fd = orig_mkostemp ? orig_mkostemp(tmp_buf, flags) : -1;
if (fd >= 0) {
size_t orig_len = strlen(template);
size_t tmp_len = strlen(tmp_buf);
if (orig_len >= 6 && tmp_len >= 6) {
memcpy(template + orig_len - 6, tmp_buf + tmp_len - 6, 6);
}
}
return fd;
}
// Hook mkstemps
int mkstemps(char *template, int suffixlen) {
static int (*orig_mkstemps)(char *, int) = NULL;
if (!orig_mkstemps) orig_mkstemps = (int (*)(char *, int))dlsym(RTLD_NEXT, "mkstemps");
if (!template) { errno = EINVAL; return -1; }
char buf[PATH_MAX];
const char *target = rewrite_path(template, buf, sizeof(buf));
if (target == template) {
return orig_mkstemps ? orig_mkstemps(template, suffixlen) : -1;
}
char tmp_buf[PATH_MAX];
strncpy(tmp_buf, target, sizeof(tmp_buf) - 1);
tmp_buf[sizeof(tmp_buf) - 1] = '\0';
int fd = orig_mkstemps ? orig_mkstemps(tmp_buf, suffixlen) : -1;
if (fd >= 0) {
size_t orig_len = strlen(template);
size_t tmp_len = strlen(tmp_buf);
if (orig_len >= (size_t)(suffixlen + 6) && tmp_len >= (size_t)(suffixlen + 6)) {
memcpy(template + orig_len - suffixlen - 6, tmp_buf + tmp_len - suffixlen - 6, 6);
}
}
return fd;
}
// Hook mkostemps
int mkostemps(char *template, int suffixlen, int flags) {
static int (*orig_mkostemps)(char *, int, int) = NULL;
if (!orig_mkostemps) orig_mkostemps = (int (*)(char *, int, int))dlsym(RTLD_NEXT, "mkostemps");
if (!template) { errno = EINVAL; return -1; }
char buf[PATH_MAX];
const char *target = rewrite_path(template, buf, sizeof(buf));
if (target == template) {
return orig_mkostemps ? orig_mkostemps(template, suffixlen, flags) : -1;
}
char tmp_buf[PATH_MAX];
strncpy(tmp_buf, target, sizeof(tmp_buf) - 1);
tmp_buf[sizeof(tmp_buf) - 1] = '\0';
int fd = orig_mkostemps ? orig_mkostemps(tmp_buf, suffixlen, flags) : -1;
if (fd >= 0) {
size_t orig_len = strlen(template);
size_t tmp_len = strlen(tmp_buf);
if (orig_len >= (size_t)(suffixlen + 6) && tmp_len >= (size_t)(suffixlen + 6)) {
memcpy(template + orig_len - suffixlen - 6, tmp_buf + tmp_len - suffixlen - 6, 6);
}
}
return fd;
}
// Hook mkdtemp
char *mkdtemp(char *template) {
static char *(*orig_mkdtemp)(char *) = NULL;
if (!orig_mkdtemp) orig_mkdtemp = (char *(*)(char *))dlsym(RTLD_NEXT, "mkdtemp");
if (!template) { errno = EINVAL; return NULL; }
char buf[PATH_MAX];
const char *target = rewrite_path(template, buf, sizeof(buf));
if (target == template) {
return orig_mkdtemp ? orig_mkdtemp(template) : NULL;
}
char tmp_buf[PATH_MAX];
strncpy(tmp_buf, target, sizeof(tmp_buf) - 1);
tmp_buf[sizeof(tmp_buf) - 1] = '\0';
char *res = orig_mkdtemp ? orig_mkdtemp(tmp_buf) : NULL;
if (res) {
size_t orig_len = strlen(template);
size_t tmp_len = strlen(tmp_buf);
if (orig_len >= 6 && tmp_len >= 6) {
memcpy(template + orig_len - 6, tmp_buf + tmp_len - 6, 6);
}
return template;
}
return NULL;
}
// Hook tmpfile
FILE *tmpfile(void) {
init_ddnatv_hook();
char template_buf[PATH_MAX];
if (g_ddnatv_root[0] != '\0') {
snprintf(template_buf, sizeof(template_buf), "%s/tmp/tmpfile.XXXXXX", g_ddnatv_root);
} else {
snprintf(template_buf, sizeof(template_buf), "/tmp/tmpfile.XXXXXX");
}
int fd = mkstemp(template_buf);
if (fd < 0) return NULL;
unlink(template_buf);
FILE *f = fdopen(fd, "w+b");
if (!f) {
int saved_errno = errno;
close(fd);
errno = saved_errno;
}
return f;
}
#ifndef __USE_FILE_OFFSET64
// Programs built with _LARGEFILE64_SOURCE call this name. With _FILE_OFFSET_BITS=64 (the 32-bit ARM
// build) the headers already export the definition above as tmpfile64.
FILE *tmpfile64(void) {
return tmpfile();
}
#endif
// Hook opendir
DIR *opendir(const char *name) {
static DIR *(*orig_opendir)(const char *) = NULL;
if (!orig_opendir) orig_opendir = (DIR *(*)(const char *))dlsym(RTLD_NEXT, "opendir");
char buf[PATH_MAX];
const char *target = rewrite_path(name, buf, sizeof(buf));
return orig_opendir(target);
}
// Hook stat
int stat(const char *pathname, struct stat *statbuf) {
static int (*orig_stat)(const char *, struct stat *) = NULL;
if (!orig_stat) orig_stat = (int (*)(const char *, struct stat *))dlsym(RTLD_NEXT, "stat");
char buf[PATH_MAX];
const char *target = rewrite_path(pathname, buf, sizeof(buf));
int ret = orig_stat ? orig_stat(target, statbuf) : -1;
if (ret != 0 && errno == ENOENT) {
char alt[PATH_MAX];
const char *retry = usrmerge_retry_path(target, alt, sizeof(alt));
if (retry) ret = orig_stat(retry, statbuf);
}
if (ret == 0) apply_stat_emulation(statbuf);
return ret;
}
// Hook lstat
int lstat(const char *pathname, struct stat *statbuf) {
static int (*orig_lstat)(const char *, struct stat *) = NULL;
if (!orig_lstat) orig_lstat = (int (*)(const char *, struct stat *))dlsym(RTLD_NEXT, "lstat");
char buf[PATH_MAX];
const char *target = rewrite_path(pathname, buf, sizeof(buf));
int ret = orig_lstat ? orig_lstat(target, statbuf) : -1;
char alt[PATH_MAX];
if (ret != 0 && errno == ENOENT) {
const char *retry = usrmerge_retry_path(target, alt, sizeof(alt));
if (retry) {
ret = orig_lstat(retry, statbuf);
if (ret == 0) target = retry;
}
}
if (ret == 0 && statbuf && S_ISLNK(statbuf->st_mode) && g_ddnatv_root[0] != '\0' && target &&
readlink_result_may_change(pathname, (long long)statbuf->st_size)) {
char link_buf[PATH_MAX];
static ssize_t (*orig_readlink)(const char *, char *, size_t) = NULL;
if (!orig_readlink) orig_readlink = (ssize_t (*)(const char *, char *, size_t))dlsym(RTLD_NEXT, "readlink");
ssize_t llen = orig_readlink ? orig_readlink(target, link_buf, sizeof(link_buf) - 1) : -1;
if (llen > 0) {
ssize_t post_len = postprocess_readlink(pathname, link_buf, llen, sizeof(link_buf));
if (post_len > 0) {
statbuf->st_size = post_len;
}
}
}
if (ret == 0) apply_stat_emulation(statbuf);
return ret;
}
// Hook fstatat
int fstatat(int dirfd, const char *pathname, struct stat *statbuf, int flags) {
static int (*orig_fstatat)(int, const char *, struct stat *, int) = NULL;
if (!orig_fstatat) orig_fstatat = (int (*)(int, const char *, struct stat *, int))dlsym(RTLD_NEXT, "fstatat");
char buf[PATH_MAX];
const char *target = (pathname && pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname;
int ret = orig_fstatat ? orig_fstatat(dirfd, target, statbuf, flags) : -1;
char alt[PATH_MAX];
if (ret != 0 && errno == ENOENT && pathname && pathname[0] == '/') {
const char *retry = usrmerge_retry_path(target, alt, sizeof(alt));
if (retry) {
ret = orig_fstatat(dirfd, retry, statbuf, flags);
if (ret == 0) target = retry;
}
}
if (ret == 0 && statbuf && (flags & AT_SYMLINK_NOFOLLOW) && S_ISLNK(statbuf->st_mode) && g_ddnatv_root[0] != '\0' && target &&
readlink_result_may_change(pathname, (long long)statbuf->st_size)) {
char link_buf[PATH_MAX];
static ssize_t (*orig_readlinkat)(int, const char *, char *, size_t) = NULL;
if (!orig_readlinkat) orig_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat");
ssize_t llen = orig_readlinkat ? orig_readlinkat(dirfd, target, link_buf, sizeof(link_buf) - 1) : -1;
if (llen > 0) {
ssize_t post_len = postprocess_readlink(pathname, link_buf, llen, sizeof(link_buf));
if (post_len > 0) {
statbuf->st_size = post_len;
}
}
}
if (ret == 0) apply_stat_emulation(statbuf);
return ret;
}
// Hook fstat
int fstat(int fd, struct stat *statbuf) {
static int (*orig_fstat)(int, struct stat *) = NULL;
if (!orig_fstat) orig_fstat = (int (*)(int, struct stat *))dlsym(RTLD_NEXT, "fstat");
int ret = orig_fstat ? orig_fstat(fd, statbuf) : -1;
if (ret == 0) apply_stat_emulation(statbuf);
return ret;
}
// Glibc __xstat compatibility hooks
int __xstat(int ver, const char *pathname, struct stat *statbuf) {
static int (*orig___xstat)(int, const char *, struct stat *) = NULL;
if (!orig___xstat) orig___xstat = (int (*)(int, const char *, struct stat *))dlsym(RTLD_NEXT, "__xstat");
char buf[PATH_MAX];
const char *target = rewrite_path(pathname, buf, sizeof(buf));
return orig___xstat ? orig___xstat(ver, target, statbuf) : stat(target, statbuf);
}
int __xstat64(int ver, const char *pathname, struct stat64 *statbuf) {
static int (*orig___xstat64)(int, const char *, struct stat64 *) = NULL;
if (!orig___xstat64) orig___xstat64 = (int (*)(int, const char *, struct stat64 *))dlsym(RTLD_NEXT, "__xstat64");
char buf[PATH_MAX];
const char *target = rewrite_path(pathname, buf, sizeof(buf));
return orig___xstat64 ? orig___xstat64(ver, target, statbuf) : stat(target, (struct stat *)statbuf);
}
int __lxstat(int ver, const char *pathname, struct stat *statbuf) {
static int (*orig___lxstat)(int, const char *, struct stat *) = NULL;
if (!orig___lxstat) orig___lxstat = (int (*)(int, const char *, struct stat *))dlsym(RTLD_NEXT, "__lxstat");
char buf[PATH_MAX];
const char *target = rewrite_path(pathname, buf, sizeof(buf));
return orig___lxstat ? orig___lxstat(ver, target, statbuf) : lstat(target, statbuf);
}
int __lxstat64(int ver, const char *pathname, struct stat64 *statbuf) {
static int (*orig___lxstat64)(int, const char *, struct stat64 *) = NULL;
if (!orig___lxstat64) orig___lxstat64 = (int (*)(int, const char *, struct stat64 *))dlsym(RTLD_NEXT, "__lxstat64");
char buf[PATH_MAX];
const char *target = rewrite_path(pathname, buf, sizeof(buf));
return orig___lxstat64 ? orig___lxstat64(ver, target, statbuf) : lstat(target, (struct stat *)statbuf);
}
int __fxstatat(int ver, int dirfd, const char *pathname, struct stat *statbuf, int flags) {
static int (*orig___fxstatat)(int, int, const char *, struct stat *, int) = NULL;
if (!orig___fxstatat) orig___fxstatat = (int (*)(int, int, const char *, struct stat *, int))dlsym(RTLD_NEXT, "__fxstatat");
char buf[PATH_MAX];
const char *target = (pathname && pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname;
return orig___fxstatat ? orig___fxstatat(ver, dirfd, target, statbuf, flags) : fstatat(dirfd, target, statbuf, flags);
}
int __fxstatat64(int ver, int dirfd, const char *pathname, struct stat64 *statbuf, int flags) {
static int (*orig___fxstatat64)(int, int, const char *, struct stat64 *, int) = NULL;
if (!orig___fxstatat64) orig___fxstatat64 = (int (*)(int, int, const char *, struct stat64 *, int))dlsym(RTLD_NEXT, "__fxstatat64");
char buf[PATH_MAX];
const char *target = (pathname && pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname;
return orig___fxstatat64 ? orig___fxstatat64(ver, dirfd, target, statbuf, flags) : fstatat(dirfd, target, (struct stat *)statbuf, flags);
}
// Hook statx
int statx(int dirfd, const char *pathname, int flags, unsigned int mask, struct statx *statxbuf) {
// Rust's standard library asks whether statx exists by calling it with a NULL path and buffer
// (EFAULT means it does). glibc's header declares both as nonnull, so the compiler would drop
// the NULL check below and read the path: every Rust program (rg, rustc, cargo...) crashed.
__asm__ volatile("" : "+r"(pathname), "+r"(statxbuf));
static int (*orig_statx)(int, const char *, int, unsigned int, struct statx *) = NULL;
if (!orig_statx) orig_statx = (int (*)(int, const char *, int, unsigned int, struct statx *))dlsym(RTLD_NEXT, "statx");
char buf[PATH_MAX];
const char *target = (pathname && pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname;
int ret = orig_statx ? orig_statx(dirfd, target, flags, mask, statxbuf) : -1;
if (ret == 0 && statxbuf && hardlinks_maybe_any()) {
const unsigned int needed = STATX_INO | STATX_NLINK | STATX_MTIME;
struct statx full;
const struct statx *sx = statxbuf;
if ((statxbuf->stx_mask & needed) != needed) {
// The caller asked for less ("stat -c %h" for the link count only): what an emulated
// link is recognized by
int saved_errno = errno;
sx = orig_statx(dirfd, target, flags, needed, &full) == 0 && (full.stx_mask & needed) == needed ? &full : NULL;
errno = saved_errno;
}
if (sx) {
struct stat st;
memset(&st, 0, sizeof(st));
st.st_dev = makedev(sx->stx_dev_major, sx->stx_dev_minor);
st.st_ino = sx->stx_ino;
st.st_nlink = sx->stx_nlink;
st.st_mtim.tv_sec = sx->stx_mtime.tv_sec;
st.st_mtim.tv_nsec = sx->stx_mtime.tv_nsec;
apply_emulated_hardlink(&st);
if (st.st_ino != sx->stx_ino || st.st_nlink != sx->stx_nlink) {
statxbuf->stx_ino = st.st_ino;
statxbuf->stx_nlink = st.st_nlink;
statxbuf->stx_mask |= STATX_INO | STATX_NLINK;
}
}
}
if (ret == 0 && statxbuf) {
uid_t uid = (uid_t)statxbuf->stx_uid;
gid_t gid = (gid_t)statxbuf->stx_gid;
present_owner_as_root((statxbuf->stx_mask & STATX_UID) ? &uid : NULL, (statxbuf->stx_mask & STATX_GID) ? &gid : NULL);
statxbuf->stx_uid = (uint32_t)uid;
statxbuf->stx_gid = (uint32_t)gid;
}
return ret;
}
#endif /* !DDNATV_HOST_TEST */
+465
View File
@@ -0,0 +1,465 @@
// Part of libddnatv-hook.so, included by ddnatv-hook.c (one translation unit, so the
// parts share their static functions and are built with the same command as before).
//
// Static Go programs: they make their system calls themselves, so Ubuntu's paths mean nothing to
// them. The code of gosys/gosys.c is added to their file.
// ---- Static Go programs -------------------------------------------------------------------
// A Go program built without cgo (all of Ubuntu's, and the single files downloaded from a project's
// releases) has no C library: the preloaded hook is never loaded into it, so "/etc/resolv.conf" is
// a file of Android's that does not exist, and so is every program it starts. Go makes all of its
// system calls but a few of its runtime's in one assembly function, internal/runtime/syscall.
// Syscall6, which loads the number and the arguments from the stack and executes "svc #0".
//
// Before such a program (AArch64, Go 1.19 or newer) starts, The native userland changes its file in place, once:
// - the code of gosys/gosys.c is put after the program's code, in the zero padding that the Go
// linker leaves between its segments (the segment is made longer, and executable if it only
// was readable),
// - zero-filled memory for it is added to the end of the program's data segment,
// - the "svc #0" of Syscall6 becomes a branch to a few instructions in that code, which call it
// and go back to the instruction after the "svc".
// The code maps the paths of the calls into the rootfs, as the hook does for C programs, and starts
// the programs of the rootfs through the hook. The file keeps its size, its times and its mode;
// only the program headers, the padding and one instruction differ. The file is changed back and
// patched again when the code of a newer The native userland differs (the trailer says what to undo).
#ifdef DDNATV_HAVE_GOSYS
#define GO_MAX_PH 32
#define GO_PF_X 1u
#define GO_PF_W 2u
#define GO_ET_EXEC 2
#define GO_ET_DYN 3
struct go_ph {
uint32_t type, flags;
uint64_t offset, vaddr, filesz, memsz;
uint64_t pos; // where the entry is in the file
};
static uint64_t go_rd64(const unsigned char *p) { return (uint64_t)rd32(p) | ((uint64_t)rd32(p + 4) << 32); }
static void go_wr64(unsigned char *p, uint64_t v) { wr32(p, (uint32_t)v); wr32(p + 4, (uint32_t)(v >> 32)); }
// The program headers of a 64-bit little-endian ELF; their number, or -1
static int go_read_phdrs(int fd, struct go_ph *ph, uint16_t *etype, uint16_t *machine) {
unsigned char eh[64];
if (pread(fd, eh, sizeof(eh), 0) != (ssize_t)sizeof(eh) || memcmp(eh, "\x7f" "ELF", 4) != 0 || eh[4] != 2 || eh[5] != 1)
return -1;
*etype = rd16(eh + 16);
*machine = rd16(eh + 18);
uint64_t phoff = go_rd64(eh + 32);
uint16_t phentsize = rd16(eh + 54), phnum = rd16(eh + 56);
if (phentsize != 56 || phnum == 0 || phnum > GO_MAX_PH) return -1;
for (int i = 0; i < phnum; i++) {
unsigned char e[56];
uint64_t pos = phoff + (uint64_t)i * 56;
if (pread(fd, e, sizeof(e), (off_t)pos) != (ssize_t)sizeof(e)) return -1;
ph[i].type = rd32(e);
ph[i].flags = rd32(e + 4);
ph[i].offset = go_rd64(e + 8);
ph[i].vaddr = go_rd64(e + 16);
ph[i].filesz = go_rd64(e + 32);
ph[i].memsz = go_rd64(e + 40);
ph[i].pos = pos;
}
return phnum;
}
// The instructions of Syscall6 up to its system call: x8 and x0 to x5 loaded from the stack
// (ldr x8, [sp, #8]; ldr x0, [sp, #16] ... ldr x5, [sp, #56]), then "svc #0" and "cmn x0, #4095"
static const uint32_t k_go_syscall6[7] = {
0xf94007e8u, 0xf9400be0u, 0xf9400fe1u, 0xf94013e2u, 0xf94017e3u, 0xf9401be4u, 0xf9401fe5u,
};
#define GO_SVC 0xd4000001u
#define GO_CMN_X0_4095 0xb13ffc1fu
// Where Syscall6 makes its call: the file offset of the instruction after the seven loads (the
// "svc #0", or the branch that replaced it). *found counts the places; the first is returned.
static int64_t go_find_syscall6(int fd, const struct go_ph *ph, int n, int *found) {
int64_t first = -1;
*found = 0;
enum { CHUNK = 1 << 20, KEEP = 36 };
unsigned char *buf = (unsigned char *)malloc(CHUNK + KEEP);
if (!buf) return -1;
for (int i = 0; i < n; i++) {
if (ph[i].type != 1 /* PT_LOAD */ || !(ph[i].flags & GO_PF_X) || ph[i].filesz == 0) continue;
uint64_t pos = 0;
while (pos < ph[i].filesz) {
uint64_t want = ph[i].filesz - pos;
if (want > CHUNK + KEEP) want = CHUNK + KEEP;
ssize_t got = pread(fd, buf, (size_t)want, (off_t)(ph[i].offset + pos));
if (got <= KEEP) break;
for (ssize_t o = 0; o + 36 <= got; o += 4) {
if (rd32(buf + o) != k_go_syscall6[0]) continue;
int same = 1;
for (int k = 1; k < 7 && same; k++) same = rd32(buf + o + 4 * k) == k_go_syscall6[k];
if (!same || rd32(buf + o + 32) != GO_CMN_X0_4095) continue;
if (*found == 0) first = (int64_t)(ph[i].offset + pos + (uint64_t)o + 28);
(*found)++;
}
if (pos + (uint64_t)got >= ph[i].filesz) break;
pos += (uint64_t)got - (KEEP - 4); // the next chunk starts where the last place of this could begin, no place is split or counted twice
}
}
free(buf);
return first;
}
// "b <delta>" / "bl <delta>" for a distance in bytes, or 0 when it does not fit
static uint32_t go_branch(uint32_t base, int64_t delta) {
if ((delta & 3) != 0 || delta >= (1LL << 27) || delta < -(1LL << 27)) return 0;
return base | (uint32_t)((delta >> 2) & 0x3ffffff);
}
static uint64_t go_align_up(uint64_t v, uint64_t a) { return (v + a - 1) & ~(a - 1); }
// The strings the added code needs, as they are now
static int go_make_header(struct gosys_hdr *h) {
if (g_ddnatv_root_len == 0 || g_ddnatv_root_len >= GOSYS_ROOT_MAX) return -1;
memcpy(h->root, g_ddnatv_root, g_ddnatv_root_len);
h->root_len = (uint32_t)g_ddnatv_root_len;
char buf[PATH_MAX];
if (find_dynamic_linker_for_machine(g_ddnatv_root, EM_AARCH64, buf, sizeof(buf)) && strlen(buf) < GOSYS_PATH_MAX) {
h->ldso_len = (uint32_t)strlen(buf);
memcpy(h->ldso, buf, h->ldso_len);
}
static const char *const hooks[] = { "/usr/lib/libddnatv-hook.so", "/lib/libddnatv-hook.so" };
for (size_t i = 0; i < sizeof(hooks) / sizeof(hooks[0]); i++) {
size_t n = ddnatv_append(buf, sizeof(buf), 0, g_ddnatv_root, g_ddnatv_root_len);
n = ddnatv_append(buf, sizeof(buf), n, hooks[i], strlen(hooks[i]));
if (n < GOSYS_PATH_MAX && access(buf, F_OK) == 0) {
h->hook_len = (uint32_t)n;
memcpy(h->hook, buf, n);
break;
}
}
// The program that starts the others: bash, which can give them the argv[0] they are asked for
static const char *const runners[] = { "/usr/bin/bash", "/bin/bash", "/usr/bin/env", "/bin/env" };
for (size_t i = 0; i < sizeof(runners) / sizeof(runners[0]); i++) {
size_t n = ddnatv_append(buf, sizeof(buf), 0, g_ddnatv_root, g_ddnatv_root_len);
n = ddnatv_append(buf, sizeof(buf), n, runners[i], strlen(runners[i]));
if (n < GOSYS_PATH_MAX && access(buf, F_OK) == 0) {
h->runner_len = (uint32_t)n;
memcpy(h->runner, buf, n);
if (i < 2) h->flags |= GOSYS_FLAG_RUNNER_IS_BASH;
break;
}
}
// The directories the programs of an AArch64 rootfs load their libraries from
static const int dirs[] = { 0, 1, 4, 5, 6 };
size_t used = 0;
for (size_t i = 0; i < sizeof(dirs) / sizeof(dirs[0]); i++) {
const char *d = k_rootfs_lib_dirs[dirs[i]];
if (i > 0) used = ddnatv_append(buf, sizeof(buf), used, ":", 1);
used = ddnatv_append(buf, sizeof(buf), used, g_ddnatv_root, g_ddnatv_root_len);
used = ddnatv_append(buf, sizeof(buf), used, d, strlen(d));
}
if (used < GOSYS_LIBS_MAX) {
h->libs_len = (uint32_t)used;
memcpy(h->libs, buf, used);
}
if (h->ldso_len == 0 || h->runner_len == 0) h->runner_len = 0; // Ubuntu programs cannot be started
return 0;
}
static int go_pwrite_all(int fd, const void *buf, size_t len, uint64_t off) {
return pwrite(fd, buf, len, (off_t)off) == (ssize_t)len ? 0 : -1;
}
static int go_open_for_write(int fd, const struct stat *st, const char *path, int *made_writable) {
int wfd = open(path, O_WRONLY | O_CLOEXEC);
if (wfd < 0 && errno == EACCES && fchmod(fd, (st->st_mode | S_IWUSR) & 07777) == 0) {
*made_writable = 1;
wfd = open(path, O_WRONLY | O_CLOEXEC);
}
return wfd; // ETXTBSY: the program is running right now, patched at its next start
}
// The bytes of the added code for a given place: the code with its header (the strings, and where
// the scratch memory is), the instructions that connect the call site to it, and the trailer that
// says what was changed to put it there.
static void go_build_image(unsigned char *img, const struct gosys_hdr *strings, uint64_t cave_v, uint64_t scratch_v,
uint32_t to_entry, uint32_t back, const struct gosys_trailer *info) {
memcpy(img, gosys_blob, GOSYS_BLOB_SIZE);
struct gosys_hdr h = *strings;
h.scratch_rel = (int64_t)scratch_v - (int64_t)cave_v;
memcpy(img, &h, sizeof(h));
unsigned char *th = img + GOSYS_THUNKS_OFF;
wr32(th + 0, 0xd10043ffu); // sub sp, sp, #16
wr32(th + 4, 0xf90003feu); // str x30, [sp]
wr32(th + 8, 0xaa0803e7u); // mov x7, x8 (the number is the eighth argument)
wr32(th + 12, to_entry); // bl entry
wr32(th + 16, 0xf94003feu); // ldr x30, [sp]
wr32(th + 20, 0x910043ffu); // add sp, sp, #16
wr32(th + 24, back); // b <the instruction after the call>
struct gosys_trailer t;
memcpy(&t, img + GOSYS_BLOB_SIZE - sizeof(t), sizeof(t));
t.version = GOSYS_VERSION;
t.total_size = GOSYS_BLOB_SIZE;
t.text_orig_filesz = info->text_orig_filesz;
t.text_orig_flags = info->text_orig_flags;
t.rw_orig_memsz = info->rw_orig_memsz;
t.text_index = info->text_index;
t.rw_index = info->rw_index;
t.site_file_off = info->site_file_off;
memcpy(img + GOSYS_BLOB_SIZE - sizeof(t), &t, sizeof(t));
}
// A short fingerprint of the added code, so that a program patched by an older The native userland is looked at
// again (the marker of a prepared program has it)
static uint32_t go_blob_fingerprint(void) {
static uint32_t fp;
if (fp == 0) {
uint32_t h = 2166136261u;
for (size_t i = 0; i < GOSYS_BLOB_SIZE; i++) h = (h ^ gosys_blob[i]) * 16777619u;
fp = h ? h : 1;
}
return fp;
}
// Gives the program its old segments and call back: the added code is zeroed, the data segment
// is shortened, the instruction is a "svc #0" again.
static int go_undo(int wfd, struct go_ph *ph, int cave_seg, const struct gosys_trailer *tr, int64_t site_off) {
uint64_t cave_off = ph[cave_seg].offset + ph[cave_seg].filesz - tr->total_size;
unsigned char word[4];
wr32(word, GO_SVC);
if (go_pwrite_all(wfd, word, 4, (uint64_t)site_off) != 0) return -1;
unsigned char sz[16];
go_wr64(sz, tr->text_orig_filesz);
go_wr64(sz + 8, tr->text_orig_filesz);
if (go_pwrite_all(wfd, sz, 16, ph[cave_seg].pos + 32) != 0) return -1;
wr32(word, tr->text_orig_flags);
if (go_pwrite_all(wfd, word, 4, ph[cave_seg].pos + 4) != 0) return -1;
if (tr->rw_index < GO_MAX_PH) {
unsigned char mem[8];
go_wr64(mem, tr->rw_orig_memsz);
if (go_pwrite_all(wfd, mem, 8, ph[tr->rw_index].pos + 40) != 0) return -1;
}
unsigned char *zero = (unsigned char *)calloc(1, tr->total_size);
if (!zero) return -1;
int rc = go_pwrite_all(wfd, zero, tr->total_size, cave_off);
free(zero);
return rc;
}
// DDNATV_NO_GOSYS=1 (any value but empty or 0): no code is added to Go programs, and the code that is
// in one is taken out again, so that a program can be run as it was built, to see whether a fault
// is the program's or the code's. The marker of a prepared program says it (static_marker).
static int go_disabled(void) {
const char *v = getenv("DDNATV_NO_GOSYS");
return v && v[0] != '\0' && strcmp(v, "0") != 0;
}
// The three branches that connect the call site and the code: site -> thunk, thunk -> entry (bl),
// thunk -> the instruction after the site. 0 when one of them is too far.
static int go_branches(uint64_t cave_v, uint64_t site_v, uint32_t *to_thunk, uint32_t *to_entry, uint32_t *back) {
uint64_t thunk_v = cave_v + GOSYS_THUNKS_OFF;
*to_thunk = go_branch(0x14000000u, (int64_t)thunk_v - (int64_t)site_v);
*to_entry = go_branch(0x94000000u, (int64_t)(cave_v + GOSYS_ENTRY_OFF) - (int64_t)(thunk_v + 12));
*back = go_branch(0x14000000u, (int64_t)(site_v + 4) - (int64_t)(thunk_v + 24));
return *to_thunk && *to_entry && *back;
}
// Adds the code to the program, or brings it up to date. Returns 1 when it changed the file, 0 when
// there was nothing to do (not a Go program of a kind the code can serve, or already done), -1 when
// the file could not be changed (it is started as it is).
static int prepare_go_program(int fd, const char *path, const struct stat *st) {
struct go_ph ph[GO_MAX_PH];
uint16_t etype = 0, machine = 0;
int n = go_read_phdrs(fd, ph, &etype, &machine);
if (n < 0) return -1;
if (machine != EM_AARCH64 || (etype != GO_ET_EXEC && etype != GO_ET_DYN)) return 0;
int found = 0;
int64_t site_off = go_find_syscall6(fd, ph, n, &found);
if (found != 1) return 0; // not a Go of 1.19 or newer (or its function is not there once)
// The loadable segments, by address
int order[GO_MAX_PH], nl = 0;
for (int i = 0; i < n; i++) {
if (ph[i].type != 1 /* PT_LOAD */) continue;
int k = nl++;
while (k > 0 && ph[order[k - 1]].vaddr > ph[i].vaddr) {
order[k] = order[k - 1];
k--;
}
order[k] = i;
}
if (nl < 2) return 0;
// The call site must be in a segment that is mapped as code
uint64_t site_v = 0;
for (int i = 0; i < nl; i++) {
const struct go_ph *s = &ph[order[i]];
if ((s->flags & GO_PF_X) && (uint64_t)site_off >= s->offset && (uint64_t)site_off < s->offset + s->filesz)
site_v = s->vaddr + ((uint64_t)site_off - s->offset);
}
if (site_v == 0) return 0;
struct gosys_hdr strings;
memset(&strings, 0, sizeof(strings));
memcpy(strings.magic, "CXGOSYS1", 8);
strings.version = GOSYS_VERSION;
if (go_make_header(&strings) != 0) return 0;
unsigned char *img = (unsigned char *)malloc(GOSYS_BLOB_SIZE);
unsigned char *have = (unsigned char *)malloc(GOSYS_BLOB_SIZE);
if (!img || !have) {
free(img);
free(have);
return -1;
}
int wfd = -1, made_writable = 0, changed = 0, rc = 0;
unsigned char word[4];
// An earlier run's code: it ends the segment it is in, and says what it changed
int cave_seg = -1;
struct gosys_trailer tr;
memset(&tr, 0, sizeof(tr));
for (int i = 0; i < nl && cave_seg < 0; i++) {
const struct go_ph *s = &ph[order[i]];
if (s->filesz < sizeof(tr) + sizeof(struct gosys_hdr)) continue;
struct gosys_trailer t;
if (pread(fd, &t, sizeof(t), (off_t)(s->offset + s->filesz - sizeof(t))) != (ssize_t)sizeof(t)) continue;
if (memcmp(t.magic, "CXGOEND1", 8) != 0 || t.total_size > s->filesz || t.total_size < sizeof(t) + sizeof(struct gosys_hdr)) continue;
tr = t;
cave_seg = order[i];
}
if (go_disabled()) {
if (cave_seg >= 0) {
wfd = go_open_for_write(fd, st, path, &made_writable);
if (wfd < 0) {
rc = -1;
} else {
rc = go_undo(wfd, ph, cave_seg, &tr, site_off);
changed = rc == 0;
}
}
goto done;
}
if (cave_seg >= 0) {
uint64_t cave_off = ph[cave_seg].offset + ph[cave_seg].filesz - tr.total_size;
uint64_t cave_v = ph[cave_seg].vaddr + (cave_off - ph[cave_seg].offset);
int same = 0, site_ok = 0;
uint32_t to_thunk = 0, to_entry = 0, back = 0;
// Is it what would be put there now? (the code of an older The native userland differs)
if (tr.total_size == GOSYS_BLOB_SIZE && tr.rw_index < (uint32_t)n && ph[tr.rw_index].type == 1 &&
go_branches(cave_v, site_v, &to_thunk, &to_entry, &back)) {
uint64_t scratch_v = go_align_up(ph[tr.rw_index].vaddr + tr.rw_orig_memsz, 64);
go_build_image(img, &strings, cave_v, scratch_v, to_entry, back, &tr);
same = pread(fd, have, GOSYS_BLOB_SIZE, (off_t)cave_off) == (ssize_t)GOSYS_BLOB_SIZE &&
memcmp(have, img, GOSYS_BLOB_SIZE) == 0 &&
ph[tr.rw_index].memsz == scratch_v - ph[tr.rw_index].vaddr + GOSYS_SCRATCH_SIZE;
}
unsigned char cur[4];
site_ok = same && pread(fd, cur, 4, (off_t)site_off) == 4 && rd32(cur) == to_thunk;
if (same && site_ok) goto done;
wfd = go_open_for_write(fd, st, path, &made_writable);
if (wfd < 0) {
rc = -1;
goto done;
}
if (same) {
// The code is there, only the branch is not (a patch that was cut short)
wr32(word, to_thunk);
rc = go_pwrite_all(wfd, word, 4, (uint64_t)site_off);
changed = rc == 0;
goto done;
}
// An older code, or other strings: back to the plain program, then patch again
if (go_undo(wfd, ph, cave_seg, &tr, site_off) != 0) {
rc = -1;
goto done;
}
close(wfd);
wfd = -1;
if (made_writable) fchmod(fd, st->st_mode & 07777);
free(img);
free(have);
return prepare_go_program(fd, path, st);
}
// A place for the code: the end of a segment that is followed by padding up to the next one
uint64_t total = GOSYS_BLOB_SIZE;
int text = -1;
uint64_t cave_v = 0, cave_off = 0;
for (int pass = 0; pass < 2 && text < 0; pass++) {
for (int k = 0; k + 1 < nl && text < 0; k++) {
const struct go_ph *s = &ph[order[k]], *nx = &ph[order[k + 1]];
if (pass == 0 ? !(s->flags & GO_PF_X) : (s->flags & GO_PF_W)) continue;
if (s->memsz != s->filesz || s->filesz == 0) continue;
uint64_t v = go_align_up(s->vaddr + s->filesz, 64);
uint64_t off = s->offset + (v - s->vaddr);
if (v + total > nx->vaddr || (nx->vaddr & 0x3fff) != 0) continue;
if (off + total > nx->offset || off + total > (uint64_t)st->st_size) continue;
// Only padding may be written over
uint64_t pad_from = s->offset + s->filesz, pad_len = off + total - pad_from;
unsigned char *pad = (unsigned char *)malloc(pad_len);
if (!pad) continue;
int zero = pread(fd, pad, pad_len, (off_t)pad_from) == (ssize_t)pad_len;
for (uint64_t i = 0; zero && i < pad_len; i++) zero = pad[i] == 0;
free(pad);
if (!zero) continue;
text = order[k];
cave_v = v;
cave_off = off;
}
}
int rw = order[nl - 1];
uint32_t to_thunk = 0, to_entry = 0, back = 0;
if (text < 0 || !(ph[rw].flags & GO_PF_W) || rw == text || !go_branches(cave_v, site_v, &to_thunk, &to_entry, &back)) goto done;
uint64_t scratch_v = go_align_up(ph[rw].vaddr + ph[rw].memsz, 64);
struct gosys_trailer info;
memset(&info, 0, sizeof(info));
info.text_orig_filesz = ph[text].filesz;
info.text_orig_flags = ph[text].flags;
info.rw_orig_memsz = ph[rw].memsz;
info.text_index = (uint32_t)text;
info.rw_index = (uint32_t)rw;
info.site_file_off = (uint64_t)site_off;
go_build_image(img, &strings, cave_v, scratch_v, to_entry, back, &info);
wfd = go_open_for_write(fd, st, path, &made_writable);
if (wfd < 0) {
rc = -1;
goto done;
}
// The code first and the call site last: whatever is cut short leaves a program that runs
unsigned char sz[16];
unsigned char mem[8];
go_wr64(mem, scratch_v - ph[rw].vaddr + GOSYS_SCRATCH_SIZE);
go_wr64(sz, cave_v + GOSYS_BLOB_SIZE - ph[text].vaddr);
go_wr64(sz + 8, cave_v + GOSYS_BLOB_SIZE - ph[text].vaddr);
rc = go_pwrite_all(wfd, img, GOSYS_BLOB_SIZE, cave_off);
if (rc == 0) rc = go_pwrite_all(wfd, mem, 8, ph[rw].pos + 40);
if (rc == 0) rc = go_pwrite_all(wfd, sz, 16, ph[text].pos + 32);
if (rc == 0 && !(ph[text].flags & GO_PF_X)) {
wr32(word, ph[text].flags | GO_PF_X);
rc = go_pwrite_all(wfd, word, 4, ph[text].pos + 4);
}
if (rc == 0) {
wr32(word, to_thunk);
rc = go_pwrite_all(wfd, word, 4, (uint64_t)site_off);
}
changed = rc == 0;
done:
free(img);
free(have);
if (wfd >= 0) {
// Keep the times: make and friends must not see a rebuilt program.
const struct timespec times[2] = { st->st_atim, st->st_mtim };
futimens(wfd, times);
close(wfd);
}
if (made_writable) fchmod(fd, st->st_mode & 07777);
if (rc != 0) return -1;
return changed ? 1 : 0;
}
#endif /* DDNATV_HAVE_GOSYS */
+628
View File
@@ -0,0 +1,628 @@
// Part of libddnatv-hook.so, included by ddnatv-hook.c (one translation unit, so the
// parts share their static functions and are built with the same command as before).
//
// Hard links: link() falls back to a copy that reports the link count of a real link, in every
// process of the rootfs.
// Emulated hard links. Android does not let apps create hard links, so link() falls back to a copy
// (ddnatv_emulate_hardlinkat). Programs that check the result through the link count, such as the
// lock files of shadow (link(file.PID, file.lock), then stat(file.PID).st_nlink == 2), and those
// that look for files linked to each other (tar, rsync -H, du, find -samefile), are shown what a
// real link would give: every copy of one emulated link reports the inode number of the original
// and the number of copies as its link count.
//
// The copies are recorded in a table that every process of the rootfs maps
// ($DDNATV_ROOT/var/lib/ddnatv/hardlinks), so "ln a b" in one process and "stat a" in the next
// agree, also after the app restarts. Copies are recorded by device and inode, so a relative name,
// an absolute name and an open descriptor of the same file all match, and with their modification
// time: a copy written to since (it no longer shares the original's content) or a new file that got
// the inode number of a removed copy (removed outside the hook, e.g. in root mode) do not match.
//
// Readers (every stat) take no lock: a sequence number that writers make odd while they change the
// table tells them to read again. Writers (link, unlink, rename) take an fcntl lock on the file.
// Without a rootfs (or when the file cannot be made) the table is private to the process and its
// children, as it was before.
#define DDNATV_HL_MAGIC 0x6b6e6c43u // "Clnk"
#define DDNATV_HL_VERSION 1u
#define DDNATV_HL_SLOTS 8192u // a power of two
#define DDNATV_HL_MAX_USED 6144u // at most 3/4 full, so that lookups stay short
#define DDNATV_HL_EMPTY 0u
#define DDNATV_HL_USED 1u
#define DDNATV_HL_DELETED 2u
typedef struct {
uint64_t dev, ino; // this copy
int64_t mtime_sec, mtime_nsec; // its modification time when it was linked (compared in whole
// seconds: stat() and statx() need not agree on the fraction)
uint64_t group_dev, group_ino; // the original, whose inode number every copy reports
uint32_t state;
uint32_t nlink; // copies in the group
uint32_t pad[2];
} ddnatv_hl_slot_t;
typedef struct {
uint32_t magic, version;
uint32_t seq; // odd while a writer changes the table
uint32_t used, deleted;
uint32_t pad[11];
ddnatv_hl_slot_t slots[DDNATV_HL_SLOTS];
} ddnatv_hl_table_t;
// The file and the mapping, in whole 64 KB: a size that is a multiple of every page size
#define DDNATV_HL_MAP_SIZE ((sizeof(ddnatv_hl_table_t) + 0xffff) & ~(size_t)0xffff)
static ddnatv_hl_table_t *g_hl_table = NULL; // set once, then never changed (until a test resets it)
static int g_hl_shared = 0; // mapped from the rootfs' file
static long g_hl_next_try = 0; // when to look for the file again (monotonic seconds)
static pthread_mutex_t g_hardlinks_lock = PTHREAD_MUTEX_INITIALIZER;
#ifndef DDNATV_HOST_TEST
static void init_ddnatv_hook(void);
#endif
static size_t hl_table_path(char *buf, size_t size) {
#ifndef DDNATV_HOST_TEST
// The rootfs is known once a path was rewritten; "ln a b" or "stat a" name only relative ones
init_ddnatv_hook();
#endif
if (g_ddnatv_root_len == 0) return 0;
size_t n = ddnatv_append(buf, size, 0, g_ddnatv_root, g_ddnatv_root_len);
static const char rel[] = "/var/lib/ddnatv/hardlinks";
n = ddnatv_append(buf, size, n, rel, sizeof(rel) - 1);
return n == g_ddnatv_root_len + sizeof(rel) - 1 ? n : 0;
}
static long hl_now_seconds(void) {
struct timespec ts;
#ifdef CLOCK_MONOTONIC_COARSE
if (clock_gettime(CLOCK_MONOTONIC_COARSE, &ts) == 0) return (long)ts.tv_sec;
#endif
if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) return (long)ts.tv_sec;
return 0;
}
static int hl_open_file(const char *path, int create) {
return (int)syscall(SYS_openat, AT_FDCWD, path, O_RDWR | O_CLOEXEC | (create ? O_CREAT : 0), 0600);
}
// Takes the writers' lock on the table's file (blocking); -1 when there is no file to lock.
static int hl_lock_file(void) {
if (!g_hl_shared) return -1;
char path[PATH_MAX];
if (!hl_table_path(path, sizeof(path))) return -1;
int fd = hl_open_file(path, 0);
if (fd < 0) return -1;
struct flock fl;
memset(&fl, 0, sizeof(fl));
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
while (fcntl(fd, F_SETLKW, &fl) != 0 && errno == EINTR) {
}
return fd;
}
static void hl_unlock_file(int fd) {
if (fd >= 0) syscall(SYS_close, fd); // closing the file drops the lock
}
static void hl_init_header(ddnatv_hl_table_t *t) {
memset(t, 0, sizeof(*t));
t->version = DDNATV_HL_VERSION;
__atomic_store_n(&t->magic, DDNATV_HL_MAGIC, __ATOMIC_RELEASE);
}
// The size of an open file. Not fstat(): this library's own fstat() looks into the table, which
// would wait for the lock that the caller holds.
static off_t hl_file_size(int fd) {
return lseek(fd, 0, SEEK_END);
}
// Maps the table. Readers (create = 0) get NULL while no process has made the file yet, and look
// for it again a second later; writers make it, or fall back to a table of this process. Readers
// never wait for the lock (a stat() while it is held, or in a child forked while another thread
// held it, would wait forever): they find no table then.
static ddnatv_hl_table_t *hl_table(int create) {
ddnatv_hl_table_t *t = __atomic_load_n(&g_hl_table, __ATOMIC_ACQUIRE);
if (t) return t;
if (!create && __atomic_load_n(&g_hl_next_try, __ATOMIC_RELAXED) > hl_now_seconds()) return NULL;
int saved_errno = errno;
if (create) {
pthread_mutex_lock(&g_hardlinks_lock);
} else if (pthread_mutex_trylock(&g_hardlinks_lock) != 0) {
errno = saved_errno;
return NULL;
}
t = g_hl_table;
if (!t) {
char path[PATH_MAX];
path[0] = '\0';
int have_path = hl_table_path(path, sizeof(path)) != 0;
int fd = have_path ? hl_open_file(path, 0) : -1;
if (fd < 0 && create && path[0]) {
// var/lib/ddnatv may not exist yet
char dir[PATH_MAX];
size_t n = ddnatv_append(dir, sizeof(dir), 0, path, strlen(path) - strlen("/hardlinks"));
if (n > 0) syscall(SYS_mkdirat, AT_FDCWD, dir, 0700);
fd = hl_open_file(path, 1);
}
if (fd >= 0) {
off_t size = hl_file_size(fd);
int ok = size >= 0;
if (ok && (size_t)size < DDNATV_HL_MAP_SIZE) {
// New (or an older, shorter format): made by a writer, under the lock
ok = 0;
if (create) {
struct flock fl;
memset(&fl, 0, sizeof(fl));
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
while (fcntl(fd, F_SETLKW, &fl) != 0 && errno == EINTR) {
}
size = hl_file_size(fd);
ok = size >= 0 &&
((size_t)size >= DDNATV_HL_MAP_SIZE || ftruncate(fd, DDNATV_HL_MAP_SIZE) == 0);
}
}
if (ok) {
void *m = mmap(NULL, DDNATV_HL_MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (m != MAP_FAILED) {
t = (ddnatv_hl_table_t *)m;
if (t->magic != DDNATV_HL_MAGIC || t->version != DDNATV_HL_VERSION) {
if (create) {
// Still under the lock taken above when the file was new; otherwise take it
struct flock fl;
memset(&fl, 0, sizeof(fl));
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
while (fcntl(fd, F_SETLKW, &fl) != 0 && errno == EINTR) {
}
if (t->magic != DDNATV_HL_MAGIC || t->version != DDNATV_HL_VERSION) hl_init_header(t);
} else {
munmap(m, DDNATV_HL_MAP_SIZE);
t = NULL;
}
}
if (t) g_hl_shared = 1;
}
}
syscall(SYS_close, fd); // the mapping stays; also drops the lock
}
if (!t && create) {
// No rootfs file: this process and its children share a table
void *m = mmap(NULL, DDNATV_HL_MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (m != MAP_FAILED) {
t = (ddnatv_hl_table_t *)m;
hl_init_header(t);
g_hl_shared = 0;
}
}
if (t) {
__atomic_store_n(&g_hl_table, t, __ATOMIC_RELEASE);
} else if (have_path) {
// No table yet: looked for again a second later (without a rootfs there is none to wait for)
__atomic_store_n(&g_hl_next_try, hl_now_seconds() + 1, __ATOMIC_RELAXED);
}
}
pthread_mutex_unlock(&g_hardlinks_lock);
errno = saved_errno;
return t;
}
// Whether any emulated link may exist; what the stat() hooks check first.
static inline int hardlinks_maybe_any(void) {
ddnatv_hl_table_t *t = hl_table(0);
return t && __atomic_load_n(&t->used, __ATOMIC_RELAXED) > 0;
}
static inline uint32_t hl_hash(uint64_t dev, uint64_t ino) {
uint64_t h = ino * 0x9E3779B97F4A7C15ull ^ (dev + 0x632BE59BD9B4E019ull) * 0xC2B2AE3D27D4EB4Full;
return (uint32_t)(h >> 40) & (DDNATV_HL_SLOTS - 1);
}
// The slot of a copy, or -1. Writers only (under the locks).
static long hl_find_locked(ddnatv_hl_table_t *t, uint64_t dev, uint64_t ino) {
uint32_t i = hl_hash(dev, ino);
for (uint32_t n = 0; n < DDNATV_HL_SLOTS; n++, i = (i + 1) & (DDNATV_HL_SLOTS - 1)) {
ddnatv_hl_slot_t *s = &t->slots[i];
if (s->state == DDNATV_HL_EMPTY) return -1;
if (s->state == DDNATV_HL_USED && s->ino == ino && s->dev == dev) return (long)i;
}
return -1;
}
// Writers: the process' mutex, the file's lock, then the sequence number made odd.
static int hl_write_begin(ddnatv_hl_table_t *t) {
pthread_mutex_lock(&g_hardlinks_lock);
int fd = hl_lock_file();
uint32_t seq = __atomic_load_n(&t->seq, __ATOMIC_RELAXED);
// An odd number left by a writer that died: the lock was given up with it
if (!(seq & 1)) seq++;
__atomic_store_n(&t->seq, seq, __ATOMIC_RELAXED);
__atomic_thread_fence(__ATOMIC_RELEASE);
return fd;
}
static void hl_write_end(ddnatv_hl_table_t *t, int fd) {
__atomic_store_n(&t->seq, __atomic_load_n(&t->seq, __ATOMIC_RELAXED) + 1, __ATOMIC_RELEASE);
hl_unlock_file(fd);
pthread_mutex_unlock(&g_hardlinks_lock);
}
// Rebuilds the table without the slots of removed copies, which make every lookup longer.
static void hl_compact_locked(ddnatv_hl_table_t *t) {
ddnatv_hl_slot_t *keep = (ddnatv_hl_slot_t *)malloc(sizeof(ddnatv_hl_slot_t) * DDNATV_HL_MAX_USED);
if (!keep) return;
uint32_t n = 0;
for (uint32_t i = 0; i < DDNATV_HL_SLOTS && n < DDNATV_HL_MAX_USED; i++) {
if (t->slots[i].state == DDNATV_HL_USED) keep[n++] = t->slots[i];
}
memset(t->slots, 0, sizeof(t->slots));
for (uint32_t k = 0; k < n; k++) {
uint32_t i = hl_hash(keep[k].dev, keep[k].ino);
while (t->slots[i].state != DDNATV_HL_EMPTY) i = (i + 1) & (DDNATV_HL_SLOTS - 1);
t->slots[i] = keep[k];
}
t->used = n;
t->deleted = 0;
free(keep);
}
static int hl_put_locked(ddnatv_hl_table_t *t, const struct stat *st, uint64_t group_dev, uint64_t group_ino) {
long i = hl_find_locked(t, st->st_dev, st->st_ino);
if (i < 0) {
if (t->used >= DDNATV_HL_MAX_USED) return -1;
if (t->used + t->deleted >= DDNATV_HL_SLOTS - DDNATV_HL_SLOTS / 8) hl_compact_locked(t);
uint32_t j = hl_hash(st->st_dev, st->st_ino);
while (t->slots[j].state == DDNATV_HL_USED) j = (j + 1) & (DDNATV_HL_SLOTS - 1);
if (t->slots[j].state == DDNATV_HL_DELETED) t->deleted--;
i = (long)j;
t->used++;
}
ddnatv_hl_slot_t *s = &t->slots[i];
s->dev = st->st_dev;
s->ino = st->st_ino;
s->mtime_sec = st->st_mtim.tv_sec;
s->mtime_nsec = st->st_mtim.tv_nsec;
s->group_dev = group_dev;
s->group_ino = group_ino;
s->nlink = 1;
s->state = DDNATV_HL_USED;
return 0;
}
static void hl_remove_locked(ddnatv_hl_table_t *t, long i) {
t->slots[i].state = DDNATV_HL_DELETED;
t->used--;
t->deleted++;
}
// Gives every copy of a group its size; a group of one is a plain file again.
static void hl_update_group_locked(ddnatv_hl_table_t *t, uint64_t group_dev, uint64_t group_ino) {
uint32_t n = 0;
long last = -1;
for (uint32_t i = 0; i < DDNATV_HL_SLOTS; i++) {
ddnatv_hl_slot_t *s = &t->slots[i];
if (s->state == DDNATV_HL_USED && s->group_ino == group_ino && s->group_dev == group_dev) {
n++;
last = (long)i;
}
}
if (n == 1) {
hl_remove_locked(t, last);
return;
}
for (uint32_t i = 0; i < DDNATV_HL_SLOTS && n > 1; i++) {
ddnatv_hl_slot_t *s = &t->slots[i];
if (s->state == DDNATV_HL_USED && s->group_ino == group_ino && s->group_dev == group_dev) s->nlink = n;
}
}
// Removes the copy in slot i. A group reports the inode number of one of its copies (the original);
// when that copy goes, the group reports another one's: the number of a removed file can be given to
// a new file, which must not show up as linked to the copies that are left.
static void hl_remove_copy_locked(ddnatv_hl_table_t *t, long i) {
uint64_t group_dev = t->slots[i].group_dev, group_ino = t->slots[i].group_ino;
int reported = t->slots[i].dev == group_dev && t->slots[i].ino == group_ino;
hl_remove_locked(t, i);
if (reported) {
uint64_t new_dev = 0, new_ino = 0;
int found = 0;
for (uint32_t j = 0; j < DDNATV_HL_SLOTS; j++) {
ddnatv_hl_slot_t *s = &t->slots[j];
if (s->state != DDNATV_HL_USED || s->group_ino != group_ino || s->group_dev != group_dev) continue;
if (!found) {
new_dev = s->dev;
new_ino = s->ino;
found = 1;
}
s->group_dev = new_dev;
s->group_ino = new_ino;
}
if (found) {
group_dev = new_dev;
group_ino = new_ino;
}
}
hl_update_group_locked(t, group_dev, group_ino);
}
// Records that the file [copy] is an emulated hard link of [old].
static void register_emulated_hardlink(const struct stat *old, const struct stat *copy) {
ddnatv_hl_table_t *t = hl_table(1);
if (!t) return;
int saved_errno = errno;
int fd = hl_write_begin(t);
uint64_t group_dev = old->st_dev, group_ino = old->st_ino;
long i = hl_find_locked(t, old->st_dev, old->st_ino);
if (i >= 0 && t->slots[i].mtime_sec == old->st_mtim.tv_sec) {
// Linking a copy again: the new copy joins the same group
group_dev = t->slots[i].group_dev;
group_ino = t->slots[i].group_ino;
} else {
// A stale slot of an earlier file with this inode number
if (i >= 0) hl_remove_copy_locked(t, i);
hl_put_locked(t, old, group_dev, group_ino);
}
if (hl_put_locked(t, copy, group_dev, group_ino) == 0 || hl_find_locked(t, old->st_dev, old->st_ino) >= 0) {
hl_update_group_locked(t, group_dev, group_ino);
}
hl_write_end(t, fd);
errno = saved_errno;
}
// Forgets a copy whose name was removed; the last copy of a group goes back to a plain file.
static void unregister_emulated_hardlink(dev_t dev, ino_t ino) {
ddnatv_hl_table_t *t = hl_table(0);
if (!t || __atomic_load_n(&t->used, __ATOMIC_RELAXED) == 0) return;
int saved_errno = errno;
int fd = hl_write_begin(t);
long i = hl_find_locked(t, dev, ino);
if (i >= 0) hl_remove_copy_locked(t, i);
hl_write_end(t, fd);
errno = saved_errno;
}
// Reads the slot of a copy without a lock: 1 and [out] when there is one.
static int hl_read(ddnatv_hl_table_t *t, uint64_t dev, uint64_t ino, ddnatv_hl_slot_t *out) {
for (int tries = 0; tries < 64; tries++) {
uint32_t seq = __atomic_load_n(&t->seq, __ATOMIC_ACQUIRE);
if (seq & 1) {
sched_yield();
continue;
}
int found = 0;
uint32_t i = hl_hash(dev, ino);
for (uint32_t n = 0; n < DDNATV_HL_SLOTS; n++, i = (i + 1) & (DDNATV_HL_SLOTS - 1)) {
const volatile ddnatv_hl_slot_t *s = &t->slots[i];
uint32_t state = s->state;
if (state == DDNATV_HL_EMPTY) break;
if (state == DDNATV_HL_USED && s->ino == ino && s->dev == dev) {
memcpy(out, (const void *)s, sizeof(*out));
found = 1;
break;
}
}
__atomic_thread_fence(__ATOMIC_ACQUIRE);
if (__atomic_load_n(&t->seq, __ATOMIC_RELAXED) == seq) return found;
}
return 0; // a writer that does not finish: as if there were no links
}
// Makes a stat() result of an emulated hard link look like a real one: the inode number of the
// original and the number of copies as the link count.
static void apply_emulated_hardlink(struct stat *st) {
if (!st || !hardlinks_maybe_any()) return;
ddnatv_hl_slot_t s;
if (!hl_read(g_hl_table, st->st_dev, st->st_ino, &s)) return;
if (s.mtime_sec != (int64_t)st->st_mtim.tv_sec) return;
if (s.nlink > (uint32_t)st->st_nlink) st->st_nlink = (nlink_t)s.nlink;
st->st_ino = (ino_t)s.group_ino;
}
// The app's own user and group, which the hook presents as root: getuid() and getpwuid() say so,
// and stat() does as well, so that a program that compares a file's owner with getuid() sees the
// files it made as its own (git's "dubious ownership", sshd's /run/sshd, tmux's socket directory,
// ssh's ~/.ssh/config). -1 until known; a test sets them.
static uid_t g_app_uid = (uid_t)-1;
static gid_t g_app_gid = (gid_t)-1;
static void load_app_ids(void) {
#ifdef DDNATV_HOST_TEST
uid_t uid = getuid();
gid_t gid = getgid();
#else
// The real ones (getuid() and syscall() are the hook's own, which answer 0)
static uid_t (*orig_getuid)(void) = NULL;
static gid_t (*orig_getgid)(void) = NULL;
if (!orig_getuid) orig_getuid = (uid_t (*)(void))dlsym(RTLD_NEXT, "getuid");
if (!orig_getgid) orig_getgid = (gid_t (*)(void))dlsym(RTLD_NEXT, "getgid");
if (!orig_getuid || !orig_getgid) return;
uid_t uid = orig_getuid();
gid_t gid = orig_getgid();
#endif
__atomic_store_n(&g_app_gid, gid, __ATOMIC_RELAXED);
__atomic_store_n(&g_app_uid, uid, __ATOMIC_RELAXED);
}
static void present_owner_as_root(uid_t *uid, gid_t *gid) {
if (__atomic_load_n(&g_app_uid, __ATOMIC_RELAXED) == (uid_t)-1) load_app_ids();
uid_t app_uid = __atomic_load_n(&g_app_uid, __ATOMIC_RELAXED);
gid_t app_gid = __atomic_load_n(&g_app_gid, __ATOMIC_RELAXED);
if (app_uid == (uid_t)-1) return;
if (uid && *uid == app_uid) *uid = 0;
if (gid && *gid == app_gid) *gid = 0;
}
// What the stat() family returns: emulated hard links as real ones, the app's files as root's.
static void apply_stat_emulation(struct stat *st) {
if (!st) return;
apply_emulated_hardlink(st);
present_owner_as_root(&st->st_uid, &st->st_gid);
}
static int real_fstatat(int dirfd, const char *path, struct stat *st, int flags) {
#ifdef DDNATV_HOST_TEST
return fstatat(dirfd, path, st, flags);
#else
static int (*orig_fstatat)(int, const char *, struct stat *, int) = NULL;
if (!orig_fstatat) orig_fstatat = (int (*)(int, const char *, struct stat *, int))dlsym(RTLD_NEXT, "fstatat");
return orig_fstatat ? orig_fstatat(dirfd, path, st, flags) : fstatat(dirfd, path, st, flags);
#endif
}
// Before a name is removed or replaced (unlink, rename over it): whether it is an emulated hard
// link, and which. Costs nothing until the process has made one.
static int lookup_emulated_hardlink_at(int dirfd, const char *path, dev_t *dev, ino_t *ino) {
if (!path || !hardlinks_maybe_any()) return 0;
int saved_errno = errno;
struct stat st;
int found = 0;
if (real_fstatat(dirfd, path, &st, AT_SYMLINK_NOFOLLOW) == 0) {
ddnatv_hl_slot_t s;
found = hl_read(g_hl_table, st.st_dev, st.st_ino, &s);
*dev = st.st_dev;
*ino = st.st_ino;
}
errno = saved_errno;
return found;
}
static int ddnatv_emulate_hardlinkat(int olddirfd, const char *rold, int newdirfd, const char *rnew) {
if (!rold || !rnew) {
errno = EINVAL;
return -1;
}
struct stat st;
#ifdef DDNATV_HOST_TEST
if (fstatat(olddirfd, rold, &st, 0) != 0) {
return -1;
}
#else
static int (*orig_fstatat)(int, const char *, struct stat *, int) = NULL;
if (!orig_fstatat) orig_fstatat = (int (*)(int, const char *, struct stat *, int))dlsym(RTLD_NEXT, "fstatat");
if (orig_fstatat) {
if (orig_fstatat(olddirfd, rold, &st, 0) != 0) return -1;
} else {
if (fstatat(olddirfd, rold, &st, 0) != 0) return -1;
}
#endif
if (S_ISDIR(st.st_mode)) {
errno = EPERM;
return -1;
}
// Clean up stale dangling symlink or stale dead-process lock file at rnew
#ifndef DDNATV_HOST_TEST
struct stat lst;
int have_lst = 0;
if (orig_fstatat) {
if (orig_fstatat(newdirfd, rnew, &lst, AT_SYMLINK_NOFOLLOW) == 0) have_lst = 1;
} else {
if (fstatat(newdirfd, rnew, &lst, AT_SYMLINK_NOFOLLOW) == 0) have_lst = 1;
}
if (have_lst) {
if (S_ISLNK(lst.st_mode)) {
unlinkat(newdirfd, rnew, 0);
} else if (strstr(rnew, ".lock")) {
static int (*orig_openat)(int, const char *, int, ...) = NULL;
if (!orig_openat) orig_openat = (int (*)(int, const char *, int, ...))dlsym(RTLD_NEXT, "openat");
int rfd = orig_openat ? orig_openat(newdirfd, rnew, O_RDONLY | O_CLOEXEC)
: openat(newdirfd, rnew, O_RDONLY | O_CLOEXEC);
if (rfd >= 0) {
char pbuf[32] = {0};
ssize_t pr = read(rfd, pbuf, sizeof(pbuf) - 1);
close(rfd);
if (pr > 0) {
pid_t lpid = (pid_t)atoi(pbuf);
if (lpid > 0 && kill(lpid, 0) == -1 && errno == ESRCH) {
unlinkat(newdirfd, rnew, 0);
}
} else {
unlinkat(newdirfd, rnew, 0);
}
}
}
}
#endif
#ifdef DDNATV_HOST_TEST
int fd_new = openat(newdirfd, rnew, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, st.st_mode & 0777);
if (fd_new < 0) return -1;
int fd_old = openat(olddirfd, rold, O_RDONLY | O_CLOEXEC);
#else
static int (*orig_openat)(int, const char *, int, ...) = NULL;
if (!orig_openat) orig_openat = (int (*)(int, const char *, int, ...))dlsym(RTLD_NEXT, "openat");
int fd_new = orig_openat ? orig_openat(newdirfd, rnew, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, st.st_mode & 0777)
: openat(newdirfd, rnew, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, st.st_mode & 0777);
if (fd_new < 0) return -1;
int fd_old = orig_openat ? orig_openat(olddirfd, rold, O_RDONLY | O_CLOEXEC)
: openat(olddirfd, rold, O_RDONLY | O_CLOEXEC);
#endif
if (fd_old < 0) {
int err = errno;
close(fd_new);
unlinkat(newdirfd, rnew, 0);
errno = err;
return -1;
}
ssize_t sent = 0;
int copy_failed = 0;
while (sent < st.st_size) {
ssize_t s = sendfile(fd_new, fd_old, NULL, (size_t)(st.st_size - sent));
if (s > 0) {
sent += s;
} else {
break;
}
}
if (sent < st.st_size) {
char cbuf[16384];
ssize_t nread;
while ((nread = read(fd_old, cbuf, sizeof(cbuf))) > 0) {
ssize_t nwritten = 0;
while (nwritten < nread) {
ssize_t w = write(fd_new, cbuf + nwritten, nread - nwritten);
if (w < 0) {
copy_failed = 1;
break;
}
nwritten += w;
}
if (copy_failed) break;
}
if (nread < 0) copy_failed = 1;
}
fchmod(fd_new, st.st_mode & 0777);
// A hard link shares the times of the original (tar, dpkg and make compare them).
const struct timespec times[2] = { st.st_atim, st.st_mtim };
futimens(fd_new, times);
struct stat st_new;
memset(&st_new, 0, sizeof(st_new));
#ifndef DDNATV_HOST_TEST
static int (*orig_fstat)(int, struct stat *) = NULL;
if (!orig_fstat) orig_fstat = (int (*)(int, struct stat *))dlsym(RTLD_NEXT, "fstat");
if (orig_fstat) orig_fstat(fd_new, &st_new);
else fstat(fd_new, &st_new);
#else
fstat(fd_new, &st_new);
#endif
close(fd_old);
close(fd_new);
if (copy_failed) {
unlinkat(newdirfd, rnew, 0);
errno = EIO;
return -1;
}
register_emulated_hardlink(&st, &st_new);
return 0;
}
static inline int ddnatv_emulate_hardlink(const char *rold, const char *rnew) {
return ddnatv_emulate_hardlinkat(AT_FDCWD, rold, AT_FDCWD, rnew);
}
+795
View File
@@ -0,0 +1,795 @@
// Part of libddnatv-hook.so, included by ddnatv-hook.c (one translation unit, so the
// parts share their static functions and are built with the same command as before).
//
// Fake root: user and group ids, the shadow lock, and passwd/group lookups from the rootfs.
#ifndef DDNATV_HOST_TEST
// Fakeroot identity hooks for APT and DPKG to operate without superuser restrictions
uid_t getuid(void) { return 0; }
uid_t geteuid(void) { return 0; }
gid_t getgid(void) { return 0; }
gid_t getegid(void) { return 0; }
int setuid(uid_t uid) { (void)uid; return 0; }
int seteuid(uid_t uid) { (void)uid; return 0; }
int setgid(gid_t gid) { (void)gid; return 0; }
int setegid(gid_t gid) { (void)gid; return 0; }
int setreuid(uid_t ruid, uid_t euid) { (void)ruid; (void)euid; return 0; }
int setregid(gid_t rgid, gid_t egid) { (void)rgid; (void)egid; return 0; }
int setresuid(uid_t ruid, uid_t euid, uid_t suid) { (void)ruid; (void)euid; (void)suid; return 0; }
int setresgid(gid_t rgid, gid_t egid, gid_t sgid) { (void)rgid; (void)egid; (void)sgid; return 0; }
int getgroups(int size, gid_t list[]) {
if (size > 0 && list != NULL) list[0] = 0;
return 1;
}
// What programs built with _FORTIFY_SOURCE call when the buffer's size is known (the check is
// glibc's): without it the count came from the hook (1) and the list from the kernel (the app's
// groups, more than one), and sshd ended the login on "getgroups: Invalid argument"
extern void __chk_fail(void) __attribute__((__noreturn__));
int __getgroups_chk(int size, gid_t list[], size_t listlen) {
if (size > 0 && (size_t)size * sizeof(gid_t) > listlen) __chk_fail();
return getgroups(size, list);
}
int setgroups(size_t size, const gid_t *list) { (void)size; (void)list; return 0; }
int initgroups(const char *user, gid_t group) { (void)user; (void)group; return 0; }
int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups) {
(void)user;
if (!ngroups) {
errno = EINVAL;
return -1;
}
if (*ngroups > 0 && groups) {
groups[0] = group;
*ngroups = 1;
return 1;
}
// Too small (a caller asking for the size first): -1 and the number needed, as glibc does.
*ngroups = 1;
return -1;
}
#endif /* !DDNATV_HOST_TEST */
static uid_t real_uid(void) {
#ifdef DDNATV_HOST_TEST
return 10000;
#else
static uid_t (*orig_getuid)(void) = NULL;
if (!orig_getuid) orig_getuid = (uid_t (*)(void))dlsym(RTLD_NEXT, "getuid");
return orig_getuid ? orig_getuid() : 0;
#endif
}
static gid_t real_gid(void) {
#ifdef DDNATV_HOST_TEST
return 10000;
#else
static gid_t (*orig_getgid)(void) = NULL;
if (!orig_getgid) orig_getgid = (gid_t (*)(void))dlsym(RTLD_NEXT, "getgid");
return orig_getgid ? orig_getgid() : 0;
#endif
}
#ifdef DDNATV_HOST_TEST
#define DDNATV_NSS_SYM(name) hook_##name
#define DDNATV_SHADOW_SYM(name) hook_##name
static int g_test_orig_nss_r_ret = 0;
static int g_test_orig_nss_r_found = 0;
int hook_link(const char *oldpath, const char *newpath) {
int ret = link(oldpath, newpath);
if (ret != 0 && (errno == EXDEV || errno == EPERM || errno == EACCES || errno == ENOTSUP || errno == ENOSYS)) {
ret = ddnatv_emulate_hardlink(oldpath, newpath);
}
return ret;
}
int hook_linkat(int olddirfd, const char *oldpath, int newdirfd, const char *newpath, int flags) {
int ret = linkat(olddirfd, oldpath, newdirfd, newpath, flags);
if (ret != 0 && (errno == EXDEV || errno == EPERM || errno == EACCES || errno == ENOTSUP || errno == ENOSYS)) {
ret = ddnatv_emulate_hardlinkat(olddirfd, oldpath, newdirfd, newpath);
}
return ret;
}
int hook_stat(const char *path, struct stat *st) {
int ret = stat(path, st);
if (ret == 0) apply_stat_emulation(st);
return ret;
}
int hook_unlink(const char *path) {
dev_t hl_dev = 0;
ino_t hl_ino = 0;
int hardlinked = lookup_emulated_hardlink_at(AT_FDCWD, path, &hl_dev, &hl_ino);
int ret = unlink(path);
if (ret == 0 && hardlinked) unregister_emulated_hardlink(hl_dev, hl_ino);
return ret;
}
#else
#define DDNATV_NSS_SYM(name) name
#define DDNATV_SHADOW_SYM(name) name
#endif
// Hook lckpwdf and ulckpwdf (shadow password database locking)
// In glibc, lckpwdf() attempts to open /etc/.pwd.lock directly using internal syscalls
// which fails with EROFS on Android because host /etc is mounted read-only.
static int g_pwd_lock_fd = -1;
static pthread_mutex_t g_pwd_lock_mutex = PTHREAD_MUTEX_INITIALIZER;
int DDNATV_SHADOW_SYM(lckpwdf)(void) {
#ifndef DDNATV_HOST_TEST
init_ddnatv_hook();
pthread_mutex_lock(&g_pwd_lock_mutex);
if (g_pwd_lock_fd != -1) {
pthread_mutex_unlock(&g_pwd_lock_mutex);
return 0; // Already locked
}
char buf[PATH_MAX];
const char *target = rewrite_path("/etc/.pwd.lock", buf, sizeof(buf));
static int (*orig_open)(const char *, int, ...) = NULL;
if (!orig_open) orig_open = (int (*)(const char *, int, ...))dlsym(RTLD_NEXT, "open");
if (orig_open && target) {
g_pwd_lock_fd = orig_open(target, O_WRONLY | O_CREAT | O_CLOEXEC, 0600);
if (g_pwd_lock_fd >= 0) {
struct flock fl;
memset(&fl, 0, sizeof(fl));
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fcntl(g_pwd_lock_fd, F_SETLK, &fl);
}
}
if (g_pwd_lock_fd < 0) {
g_pwd_lock_fd = -2; // In-memory lock held
}
pthread_mutex_unlock(&g_pwd_lock_mutex);
#endif
return 0;
}
int DDNATV_SHADOW_SYM(ulckpwdf)(void) {
#ifndef DDNATV_HOST_TEST
pthread_mutex_lock(&g_pwd_lock_mutex);
if (g_pwd_lock_fd >= 0) {
close(g_pwd_lock_fd);
}
g_pwd_lock_fd = -1;
pthread_mutex_unlock(&g_pwd_lock_mutex);
#endif
return 0;
}
// Group lookup helper: reads $DDNATV_ROOT/etc/group or falls back to known entries
static int ddnatv_lookup_group(const char *search_name, gid_t search_gid, int by_name,
struct group *grp, char *buf, size_t buflen) {
if (!grp || !buf || buflen < 64) {
return ERANGE;
}
int found = 0;
char found_name[64] = {0};
char found_pass[32] = {0};
gid_t found_gid = 0;
char found_members[256] = {0};
// 1. Try reading /etc/group from The native userland rootfs
#ifndef DDNATV_HOST_TEST
char path_buf[PATH_MAX];
const char *grp_path = rewrite_path("/etc/group", path_buf, sizeof(path_buf));
static int (*orig_open)(const char *, int, ...) = NULL;
if (!orig_open) orig_open = (int (*)(const char *, int, ...))dlsym(RTLD_NEXT, "open");
int fd = (orig_open && grp_path) ? orig_open(grp_path, O_RDONLY | O_CLOEXEC) : -1;
if (fd >= 0) {
char file_buf[8192];
ssize_t n = read(fd, file_buf, sizeof(file_buf) - 1);
close(fd);
if (n > 0) {
file_buf[n] = '\0';
char *line = file_buf;
while (*line && !found) {
char *next_line = strchr(line, '\n');
if (next_line) {
*next_line = '\0';
}
size_t llen = strlen(line);
if (llen > 0 && line[llen - 1] == '\r') line[llen - 1] = '\0';
// format: name:pass:gid:members
char *p1 = strchr(line, ':');
if (p1) {
*p1 = '\0';
char *p2 = strchr(p1 + 1, ':');
if (p2) {
*p2 = '\0';
char *p3 = strchr(p2 + 1, ':');
if (p3) {
*p3 = '\0';
const char *gname = line;
const char *gpass = p1 + 1;
gid_t ggid = (gid_t)strtoul(p2 + 1, NULL, 10);
const char *gmem = p3 + 1;
if (by_name && search_name && strcmp(gname, search_name) == 0) {
snprintf(found_name, sizeof(found_name), "%s", gname);
snprintf(found_pass, sizeof(found_pass), "%s", gpass);
found_gid = ggid;
snprintf(found_members, sizeof(found_members), "%s", gmem);
found = 1;
} else if (!by_name && ggid == search_gid) {
snprintf(found_name, sizeof(found_name), "%s", gname);
snprintf(found_pass, sizeof(found_pass), "%s", gpass);
found_gid = ggid;
snprintf(found_members, sizeof(found_members), "%s", gmem);
found = 1;
}
}
}
}
if (!next_line) break;
line = next_line + 1;
}
}
}
#endif
// 2. Fallbacks for well-known groups if absent from file
if (!found) {
if (by_name) {
if (!search_name) return ENOENT;
if (strcmp(search_name, "root") == 0 || strcmp(search_name, "ddnatv") == 0) {
snprintf(found_name, sizeof(found_name), "%s", search_name);
snprintf(found_pass, sizeof(found_pass), "x");
found_gid = 0;
snprintf(found_members, sizeof(found_members), "%s", search_name);
found = 1;
} else if (strcmp(search_name, "_ssh") == 0) {
snprintf(found_name, sizeof(found_name), "_ssh");
snprintf(found_pass, sizeof(found_pass), "x");
found_gid = 100;
found = 1;
} else if (strcmp(search_name, "ssh") == 0) {
snprintf(found_name, sizeof(found_name), "ssh");
snprintf(found_pass, sizeof(found_pass), "x");
found_gid = 101;
found = 1;
} else if (strcmp(search_name, "nogroup") == 0 || strcmp(search_name, "nobody") == 0) {
snprintf(found_name, sizeof(found_name), "%s", search_name);
snprintf(found_pass, sizeof(found_pass), "x");
found_gid = 65534;
found = 1;
}
} else {
if (search_gid == 0 || search_gid == real_gid()) {
snprintf(found_name, sizeof(found_name), "root");
snprintf(found_pass, sizeof(found_pass), "x");
found_gid = search_gid;
snprintf(found_members, sizeof(found_members), "root");
found = 1;
}
}
}
if (!found) {
return ENOENT;
}
// 3. Assemble struct group into caller's buf
size_t mem_ptr_count = 1;
char *m_copy = found_members;
while (*m_copy) {
if (*m_copy == ',') mem_ptr_count++;
m_copy++;
}
if (found_members[0] != '\0') mem_ptr_count++;
size_t mem_array_bytes = (mem_ptr_count + 1) * sizeof(char *);
mem_array_bytes = (mem_array_bytes + sizeof(void *) - 1) & ~(sizeof(void *) - 1);
size_t name_len = strlen(found_name) + 1;
size_t pass_len = strlen(found_pass) + 1;
size_t mem_str_len = strlen(found_members) + 1;
if (mem_array_bytes + name_len + pass_len + mem_str_len > buflen) {
return ERANGE;
}
char **mem_array = (char **)buf;
char *str_cursor = buf + mem_array_bytes;
grp->gr_name = str_cursor;
memcpy(str_cursor, found_name, name_len);
str_cursor += name_len;
grp->gr_passwd = str_cursor;
memcpy(str_cursor, found_pass, pass_len);
str_cursor += pass_len;
grp->gr_gid = found_gid;
size_t m_idx = 0;
if (found_members[0] != '\0') {
char *m_tok = str_cursor;
memcpy(str_cursor, found_members, mem_str_len);
str_cursor += mem_str_len;
char *curr = m_tok;
while (curr && *curr) {
char *comma = strchr(curr, ',');
if (comma) {
*comma = '\0';
}
if (*curr) {
mem_array[m_idx++] = curr;
}
curr = comma ? comma + 1 : NULL;
}
}
mem_array[m_idx] = NULL;
grp->gr_mem = mem_array;
return 0;
}
// Passwd lookup helper: reads $DDNATV_ROOT/etc/passwd or falls back to known entries
static int ddnatv_lookup_passwd(const char *search_name, uid_t search_uid, int by_name,
struct passwd *pwd, char *buf, size_t buflen) {
if (!pwd || !buf || buflen < 128) {
return ERANGE;
}
int found = 0;
char found_name[64] = {0};
char found_pass[32] = {0};
uid_t found_uid = 0;
gid_t found_gid = 0;
char found_gecos[64] = {0};
char found_dir[128] = {0};
char found_shell[64] = {0};
// 1. Try reading /etc/passwd from The native userland rootfs
#ifndef DDNATV_HOST_TEST
char path_buf[PATH_MAX];
const char *pwd_path = rewrite_path("/etc/passwd", path_buf, sizeof(path_buf));
static int (*orig_open)(const char *, int, ...) = NULL;
if (!orig_open) orig_open = (int (*)(const char *, int, ...))dlsym(RTLD_NEXT, "open");
int fd = (orig_open && pwd_path) ? orig_open(pwd_path, O_RDONLY | O_CLOEXEC) : -1;
if (fd >= 0) {
char file_buf[8192];
ssize_t n = read(fd, file_buf, sizeof(file_buf) - 1);
close(fd);
if (n > 0) {
file_buf[n] = '\0';
char *line = file_buf;
while (*line && !found) {
char *next_line = strchr(line, '\n');
if (next_line) {
*next_line = '\0';
}
size_t llen = strlen(line);
if (llen > 0 && line[llen - 1] == '\r') line[llen - 1] = '\0';
// format: name:pass:uid:gid:gecos:dir:shell
char *f[7] = {0};
char *curr = line;
int f_idx = 0;
while (curr && f_idx < 7) {
f[f_idx++] = curr;
char *col = strchr(curr, ':');
if (col && f_idx < 7) {
*col = '\0';
curr = col + 1;
} else {
break;
}
}
if (f_idx >= 7) {
const char *uname = f[0];
const char *upass = f[1];
uid_t uuid = (uid_t)strtoul(f[2], NULL, 10);
gid_t ugid = (gid_t)strtoul(f[3], NULL, 10);
const char *ugecos = f[4];
const char *udir = f[5];
const char *ushell = f[6];
if (by_name && search_name && strcmp(uname, search_name) == 0) {
snprintf(found_name, sizeof(found_name), "%s", uname);
snprintf(found_pass, sizeof(found_pass), "%s", upass);
found_uid = uuid;
found_gid = ugid;
snprintf(found_gecos, sizeof(found_gecos), "%s", ugecos);
snprintf(found_dir, sizeof(found_dir), "%s", udir);
snprintf(found_shell, sizeof(found_shell), "%s", ushell);
found = 1;
} else if (!by_name && uuid == search_uid) {
snprintf(found_name, sizeof(found_name), "%s", uname);
snprintf(found_pass, sizeof(found_pass), "%s", upass);
found_uid = uuid;
found_gid = ugid;
snprintf(found_gecos, sizeof(found_gecos), "%s", ugecos);
snprintf(found_dir, sizeof(found_dir), "%s", udir);
snprintf(found_shell, sizeof(found_shell), "%s", ushell);
found = 1;
}
}
if (!next_line) break;
line = next_line + 1;
}
}
}
#endif
// 2. Fallbacks for well-known users if absent from file
if (!found) {
if (by_name) {
if (!search_name) return ENOENT;
if (strcmp(search_name, "root") == 0) {
snprintf(found_name, sizeof(found_name), "root");
snprintf(found_pass, sizeof(found_pass), "x");
found_uid = 0;
found_gid = 0;
snprintf(found_gecos, sizeof(found_gecos), "root");
snprintf(found_dir, sizeof(found_dir), "/root");
snprintf(found_shell, sizeof(found_shell), "/bin/bash");
found = 1;
} else if (strcmp(search_name, "ddnatv") == 0) {
snprintf(found_name, sizeof(found_name), "ddnatv");
snprintf(found_pass, sizeof(found_pass), "x");
found_uid = 0;
found_gid = 0;
snprintf(found_gecos, sizeof(found_gecos), "The native userland");
snprintf(found_dir, sizeof(found_dir), "/home/ddnatv");
snprintf(found_shell, sizeof(found_shell), "/bin/bash");
found = 1;
} else if (strcmp(search_name, "_ssh") == 0) {
snprintf(found_name, sizeof(found_name), "_ssh");
snprintf(found_pass, sizeof(found_pass), "x");
found_uid = 100;
found_gid = 100;
snprintf(found_gecos, sizeof(found_gecos), "OpenSSH daemon");
snprintf(found_dir, sizeof(found_dir), "/run/sshd");
snprintf(found_shell, sizeof(found_shell), "/usr/sbin/nologin");
found = 1;
} else if (strcmp(search_name, "sshd") == 0) {
snprintf(found_name, sizeof(found_name), "sshd");
snprintf(found_pass, sizeof(found_pass), "x");
found_uid = 101;
found_gid = 101;
snprintf(found_gecos, sizeof(found_gecos), "Privilege-separated SSH");
snprintf(found_dir, sizeof(found_dir), "/run/sshd");
snprintf(found_shell, sizeof(found_shell), "/usr/sbin/nologin");
found = 1;
} else if (strcmp(search_name, "nobody") == 0) {
snprintf(found_name, sizeof(found_name), "nobody");
snprintf(found_pass, sizeof(found_pass), "x");
found_uid = 65534;
found_gid = 65534;
snprintf(found_gecos, sizeof(found_gecos), "nobody");
snprintf(found_dir, sizeof(found_dir), "/nonexistent");
snprintf(found_shell, sizeof(found_shell), "/usr/sbin/nologin");
found = 1;
}
} else {
if (search_uid == 0 || search_uid == real_uid()) {
snprintf(found_name, sizeof(found_name), "root");
snprintf(found_pass, sizeof(found_pass), "x");
found_uid = search_uid;
found_gid = 0;
snprintf(found_gecos, sizeof(found_gecos), "root");
snprintf(found_dir, sizeof(found_dir), "/home");
snprintf(found_shell, sizeof(found_shell), "/bin/bash");
found = 1;
}
}
}
if (!found) {
return ENOENT;
}
// 3. Assemble struct passwd into caller's buf
size_t name_len = strlen(found_name) + 1;
size_t pass_len = strlen(found_pass) + 1;
size_t gecos_len = strlen(found_gecos) + 1;
size_t dir_len = strlen(found_dir) + 1;
size_t shell_len = strlen(found_shell) + 1;
size_t total_str_bytes = name_len + pass_len + gecos_len + dir_len + shell_len;
if (total_str_bytes > buflen) {
return ERANGE;
}
char *str_cursor = buf;
pwd->pw_name = str_cursor;
memcpy(str_cursor, found_name, name_len);
str_cursor += name_len;
pwd->pw_passwd = str_cursor;
memcpy(str_cursor, found_pass, pass_len);
str_cursor += pass_len;
pwd->pw_uid = found_uid;
pwd->pw_gid = found_gid;
pwd->pw_gecos = str_cursor;
memcpy(str_cursor, found_gecos, gecos_len);
str_cursor += gecos_len;
pwd->pw_dir = str_cursor;
memcpy(str_cursor, found_dir, dir_len);
str_cursor += dir_len;
pwd->pw_shell = str_cursor;
memcpy(str_cursor, found_shell, shell_len);
str_cursor += shell_len;
return 0;
}
#ifndef DDNATV_HOST_TEST
// The shadow database (/etc/shadow) of the rootfs. libc reads the real /etc/shadow of the machine,
// which Android does not have: pam_unix's account check for root found no entry and answered
// "Authentication failure", so chfn, chsh and `adduser --gecos` (the installation of PostgreSQL)
// failed. The fields are "name:hash:lastchange:min:max:warn:inactive:expire:flag", numbers empty
// when unset (libc stores -1 then).
static int ddnatv_lookup_shadow(const char *name, struct spwd *sp, char *buf, size_t buflen) {
if (!name || !sp || !buf) return EINVAL;
char path_buf[PATH_MAX];
const char *path = rewrite_path("/etc/shadow", path_buf, sizeof(path_buf));
static int (*orig_open)(const char *, int, ...) = NULL;
if (!orig_open) orig_open = (int (*)(const char *, int, ...))dlsym(RTLD_NEXT, "open");
int fd = (orig_open && path) ? orig_open(path, O_RDONLY | O_CLOEXEC) : -1;
if (fd < 0) return ENOENT;
FILE *f = fdopen(fd, "r");
if (!f) {
close(fd);
return ENOENT;
}
size_t name_len = strlen(name);
char line[1024];
int err = ENOENT;
while (fgets(line, sizeof(line), f)) {
if (strncmp(line, name, name_len) != 0 || line[name_len] != ':') continue;
line[strcspn(line, "\r\n")] = '\0';
char *fields[9] = {0};
int n = 0;
char *cursor = line;
while (n < 9) {
fields[n++] = cursor;
char *colon = strchr(cursor, ':');
if (!colon) break;
*colon = '\0';
cursor = colon + 1;
}
size_t need = strlen(fields[0]) + 1 + strlen(fields[1] ? fields[1] : "") + 1;
if (n < 2 || need > buflen) {
err = n < 2 ? ENOENT : ERANGE;
break;
}
char *out = buf;
sp->sp_namp = out;
memcpy(out, fields[0], strlen(fields[0]) + 1);
out += strlen(fields[0]) + 1;
sp->sp_pwdp = out;
memcpy(out, fields[1], strlen(fields[1]) + 1);
long number[6];
for (int i = 0; i < 6; i++) {
const char *v = (2 + i < n) ? fields[2 + i] : NULL;
number[i] = (v && v[0] != '\0') ? strtol(v, NULL, 10) : -1;
}
sp->sp_lstchg = number[0];
sp->sp_min = number[1];
sp->sp_max = number[2];
sp->sp_warn = number[3];
sp->sp_inact = number[4];
sp->sp_expire = number[5];
sp->sp_flag = (8 < n && fields[8][0] != '\0') ? strtoul(fields[8], NULL, 10) : (unsigned long)-1;
err = 0;
break;
}
fclose(f);
return err;
}
int getspnam_r(const char *name, struct spwd *spbuf, char *buf, size_t buflen, struct spwd **result) {
static int (*orig_getspnam_r)(const char *, struct spwd *, char *, size_t, struct spwd **) = NULL;
if (!orig_getspnam_r) orig_getspnam_r = (int (*)(const char *, struct spwd *, char *, size_t, struct spwd **))dlsym(RTLD_NEXT, "getspnam_r");
int ret = ENOENT;
if (orig_getspnam_r) {
ret = orig_getspnam_r(name, spbuf, buf, buflen, result);
if ((ret == 0 && result && *result) || ret == ERANGE) return ret;
}
int err = ddnatv_lookup_shadow(name, spbuf, buf, buflen);
if (err == 0) {
if (result) *result = spbuf;
return 0;
}
if (result) *result = NULL;
return err == ENOENT ? (ret != 0 ? ret : ENOENT) : err;
}
struct spwd *getspnam(const char *name) {
static struct spwd entry;
static char entry_buf[1024];
struct spwd *found = NULL;
int err = getspnam_r(name, &entry, entry_buf, sizeof(entry_buf), &found);
if (err != 0) {
errno = err;
return NULL;
}
return found;
}
#endif /* !DDNATV_HOST_TEST */
static struct group s_grp_storage;
static char s_grp_buf[2048];
static struct passwd s_pwd_storage;
static char s_pwd_buf[2048];
struct group *DDNATV_NSS_SYM(getgrgid)(gid_t gid) {
#ifndef DDNATV_HOST_TEST
static struct group *(*orig_getgrgid)(gid_t) = NULL;
if (!orig_getgrgid) orig_getgrgid = (struct group *(*)(gid_t))dlsym(RTLD_NEXT, "getgrgid");
struct group *res = orig_getgrgid ? orig_getgrgid(gid) : NULL;
if (res) return res;
#endif
int err = ddnatv_lookup_group(NULL, gid, 0, &s_grp_storage, s_grp_buf, sizeof(s_grp_buf));
if (err == 0) return &s_grp_storage;
return NULL;
}
struct group *DDNATV_NSS_SYM(getgrnam)(const char *name) {
#ifndef DDNATV_HOST_TEST
static struct group *(*orig_getgrnam)(const char *) = NULL;
if (!orig_getgrnam) orig_getgrnam = (struct group *(*)(const char *))dlsym(RTLD_NEXT, "getgrnam");
struct group *res = orig_getgrnam ? orig_getgrnam(name) : NULL;
if (res) return res;
#endif
int err = ddnatv_lookup_group(name, 0, 1, &s_grp_storage, s_grp_buf, sizeof(s_grp_buf));
if (err == 0) return &s_grp_storage;
return NULL;
}
int DDNATV_NSS_SYM(getgrgid_r)(gid_t gid, struct group *grp, char *buf, size_t buflen, struct group **result) {
#ifndef DDNATV_HOST_TEST
static int (*orig_getgrgid_r)(gid_t, struct group *, char *, size_t, struct group **) = NULL;
if (!orig_getgrgid_r) orig_getgrgid_r = (int (*)(gid_t, struct group *, char *, size_t, struct group **))dlsym(RTLD_NEXT, "getgrgid_r");
int ret = orig_getgrgid_r ? orig_getgrgid_r(gid, grp, buf, buflen, result) : ENOENT;
#else
int ret = g_test_orig_nss_r_ret;
if (result) *result = (ret == 0 && g_test_orig_nss_r_found) ? grp : NULL;
#endif
if (ret == 0 && result && *result != NULL) return 0;
if (ret != 0 && ret != ENOENT) {
if (result) *result = NULL;
return ret;
}
int err = ddnatv_lookup_group(NULL, gid, 0, grp, buf, buflen);
if (err == 0) {
if (result) *result = grp;
return 0;
}
if (result) *result = NULL;
return (err == ERANGE) ? ERANGE : 0;
}
int DDNATV_NSS_SYM(getgrnam_r)(const char *name, struct group *grp, char *buf, size_t buflen, struct group **result) {
#ifndef DDNATV_HOST_TEST
static int (*orig_getgrnam_r)(const char *, struct group *, char *, size_t, struct group **) = NULL;
if (!orig_getgrnam_r) orig_getgrnam_r = (int (*)(const char *, struct group *, char *, size_t, struct group **))dlsym(RTLD_NEXT, "getgrnam_r");
int ret = orig_getgrnam_r ? orig_getgrnam_r(name, grp, buf, buflen, result) : ENOENT;
#else
int ret = g_test_orig_nss_r_ret;
if (result) *result = (ret == 0 && g_test_orig_nss_r_found) ? grp : NULL;
#endif
if (ret == 0 && result && *result != NULL) return 0;
if (ret != 0 && ret != ENOENT) {
if (result) *result = NULL;
return ret;
}
int err = ddnatv_lookup_group(name, 0, 1, grp, buf, buflen);
if (err == 0) {
if (result) *result = grp;
return 0;
}
if (result) *result = NULL;
return (err == ERANGE) ? ERANGE : 0;
}
// sshd's privilege-separated user is root's ids: The native userland cannot drop privileges (setuid() and
// setgid() only pretend to), and sshd's unprivileged part checks after dropping them that it cannot
// take them back, which ended it ("permanently_set_uid: was able to restore old [e]gid"). Like apt's
// sandbox user (APT::Sandbox::User "root"), it then runs as the rest does.
static struct passwd *present_privsep_user_as_root(struct passwd *pwd) {
if (pwd && pwd->pw_name && strcmp(pwd->pw_name, "sshd") == 0) {
pwd->pw_uid = 0;
pwd->pw_gid = 0;
}
return pwd;
}
struct passwd *DDNATV_NSS_SYM(getpwuid)(uid_t uid) {
#ifndef DDNATV_HOST_TEST
static struct passwd *(*orig_getpwuid)(uid_t) = NULL;
if (!orig_getpwuid) orig_getpwuid = (struct passwd *(*)(uid_t))dlsym(RTLD_NEXT, "getpwuid");
struct passwd *res = orig_getpwuid ? orig_getpwuid(uid) : NULL;
if (res) return res;
#endif
int err = ddnatv_lookup_passwd(NULL, uid, 0, &s_pwd_storage, s_pwd_buf, sizeof(s_pwd_buf));
if (err == 0) return &s_pwd_storage;
return NULL;
}
struct passwd *DDNATV_NSS_SYM(getpwnam)(const char *name) {
#ifndef DDNATV_HOST_TEST
static struct passwd *(*orig_getpwnam)(const char *) = NULL;
if (!orig_getpwnam) orig_getpwnam = (struct passwd *(*)(const char *))dlsym(RTLD_NEXT, "getpwnam");
struct passwd *res = orig_getpwnam ? orig_getpwnam(name) : NULL;
if (res) return present_privsep_user_as_root(res);
#endif
int err = ddnatv_lookup_passwd(name, 0, 1, &s_pwd_storage, s_pwd_buf, sizeof(s_pwd_buf));
if (err == 0) return present_privsep_user_as_root(&s_pwd_storage);
return NULL;
}
int DDNATV_NSS_SYM(getpwuid_r)(uid_t uid, struct passwd *pwd, char *buf, size_t buflen, struct passwd **result) {
#ifndef DDNATV_HOST_TEST
static int (*orig_getpwuid_r)(uid_t, struct passwd *, char *, size_t, struct passwd **) = NULL;
if (!orig_getpwuid_r) orig_getpwuid_r = (int (*)(uid_t, struct passwd *, char *, size_t, struct passwd **))dlsym(RTLD_NEXT, "getpwuid_r");
int ret = orig_getpwuid_r ? orig_getpwuid_r(uid, pwd, buf, buflen, result) : ENOENT;
#else
int ret = g_test_orig_nss_r_ret;
if (result) *result = (ret == 0 && g_test_orig_nss_r_found) ? pwd : NULL;
#endif
if (ret == 0 && result && *result != NULL) return 0;
if (ret != 0 && ret != ENOENT) {
if (result) *result = NULL;
return ret;
}
int err = ddnatv_lookup_passwd(NULL, uid, 0, pwd, buf, buflen);
if (err == 0) {
if (result) *result = pwd;
return 0;
}
if (result) *result = NULL;
return (err == ERANGE) ? ERANGE : 0;
}
int DDNATV_NSS_SYM(getpwnam_r)(const char *name, struct passwd *pwd, char *buf, size_t buflen, struct passwd **result) {
#ifndef DDNATV_HOST_TEST
static int (*orig_getpwnam_r)(const char *, struct passwd *, char *, size_t, struct passwd **) = NULL;
if (!orig_getpwnam_r) orig_getpwnam_r = (int (*)(const char *, struct passwd *, char *, size_t, struct passwd **))dlsym(RTLD_NEXT, "getpwnam_r");
int ret = orig_getpwnam_r ? orig_getpwnam_r(name, pwd, buf, buflen, result) : ENOENT;
#else
int ret = g_test_orig_nss_r_ret;
if (result) *result = (ret == 0 && g_test_orig_nss_r_found) ? pwd : NULL;
#endif
if (ret == 0 && result && *result != NULL) {
present_privsep_user_as_root(*result);
return 0;
}
if (ret != 0 && ret != ENOENT) {
if (result) *result = NULL;
return ret;
}
int err = ddnatv_lookup_passwd(name, 0, 1, pwd, buf, buflen);
if (err == 0) {
present_privsep_user_as_root(pwd);
if (result) *result = pwd;
return 0;
}
if (result) *result = NULL;
return (err == ERANGE) ? ERANGE : 0;
}
+996
View File
@@ -0,0 +1,996 @@
// Part of libddnatv-hook.so, included by ddnatv-hook.c (one translation unit, so the
// parts share their static functions and are built with the same command as before).
//
// Name resolution: DNS packets, the network's DNS servers, the fallback resolver, getaddrinfo()
// and the resolver state, and DNS queries to loopback redirected to a real server.
// ---- DNS packets and servers -------------------------------------------------------------
// Pure functions (no syscalls apart from if_nametoindex), so tests/native can check them directly.
#define DDNATV_DNS_TYPE_A 1
#define DDNATV_DNS_TYPE_AAAA 28
#define DDNATV_DNS_MAX_SERVERS 8
typedef struct {
struct sockaddr_storage addr;
socklen_t len;
} ddnatv_dns_server_t;
// Fills `server` with the DNS server `text` (an IPv4 or IPv6 address, IPv6 optionally with a
// "%interface" scope) on port 53. Returns 0 for loopback and unspecified addresses (nothing answers
// there on Android), for a link-local IPv6 address without a scope, and for anything invalid.
static int dns_server_from_string(const char *text, ddnatv_dns_server_t *server) {
memset(server, 0, sizeof(*server));
if (!text) return 0;
struct in_addr a4;
if (inet_pton(AF_INET, text, &a4) == 1) {
if ((ntohl(a4.s_addr) >> 24) == 127 || a4.s_addr == 0) return 0;
struct sockaddr_in *sin = (struct sockaddr_in *)&server->addr;
sin->sin_family = AF_INET;
sin->sin_port = htons(53);
sin->sin_addr = a4;
server->len = sizeof(*sin);
return 1;
}
char host[INET6_ADDRSTRLEN + IF_NAMESIZE + 2];
if (strlen(text) >= sizeof(host)) return 0;
strcpy(host, text);
unsigned int scope = 0;
char *pct = strchr(host, '%');
if (pct) {
*pct++ = '\0';
if (*pct >= '0' && *pct <= '9') {
scope = (unsigned int)strtoul(pct, NULL, 10);
} else {
scope = if_nametoindex(pct);
}
}
struct in6_addr a6;
if (inet_pton(AF_INET6, host, &a6) != 1) return 0;
if (IN6_IS_ADDR_LOOPBACK(&a6) || IN6_IS_ADDR_UNSPECIFIED(&a6)) return 0;
if (IN6_IS_ADDR_V4MAPPED(&a6) && (a6.s6_addr[12] == 127 || (a6.s6_addr[12] | a6.s6_addr[13] | a6.s6_addr[14] | a6.s6_addr[15]) == 0)) return 0;
if (IN6_IS_ADDR_LINKLOCAL(&a6) && scope == 0) return 0;
struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&server->addr;
sin6->sin6_family = AF_INET6;
sin6->sin6_port = htons(53);
sin6->sin6_addr = a6;
sin6->sin6_scope_id = scope;
server->len = sizeof(*sin6);
return 1;
}
// The "nameserver" lines of a resolv.conf, in order: up to `max` usable servers, IPv4 and IPv6.
static int parse_nameservers(const char *text, ddnatv_dns_server_t *out, int max) {
int count = 0;
const char *line = text;
while (line && *line && count < max) {
const char *next = strchr(line, '\n');
size_t len = next ? (size_t)(next - line) : strlen(line);
char buf[256];
if (len >= sizeof(buf)) len = sizeof(buf) - 1;
memcpy(buf, line, len);
buf[len] = '\0';
char *p = buf;
while (*p == ' ' || *p == '\t') p++;
if (strncmp(p, "nameserver", 10) == 0 && (p[10] == ' ' || p[10] == '\t')) {
p += 10;
while (*p == ' ' || *p == '\t') p++;
char *end = p;
while (*end && *end != ' ' && *end != '\t' && *end != '\r' && *end != '#' && *end != ';') end++;
*end = '\0';
if (dns_server_from_string(p, &out[count])) count++;
}
line = next ? next + 1 : NULL;
}
return count;
}
static int dns_server_equal(const ddnatv_dns_server_t *a, const ddnatv_dns_server_t *b) {
return a->len == b->len && memcmp(&a->addr, &b->addr, a->len) == 0;
}
// Builds a recursive query for one name and record type; returns its length, or -1 when the name
// is not a valid DNS name (an empty label, a label over 63 bytes, over 253 bytes in all).
static int dns_build_query(const char *name, int qtype, uint16_t txid, unsigned char *packet, size_t size) {
if (!name || !packet || size < 12) return -1;
size_t name_len = strlen(name);
if (name_len > 0 && name[name_len - 1] == '.') name_len--; // "example.com." is absolute
if (name_len == 0 || name_len > 253) return -1;
memset(packet, 0, 12);
packet[0] = (unsigned char)(txid >> 8);
packet[1] = (unsigned char)(txid & 0xff);
packet[2] = 0x01; // recursion desired
packet[5] = 0x01; // one question
size_t pos = 12;
size_t start = 0;
for (;;) {
size_t end = start;
while (end < name_len && name[end] != '.') end++;
size_t len = end - start;
if (len == 0 || len > 63 || pos + 1 + len + 1 + 4 > size) return -1;
packet[pos++] = (unsigned char)len;
memcpy(packet + pos, name + start, len);
pos += len;
if (end == name_len) break;
start = end + 1;
}
packet[pos++] = 0;
packet[pos++] = (unsigned char)(qtype >> 8);
packet[pos++] = (unsigned char)(qtype & 0xff);
packet[pos++] = 0x00;
packet[pos++] = 0x01; // class IN
return (int)pos;
}
// Offset after the (possibly compressed) name at `off`, or -1 when it is malformed.
static int dns_skip_name(const unsigned char *msg, int n, int off) {
for (int labels = 0; labels < 128; labels++) {
if (off >= n) return -1;
unsigned char len = msg[off];
if (len == 0) return off + 1;
if ((len & 0xc0) == 0xc0) return off + 2 <= n ? off + 2 : -1;
if (len & 0xc0) return -1;
off += 1 + len;
}
return -1;
}
// Copies the first address of type `qtype` (4 bytes for A, 16 for AAAA) from the reply `msg` to the
// query `txid` and returns 0. Returns 1 when the reply says there is no such address (the name does
// not exist, or has no record of that type): asking other servers would only send the name to more
// of them. Returns -1 for anything that is worth asking another server about: a failure (SERVFAIL,
// REFUSED), a truncated, malformed or foreign reply.
static int dns_parse_answer(const unsigned char *msg, int n, uint16_t txid, int qtype, unsigned char *out) {
if (!msg || n < 12) return -1;
if (((msg[0] << 8) | msg[1]) != txid) return -1;
if (!(msg[2] & 0x80)) return -1; // not a reply
int rcode = msg[3] & 0x0f;
if (rcode == 3) return 1; // NXDOMAIN
if (rcode != 0) return -1;
int qdcount = (msg[4] << 8) | msg[5];
int ancount = (msg[6] << 8) | msg[7];
int off = 12;
for (int q = 0; q < qdcount; q++) {
off = dns_skip_name(msg, n, off);
if (off < 0 || off + 4 > n) return -1;
off += 4;
}
int want = qtype == DDNATV_DNS_TYPE_AAAA ? 16 : 4;
for (int a = 0; a < ancount; a++) {
off = dns_skip_name(msg, n, off);
if (off < 0 || off + 10 > n) return -1;
int rtype = (msg[off] << 8) | msg[off + 1];
int rclass = (msg[off + 2] << 8) | msg[off + 3];
int rdlen = (msg[off + 8] << 8) | msg[off + 9];
off += 10;
if (off + rdlen > n) return -1;
if (rtype == qtype && rclass == 1 && rdlen == want) {
memcpy(out, msg + off, (size_t)want);
return 0;
}
off += rdlen;
}
return (msg[2] & 0x02) ? -1 : 1; // no such record, unless the reply was truncated
}
// ---- Sockets bound to a port the program chose ----------------------------------------------
// Which descriptors are TCP/UDP sockets that bind() gave a port the program asked for (not 0,
// where the kernel picks one). listen() reports only those to the app, which connects to a
// reported port to see whether it serves web pages (sockets.c). Descriptors past the bitmap
// are taken as not chosen: they are not reported.
#define DDNATV_CHOSEN_PORT_FDS 65536
static unsigned char g_chosen_port_fds[DDNATV_CHOSEN_PORT_FDS / 8];
static void set_chosen_port_fd(int fd, int chosen) {
if (fd < 0 || fd >= DDNATV_CHOSEN_PORT_FDS) return;
unsigned char bit = (unsigned char)(1u << (fd & 7));
// Written only when it changes: a page of the bitmap is copied for a forked child only then
if (chosen) {
if (!(__atomic_load_n(&g_chosen_port_fds[fd >> 3], __ATOMIC_RELAXED) & bit))
__atomic_fetch_or(&g_chosen_port_fds[fd >> 3], bit, __ATOMIC_RELAXED);
} else if (__atomic_load_n(&g_chosen_port_fds[fd >> 3], __ATOMIC_RELAXED) & bit) {
__atomic_fetch_and(&g_chosen_port_fds[fd >> 3], (unsigned char)~bit, __ATOMIC_RELAXED);
}
}
static int is_chosen_port_fd(int fd) {
if (fd < 0 || fd >= DDNATV_CHOSEN_PORT_FDS) return 0;
return (__atomic_load_n(&g_chosen_port_fds[fd >> 3], __ATOMIC_RELAXED) >> (fd & 7)) & 1;
}
#ifndef DDNATV_HOST_TEST
// DNS resolution hooking and localhost DNS redirect
#define DNS_REDIRECT_MAX 64
static struct {
int fd;
struct sockaddr_storage orig;
socklen_t orig_len;
uint32_t active;
} g_dns_redirects[DNS_REDIRECT_MAX];
static pthread_mutex_t g_dns_redirect_mutex = PTHREAD_MUTEX_INITIALIZER;
static void record_dns_redirect(int fd, const struct sockaddr *orig, socklen_t orig_len) {
if (fd < 0 || !orig) return;
if (orig_len > sizeof(struct sockaddr_storage)) orig_len = sizeof(struct sockaddr_storage);
pthread_mutex_lock(&g_dns_redirect_mutex);
int target_idx = (fd >= 0 ? fd : -fd) % DNS_REDIRECT_MAX;
g_dns_redirects[target_idx].fd = fd;
memcpy(&g_dns_redirects[target_idx].orig, orig, orig_len);
g_dns_redirects[target_idx].orig_len = orig_len;
g_dns_redirects[target_idx].active = 1;
pthread_mutex_unlock(&g_dns_redirect_mutex);
}
static void clear_dns_redirect(int fd) {
if (fd < 0) return;
int target_idx = (fd >= 0 ? fd : -fd) % DNS_REDIRECT_MAX;
if (!g_dns_redirects[target_idx].active || g_dns_redirects[target_idx].fd != fd) {
return;
}
pthread_mutex_lock(&g_dns_redirect_mutex);
if (g_dns_redirects[target_idx].active && g_dns_redirects[target_idx].fd == fd) {
g_dns_redirects[target_idx].active = 0;
g_dns_redirects[target_idx].fd = -1;
g_dns_redirects[target_idx].orig_len = 0;
}
pthread_mutex_unlock(&g_dns_redirect_mutex);
}
int close(int fd) {
static int (*orig_close)(int) = NULL;
if (!orig_close) orig_close = (int (*)(int))dlsym(RTLD_NEXT, "close");
// The ARM translator's memory file (privileged.c): left open, as if it were closed
if (g_kept_fd_count > 0 && is_kept_fd(fd)) return 0;
clear_dns_redirect(fd);
set_chosen_port_fd(fd, 0);
return orig_close ? orig_close(fd) : -1;
}
int dup2(int oldfd, int newfd) {
static int (*orig_dup2)(int, int) = NULL;
if (!orig_dup2) orig_dup2 = (int (*)(int, int))dlsym(RTLD_NEXT, "dup2");
if (oldfd != newfd) {
clear_dns_redirect(newfd);
set_chosen_port_fd(newfd, is_chosen_port_fd(oldfd));
}
return orig_dup2 ? orig_dup2(oldfd, newfd) : -1;
}
int dup3(int oldfd, int newfd, int flags) {
static int (*orig_dup3)(int, int, int) = NULL;
if (!orig_dup3) orig_dup3 = (int (*)(int, int, int))dlsym(RTLD_NEXT, "dup3");
if (oldfd != newfd) {
clear_dns_redirect(newfd);
set_chosen_port_fd(newfd, is_chosen_port_fd(oldfd));
}
return orig_dup3 ? orig_dup3(oldfd, newfd, flags) : -1;
}
static int get_dns_redirect(int fd, struct sockaddr_storage *orig, socklen_t *orig_len) {
if (fd < 0) return 0;
int found = 0;
pthread_mutex_lock(&g_dns_redirect_mutex);
int target_idx = (fd >= 0 ? fd : -fd) % DNS_REDIRECT_MAX;
if (g_dns_redirects[target_idx].active && g_dns_redirects[target_idx].fd == fd) {
if (orig) *orig = g_dns_redirects[target_idx].orig;
if (orig_len) *orig_len = g_dns_redirects[target_idx].orig_len;
found = 1;
}
pthread_mutex_unlock(&g_dns_redirect_mutex);
return found;
}
// A DNS query to 127.0.0.0/8 or ::1 (or ::ffff:127.x), where nothing listens on Android.
static inline int is_loopback_dns(const struct sockaddr *addr, socklen_t addrlen) {
if (!addr || addrlen < sizeof(sa_family_t)) return 0;
if (addr->sa_family == AF_INET && addrlen >= sizeof(struct sockaddr_in)) {
const struct sockaddr_in *sin = (const struct sockaddr_in *)addr;
return (sin->sin_port == htons(53) && ((ntohl(sin->sin_addr.s_addr) >> 24) == 127));
}
if (addr->sa_family == AF_INET6 && addrlen >= sizeof(struct sockaddr_in6)) {
const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)addr;
if (sin6->sin6_port != htons(53)) return 0;
return IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr) ||
(IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) && sin6->sin6_addr.s6_addr[12] == 127);
}
return 0;
}
static in_addr_t get_primary_dns(void) {
static in_addr_t cached_dns = 0;
static time_t last_check = 0;
static pthread_mutex_t dns_mutex = PTHREAD_MUTEX_INITIALIZER;
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
time_t now = ts.tv_sec;
// Fast path: cached value valid within 5s TTL
if (cached_dns != 0 && (now - last_check < 5)) {
return cached_dns;
}
pthread_mutex_lock(&dns_mutex);
if (cached_dns != 0 && (now - last_check < 5)) {
in_addr_t val = cached_dns;
pthread_mutex_unlock(&dns_mutex);
return val;
}
last_check = now;
in_addr_t new_dns = 0;
init_ddnatv_hook();
// 1. Check Android system property net.dns1 via Bionic libc
static int (*orig_sys_prop_get)(const char *, char *) = NULL;
static int prop_lookup_done = 0;
if (!prop_lookup_done) {
orig_sys_prop_get = (int (*)(const char *, char *))dlsym(RTLD_DEFAULT, "__system_property_get");
prop_lookup_done = 1;
}
if (orig_sys_prop_get) {
char prop_val[256];
if (orig_sys_prop_get("net.dns1", prop_val) > 0 && prop_val[0] != '\0') {
struct in_addr a;
if (inet_aton(prop_val, &a)) {
if ((ntohl(a.s_addr) >> 24) != 127 && a.s_addr != 0) {
new_dns = a.s_addr;
}
}
}
}
// 2. Parse /etc/resolv.conf in The native userland rootfs
char resolv_path[PATH_MAX];
if (g_ddnatv_root[0] != '\0') {
snprintf(resolv_path, sizeof(resolv_path), "%s/etc/resolv.conf", g_ddnatv_root);
} else {
snprintf(resolv_path, sizeof(resolv_path), "/etc/resolv.conf");
}
struct stat st;
if (stat(resolv_path, &st) == 0) {
if (new_dns == 0) {
FILE *f = fopen(resolv_path, "r");
if (f) {
char line[256];
while (fgets(line, sizeof(line), f)) {
char *p = line;
while (*p == ' ' || *p == '\t') p++;
if (strncmp(p, "nameserver", 10) == 0) {
p += 10;
while (*p == ' ' || *p == '\t') p++;
char *end = p;
while (*end && *end != ' ' && *end != '\t' && *end != '\r' && *end != '\n') end++;
*end = '\0';
struct in_addr a;
if (inet_aton(p, &a)) {
// Only accept valid, non-loopback DNS servers
if ((ntohl(a.s_addr) >> 24) != 127 && a.s_addr != 0) {
new_dns = a.s_addr;
break;
}
}
}
}
fclose(f);
}
}
}
if (new_dns == 0) {
new_dns = inet_addr("8.8.8.8");
}
cached_dns = new_dns;
pthread_mutex_unlock(&dns_mutex);
return cached_dns;
}
// The DNS servers in the rootfs resolv.conf (which the app writes from Android's network settings),
// read again at most every 5 seconds.
static int get_dns_servers(ddnatv_dns_server_t *out, int max) {
static ddnatv_dns_server_t cached[DDNATV_DNS_MAX_SERVERS];
static int cached_count = 0;
static time_t last_check = 0;
static int checked = 0;
static pthread_mutex_t servers_mutex = PTHREAD_MUTEX_INITIALIZER;
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
pthread_mutex_lock(&servers_mutex);
if (!checked || ts.tv_sec - last_check >= 5) {
checked = 1;
last_check = ts.tv_sec;
init_ddnatv_hook();
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/etc/resolv.conf", g_ddnatv_root[0] ? g_ddnatv_root : "");
char text[4096];
ssize_t n = -1;
int fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd >= 0) {
n = read(fd, text, sizeof(text) - 1);
close(fd);
}
text[n > 0 ? n : 0] = '\0';
cached_count = parse_nameservers(text, cached, DDNATV_DNS_MAX_SERVERS);
}
int count = cached_count < max ? cached_count : max;
memcpy(out, cached, (size_t)count * sizeof(cached[0]));
pthread_mutex_unlock(&servers_mutex);
return count;
}
// Where a DNS query to a loopback address goes instead: the network's DNS server, in the family of
// the socket (an IPv6 socket gets the first IPv6 server, else the IPv4 one as ::ffff:a.b.c.d).
// Returns the length of the address written to `out`.
static socklen_t dns_redirect_target(const struct sockaddr *orig, struct sockaddr_storage *out) {
memset(out, 0, sizeof(*out));
if (orig->sa_family == AF_INET) {
memcpy(out, orig, sizeof(struct sockaddr_in));
((struct sockaddr_in *)out)->sin_addr.s_addr = get_primary_dns();
return sizeof(struct sockaddr_in);
}
struct sockaddr_in6 *dst = (struct sockaddr_in6 *)out;
memcpy(dst, orig, sizeof(*dst));
ddnatv_dns_server_t servers[DDNATV_DNS_MAX_SERVERS];
int n = get_dns_servers(servers, DDNATV_DNS_MAX_SERVERS);
for (int i = 0; i < n; i++) {
if (servers[i].addr.ss_family == AF_INET6) {
const struct sockaddr_in6 *s6 = (const struct sockaddr_in6 *)&servers[i].addr;
dst->sin6_addr = s6->sin6_addr;
dst->sin6_scope_id = s6->sin6_scope_id;
return sizeof(*dst);
}
}
in_addr_t v4 = get_primary_dns();
memset(&dst->sin6_addr, 0, sizeof(dst->sin6_addr));
dst->sin6_addr.s6_addr[10] = 0xff;
dst->sin6_addr.s6_addr[11] = 0xff;
memcpy(&dst->sin6_addr.s6_addr[12], &v4, 4);
dst->sin6_scope_id = 0;
return sizeof(*dst);
}
// Puts the loopback address that a DNS socket was redirected from back into the source address of a
// reply (`cap` is the size of the caller's buffer), so resolvers that check the sender accept it.
static void restore_dns_source(int fd, struct sockaddr *addr, socklen_t cap, socklen_t *len) {
if (!addr || cap < sizeof(sa_family_t)) return;
in_port_t port;
if (addr->sa_family == AF_INET && cap >= sizeof(struct sockaddr_in)) {
port = ((const struct sockaddr_in *)addr)->sin_port;
} else if (addr->sa_family == AF_INET6 && cap >= sizeof(struct sockaddr_in6)) {
port = ((const struct sockaddr_in6 *)addr)->sin6_port;
} else {
return;
}
if (port != htons(53)) return;
struct sockaddr_storage orig;
socklen_t orig_len = 0;
if (!get_dns_redirect(fd, &orig, &orig_len) || orig.ss_family != addr->sa_family) return;
memcpy(addr, &orig, orig_len < cap ? orig_len : cap);
if (len) *len = orig_len;
}
#define DDNATV_ADDRINFO_MAGIC 0x434f5254
// One addrinfo for an IPv4 (4 bytes) or IPv6 (16 bytes) address; freed by the freeaddrinfo hook.
static struct addrinfo *alloc_addrinfo(const char *node, int family, const void *addr, int port, int socktype, int protocol) {
struct addrinfo *ai = (struct addrinfo *)calloc(1, sizeof(struct addrinfo));
if (!ai) return NULL;
socklen_t len = family == AF_INET6 ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in);
void *sa = calloc(1, len);
if (!sa) {
free(ai);
return NULL;
}
if (family == AF_INET6) {
struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
sin6->sin6_family = AF_INET6;
sin6->sin6_port = htons((uint16_t)port);
memcpy(&sin6->sin6_addr, addr, 16);
} else {
struct sockaddr_in *sin = (struct sockaddr_in *)sa;
sin->sin_family = AF_INET;
sin->sin_port = htons((uint16_t)port);
memcpy(&sin->sin_addr, addr, 4);
}
ai->ai_flags = DDNATV_ADDRINFO_MAGIC;
ai->ai_family = family;
ai->ai_socktype = socktype ? socktype : SOCK_STREAM;
ai->ai_protocol = protocol ? protocol : IPPROTO_TCP;
ai->ai_addrlen = len;
ai->ai_addr = (struct sockaddr *)sa;
ai->ai_canonname = node ? strdup(node) : NULL;
ai->ai_next = NULL;
return ai;
}
static struct addrinfo *alloc_one_addrinfo(const char *node, const char *ip_str, int port, int socktype, int protocol) {
struct in_addr a;
if (inet_pton(AF_INET, ip_str, &a) != 1) return NULL;
return alloc_addrinfo(node, AF_INET, &a, port, socktype, protocol);
}
static uint16_t generate_dns_txid(void) {
uint16_t txid = 0;
static ssize_t (*libc_getrandom)(void *, size_t, unsigned int) = NULL;
static int getrandom_checked = 0;
if (!getrandom_checked) {
libc_getrandom = (ssize_t (*)(void *, size_t, unsigned int))dlsym(RTLD_DEFAULT, "getrandom");
getrandom_checked = 1;
}
if (libc_getrandom) {
if (libc_getrandom(&txid, sizeof(txid), 1 /* GRND_NONBLOCK */) == sizeof(txid) && txid != 0) {
return txid;
}
}
#if defined(SYS_getrandom) || defined(__NR_getrandom)
#ifndef __NR_getrandom
#define __NR_getrandom SYS_getrandom
#endif
long r = syscall(__NR_getrandom, &txid, sizeof(txid), 1 /* GRND_NONBLOCK */);
if (r == (long)sizeof(txid) && txid != 0) {
return txid;
}
#endif
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
uint32_t val = (uint32_t)(ts.tv_nsec ^ (ts.tv_sec << 16) ^ (uintptr_t)&txid);
txid = (uint16_t)((val & 0xffff) ^ (val >> 16));
if (txid == 0) txid = 0x5a6b;
return txid;
}
static void add_dns_server(ddnatv_dns_server_t *list, int *count, int max, const ddnatv_dns_server_t *server) {
if (*count >= max) return;
for (int i = 0; i < *count; i++) {
if (dns_server_equal(&list[i], server)) return;
}
list[(*count)++] = *server;
}
// Looks one address of `name` up itself, for when glibc found none: asks the network's DNS servers,
// then public ones (IPv4 first, then IPv6, for IPv6-only networks without IPv4 translation), and
// stops at the first that answers. `qtype` is DDNATV_DNS_TYPE_A (4 bytes into `out`) or
// DDNATV_DNS_TYPE_AAAA (16 bytes). `*server` is -1 to ask them in turn, or the index of the only
// server to ask; on return it holds the server that answered (-1 when none did).
static int dns_lookup(const char *name, int qtype, unsigned char *out, int *server) {
if (!name || !out) return -1;
int family = qtype == DDNATV_DNS_TYPE_AAAA ? AF_INET6 : AF_INET;
if (inet_pton(family, name, out) == 1) return 0;
static const char *const k_public_dns[] = {
"8.8.8.8", "1.1.1.1", "9.9.9.9", "2001:4860:4860::8888", "2606:4700:4700::1111",
};
ddnatv_dns_server_t servers[DDNATV_DNS_MAX_SERVERS + 6];
int max = (int)(sizeof(servers) / sizeof(servers[0]));
int count = 0;
ddnatv_dns_server_t s;
char primary[INET_ADDRSTRLEN];
in_addr_t p_dns = get_primary_dns(); // also covers net.dns1 of older Android versions
if (inet_ntop(AF_INET, &p_dns, primary, sizeof(primary)) && dns_server_from_string(primary, &s)) {
add_dns_server(servers, &count, max, &s);
}
ddnatv_dns_server_t network[DDNATV_DNS_MAX_SERVERS];
int network_count = get_dns_servers(network, DDNATV_DNS_MAX_SERVERS);
for (int i = 0; i < network_count; i++) add_dns_server(servers, &count, max, &network[i]);
for (size_t i = 0; i < sizeof(k_public_dns) / sizeof(k_public_dns[0]); i++) {
if (dns_server_from_string(k_public_dns[i], &s)) add_dns_server(servers, &count, max, &s);
}
unsigned char packet[512];
uint16_t txid = generate_dns_txid();
int packet_len = dns_build_query(name, qtype, txid, packet, sizeof(packet));
if (packet_len < 0) return -1;
int only = *server;
*server = -1;
for (int i = (only >= 0 ? only : 0); i < count && (only < 0 || i == only); i++) {
int sock = socket(servers[i].addr.ss_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
if (sock < 0) continue;
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 600000; // 600ms fast failover
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
// A connected socket only receives datagrams from that server.
if (connect(sock, (const struct sockaddr *)&servers[i].addr, servers[i].len) != 0 ||
send(sock, packet, (size_t)packet_len, 0) != packet_len) {
close(sock);
continue;
}
unsigned char resp[1500];
ssize_t n = recv(sock, resp, sizeof(resp), 0);
close(sock);
int result = n > 0 ? dns_parse_answer(resp, (int)n, txid, qtype, out) : -1;
if (result >= 0) {
*server = i;
return result == 0 ? 0 : -1;
}
}
return -1;
}
// Whether the network's DNS servers are all IPv6 ones, as on an IPv6-only mobile network.
static int network_dns_is_ipv6_only(void) {
ddnatv_dns_server_t servers[DDNATV_DNS_MAX_SERVERS];
int n = get_dns_servers(servers, DDNATV_DNS_MAX_SERVERS);
for (int i = 0; i < n; i++) {
if (servers[i].addr.ss_family != AF_INET6) return 0;
}
return n > 0;
}
static int domain_matches(const char *node, const char *suffix) {
if (!node || !suffix) return 0;
size_t nlen = strlen(node);
size_t slen = strlen(suffix);
if (nlen < slen) return 0;
if (strcasecmp(node + (nlen - slen), suffix) != 0) return 0;
if (nlen == slen) return 1;
return (node[nlen - slen - 1] == '.');
}
static int synthesize_fallback_addrinfo(const char *node, const char *service,
const struct addrinfo *hints,
struct addrinfo **res) {
if (!node || !res) return EAI_NONAME;
int socktype = (hints && hints->ai_socktype) ? hints->ai_socktype : SOCK_STREAM;
int protocol = (hints && hints->ai_protocol) ? hints->ai_protocol : IPPROTO_TCP;
int family = hints ? hints->ai_family : AF_UNSPEC;
int port = 80;
if (service) {
if (strcmp(service, "https") == 0 || strcmp(service, "443") == 0) {
port = 443;
} else if (strcmp(service, "http") == 0 || strcmp(service, "80") == 0) {
port = 80;
} else if (service[0] >= '0' && service[0] <= '9') {
int p = 0;
const char *sp = service;
while (*sp >= '0' && *sp <= '9') {
p = p * 10 + (*sp - '0');
sp++;
}
if (p > 0 && p < 65536) port = p;
} else {
// A service name such as "ssh" or "domain", from /etc/services
struct servent se, *found = NULL;
char se_buf[1024];
if (getservbyname_r(service, socktype == SOCK_DGRAM ? "udp" : "tcp", &se, se_buf, sizeof(se_buf), &found) == 0 && found) {
port = ntohs((uint16_t)found->s_port);
}
}
}
// The address families the caller asked for: an IPv6-only caller must not get an IPv4 address,
// and AF_UNSPEC gets both, IPv6 first on a network whose DNS servers are all IPv6 ones. The second
// lookup only asks the server that answered the first, and is skipped when none answered.
int want4 = family == AF_UNSPEC || family == AF_INET;
int want6 = family == AF_UNSPEC || family == AF_INET6;
int v6_first = want6 && (!want4 || network_dns_is_ipv6_only());
unsigned char resolved[16];
int server = -1;
struct addrinfo *first = NULL;
struct addrinfo *second = NULL;
if (dns_lookup(node, v6_first ? DDNATV_DNS_TYPE_AAAA : DDNATV_DNS_TYPE_A, resolved, &server) == 0) {
first = alloc_addrinfo(node, v6_first ? AF_INET6 : AF_INET, resolved, port, socktype, protocol);
}
if (want4 && want6 && server >= 0 &&
dns_lookup(node, v6_first ? DDNATV_DNS_TYPE_A : DDNATV_DNS_TYPE_AAAA, resolved, &server) == 0) {
second = alloc_addrinfo(node, v6_first ? AF_INET : AF_INET6, resolved, port, socktype, protocol);
}
if (first && second) {
first->ai_next = second;
}
struct addrinfo *ai = first ? first : second;
if (ai) {
*res = ai;
return 0;
}
// The built-in addresses below are IPv4 ones.
if (family == AF_INET6) return EAI_NONAME;
if (domain_matches(node, "ubuntu.com")) {
struct addrinfo *ai1 = alloc_one_addrinfo(node, "91.189.91.103", port, socktype, protocol);
if (!ai1) return EAI_MEMORY;
struct addrinfo *ai2 = alloc_one_addrinfo(node, "91.189.92.21", port, socktype, protocol);
if (ai2) {
ai1->ai_next = ai2;
}
*res = ai1;
return 0;
}
if (domain_matches(node, "debian.org")) {
struct addrinfo *ai1 = alloc_one_addrinfo(node, "151.101.130.132", port, socktype, protocol);
if (!ai1) return EAI_MEMORY;
struct addrinfo *ai2 = alloc_one_addrinfo(node, "151.101.2.132", port, socktype, protocol);
if (ai2) {
ai1->ai_next = ai2;
}
*res = ai1;
return 0;
}
if (domain_matches(node, "opencode.ai")) {
struct addrinfo *ai1 = alloc_one_addrinfo(node, "172.65.90.22", port, socktype, protocol);
if (!ai1) return EAI_MEMORY;
struct addrinfo *ai2 = alloc_one_addrinfo(node, "172.65.90.23", port, socktype, protocol);
if (ai2) {
ai1->ai_next = ai2;
}
*res = ai1;
return 0;
}
if (domain_matches(node, "github.com")) {
struct addrinfo *ai1 = alloc_one_addrinfo(node, "140.82.121.6", port, socktype, protocol);
if (!ai1) return EAI_MEMORY;
struct addrinfo *ai2 = alloc_one_addrinfo(node, "140.82.121.4", port, socktype, protocol);
if (ai2) {
ai1->ai_next = ai2;
}
*res = ai1;
return 0;
}
if (domain_matches(node, "githubusercontent.com")) {
struct addrinfo *ai1 = alloc_one_addrinfo(node, "185.199.110.133", port, socktype, protocol);
if (!ai1) return EAI_MEMORY;
struct addrinfo *ai2 = alloc_one_addrinfo(node, "185.199.108.133", port, socktype, protocol);
if (ai2) {
ai1->ai_next = ai2;
}
*res = ai1;
return 0;
}
if (domain_matches(node, "npmjs.org") || domain_matches(node, "npmjs.com")) {
struct addrinfo *ai1 = alloc_one_addrinfo(node, "104.16.2.34", port, socktype, protocol);
if (!ai1) return EAI_MEMORY;
struct addrinfo *ai2 = alloc_one_addrinfo(node, "104.16.3.34", port, socktype, protocol);
if (ai2) {
ai1->ai_next = ai2;
}
*res = ai1;
return 0;
}
if (domain_matches(node, "googleapis.com") || domain_matches(node, "accounts.google.com")) {
struct addrinfo *ai1 = alloc_one_addrinfo(node, "142.251.127.95", port, socktype, protocol);
if (!ai1) return EAI_MEMORY;
struct addrinfo *ai2 = alloc_one_addrinfo(node, "142.251.127.84", port, socktype, protocol);
if (ai2) {
ai1->ai_next = ai2;
}
*res = ai1;
return 0;
}
if (domain_matches(node, "meta.ai") || domain_matches(node, "meta.com") || domain_matches(node, "facebook.com")) {
const char *ip = domain_matches(node, "lookaside.facebook.com") ? "57.144.36.128" : "57.144.36.141";
struct addrinfo *ai = alloc_one_addrinfo(node, ip, port, socktype, protocol);
if (ai) {
*res = ai;
return 0;
}
}
return EAI_NONAME;
}
int getaddrinfo(const char *node, const char *service,
const struct addrinfo *hints,
struct addrinfo **res) {
static int (*orig_getaddrinfo)(const char *, const char *, const struct addrinfo *, struct addrinfo **) = NULL;
if (!orig_getaddrinfo) orig_getaddrinfo = (int (*)(const char *, const char *, const struct addrinfo *, struct addrinfo **))dlsym(RTLD_NEXT, "getaddrinfo");
struct addrinfo mod_hints;
if (hints) {
mod_hints = *hints;
// On Android, unprivileged apps are blocked by SELinux from querying netlink routing interfaces.
// Glibc's AI_ADDRCONFIG flag causes getaddrinfo to fail or return no addresses when netlink fails.
// Clearing AI_ADDRCONFIG ensures normal, robust DNS resolution.
mod_hints.ai_flags &= ~AI_ADDRCONFIG;
} else {
memset(&mod_hints, 0, sizeof(mod_hints));
mod_hints.ai_family = AF_UNSPEC;
mod_hints.ai_flags = 0;
}
int ret = orig_getaddrinfo ? orig_getaddrinfo(node, service, &mod_hints, res) : EAI_FAIL;
// A numeric-only lookup must never turn into a DNS query.
if ((ret != 0 || !res || !*res) && node && !(hints && (hints->ai_flags & AI_NUMERICHOST))) {
int fallback = synthesize_fallback_addrinfo(node, service, hints, res);
// When the fallback finds nothing either, glibc's own error (EAI_AGAIN: try again later,
// EAI_NONAME: no such name) is the more precise one.
if (fallback == 0 || ret == 0) ret = fallback;
}
return ret;
}
void freeaddrinfo(struct addrinfo *res) {
static void (*orig_freeaddrinfo)(struct addrinfo *) = NULL;
if (!orig_freeaddrinfo) orig_freeaddrinfo = (void (*)(struct addrinfo *))dlsym(RTLD_NEXT, "freeaddrinfo");
if (!res) return;
if (res->ai_flags == DDNATV_ADDRINFO_MAGIC) {
struct addrinfo *curr = res;
while (curr) {
struct addrinfo *next = curr->ai_next;
if (curr->ai_canonname) free(curr->ai_canonname);
if (curr->ai_addr) free(curr->ai_addr);
free(curr);
curr = next;
}
return;
}
if (orig_freeaddrinfo) orig_freeaddrinfo(res);
}
// Whether a resolver state names a server other than loopback. glibc keeps IPv6 servers in the
// extension (their nsaddr_list entry has family 0), so an IPv6-only resolv.conf counts too.
static int res_state_has_usable_server(res_state statp) {
for (int i = 0; i < statp->nscount && i < MAXNS; i++) {
if (statp->nsaddr_list[i].sin_family == AF_INET) {
in_addr_t a = statp->nsaddr_list[i].sin_addr.s_addr;
if ((ntohl(a) >> 24) != 127 && a != 0) return 1;
} else if (statp->_u._ext.nsaddrs[i] != NULL) {
const struct in6_addr *a6 = &statp->_u._ext.nsaddrs[i]->sin6_addr;
if (!IN6_IS_ADDR_LOOPBACK(a6) && !IN6_IS_ADDR_UNSPECIFIED(a6)) return 1;
}
}
return 0;
}
int res_init(void) {
static int (*orig_res_init)(void) = NULL;
if (!orig_res_init) orig_res_init = (int (*)(void))dlsym(RTLD_NEXT, "res_init");
int ret = orig_res_init ? orig_res_init() : 0;
res_state statp = __res_state();
if (statp) {
if (!res_state_has_usable_server(statp)) {
statp->nscount = 2;
statp->nsaddr_list[0].sin_family = AF_INET;
statp->nsaddr_list[0].sin_port = htons(53);
statp->nsaddr_list[0].sin_addr.s_addr = get_primary_dns();
statp->nsaddr_list[1].sin_family = AF_INET;
statp->nsaddr_list[1].sin_port = htons(53);
inet_pton(AF_INET, "8.8.8.8", &statp->nsaddr_list[1].sin_addr);
}
statp->retrans = 1;
statp->retry = 2;
}
return ret;
}
int res_ninit(res_state statp) {
static int (*orig_res_ninit)(res_state) = NULL;
if (!orig_res_ninit) orig_res_ninit = (int (*)(res_state))dlsym(RTLD_NEXT, "res_ninit");
if (statp) {
memset(statp, 0, sizeof(*statp));
statp->_vcsock = -1;
for (int i = 0; i < MAXNS; i++) {
statp->_u._ext.nssocks[i] = -1;
}
}
int ret = orig_res_ninit ? orig_res_ninit(statp) : 0;
if (statp) {
if (!res_state_has_usable_server(statp)) {
statp->nscount = 2;
statp->nsaddr_list[0].sin_family = AF_INET;
statp->nsaddr_list[0].sin_port = htons(53);
statp->nsaddr_list[0].sin_addr.s_addr = get_primary_dns();
statp->nsaddr_list[1].sin_family = AF_INET;
statp->nsaddr_list[1].sin_port = htons(53);
inet_pton(AF_INET, "8.8.8.8", &statp->nsaddr_list[1].sin_addr);
}
statp->retrans = 1;
statp->retry = 2;
}
return ret;
}
int res_nquery(res_state statp, const char *dname, int class, int type,
unsigned char *answer, int anslen) {
static int (*orig_res_nquery)(res_state, const char *, int, int, unsigned char *, int) = NULL;
if (!orig_res_nquery) orig_res_nquery = (int (*)(res_state, const char *, int, int, unsigned char *, int))dlsym(RTLD_NEXT, "res_nquery");
// DNS SRV queries are optional for APT mirrors and frequently cause delays or issues
if (type == 33 /* T_SRV */) {
h_errno = NO_DATA;
return -1;
}
return orig_res_nquery ? orig_res_nquery(statp, dname, class, type, answer, anslen) : -1;
}
int res_query(const char *dname, int class, int type,
unsigned char *answer, int anslen) {
static int (*orig_res_query)(const char *, int, int, unsigned char *, int) = NULL;
if (!orig_res_query) orig_res_query = (int (*)(const char *, int, int, unsigned char *, int))dlsym(RTLD_NEXT, "res_query");
if (type == 33 /* T_SRV */) {
h_errno = NO_DATA;
return -1;
}
return orig_res_query ? orig_res_query(dname, class, type, answer, anslen) : -1;
}
int res_nsearch(res_state statp, const char *dname, int class, int type,
unsigned char *answer, int anslen) {
static int (*orig_res_nsearch)(res_state, const char *, int, int, unsigned char *, int) = NULL;
if (!orig_res_nsearch) orig_res_nsearch = (int (*)(res_state, const char *, int, int, unsigned char *, int))dlsym(RTLD_NEXT, "res_nsearch");
if (type == 33 /* T_SRV */) {
h_errno = NO_DATA;
return -1;
}
return orig_res_nsearch ? orig_res_nsearch(statp, dname, class, type, answer, anslen) : -1;
}
int res_search(const char *dname, int class, int type,
unsigned char *answer, int anslen) {
static int (*orig_res_search)(const char *, int, int, unsigned char *, int) = NULL;
if (!orig_res_search) orig_res_search = (int (*)(const char *, int, int, unsigned char *, int))dlsym(RTLD_NEXT, "res_search");
if (type == 33 /* T_SRV */) {
h_errno = NO_DATA;
return -1;
}
return orig_res_search ? orig_res_search(dname, class, type, answer, anslen) : -1;
}
static struct hostent s_fallback_hostent;
static char *s_fallback_aliases[1] = { NULL };
static in_addr_t s_fallback_addr1;
static in_addr_t s_fallback_addr2;
static char *s_fallback_addr_list[3] = { NULL, NULL, NULL };
static struct hostent *get_fallback_hostent(const char *name) {
if (!name) return NULL;
if (strstr(name, "ubuntu.com") != NULL) {
inet_pton(AF_INET, "91.189.91.103", &s_fallback_addr1);
inet_pton(AF_INET, "91.189.92.21", &s_fallback_addr2);
} else if (strstr(name, "debian.org") != NULL) {
inet_pton(AF_INET, "151.101.130.132", &s_fallback_addr1);
inet_pton(AF_INET, "151.101.2.132", &s_fallback_addr2);
} else {
return NULL;
}
s_fallback_addr_list[0] = (char *)&s_fallback_addr1;
s_fallback_addr_list[1] = (char *)&s_fallback_addr2;
s_fallback_addr_list[2] = NULL;
s_fallback_hostent.h_name = (char *)name;
s_fallback_hostent.h_aliases = s_fallback_aliases;
s_fallback_hostent.h_addrtype = AF_INET;
s_fallback_hostent.h_length = sizeof(in_addr_t);
s_fallback_hostent.h_addr_list = s_fallback_addr_list;
return &s_fallback_hostent;
}
struct hostent *gethostbyname(const char *name) {
static struct hostent *(*orig_gethostbyname)(const char *) = NULL;
if (!orig_gethostbyname) orig_gethostbyname = (struct hostent *(*)(const char *))dlsym(RTLD_NEXT, "gethostbyname");
struct hostent *ret = orig_gethostbyname ? orig_gethostbyname(name) : NULL;
if (!ret && name && (strstr(name, "ubuntu.com") || strstr(name, "debian.org"))) {
return get_fallback_hostent(name);
}
return ret;
}
struct hostent *gethostbyname2(const char *name, int af) {
static struct hostent *(*orig_gethostbyname2)(const char *, int) = NULL;
if (!orig_gethostbyname2) orig_gethostbyname2 = (struct hostent *(*)(const char *, int))dlsym(RTLD_NEXT, "gethostbyname2");
struct hostent *ret = orig_gethostbyname2 ? orig_gethostbyname2(name, af) : NULL;
if (!ret && (af == AF_INET || af == AF_UNSPEC) && name && (strstr(name, "ubuntu.com") || strstr(name, "debian.org"))) {
return get_fallback_hostent(name);
}
return ret;
}
#endif /* !DDNATV_HOST_TEST */
Binary file not shown.
+33
View File
@@ -0,0 +1,33 @@
// Part of libddnatv-hook.so, included by ddnatv-hook.c.
//
// shm_open() and shm_unlink() of glibc open /dev/shm/NAME with a system call of their own, which
// the path hooks never see and Android has no /dev/shm for. They go through open() and unlink()
// here, which map /dev/shm.
#ifndef DDNATV_HOST_TEST
static int posix_shm_path(const char *name, char *path, size_t size) {
if (!name) { errno = EINVAL; return -1; }
while (*name == '/') name++;
size_t len = strlen(name);
if (len == 0 || len > NAME_MAX || strchr(name, '/') || strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
errno = len > NAME_MAX ? ENAMETOOLONG : EINVAL;
return -1;
}
if (snprintf(path, size, "/dev/shm/%s", name) >= (int)size) { errno = ENAMETOOLONG; return -1; }
return 0;
}
int shm_open(const char *name, int oflag, mode_t mode) {
char path[PATH_MAX];
if (posix_shm_path(name, path, sizeof(path)) < 0) return -1;
return open(path, (oflag & (O_ACCMODE | O_CREAT | O_EXCL | O_TRUNC)) | O_NOFOLLOW | O_CLOEXEC, mode);
}
int shm_unlink(const char *name) {
char path[PATH_MAX];
if (posix_shm_path(name, path, sizeof(path)) < 0) return -1;
return unlink(path);
}
#endif /* !DDNATV_HOST_TEST */
+786
View File
@@ -0,0 +1,786 @@
// Part of libddnatv-hook.so, included by ddnatv-hook.c (one translation unit, so the
// parts share their static functions and are built with the same command as before).
//
// Calls an app may not make (chown, mknod, capabilities, prctl, landlock, seccomp, namespaces,
// close_range) and the generic syscall() entry point.
// The ARM translator of x86 devices and emulators (ndk_translation, houdini) keeps memory files of
// its own open in the process (ndk_translation at descriptor 3) and needs them whenever it
// translates more code: a program that closes every descriptor it did not open (sshd at start,
// closefrom(3)) made it abort later ("CHECK failed" in mmap_posix.cc). Its memory files open when
// the hook starts survive close(), close_range() and closefrom(); phones that run ARM code
// themselves have none.
#define DDNATV_MAX_KEPT_FDS 4
static int g_kept_fds[DDNATV_MAX_KEPT_FDS]; // ascending
static int g_kept_fd_count = 0;
static int is_kept_fd(int fd) {
for (int i = 0; i < g_kept_fd_count; i++) {
if (g_kept_fds[i] == fd) return 1;
}
return 0;
}
// Calls fn for each part of [first, last] that leaves out the descriptors in kept (ascending);
// the first nonzero answer of fn is returned, else 0.
static int for_each_range_without(unsigned int first, unsigned int last, const int *kept, int nkept,
int (*fn)(unsigned int, unsigned int, void *), void *arg) {
unsigned int from = first;
for (int i = 0; i < nkept && from <= last; i++) {
if (kept[i] < 0 || (unsigned int)kept[i] < from || (unsigned int)kept[i] > last) continue;
unsigned int k = (unsigned int)kept[i];
if (k > from) {
int r = fn(from, k - 1, arg);
if (r != 0) return r;
}
if (k == last) return 0;
from = k + 1;
}
return from <= last ? fn(from, last, arg) : 0;
}
#ifndef DDNATV_HOST_TEST
// ndk_translation's file is "/memfd:child"; any memory file counts in a process whose executable is
// a translator's runner (houdini). ndk_translation shows a program its own path as /proc/self/exe,
// so the name is what tells there.
//
// This runs at the start of every program, so it costs three system calls on a phone that runs ARM
// code itself: the descriptors that are open (/proc/self/fd, read at once) are all that are asked
// about, where asking about each of the numbers from 3 to 63 was 61 readlink() calls in every
// process that was started.
// Set once this process knows that it has none (it looked, or was told by DDNATV_NT=0 in its
// environment, which prepare_ddnatv_env hands on to the programs it starts)
static int g_no_translator = 0;
__attribute__((constructor(102))) static void find_translator_files(void) {
// The first program of a session looks; the ones it starts are told (a translator is there for
// all the programs of a machine or for none, and where it is not known they look as before)
const char *known = getenv("DDNATV_NT");
if (known && known[0] == '0' && known[1] == '\0') {
g_no_translator = 1;
return;
}
ssize_t (*real_readlink)(const char *, char *, size_t) = (ssize_t (*)(const char *, char *, size_t))dlsym(RTLD_NEXT, "readlink");
int (*real_open)(const char *, int, ...) = (int (*)(const char *, int, ...))dlsym(RTLD_NEXT, "open");
int (*real_close)(int) = (int (*)(int))dlsym(RTLD_NEXT, "close");
ssize_t (*real_getdents64)(int, void *, size_t) = (ssize_t (*)(int, void *, size_t))dlsym(RTLD_NEXT, "getdents64");
if (!real_readlink || !real_open || !real_close) return;
int dir = real_getdents64 ? real_open("/proc/self/fd", O_RDONLY | O_DIRECTORY | O_CLOEXEC) : -1;
if (dir < 0) return;
// The numbers of the descriptors open now, those from 3 to 63 (the directory's own left out)
char entries[2048];
unsigned char open_fds[64];
int nopen = 0;
for (;;) {
long n = real_getdents64(dir, entries, sizeof(entries));
if (n <= 0) break;
for (long off = 0; off < n;) {
// struct linux_dirent64: d_ino (8), d_off (8), d_reclen (2), d_type (1), then d_name
unsigned short reclen;
memcpy(&reclen, entries + off + 16, sizeof(reclen));
const char *name = entries + off + 19;
off += reclen ? reclen : n; // a record without a length ends the buffer
if (name[0] < '0' || name[0] > '9') continue; // "." and ".."
int fd = atoi(name);
if (fd >= 3 && fd < 64 && fd != dir) open_fds[nopen++] = (unsigned char)fd;
}
// A short answer is the whole directory; asking again would only be told "no more"
if ((size_t)n + 64 <= sizeof(entries)) break;
}
real_close(dir);
if (nopen == 0) {
g_no_translator = 1;
return;
}
char path[PATH_MAX];
int runner = 0;
ssize_t n = real_readlink("/proc/self/exe", path, sizeof(path) - 1);
if (n > 0) {
path[n] = '\0';
const char *base = strrchr(path, '/');
base = base ? base + 1 : path;
runner = strncmp(base, "ndk_translation", 15) == 0 || strncmp(base, "houdini", 7) == 0;
}
// In ascending order, as the list is kept
for (int i = 0; i < nopen - 1; i++) {
for (int j = i + 1; j < nopen; j++) {
if (open_fds[j] < open_fds[i]) {
unsigned char t = open_fds[i];
open_fds[i] = open_fds[j];
open_fds[j] = t;
}
}
}
for (int i = 0; i < nopen && g_kept_fd_count < DDNATV_MAX_KEPT_FDS; i++) {
char link[32], target[64];
snprintf(link, sizeof(link), "/proc/self/fd/%d", open_fds[i]);
ssize_t m = real_readlink(link, target, sizeof(target) - 1);
if (m <= 0) continue;
target[m] = '\0';
if (strncmp(target, "/memfd:child", 12) == 0 || (runner && strncmp(target, "/memfd:", 7) == 0)) {
g_kept_fds[g_kept_fd_count++] = open_fds[i];
}
}
if (g_kept_fd_count == 0) g_no_translator = 1;
}
int chown(const char *pathname, uid_t owner, gid_t group) { (void)pathname; (void)owner; (void)group; return 0; }
int fchown(int fd, uid_t owner, gid_t group) { (void)fd; (void)owner; (void)group; return 0; }
int lchown(const char *pathname, uid_t owner, gid_t group) { (void)pathname; (void)owner; (void)group; return 0; }
int fchownat(int dirfd, const char *pathname, uid_t owner, gid_t group, int flags) {
(void)dirfd; (void)pathname; (void)owner; (void)group; (void)flags; return 0;
}
int chroot(const char *path) { (void)path; return 0; }
// Hook mkfifo / mkfifoat / mknod / mknodat
int mkfifo(const char *pathname, mode_t mode);
int mkfifoat(int dirfd, const char *pathname, mode_t mode);
int mknodat(int dirfd, const char *pathname, mode_t mode, dev_t dev) {
(void)dev;
if (!pathname) {
errno = EFAULT;
return -1;
}
char buf[PATH_MAX];
const char *target = (pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname;
// A file type of 0 means a regular file, as in mknod(2), which also fails with EEXIST instead
// of touching an existing file.
if (S_ISREG(mode) || (mode & S_IFMT) == 0) {
// mknod(2) returns 0 on success, never a file descriptor: close the
// transient fd instead of leaking one per call (tar/dpkg extract
// thousands of files; leaked fds exhaust the table -> EBADF noise).
int fd = openat(dirfd, target, O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC, mode & 07777);
if (fd >= 0) {
close(fd);
return 0;
}
return -1;
}
if (S_ISFIFO(mode)) {
return mkfifoat(dirfd, target, mode);
}
return 0;
}
int mknod(const char *pathname, mode_t mode, dev_t dev) {
return mknodat(AT_FDCWD, pathname, mode, dev);
}
int mkfifoat(int dirfd, const char *pathname, mode_t mode) {
static int (*orig_mkfifoat)(int, const char *, mode_t) = NULL;
if (!orig_mkfifoat) orig_mkfifoat = (int (*)(int, const char *, mode_t))dlsym(RTLD_NEXT, "mkfifoat");
if (!pathname) {
errno = EFAULT;
return -1;
}
char buf[PATH_MAX];
const char *target = (pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname;
if (orig_mkfifoat) {
return orig_mkfifoat(dirfd, target, mode);
}
static int (*orig_mkfifo)(const char *, mode_t) = NULL;
if (!orig_mkfifo) orig_mkfifo = (int (*)(const char *, mode_t))dlsym(RTLD_NEXT, "mkfifo");
if (orig_mkfifo && dirfd == AT_FDCWD) {
return orig_mkfifo(target, mode);
}
return -1;
}
int mkfifo(const char *pathname, mode_t mode) {
return mkfifoat(AT_FDCWD, pathname, mode);
}
// Hook sync / syncfs to prevent Android flash storage stalls during dpkg operations
void sync(void) {
// No-op
}
int syncfs(int fd) {
(void)fd;
return 0;
}
int capget(void *hdrp, void *datap) {
static int (*orig_capget)(void *, void *) = NULL;
if (!orig_capget) orig_capget = (int (*)(void *, void *))dlsym(RTLD_NEXT, "capget");
if (orig_capget && orig_capget(hdrp, datap) == 0) {
return 0;
}
if (datap) {
uint32_t ver = hdrp ? *(const uint32_t *)hdrp : 0;
size_t nbytes = (ver == 0x20071026U || ver == 0x20080522U) ? 24 : 12;
memset(datap, 0, nbytes);
}
errno = 0;
return 0;
}
int capset(void *hdrp, const void *datap) { (void)hdrp; (void)datap; return 0; }
int prctl(int option, ...) {
va_list ap;
va_start(ap, option);
unsigned long arg2 = va_arg(ap, unsigned long);
unsigned long arg3 = va_arg(ap, unsigned long);
unsigned long arg4 = va_arg(ap, unsigned long);
unsigned long arg5 = va_arg(ap, unsigned long);
va_end(ap);
// PR_SET_NO_NEW_PRIVS = 38, PR_GET_NO_NEW_PRIVS = 39
#ifdef PR_SET_NO_NEW_PRIVS
if (option == PR_SET_NO_NEW_PRIVS) return 0;
#endif
if (option == 38) return 0;
#ifdef PR_GET_NO_NEW_PRIVS
if (option == PR_GET_NO_NEW_PRIVS) return 1;
#endif
if (option == 39) return 1;
// PR_SET_SECCOMP = 22, PR_GET_SECCOMP = 21
#ifdef PR_SET_SECCOMP
if (option == PR_SET_SECCOMP) { errno = EINVAL; return -1; }
#endif
if (option == 22) { errno = EINVAL; return -1; }
#ifdef PR_GET_SECCOMP
if (option == PR_GET_SECCOMP) return 0;
#endif
if (option == 21) return 0;
// PR_SET_SPECULATION_CTRL = 47
if (option == 47) return 0;
static int (*orig_prctl)(int, unsigned long, unsigned long, unsigned long, unsigned long) = NULL;
if (!orig_prctl) orig_prctl = (int (*)(int, unsigned long, unsigned long, unsigned long, unsigned long))dlsym(RTLD_NEXT, "prctl");
return orig_prctl ? orig_prctl(option, arg2, arg3, arg4, arg5) : 0;
}
// Limits that leave a process no new descriptors (RLIMIT_NOFILE below 16) or no file writes
// (RLIMIT_FSIZE 0) are not applied. Sandboxes give them to their unprivileged part (sshd's before
// login sets 1 and 0, with the seccomp filter above), and Android's ARM translator (emulators, x86
// devices) needs new descriptors and memory files in the process: sshd's died in it ("CHECK failed"
// in its mmap) and the client's connection was reset. Other limits are set as asked.
static int sandbox_only_limit(int resource, const struct rlimit *rlim) {
if (!rlim) return 0;
if (resource == RLIMIT_NOFILE) return rlim->rlim_cur < 16;
if (resource == RLIMIT_FSIZE) return rlim->rlim_cur == 0;
return 0;
}
int setrlimit(__rlimit_resource_t resource, const struct rlimit *rlim) {
if (sandbox_only_limit((int)resource, rlim)) return 0;
static int (*orig_setrlimit)(__rlimit_resource_t, const struct rlimit *) = NULL;
#if defined(__USE_FILE_OFFSET64) && !defined(__LP64__)
// With 64-bit file offsets on a 32-bit system this function is setrlimit64
if (!orig_setrlimit) orig_setrlimit = (int (*)(__rlimit_resource_t, const struct rlimit *))dlsym(RTLD_NEXT, "setrlimit64");
#else
if (!orig_setrlimit) orig_setrlimit = (int (*)(__rlimit_resource_t, const struct rlimit *))dlsym(RTLD_NEXT, "setrlimit");
#endif
if (!orig_setrlimit) {
errno = ENOSYS;
return -1;
}
return orig_setrlimit(resource, rlim);
}
#if defined(__LP64__)
__asm__(".globl setrlimit64\n" ".set setrlimit64, setrlimit\n");
#endif
#ifndef LANDLOCK_CREATE_RULESET_VERSION
#define LANDLOCK_CREATE_RULESET_VERSION (1U << 0)
#endif
#ifndef __NR_landlock_create_ruleset
#define __NR_landlock_create_ruleset 444
#endif
#ifndef __NR_landlock_add_rule
#define __NR_landlock_add_rule 445
#endif
#ifndef __NR_landlock_restrict_self
#define __NR_landlock_restrict_self 446
#endif
#ifndef __NR_seccomp
#if defined(__aarch64__)
#define __NR_seccomp 277
#elif defined(__x86_64__)
#define __NR_seccomp 317
#elif defined(__arm__)
#define __NR_seccomp 383
#else
#define __NR_seccomp 277
#endif
#endif
#ifndef __NR_unshare
#if defined(__aarch64__)
#define __NR_unshare 97
#elif defined(__x86_64__)
#define __NR_unshare 272
#elif defined(__arm__)
#define __NR_unshare 337
#else
#define __NR_unshare 97
#endif
#endif
#ifndef __NR_setns
#if defined(__aarch64__)
#define __NR_setns 268
#elif defined(__x86_64__)
#define __NR_setns 308
#elif defined(__arm__)
#define __NR_setns 375
#else
#define __NR_setns 268
#endif
#endif
#ifndef __NR_clone3
#define __NR_clone3 435
#endif
#ifndef __NR_pidfd_open
#define __NR_pidfd_open 434
#endif
#ifndef __NR_pidfd_send_signal
#define __NR_pidfd_send_signal 424
#endif
#ifndef __NR_pidfd_getfd
#define __NR_pidfd_getfd 438
#endif
#ifndef __NR_close_range
#define __NR_close_range 436
#endif
#ifndef __NR_faccessat
#if defined(__aarch64__)
#define __NR_faccessat 48
#elif defined(__arm__)
#define __NR_faccessat 334
#elif defined(__x86_64__)
#define __NR_faccessat 269
#endif
#endif
#ifndef __NR_faccessat2
#define __NR_faccessat2 439
#endif
#ifndef __NR_statx
#if defined(__aarch64__) || defined(__arm__)
#define __NR_statx 291
#elif defined(__x86_64__)
#define __NR_statx 332
#endif
#endif
#ifndef SECCOMP_SET_MODE_STRICT
#define SECCOMP_SET_MODE_STRICT 0
#endif
#ifndef SECCOMP_SET_MODE_FILTER
#define SECCOMP_SET_MODE_FILTER 1
#endif
#ifndef SECCOMP_GET_ACTION_AVAIL
#define SECCOMP_GET_ACTION_AVAIL 2
#endif
int landlock_create_ruleset(const void *attr, size_t size, uint32_t flags) {
(void)attr;
(void)size;
(void)flags;
errno = ENOSYS;
return -1;
}
int landlock_add_rule(int ruleset_fd, int rule_type, const void *rule_attr, uint32_t flags) {
(void)ruleset_fd;
(void)rule_type;
(void)rule_attr;
(void)flags;
errno = ENOSYS;
return -1;
}
int landlock_restrict_self(int ruleset_fd, uint32_t flags) {
(void)ruleset_fd;
(void)flags;
errno = ENOSYS;
return -1;
}
int seccomp(unsigned int operation, unsigned int flags, void *args) {
(void)flags;
(void)args;
if (operation != SECCOMP_SET_MODE_STRICT &&
operation != SECCOMP_SET_MODE_FILTER &&
operation != SECCOMP_GET_ACTION_AVAIL &&
operation != 3 /* SECCOMP_GET_NOTIF_SIZES */) {
errno = EINVAL;
return -1;
}
errno = ENOSYS;
return -1;
}
int unshare(int flags) {
(void)flags;
errno = ENOSYS;
return -1;
}
int setns(int fd, int nstype) {
(void)fd;
(void)nstype;
errno = ENOSYS;
return -1;
}
#ifndef CLOSE_RANGE_CLOEXEC
#define CLOSE_RANGE_CLOEXEC (1U << 2)
#endif
static int close_range_all(unsigned int first, unsigned int last, int flags);
static int close_range_part(unsigned int first, unsigned int last, void *flags) {
return close_range_all(first, last, *(int *)flags);
}
int close_range(unsigned int first, unsigned int last, int flags) {
// Close-on-exec only (CLOSE_RANGE_CLOEXEC) leaves the translator's files open
if (g_kept_fd_count > 0 && !(flags & CLOSE_RANGE_CLOEXEC)) {
return for_each_range_without(first, last, g_kept_fds, g_kept_fd_count, close_range_part, &flags);
}
return close_range_all(first, last, flags);
}
// glibc's closefrom() makes the close_range system call itself, past the function above
void closefrom(int lowfd) {
close_range(lowfd < 0 ? 0U : (unsigned int)lowfd, ~0U, 0);
}
static int close_range_all(unsigned int first, unsigned int last, int flags) {
static int (*orig_close_range)(unsigned int, unsigned int, int) = NULL;
if (!orig_close_range) {
orig_close_range = (int (*)(unsigned int, unsigned int, int))dlsym(RTLD_NEXT, "close_range");
}
#ifdef __NR_close_range
static long (*orig_raw_syscall)(long, ...) = NULL;
if (!orig_raw_syscall) orig_raw_syscall = (long (*)(long, ...))dlsym(RTLD_NEXT, "syscall");
if (orig_raw_syscall) {
long sret = orig_raw_syscall(__NR_close_range, first, last, flags);
if (sret == 0) return 0;
if (sret < 0 && errno != ENOSYS) return -1;
}
#endif
if (orig_close_range) {
int cret = orig_close_range(first, last, flags);
if (cret == 0) return 0;
if (cret < 0 && errno != ENOSYS) return -1;
}
int set_cloexec = (flags & CLOSE_RANGE_CLOEXEC) != 0;
DIR *d = opendir("/proc/self/fd");
if (d) {
int dfd = dirfd(d);
struct dirent *de;
while ((de = readdir(d)) != NULL) {
if (de->d_name[0] == '.') continue;
int fd = atoi(de->d_name);
if (fd >= (int)first && (last == ~0U || (unsigned int)fd <= last) && fd != dfd) {
if (set_cloexec) {
int fl = fcntl(fd, F_GETFD);
if (fl >= 0) {
fcntl(fd, F_SETFD, fl | FD_CLOEXEC);
}
} else {
close(fd);
}
}
}
closedir(d);
return 0;
}
int max_fd = (int)sysconf(_SC_OPEN_MAX);
if (max_fd <= 0 || max_fd > 1024) max_fd = 1024;
int end = (last < (unsigned int)max_fd) ? (int)last : max_fd;
for (int fd = (int)first; fd <= end; fd++) {
if (set_cloexec) {
int fl = fcntl(fd, F_GETFD);
if (fl >= 0) {
fcntl(fd, F_SETFD, fl | FD_CLOEXEC);
}
} else {
close(fd);
}
}
return 0;
}
long syscall(long number, ...) {
va_list ap;
va_start(ap, number);
unsigned long arg1 = va_arg(ap, unsigned long);
unsigned long arg2 = va_arg(ap, unsigned long);
unsigned long arg3 = va_arg(ap, unsigned long);
unsigned long arg4 = va_arg(ap, unsigned long);
unsigned long arg5 = va_arg(ap, unsigned long);
unsigned long arg6 = va_arg(ap, unsigned long);
va_end(ap);
#if defined(__NR_readlinkat)
if (number == __NR_readlinkat) {
return (long)readlinkat((int)arg1, (const char *)arg2, (char *)arg3, (size_t)arg4);
}
#endif
#if defined(__NR_readlink)
if (number == __NR_readlink) {
return (long)readlink((const char *)arg1, (char *)arg2, (size_t)arg3);
}
#endif
#if defined(__NR_linkat)
if (number == __NR_linkat) {
return (long)linkat((int)arg1, (const char *)arg2, (int)arg3, (const char *)arg4, (int)arg5);
}
#endif
#if defined(__NR_link)
if (number == __NR_link) {
return (long)link((const char *)arg1, (const char *)arg2);
}
#endif
#ifdef __NR_landlock_create_ruleset
if (number == __NR_landlock_create_ruleset) {
return (long)landlock_create_ruleset((const void *)arg1, (size_t)arg2, (uint32_t)arg3);
}
if (number == __NR_landlock_add_rule) {
return (long)landlock_add_rule((int)arg1, (int)arg2, (const void *)arg3, (uint32_t)arg4);
}
if (number == __NR_landlock_restrict_self) {
return (long)landlock_restrict_self((int)arg1, (uint32_t)arg2);
}
#endif
#ifdef __NR_seccomp
if (number == __NR_seccomp) {
return (long)seccomp((unsigned int)arg1, (unsigned int)arg2, (void *)arg3);
}
#endif
#ifdef __NR_unshare
if (number == __NR_unshare) {
return (long)unshare((int)arg1);
}
#endif
#ifdef __NR_setns
if (number == __NR_setns) {
return (long)setns((int)arg1, (int)arg2);
}
#endif
#ifdef __NR_clone3
if (number == __NR_clone3) {
errno = ENOSYS;
return -1;
}
#endif
#ifdef __NR_pidfd_open
if (number == __NR_pidfd_open) {
errno = ENOSYS;
return -1;
}
#endif
#ifdef __NR_pidfd_send_signal
if (number == __NR_pidfd_send_signal) {
errno = ENOSYS;
return -1;
}
#endif
#ifdef __NR_pidfd_getfd
if (number == __NR_pidfd_getfd) {
errno = ENOSYS;
return -1;
}
#endif
#ifdef __NR_close_range
if (number == __NR_close_range) {
return (long)close_range((unsigned int)arg1, (unsigned int)arg2, (int)arg3);
}
#endif
#ifdef __NR_openat2
if (number == __NR_openat2) {
return (long)openat2((int)arg1, (const char *)arg2, (struct ddnatv_open_how *)arg3, (size_t)arg4);
}
#endif
#ifdef __NR_fchmodat2
if (number == __NR_fchmodat2) {
return (long)fchmodat2((int)arg1, (const char *)arg2, (mode_t)arg3, (int)arg4);
}
#endif
#if defined(__NR_statx)
if (number == __NR_statx) {
return (long)statx((int)arg1, (const char *)arg2, (int)arg3, (unsigned int)arg4, (struct statx *)arg5);
}
#endif
#if defined(__NR_faccessat)
if (number == __NR_faccessat) {
return (long)faccessat((int)arg1, (const char *)arg2, (int)arg3, 0);
}
#endif
#if defined(__NR_faccessat2)
if (number == __NR_faccessat2) {
return (long)faccessat2((int)arg1, (const char *)arg2, (int)arg3, (int)arg4);
}
#endif
#if defined(__NR_mknodat)
if (number == __NR_mknodat) {
return (long)mknodat((int)arg1, (const char *)arg2, (mode_t)arg3, (dev_t)arg4);
}
#endif
#if defined(__NR_mknod)
if (number == __NR_mknod) {
return (long)mknod((const char *)arg1, (mode_t)arg2, (dev_t)arg3);
}
#endif
#if defined(__NR_mkfifoat)
if (number == __NR_mkfifoat) {
return (long)mkfifoat((int)arg1, (const char *)arg2, (mode_t)arg3);
}
#endif
#if defined(__NR_setresuid)
if (number == __NR_setresuid) return 0;
#endif
#if defined(__NR_setresuid32)
if (number == __NR_setresuid32) return 0;
#endif
#if defined(__NR_setresgid)
if (number == __NR_setresgid) return 0;
#endif
#if defined(__NR_setresgid32)
if (number == __NR_setresgid32) return 0;
#endif
#if defined(__NR_setuid)
if (number == __NR_setuid) return 0;
#endif
#if defined(__NR_setuid32)
if (number == __NR_setuid32) return 0;
#endif
#if defined(__NR_setgid)
if (number == __NR_setgid) return 0;
#endif
#if defined(__NR_setgid32)
if (number == __NR_setgid32) return 0;
#endif
#if defined(__NR_setreuid)
if (number == __NR_setreuid) return 0;
#endif
#if defined(__NR_setreuid32)
if (number == __NR_setreuid32) return 0;
#endif
#if defined(__NR_setregid)
if (number == __NR_setregid) return 0;
#endif
#if defined(__NR_setregid32)
if (number == __NR_setregid32) return 0;
#endif
#if defined(__NR_setgroups)
if (number == __NR_setgroups) return 0;
#endif
#if defined(__NR_setgroups32)
if (number == __NR_setgroups32) return 0;
#endif
#if defined(__NR_setfsuid)
if (number == __NR_setfsuid) return 0;
#endif
#if defined(__NR_setfsuid32)
if (number == __NR_setfsuid32) return 0;
#endif
#if defined(__NR_setfsgid)
if (number == __NR_setfsgid) return 0;
#endif
#if defined(__NR_setfsgid32)
if (number == __NR_setfsgid32) return 0;
#endif
#if defined(__NR_getuid)
if (number == __NR_getuid) return 0;
#endif
#if defined(__NR_getuid32)
if (number == __NR_getuid32) return 0;
#endif
#if defined(__NR_geteuid)
if (number == __NR_geteuid) return 0;
#endif
#if defined(__NR_geteuid32)
if (number == __NR_geteuid32) return 0;
#endif
#if defined(__NR_getgid)
if (number == __NR_getgid) return 0;
#endif
#if defined(__NR_getgid32)
if (number == __NR_getgid32) return 0;
#endif
#if defined(__NR_getegid)
if (number == __NR_getegid) return 0;
#endif
#if defined(__NR_getegid32)
if (number == __NR_getegid32) return 0;
#endif
#if defined(__NR_getresuid)
if (number == __NR_getresuid) {
uid_t *ruid = (uid_t *)arg1;
uid_t *euid = (uid_t *)arg2;
uid_t *suid = (uid_t *)arg3;
if (ruid) *ruid = 0;
if (euid) *euid = 0;
if (suid) *suid = 0;
return 0;
}
#endif
#if defined(__NR_getresuid32)
if (number == __NR_getresuid32) {
uid_t *ruid = (uid_t *)arg1;
uid_t *euid = (uid_t *)arg2;
uid_t *suid = (uid_t *)arg3;
if (ruid) *ruid = 0;
if (euid) *euid = 0;
if (suid) *suid = 0;
return 0;
}
#endif
#if defined(__NR_getresgid)
if (number == __NR_getresgid) {
gid_t *rgid = (gid_t *)arg1;
gid_t *egid = (gid_t *)arg2;
gid_t *sgid = (gid_t *)arg3;
if (rgid) *rgid = 0;
if (egid) *egid = 0;
if (sgid) *sgid = 0;
return 0;
}
#endif
#if defined(__NR_getresgid32)
if (number == __NR_getresgid32) {
gid_t *rgid = (gid_t *)arg1;
gid_t *egid = (gid_t *)arg2;
gid_t *sgid = (gid_t *)arg3;
if (rgid) *rgid = 0;
if (egid) *egid = 0;
if (sgid) *sgid = 0;
return 0;
}
#endif
return call_orig_syscall(number, arg1, arg2, arg3, arg4, arg5, arg6);
}
#endif /* !DDNATV_HOST_TEST */
Binary file not shown.
+211
View File
@@ -0,0 +1,211 @@
// Part of libddnatv-hook.so, included by ddnatv-hook.c (one translation unit, so the
// parts share their static functions and are built with the same command as before).
//
// The SIGSYS handler for system calls Android's seccomp filter blocks, and the signal hooks that
// keep programs from replacing or blocking it.
#ifndef DDNATV_HOST_TEST
#ifndef SYS_SECCOMP
#define SYS_SECCOMP 1
#endif
static int (*get_real_sigaction(void))(int, const struct sigaction *, struct sigaction *);
// Intercept SECCOMP blocked syscalls (SIGSYS), resolve sandbox/landlock gracefully, and advance PC
static void ddnatv_sigsys_handler(int sig, siginfo_t *info, void *ctx) {
if (!ctx || !info) return;
if (info->si_code != SYS_SECCOMP) {
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
if (real_sig) {
struct sigaction sa_dfl;
memset(&sa_dfl, 0, sizeof(sa_dfl));
sa_dfl.sa_handler = SIG_DFL;
sigemptyset(&sa_dfl.sa_mask);
real_sig(sig, &sa_dfl, NULL);
}
raise(sig);
return;
}
ucontext_t *uctx = (ucontext_t *)ctx;
int sys_nr = info->si_syscall;
long ret_val = is_sigsys_synthetic_success_syscall(sys_nr) ? 0 : -ENOSYS;
#if defined(__aarch64__)
uctx->uc_mcontext.regs[0] = (uint64_t)ret_val;
if (uctx->uc_mcontext.pc >= 4) {
uint32_t insn_at_pc = 0;
uint32_t insn_before_pc = 0;
memcpy(&insn_at_pc, (const void *)uctx->uc_mcontext.pc, sizeof(insn_at_pc));
memcpy(&insn_before_pc, (const void *)(uctx->uc_mcontext.pc - 4), sizeof(insn_before_pc));
// On SECCOMP_RET_TRAP, the kernel already advanced PC past svc #0 (*(pc - 4) is svc #0).
// Only advance PC if PC itself points to svc #0 and *(pc - 4) does not.
int at_is_svc = ((insn_at_pc & 0xffe0001fU) == 0xd4000001U);
int prev_is_svc = ((insn_before_pc & 0xffe0001fU) == 0xd4000001U);
if (at_is_svc && !prev_is_svc) {
uctx->uc_mcontext.pc += 4;
}
}
#elif defined(__arm__)
uctx->uc_mcontext.arm_r0 = (unsigned long)ret_val;
if (uctx->uc_mcontext.arm_pc >= 4) {
if (uctx->uc_mcontext.arm_cpsr & 0x20) {
uint16_t insn_at_pc = 0;
uint16_t insn_before_pc = 0;
memcpy(&insn_at_pc, (const void *)uctx->uc_mcontext.arm_pc, sizeof(insn_at_pc));
memcpy(&insn_before_pc, (const void *)(uctx->uc_mcontext.arm_pc - 2), sizeof(insn_before_pc));
int at_is_svc = ((insn_at_pc & 0xff00U) == 0xdf00U);
int prev_is_svc = ((insn_before_pc & 0xff00U) == 0xdf00U);
if (at_is_svc && !prev_is_svc) {
uctx->uc_mcontext.arm_pc += 2;
}
} else {
uint32_t insn_at_pc = 0;
uint32_t insn_before_pc = 0;
memcpy(&insn_at_pc, (const void *)uctx->uc_mcontext.arm_pc, sizeof(insn_at_pc));
memcpy(&insn_before_pc, (const void *)(uctx->uc_mcontext.arm_pc - 4), sizeof(insn_before_pc));
int at_is_svc = ((insn_at_pc & 0x0f000000U) == 0x0f000000U);
int prev_is_svc = ((insn_before_pc & 0x0f000000U) == 0x0f000000U);
if (at_is_svc && !prev_is_svc) {
uctx->uc_mcontext.arm_pc += 4;
}
}
}
#elif defined(__x86_64__) && defined(REG_RAX)
uctx->uc_mcontext.gregs[REG_RAX] = (greg_t)ret_val;
if (uctx->uc_mcontext.gregs[REG_RIP] >= 2) {
unsigned char insn_at[2] = {0};
unsigned char insn_prev[2] = {0};
memcpy(insn_at, (const void *)uctx->uc_mcontext.gregs[REG_RIP], sizeof(insn_at));
memcpy(insn_prev, (const void *)(uctx->uc_mcontext.gregs[REG_RIP] - 2), sizeof(insn_prev));
int at_is_sys = (insn_at[0] == 0x0f && insn_at[1] == 0x05);
int prev_is_sys = (insn_prev[0] == 0x0f && insn_prev[1] == 0x05);
if (at_is_sys && !prev_is_sys) {
uctx->uc_mcontext.gregs[REG_RIP] += 2;
}
}
#elif defined(__i386__) && defined(REG_EAX)
uctx->uc_mcontext.gregs[REG_EAX] = (greg_t)ret_val;
if (uctx->uc_mcontext.gregs[REG_EIP] >= 2) {
unsigned char insn_at[2] = {0};
unsigned char insn_prev[2] = {0};
memcpy(insn_at, (const void *)uctx->uc_mcontext.gregs[REG_EIP], sizeof(insn_at));
memcpy(insn_prev, (const void *)(uctx->uc_mcontext.gregs[REG_EIP] - 2), sizeof(insn_prev));
int at_is_sys = (insn_at[0] == 0xcd && insn_at[1] == 0x80);
int prev_is_sys = (insn_prev[0] == 0xcd && insn_prev[1] == 0x80);
if (at_is_sys && !prev_is_sys) {
uctx->uc_mcontext.gregs[REG_EIP] += 2;
}
}
#endif
}
static int (*get_real_sigaction(void))(int, const struct sigaction *, struct sigaction *) {
static int (*real_sigaction)(int, const struct sigaction *, struct sigaction *) = NULL;
if (!real_sigaction) {
real_sigaction = (int (*)(int, const struct sigaction *, struct sigaction *))dlsym(RTLD_NEXT, "sigaction");
if (!real_sigaction) {
real_sigaction = (int (*)(int, const struct sigaction *, struct sigaction *))dlsym(RTLD_DEFAULT, "sigaction");
}
}
return real_sigaction;
}
__attribute__((constructor(101))) static void install_sigsys_handler(void) {
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
if (!real_sig) return;
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_sigaction = ddnatv_sigsys_handler;
sa.sa_flags = SA_SIGINFO | SA_RESTART;
sigemptyset(&sa.sa_mask);
real_sig(SIGSYS, &sa, NULL);
}
int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact) {
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
if (!real_sig) return -1;
if (signum == SIGSYS) {
if (act && act->sa_sigaction == ddnatv_sigsys_handler) {
return real_sig(signum, act, oldact);
}
if (oldact) {
memset(oldact, 0, sizeof(*oldact));
oldact->sa_sigaction = ddnatv_sigsys_handler;
oldact->sa_flags = SA_SIGINFO | SA_RESTART;
}
return 0;
}
return real_sig(signum, act, oldact);
}
int rt_sigaction(int signum, const struct sigaction *act, struct sigaction *oldact, size_t sigsetsize) {
static int (*orig_rt_sigaction)(int, const struct sigaction *, struct sigaction *, size_t) = NULL;
if (!orig_rt_sigaction) orig_rt_sigaction = (int (*)(int, const struct sigaction *, struct sigaction *, size_t))dlsym(RTLD_NEXT, "rt_sigaction");
if (signum == SIGSYS) {
if (act && act->sa_sigaction == ddnatv_sigsys_handler) {
return orig_rt_sigaction ? orig_rt_sigaction(signum, act, oldact, sigsetsize) : 0;
}
if (oldact) {
memset(oldact, 0, sizeof(*oldact));
oldact->sa_sigaction = ddnatv_sigsys_handler;
oldact->sa_flags = SA_SIGINFO | SA_RESTART;
}
return 0;
}
return orig_rt_sigaction ? orig_rt_sigaction(signum, act, oldact, sigsetsize) : -1;
}
int __libc_sigaction(int signum, const struct sigaction *act, struct sigaction *oldact) {
return sigaction(signum, act, oldact);
}
typedef void (*sighandler_t)(int);
sighandler_t signal(int signum, sighandler_t handler) {
static sighandler_t (*orig_signal)(int, sighandler_t) = NULL;
if (!orig_signal) orig_signal = (sighandler_t (*)(int, sighandler_t))dlsym(RTLD_NEXT, "signal");
if (signum == SIGSYS) {
return (sighandler_t)ddnatv_sigsys_handler;
}
return orig_signal ? orig_signal(signum, handler) : NULL;
}
int sigprocmask(int how, const sigset_t *set, sigset_t *oldset) {
static int (*orig_sigprocmask)(int, const sigset_t *, sigset_t *) = NULL;
if (!orig_sigprocmask) orig_sigprocmask = (int (*)(int, const sigset_t *, sigset_t *))dlsym(RTLD_NEXT, "sigprocmask");
if (set && (how == SIG_BLOCK || how == SIG_SETMASK)) {
sigset_t mod_set = *set;
sigdelset(&mod_set, SIGSYS);
return orig_sigprocmask ? orig_sigprocmask(how, &mod_set, oldset) : 0;
}
return orig_sigprocmask ? orig_sigprocmask(how, set, oldset) : 0;
}
int pthread_sigmask(int how, const sigset_t *set, sigset_t *oldset) {
static int (*orig_pthread_sigmask)(int, const sigset_t *, sigset_t *) = NULL;
if (!orig_pthread_sigmask) orig_pthread_sigmask = (int (*)(int, const sigset_t *, sigset_t *))dlsym(RTLD_NEXT, "pthread_sigmask");
if (set && (how == SIG_BLOCK || how == SIG_SETMASK)) {
sigset_t mod_set = *set;
sigdelset(&mod_set, SIGSYS);
return orig_pthread_sigmask ? orig_pthread_sigmask(how, &mod_set, oldset) : 0;
}
return orig_pthread_sigmask ? orig_pthread_sigmask(how, set, oldset) : 0;
}
int rt_sigprocmask(int how, const sigset_t *set, sigset_t *oldset, size_t sigsetsize) {
static int (*orig_rt_sigprocmask)(int, const sigset_t *, sigset_t *, size_t) = NULL;
if (!orig_rt_sigprocmask) orig_rt_sigprocmask = (int (*)(int, const sigset_t *, sigset_t *, size_t))dlsym(RTLD_NEXT, "rt_sigprocmask");
if (set && (how == SIG_BLOCK || how == SIG_SETMASK)) {
sigset_t mod_set;
memcpy(&mod_set, set, sizeof(mod_set));
sigdelset(&mod_set, SIGSYS);
return orig_rt_sigprocmask ? orig_rt_sigprocmask(how, &mod_set, oldset, sigsetsize) : 0;
}
return orig_rt_sigprocmask ? orig_rt_sigprocmask(how, set, oldset, sigsetsize) : 0;
}
#endif /* !DDNATV_HOST_TEST */
+307
View File
@@ -0,0 +1,307 @@
// Part of libddnatv-hook.so, included by ddnatv-hook.c (one translation unit, so the
// parts share their static functions and are built with the same command as before).
//
// Sockets: Unix socket paths in the rootfs, the redirected DNS queries of loopback DNS, and the
// TCP servers programs start (the app offers to open them in the browser).
// The TCP port a listening socket was bound to, 0 for other sockets.
static int listening_tcp_port(int fd) {
struct sockaddr_storage ss;
socklen_t len = sizeof(ss);
memset(&ss, 0, sizeof(ss));
if (syscall(SYS_getsockname, fd, (struct sockaddr *)&ss, &len) != 0) return 0;
if (ss.ss_family == AF_INET && len >= (socklen_t)sizeof(struct sockaddr_in))
return ntohs(((struct sockaddr_in *)&ss)->sin_port);
if (ss.ss_family == AF_INET6 && len >= (socklen_t)sizeof(struct sockaddr_in6))
return ntohs(((struct sockaddr_in6 *)&ss)->sin6_port);
return 0;
}
// Tells the app that this program listens on [port]: $DDNATV_ROOT/run/ddnatv/listening/PORT with
// "PID NAME" (ListeningPorts). Raw system calls: nothing of this library runs again.
static void report_listening_port(const char *root, size_t root_len, int port, const char *name) {
if (root_len == 0 || port <= 0 || port > 65535) return;
char path[PATH_MAX];
int n = snprintf(path, sizeof(path), "%.*s/run/ddnatv/listening/%d", (int)root_len, root, port);
if (n <= 0 || n >= (int)sizeof(path)) return;
int out = (int)syscall(SYS_openat, AT_FDCWD, path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
if (out < 0) return; // no app watching (the directory is the app's)
char line[160];
int m = snprintf(line, sizeof(line), "%d %.100s\n", (int)getpid(), name && name[0] ? name : "?");
if (m > 0) syscall(SYS_write, out, line, (size_t)(m < (int)sizeof(line) ? m : (int)sizeof(line) - 1));
syscall(SYS_close, out);
}
// The first port of the kernel's range for ports it picks itself, from the text of
// /proc/sys/net/ipv4/ip_local_port_range ("32768\t60999"); 32768, Linux's default, when there is none.
static int ephemeral_port_low(const char *range) {
if (!range) return 32768;
while (*range == ' ' || *range == '\t') range++;
int low = 0, digits = 0;
while (*range >= '0' && *range <= '9' && digits < 6) low = low * 10 + (*range++ - '0'), digits++;
return (digits > 0 && low > 0 && low <= 65535) ? low : 32768;
}
// Whether listen() tells the app about a server on `port`, which it then connects to and sends an
// HTTP request (LocalServers). Only for a port the program chose (`chosen`) below the kernel's own
// range: a server whose port the kernel picked, or one in that range, is how programs talk to
// each other (Gradle's daemon, the Kotlin daemon, a JVM's debugger, test runners). Such a server
// often accepts one connection, so the app's own took the place of the program it waited for:
// that one read EOF ("Did not receive connection preamble" from Gradle, #51). Web servers people
// open (npm run dev, vite, python3 -m http.server, jupyter) are on ports such as 3000, 5173, 8000.
static int listening_port_is_reported(int chosen, int port, int ephemeral_low) {
return chosen && port > 0 && port < ephemeral_low;
}
#ifndef DDNATV_HOST_TEST
// The kernel's range, read once (raw system calls: nothing of this library runs again)
static int kernel_ephemeral_port_low(void) {
static int low = 0;
int v = __atomic_load_n(&low, __ATOMIC_RELAXED);
if (v) return v;
char text[64];
ssize_t n = -1;
int fd = (int)syscall(SYS_openat, AT_FDCWD, "/proc/sys/net/ipv4/ip_local_port_range", O_RDONLY | O_CLOEXEC);
if (fd >= 0) {
n = syscall(SYS_read, fd, text, sizeof(text) - 1);
syscall(SYS_close, fd);
}
if (n > 0) text[n] = '\0';
v = ephemeral_port_low(n > 0 ? text : NULL);
__atomic_store_n(&low, v, __ATOMIC_RELAXED);
return v;
}
int listen(int sockfd, int backlog) {
static int (*orig_listen)(int, int) = NULL;
if (!orig_listen) orig_listen = (int (*)(int, int))dlsym(RTLD_NEXT, "listen");
if (!orig_listen) {
errno = ENOSYS;
return -1;
}
int ret = orig_listen(sockfd, backlog);
if (ret == 0) {
int saved_errno = errno;
int port = is_chosen_port_fd(sockfd) ? listening_tcp_port(sockfd) : 0;
if (listening_port_is_reported(port > 0, port, kernel_ephemeral_port_low())) {
init_ddnatv_hook();
extern char *program_invocation_short_name;
report_listening_port(g_ddnatv_root, g_ddnatv_root_len, port, program_invocation_short_name);
}
errno = saved_errno;
}
return ret;
}
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
static int (*orig_bind)(int, const struct sockaddr *, socklen_t) = NULL;
if (!orig_bind) orig_bind = (int (*)(int, const struct sockaddr *, socklen_t))dlsym(RTLD_NEXT, "bind");
if (addr && addrlen > offsetof(struct sockaddr_un, sun_path) && addr->sa_family == AF_UNIX) {
const struct sockaddr_un *sun = (const struct sockaddr_un *)addr;
if (sun->sun_path[0] != '\0') {
struct sockaddr_un mod_sun;
memset(&mod_sun, 0, sizeof(mod_sun));
mod_sun.sun_family = AF_UNIX;
rewrite_unix_socket_path(sun->sun_path, mod_sun.sun_path, sizeof(mod_sun.sun_path));
return orig_bind ? orig_bind(sockfd, (struct sockaddr *)&mod_sun, sizeof(mod_sun)) : -1;
}
}
int ret = orig_bind ? orig_bind(sockfd, addr, addrlen) : -1;
if (ret == 0 && addr) {
int saved_errno = errno;
int chosen = 0;
if (addr->sa_family == AF_INET && addrlen >= (socklen_t)sizeof(struct sockaddr_in))
chosen = ((const struct sockaddr_in *)addr)->sin_port != 0;
else if (addr->sa_family == AF_INET6 && addrlen >= (socklen_t)sizeof(struct sockaddr_in6))
chosen = ((const struct sockaddr_in6 *)addr)->sin6_port != 0;
set_chosen_port_fd(sockfd, chosen);
errno = saved_errno;
}
return ret;
}
int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
static int (*orig_connect)(int, const struct sockaddr *, socklen_t) = NULL;
if (!orig_connect) orig_connect = (int (*)(int, const struct sockaddr *, socklen_t))dlsym(RTLD_NEXT, "connect");
if (addr && addrlen > offsetof(struct sockaddr_un, sun_path) && addr->sa_family == AF_UNIX) {
const struct sockaddr_un *sun = (const struct sockaddr_un *)addr;
if (sun->sun_path[0] != '\0') {
struct sockaddr_un mod_sun;
memset(&mod_sun, 0, sizeof(mod_sun));
mod_sun.sun_family = AF_UNIX;
rewrite_unix_socket_path(sun->sun_path, mod_sun.sun_path, sizeof(mod_sun.sun_path));
return orig_connect ? orig_connect(sockfd, (struct sockaddr *)&mod_sun, sizeof(mod_sun)) : -1;
}
}
if (addr && is_loopback_dns(addr, addrlen)) {
struct sockaddr_storage redirected;
socklen_t redirected_len = dns_redirect_target(addr, &redirected);
int ret = orig_connect ? orig_connect(sockfd, (struct sockaddr *)&redirected, redirected_len) : -1;
if (ret == 0 || errno == EINPROGRESS) {
int saved_errno = errno;
record_dns_redirect(sockfd, addr, addrlen);
errno = saved_errno;
}
return ret;
}
return orig_connect ? orig_connect(sockfd, addr, addrlen) : -1;
}
ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
const struct sockaddr *dest_addr, socklen_t addrlen) {
static ssize_t (*orig_sendto)(int, const void *, size_t, int, const struct sockaddr *, socklen_t) = NULL;
if (!orig_sendto) orig_sendto = (ssize_t (*)(int, const void *, size_t, int, const struct sockaddr *, socklen_t))dlsym(RTLD_NEXT, "sendto");
if (dest_addr && is_loopback_dns(dest_addr, addrlen)) {
struct sockaddr_storage redirected;
socklen_t redirected_len = dns_redirect_target(dest_addr, &redirected);
record_dns_redirect(sockfd, dest_addr, addrlen);
return orig_sendto ? orig_sendto(sockfd, buf, len, flags, (struct sockaddr *)&redirected, redirected_len) : -1;
}
return orig_sendto ? orig_sendto(sockfd, buf, len, flags, dest_addr, addrlen) : -1;
}
#if defined(__NR_getuid32)
#define DDNATV_NR_REAL_GETUID __NR_getuid32
#define DDNATV_NR_REAL_GETGID __NR_getgid32
#else
#define DDNATV_NR_REAL_GETUID __NR_getuid
#define DDNATV_NR_REAL_GETGID __NR_getgid
#endif
// Credentials sent over a Unix socket (SCM_CREDENTIALS) have to be the process's own: the kernel
// refuses others with EPERM, and programs fill them in with getuid(), which is root's 0 here.
// PulseAudio's clients send them on every connection, which then failed ("Connection terminated").
// Returns 1 with the message copied into mod (its control data into ctrl) and the ids made real.
static int real_scm_credentials(const struct msghdr *msg, struct msghdr *mod, char *ctrl, size_t ctrl_size) {
if (!msg || !msg->msg_control || msg->msg_controllen < sizeof(struct cmsghdr) || msg->msg_controllen > ctrl_size) return 0;
int found = 0;
for (struct cmsghdr *c = CMSG_FIRSTHDR(msg); c; c = CMSG_NXTHDR((struct msghdr *)msg, c)) {
if (c->cmsg_level == SOL_SOCKET && c->cmsg_type == SCM_CREDENTIALS) found = 1;
}
if (!found) return 0;
memcpy(mod, msg, sizeof(*mod));
memcpy(ctrl, msg->msg_control, msg->msg_controllen);
mod->msg_control = ctrl;
for (struct cmsghdr *c = CMSG_FIRSTHDR(mod); c; c = CMSG_NXTHDR(mod, c)) {
if (c->cmsg_level != SOL_SOCKET || c->cmsg_type != SCM_CREDENTIALS || c->cmsg_len < CMSG_LEN(sizeof(struct ucred))) continue;
// a record that claims more than the buffer holds is the kernel's to refuse, not ours to read
if (c->cmsg_len > mod->msg_controllen - (size_t)((char *)c - ctrl)) break;
struct ucred cred;
memcpy(&cred, CMSG_DATA(c), sizeof(cred));
cred.pid = getpid();
cred.uid = (uid_t)call_orig_syscall(DDNATV_NR_REAL_GETUID, 0, 0, 0, 0, 0, 0);
cred.gid = (gid_t)call_orig_syscall(DDNATV_NR_REAL_GETGID, 0, 0, 0, 0, 0, 0);
memcpy(CMSG_DATA(c), &cred, sizeof(cred));
}
return 1;
}
ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags) {
static ssize_t (*orig_sendmsg)(int, const struct msghdr *, int) = NULL;
if (!orig_sendmsg) orig_sendmsg = (ssize_t (*)(int, const struct msghdr *, int))dlsym(RTLD_NEXT, "sendmsg");
struct msghdr cred_msg;
char cred_ctrl[512] __attribute__((aligned(8)));
if (real_scm_credentials(msg, &cred_msg, cred_ctrl, sizeof(cred_ctrl))) msg = &cred_msg;
if (msg && msg->msg_name && is_loopback_dns((const struct sockaddr *)msg->msg_name, msg->msg_namelen)) {
struct sockaddr_storage redirected;
socklen_t redirected_len = dns_redirect_target((const struct sockaddr *)msg->msg_name, &redirected);
struct msghdr mod_msg;
memcpy(&mod_msg, msg, sizeof(mod_msg));
mod_msg.msg_name = &redirected;
mod_msg.msg_namelen = redirected_len;
record_dns_redirect(sockfd, (const struct sockaddr *)msg->msg_name, msg->msg_namelen);
return orig_sendmsg ? orig_sendmsg(sockfd, &mod_msg, flags) : -1;
}
return orig_sendmsg ? orig_sendmsg(sockfd, msg, flags) : -1;
}
ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
struct sockaddr *src_addr, socklen_t *addrlen) {
static ssize_t (*orig_recvfrom)(int, void *, size_t, int, struct sockaddr *, socklen_t *) = NULL;
if (!orig_recvfrom) orig_recvfrom = (ssize_t (*)(int, void *, size_t, int, struct sockaddr *, socklen_t *))dlsym(RTLD_NEXT, "recvfrom");
socklen_t cap = addrlen ? *addrlen : 0;
ssize_t ret = orig_recvfrom ? orig_recvfrom(sockfd, buf, len, flags, src_addr, addrlen) : -1;
if (ret > 0 && src_addr && addrlen) {
int saved_errno = errno;
restore_dns_source(sockfd, src_addr, cap, addrlen);
errno = saved_errno;
}
return ret;
}
// What programs built with _FORTIFY_SOURCE call when the buffer's size is known; the check is
// glibc's
extern void __chk_fail(void) __attribute__((__noreturn__));
ssize_t __recvfrom_chk(int sockfd, void *buf, size_t len, size_t buflen, int flags,
struct sockaddr *src_addr, socklen_t *addrlen) {
if (len > buflen) __chk_fail();
return recvfrom(sockfd, buf, len, flags, src_addr, addrlen);
}
ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags) {
static ssize_t (*orig_recvmsg)(int, struct msghdr *, int) = NULL;
if (!orig_recvmsg) orig_recvmsg = (ssize_t (*)(int, struct msghdr *, int))dlsym(RTLD_NEXT, "recvmsg");
socklen_t cap = msg ? msg->msg_namelen : 0;
ssize_t ret = orig_recvmsg ? orig_recvmsg(sockfd, msg, flags) : -1;
if (ret > 0 && msg && msg->msg_name) {
int saved_errno = errno;
restore_dns_source(sockfd, (struct sockaddr *)msg->msg_name, cap, &msg->msg_namelen);
errno = saved_errno;
}
return ret;
}
int getpeername(int sockfd, struct sockaddr *addr, socklen_t *addrlen) {
static int (*orig_getpeername)(int, struct sockaddr *, socklen_t *) = NULL;
if (!orig_getpeername) orig_getpeername = (int (*)(int, struct sockaddr *, socklen_t *))dlsym(RTLD_NEXT, "getpeername");
socklen_t cap = addrlen ? *addrlen : 0;
int ret = orig_getpeername ? orig_getpeername(sockfd, addr, addrlen) : -1;
if (ret == 0 && addr && addrlen) restore_dns_source(sockfd, addr, cap, addrlen);
return ret;
}
// accept() as accept4() without flags, the call bionic makes for both: Android's seccomp filter
// for apps is made from what bionic calls. On the x86_64 emulator a translated accept() answered
// with its system call number (43) as the new descriptor, and sshd failed every connection with
// "fcntl(43, F_GETFL): Bad file descriptor" (Perl, Python and nginx use accept4 themselves).
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen) {
static int (*orig_accept4)(int, struct sockaddr *, socklen_t *, int) = NULL;
if (!orig_accept4) orig_accept4 = (int (*)(int, struct sockaddr *, socklen_t *, int))dlsym(RTLD_NEXT, "accept4");
if (!orig_accept4) {
errno = ENOSYS;
return -1;
}
return orig_accept4(sockfd, addr, addrlen, 0);
}
#ifndef AF_NETLINK
#define AF_NETLINK 16
#endif
#ifndef NETLINK_AUDIT
#define NETLINK_AUDIT 9
#endif
int socket(int domain, int type, int protocol) {
static int (*orig_socket)(int, int, int) = NULL;
if (!orig_socket) orig_socket = (int (*)(int, int, int))dlsym(RTLD_NEXT, "socket");
if (domain == AF_NETLINK && protocol == NETLINK_AUDIT) {
errno = EPROTONOSUPPORT;
return -1;
}
int fd = orig_socket ? orig_socket(domain, type, protocol) : -1;
// A new socket has not chosen a port, whatever the descriptor's last one had (close_range() and
// raw close system calls do not pass the hook's close())
if (fd >= 0) set_chosen_port_fd(fd, 0);
return fd;
}
#endif /* !DDNATV_HOST_TEST */
+345
View File
@@ -0,0 +1,345 @@
// Part of libddnatv-hook.so, included by ddnatv-hook.c (one translation unit, so the
// parts share their static functions and are built with the same command as before).
//
// Statically linked programs: their seccomp-blocked system calls are patched before they run.
// ---- Static programs ----------------------------------------------------------------------
// A statically linked program (gcc -static) carries its own copy of glibc, whose system calls the
// preloaded hook never sees. The ones Android's seccomp filter answers with SIGSYS therefore kill it:
// set_robust_list at start-up, clone3 for every thread, rseq, and the others the hook's SIGSYS
// handler catches for dynamic programs. Before such a program runs, The native userland patches those call sites
// in its file to what that handler answers (0 for set_robust_list and the set*id family, -ENOSYS,
// which glibc falls back from, for the rest), as scripts/patch-bootstrap-ld.py does to the rootfs
// ld.so and libc at build time. The scanning is a pure function over a buffer, so tests/native can
// check it against the script.
#define DDNATV_STATIC_WINDOW 16 // instructions between "mov x8, #nr" and its "svc #0"
// AArch64: what the SIGSYS handler answers for syscall `nr`: 1 for 0, 2 for -ENOSYS, 0 to leave it.
// set_robust_list keeps the script's no-op (x0 then holds its non-error first argument).
static int a64_blocked_syscall(unsigned int nr) {
switch (nr) {
case 99: // set_robust_list
return 3;
case 100: // get_robust_list
case 143: case 144: case 145: case 146: case 147: case 149: // setregid setgid setreuid setuid setresuid setresgid
case 151: case 152: case 159: // setfsuid setfsgid setgroups
return 1;
case 97: case 217: case 218: case 219: // unshare add_key request_key keyctl
case 268: case 277: case 280: case 293: // setns seccomp bpf rseq
return 2;
default:
return (nr >= 424 && nr < 512) ? 2 : 0; // newer than Android's filter (clone3, close_range, ...)
}
}
static uint32_t rd32(const unsigned char *p) { return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); }
static uint16_t rd16(const unsigned char *p) { return (uint16_t)(p[0] | (p[1] << 8)); }
static void wr32(unsigned char *p, uint32_t v) { p[0] = v & 0xff; p[1] = (v >> 8) & 0xff; p[2] = (v >> 16) & 0xff; p[3] = (v >> 24) & 0xff; }
static void wr16(unsigned char *p, uint16_t v) { p[0] = v & 0xff; p[1] = (v >> 8) & 0xff; }
// An AArch64 instruction that ends the search for the "svc #0" of a "mov x8, #nr": a branch, another
// svc, or anything with x8 in its first register field (another write to x8, most likely).
static int a64_ends_syscall_window(uint32_t insn) {
if ((insn & 0x1f) == 8) return 1;
if ((insn & 0xffe0001f) == 0xd4000001u) return 1; // svc #imm
if ((insn & 0x7c000000u) == 0x14000000u) return 1; // b, bl
if ((insn & 0xff000010u) == 0x54000000u) return 1; // b.cond
if ((insn & 0x7e000000u) == 0x34000000u) return 1; // cbz, cbnz
if ((insn & 0x7e000000u) == 0x36000000u) return 1; // tbz, tbnz
if ((insn & 0xfe000000u) == 0xd6000000u) return 1; // br, blr, ret
return 0;
}
static size_t a64_patch_seccomp_syscalls(unsigned char *data, size_t start, size_t end) {
size_t patched = 0;
start = (start + 3) & ~(size_t)3;
for (size_t pos = start; pos + 4 <= end; pos += 4) {
uint32_t insn = rd32(data + pos);
// movz x8, #nr / movz w8, #nr
if ((insn & 0x7fe0001fu) != 0x52800008u) continue;
int result = a64_blocked_syscall((insn >> 5) & 0xffff);
if (!result) continue;
for (size_t s = pos + 4, i = 0; s + 4 <= end && i < DDNATV_STATIC_WINDOW; s += 4, i++) {
uint32_t next = rd32(data + s);
if (next == 0xd4000001u) { // svc #0
wr32(data + s, result == 3 ? 0xd503201fu /* nop */
: result == 1 ? 0xd2800000u /* mov x0, #0 */
: 0x928004a0u); /* mov x0, #-38 */
patched++;
break;
}
if (a64_ends_syscall_window(next)) break;
}
}
return patched;
}
// 32-bit ARM: the three calls glibc makes on its own, with the exact patterns of the script
// (ARM mode, Thumb-2 with r7, and Thumb-2 through __libc_do_syscall with r12).
static long thumb_bl_target(const unsigned char *data, size_t size, size_t off) {
if (off + 4 > size) return -1;
uint16_t hw1 = rd16(data + off), hw2 = rd16(data + off + 2);
if ((hw1 & 0xf800) != 0xf000 || (hw2 & 0xd000) != 0xd000) return -1;
long s = (hw1 >> 10) & 1;
long imm10 = hw1 & 0x3ff;
long j1 = (hw2 >> 13) & 1, j2 = (hw2 >> 11) & 1;
long imm11 = hw2 & 0x7ff;
long i1 = (j1 ^ s) ^ 1, i2 = (j2 ^ s) ^ 1;
long imm25 = (s << 24) | (i1 << 23) | (i2 << 22) | (imm10 << 12) | (imm11 << 1);
if (s) imm25 -= (1L << 25);
return (long)off + 4 + imm25;
}
static size_t arm_patch_seccomp_syscalls(unsigned char *data, size_t start, size_t end) {
static const struct { uint32_t movw_r7; uint32_t repl; } arm[] = {
{ 0xe3007152u, 0xe320f000u }, // movw r7, #338 (set_robust_list) -> nop
{ 0xe30071b3u, 0xe3e00025u }, // movw r7, #435 (clone3) -> mvn r0, #37
{ 0xe300718eu, 0xe3e00025u }, // movw r7, #398 (rseq) -> mvn r0, #37
};
static const struct { uint16_t hw1, hw2; int nop_only; } thumb_r7[] = {
{ 0xf240, 0x1752, 1 }, // movw r7, #338
{ 0xf240, 0x17b3, 0 }, // movw r7, #435
{ 0xf240, 0x178e, 0 }, // movw r7, #398
};
static const struct { uint16_t hw1, hw2; uint16_t repl1, repl2; } thumb_r12[] = {
{ 0xf44f, 0x7ca9, 0xf04f, 0x0000 }, // mov.w r12, #338 -> mov.w r0, #0
{ 0xf44f, 0x7cc7, 0xf06f, 0x0025 }, // mov.w r12, #398 -> mvn.w r0, #37
{ 0xf240, 0x1cb3, 0xf06f, 0x0025 }, // movw r12, #435 -> mvn.w r0, #37
};
static const unsigned char do_syscall_stub[6] = { 0x80, 0xb5, 0x67, 0x46, 0x00, 0xdf };
size_t patched = 0;
size_t a4 = (start + 3) & ~(size_t)3, e4 = end & ~(size_t)3;
for (size_t pos = a4; pos + 4 < e4; pos += 4) {
uint32_t insn = rd32(data + pos);
for (size_t k = 0; k < sizeof(arm) / sizeof(arm[0]); k++) {
if (insn != arm[k].movw_r7) continue;
for (size_t s = pos + 4; s < e4 && s < pos + 68; s += 4) {
if (rd32(data + s) == 0xef000000u) { // svc #0
wr32(data + s, arm[k].repl);
patched++;
break;
}
}
}
}
size_t a2 = (start + 1) & ~(size_t)1, e2 = end & ~(size_t)1;
for (size_t t = a2; t + 4 < e2; t += 2) {
uint16_t hw1 = rd16(data + t), hw2 = rd16(data + t + 2);
int matched_r7 = 0;
for (size_t k = 0; k < sizeof(thumb_r7) / sizeof(thumb_r7[0]); k++) {
if (hw1 != thumb_r7[k].hw1 || hw2 != thumb_r7[k].hw2) continue;
matched_r7 = 1;
size_t limit = (e2 - 2 < t + 64 ? e2 - 2 : t + 64) + 2;
for (size_t s = t + 4; s < limit; s += 2) {
if (rd16(data + s) == 0xdf00) { // svc #0
if (!thumb_r7[k].nop_only) {
wr16(data + t, 0xf06f); // mvn.w r0, #37 in place of the movw
wr16(data + t + 2, 0x0025);
}
wr16(data + s, 0xbf00); // nop
patched++;
break;
}
}
break;
}
if (matched_r7) continue;
for (size_t k = 0; k < sizeof(thumb_r12) / sizeof(thumb_r12[0]); k++) {
if (hw1 != thumb_r12[k].hw1 || hw2 != thumb_r12[k].hw2) continue;
size_t limit = (e2 - 4 < t + 48 ? e2 - 4 : t + 48) + 2;
for (size_t s = t + 4; s < limit; s += 2) {
long target = thumb_bl_target(data, end, s);
if (target >= (long)start && target + 6 <= (long)end && memcmp(data + target, do_syscall_stub, 6) == 0) {
wr16(data + s, thumb_r12[k].repl1);
wr16(data + s + 2, thumb_r12[k].repl2);
patched++;
break;
}
}
break;
}
}
return patched;
}
#ifndef EM_ARM
#define EM_ARM 40
#endif
#ifndef EM_AARCH64
#define EM_AARCH64 183
#endif
// Patches the blocked syscalls in data[start, end), code of an ELF for `e_machine`; returns how many.
static size_t patch_seccomp_syscalls(unsigned char *data, size_t start, size_t end, uint16_t e_machine) {
if (!data || end <= start) return 0;
if (e_machine == EM_AARCH64) return a64_patch_seccomp_syscalls(data, start, end);
if (e_machine == EM_ARM) return arm_patch_seccomp_syscalls(data, start, end);
return 0;
}
// Reads the program headers of an ELF file into `ph` (as 64-bit fields); returns their number, or -1.
struct ddnatv_phdr { uint32_t type, flags; uint64_t offset, filesz; };
static int read_elf_phdrs(int fd, uint16_t *machine, struct ddnatv_phdr *ph, int max) {
unsigned char eh[64];
if (pread(fd, eh, sizeof(eh), 0) < 52 || memcmp(eh, "\x7f" "ELF", 4) != 0 || eh[5] != 1) return -1;
int is64 = eh[4] == 2;
uint64_t phoff = is64 ? ((uint64_t)rd32(eh + 32) | ((uint64_t)rd32(eh + 36) << 32)) : rd32(eh + 28);
uint16_t phentsize = rd16(eh + (is64 ? 54 : 42));
uint16_t phnum = rd16(eh + (is64 ? 56 : 44));
*machine = rd16(eh + 18);
if (phentsize < (is64 ? 56 : 32) || phnum == 0 || phnum > max) return -1;
for (int i = 0; i < phnum; i++) {
unsigned char e[64];
if (pread(fd, e, phentsize < sizeof(e) ? phentsize : sizeof(e), (off_t)(phoff + (uint64_t)i * phentsize)) < (is64 ? 56 : 32)) return -1;
ph[i].type = rd32(e);
if (is64) {
ph[i].flags = rd32(e + 4);
ph[i].offset = (uint64_t)rd32(e + 8) | ((uint64_t)rd32(e + 12) << 32);
ph[i].filesz = (uint64_t)rd32(e + 32) | ((uint64_t)rd32(e + 36) << 32);
} else {
ph[i].offset = rd32(e + 4);
ph[i].filesz = rd32(e + 16);
ph[i].flags = rd32(e + 24);
}
}
return phnum;
}
// Whether the ELF has a Go build-ID note: Go programs make their own system calls and never these.
static int elf_is_go(int fd, const struct ddnatv_phdr *ph, int n) {
for (int i = 0; i < n; i++) {
if (ph[i].type != 4 /* PT_NOTE */ || ph[i].filesz < 16) continue;
unsigned char note[16];
if (pread(fd, note, sizeof(note), (off_t)ph[i].offset) != sizeof(note)) continue;
if (rd32(note) == 4 && memcmp(note + 12, "Go\0\0", 4) == 0) return 1;
}
return 0;
}
#define DDNATV_STATIC_XATTR "user.ddnatv.seccomp"
#define DDNATV_STATIC_MAX_CODE (256u * 1024 * 1024)
#ifdef DDNATV_HAVE_GOSYS
static int prepare_go_program(int fd, const char *path, const struct stat *st);
static uint32_t go_blob_fingerprint(void);
static int go_disabled(void);
#endif
// What was done to a file is recorded with its size and time, with the rootfs (a Go program carries
// the paths of it) and with the code Go programs are given (go_programs.c): a newer The native userland looks at
// the programs again.
static void static_marker(const struct stat *st, char *buf, size_t size) {
unsigned fingerprint = 0;
const char *off = "";
#ifdef DDNATV_HAVE_GOSYS
fingerprint = go_blob_fingerprint();
if (go_disabled()) off = " off";
#endif
snprintf(buf, size, "3 %lld %lld.%09ld %08x %s%s", (long long)st->st_size, (long long)st->st_mtim.tv_sec,
(long)st->st_mtim.tv_nsec, fingerprint, g_ddnatv_root, off);
}
// Makes a static program safe to start (see above). Runs before every start of one, so a program
// already handled (marked by an extended attribute that holds its size and modification time) costs
// one fstat and one getxattr; without extended attributes it is scanned again each time. Returns the
// number of patched calls, 0 when there was nothing to do, -1 when the file could not be handled
// (it is then started as it is).
// go_only: leave the file alone unless it is an AArch64 Go program. That is for a program that asks for
// Android's linker (GOOS=android): it is started like the dynamic ones, but it makes its own system
// calls, so it gets the code of the static Go programs (#42).
static int prepare_static_program_ex(const char *path, int go_only) {
int fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0) return -1;
struct stat st;
char marker[PATH_MAX + 96], seen[PATH_MAX + 96];
if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
close(fd);
return -1;
}
static_marker(&st, marker, sizeof(marker));
ssize_t seen_len = fgetxattr(fd, DDNATV_STATIC_XATTR, seen, sizeof(seen) - 1);
if (seen_len > 0) {
seen[seen_len] = '\0';
if (strcmp(seen, marker) == 0) {
close(fd);
return 0;
}
}
struct ddnatv_phdr ph[64];
uint16_t machine = 0;
int n = read_elf_phdrs(fd, &machine, ph, 64);
if (go_only && !(n >= 0 && machine == EM_AARCH64 && elf_is_go(fd, ph, n))) {
close(fd);
return 0;
}
if (n < 0 || (machine != EM_AARCH64 && machine != EM_ARM) || elf_is_go(fd, ph, n)) {
// A Go program has no C library for the hook to be loaded into: it gets code of its own
int go_rc = 0;
#ifdef DDNATV_HAVE_GOSYS
if (n >= 0 && machine == EM_AARCH64 && elf_is_go(fd, ph, n)) go_rc = prepare_go_program(fd, path, &st);
#endif
if (n >= 0 && go_rc >= 0) {
struct stat after;
if (fstat(fd, &after) == 0) static_marker(&after, marker, sizeof(marker));
fsetxattr(fd, DDNATV_STATIC_XATTR, marker, strlen(marker), 0);
}
close(fd);
return n < 0 || go_rc < 0 ? -1 : 0;
}
int total = 0;
int wfd = -1;
int made_writable = 0;
for (int i = 0; i < n; i++) {
if (ph[i].type != 1 /* PT_LOAD */ || !(ph[i].flags & 1 /* PF_X */) || ph[i].filesz == 0) continue;
if (ph[i].filesz > DDNATV_STATIC_MAX_CODE || ph[i].offset > (uint64_t)st.st_size ||
ph[i].filesz > (uint64_t)st.st_size - ph[i].offset) continue;
size_t len = (size_t)ph[i].filesz;
unsigned char *code = (unsigned char *)malloc(len);
if (!code) continue;
if (pread(fd, code, len, (off_t)ph[i].offset) != (ssize_t)len) {
free(code);
continue;
}
size_t patched = patch_seccomp_syscalls(code, 0, len, machine);
if (patched > 0) {
if (wfd < 0) {
wfd = open(path, O_WRONLY | O_CLOEXEC);
if (wfd < 0 && errno == EACCES && fchmod(fd, (st.st_mode | S_IWUSR) & 07777) == 0) {
made_writable = 1;
wfd = open(path, O_WRONLY | O_CLOEXEC);
}
}
// ETXTBSY: the program is running right now, so it was handled when it started.
if (wfd < 0 || pwrite(wfd, code, len, (off_t)ph[i].offset) != (ssize_t)len) {
free(code);
total = -1;
break;
}
total += (int)patched;
}
free(code);
}
if (wfd >= 0) {
// Keep the times: make and friends must not see a rebuilt program.
const struct timespec times[2] = { st.st_atim, st.st_mtim };
futimens(wfd, times);
close(wfd);
}
if (made_writable) fchmod(fd, st.st_mode & 07777);
if (total >= 0) {
struct stat after;
if (fstat(fd, &after) == 0) {
static_marker(&after, marker, sizeof(marker));
fsetxattr(fd, DDNATV_STATIC_XATTR, marker, strlen(marker), 0);
}
}
close(fd);
return total;
}
static int prepare_static_program(const char *path) { return prepare_static_program_ex(path, 0); }
+128
View File
@@ -0,0 +1,128 @@
// Part of libddnatv-hook.so, included by ddnatv-hook.c (one translation unit, so the
// parts share their static functions and are built with the same command as before).
//
// The system calls that Android's seccomp filter answers with SIGSYS, and which of them the
// SIGSYS handler (signals.c) turns into a fake success.
static int is_sigsys_synthetic_success_syscall(int sys_nr) {
#if defined(__NR_setuid)
if (sys_nr == __NR_setuid) return 1;
#endif
#if defined(__NR_setuid32)
if (sys_nr == __NR_setuid32) return 1;
#endif
#if defined(__NR_setgid)
if (sys_nr == __NR_setgid) return 1;
#endif
#if defined(__NR_setgid32)
if (sys_nr == __NR_setgid32) return 1;
#endif
#if defined(__NR_setreuid)
if (sys_nr == __NR_setreuid) return 1;
#endif
#if defined(__NR_setreuid32)
if (sys_nr == __NR_setreuid32) return 1;
#endif
#if defined(__NR_setregid)
if (sys_nr == __NR_setregid) return 1;
#endif
#if defined(__NR_setregid32)
if (sys_nr == __NR_setregid32) return 1;
#endif
#if defined(__NR_setresuid)
if (sys_nr == __NR_setresuid) return 1;
#endif
#if defined(__NR_setresuid32)
if (sys_nr == __NR_setresuid32) return 1;
#endif
#if defined(__NR_setresgid)
if (sys_nr == __NR_setresgid) return 1;
#endif
#if defined(__NR_setresgid32)
if (sys_nr == __NR_setresgid32) return 1;
#endif
#if defined(__NR_setfsuid)
if (sys_nr == __NR_setfsuid) return 1;
#endif
#if defined(__NR_setfsuid32)
if (sys_nr == __NR_setfsuid32) return 1;
#endif
#if defined(__NR_setfsgid)
if (sys_nr == __NR_setfsgid) return 1;
#endif
#if defined(__NR_setfsgid32)
if (sys_nr == __NR_setfsgid32) return 1;
#endif
#if defined(__NR_setgroups)
if (sys_nr == __NR_setgroups) return 1;
#endif
#if defined(__NR_setgroups32)
if (sys_nr == __NR_setgroups32) return 1;
#endif
#if defined(__NR_set_robust_list)
if (sys_nr == __NR_set_robust_list) return 1;
#endif
#if defined(__NR_get_robust_list)
if (sys_nr == __NR_get_robust_list) return 1;
#endif
return 0;
}
static int is_handled_sigsys_syscall(int sys_nr) {
if (is_sigsys_synthetic_success_syscall(sys_nr)) {
return 1;
}
// Unified Linux 5.1+ syscall numbers across architectures
if (sys_nr >= 424 && sys_nr < 512) {
return 1;
}
// Architecture-specific syscall numbers guarded per target ABI
#if defined(__aarch64__)
if (sys_nr == 97 /* __NR_unshare */ ||
sys_nr == 217 /* __NR_add_key */ ||
sys_nr == 218 /* __NR_request_key */ ||
sys_nr == 219 /* __NR_keyctl */ ||
sys_nr == 268 /* __NR_setns */ ||
sys_nr == 277 /* __NR_seccomp */ ||
sys_nr == 280 /* __NR_bpf */ ||
sys_nr == 293 /* __NR_rseq */) {
return 1;
}
#elif defined(__arm__)
if (sys_nr == 309 /* __NR_add_key */ ||
sys_nr == 310 /* __NR_request_key */ ||
sys_nr == 311 /* __NR_keyctl */ ||
sys_nr == 337 /* __NR_unshare */ ||
sys_nr == 375 /* __NR_setns */ ||
sys_nr == 383 /* __NR_seccomp */ ||
sys_nr == 386 /* __NR_bpf */ ||
sys_nr == 398 /* __NR_rseq */) {
return 1;
}
#elif defined(__x86_64__)
if (sys_nr == 248 /* __NR_add_key */ ||
sys_nr == 249 /* __NR_request_key */ ||
sys_nr == 250 /* __NR_keyctl */ ||
sys_nr == 272 /* __NR_unshare */ ||
sys_nr == 308 /* __NR_setns */ ||
sys_nr == 317 /* __NR_seccomp */ ||
sys_nr == 321 /* __NR_bpf */ ||
sys_nr == 334 /* __NR_rseq */) {
return 1;
}
#elif defined(__i386__)
if (sys_nr == 286 /* __NR_add_key */ ||
sys_nr == 287 /* __NR_request_key */ ||
sys_nr == 288 /* __NR_keyctl */ ||
sys_nr == 310 /* __NR_unshare */ ||
sys_nr == 346 /* __NR_setns */ ||
sys_nr == 354 /* __NR_seccomp */ ||
sys_nr == 357 /* __NR_bpf */ ||
sys_nr == 386 /* __NR_rseq */) {
return 1;
}
#endif
return 0;
}
+497
View File
@@ -0,0 +1,497 @@
// Part of libddnatv-hook.so, included by ddnatv-hook.c (one translation unit, so the
// parts share their static functions and are built with the same command as before).
//
// System V shared memory (shmget, shmat, shmdt, shmctl). Android's seccomp filter blocks these system
// calls for apps (the SIGSYS handler turns them into ENOSYS), but X uses them: a program draws an image
// into a segment and the X server reads it from there (the MIT-SHM extension), and Qt, GTK and SDL
// programs expect it. The segments are files of their own in /tmp/.ddnatv-sysv-shm of the rootfs,
// which every process of the app can open and map:
//
// id-N the segment's description: "PID KEY MODE SIZE" (who made it, its key, its rights, its size)
// seg-N its memory (a file of SIZE bytes, mapped MAP_SHARED)
// key-K for a segment with a key: the N it belongs to (K in hex)
//
// N is chosen at random and claimed with O_EXCL, so processes never pick the same one. IPC_RMID
// removes the files at once: programs that attached the segment keep their mapping (as on Linux),
// later attaches fail, which is what X programs expect (they remove a segment as soon as the X
// server has attached it). The segments of processes that ended without removing theirs are deleted
// by the next shmget() that creates one.
#ifndef DDNATV_HOST_TEST
#ifndef MAP_FIXED_NOREPLACE
#define MAP_FIXED_NOREPLACE 0x100000
#endif
#ifndef SHM_REMAP
#define SHM_REMAP 040000
#endif
#define SHM_DIR "/tmp/.ddnatv-sysv-shm"
#define SHM_MAX_ATTACH 512
struct shm_meta {
int pid;
long key;
unsigned mode;
size_t size;
};
struct shm_attach {
void *addr;
size_t size;
int id;
};
static struct shm_attach g_shm_attach[SHM_MAX_ATTACH];
static pthread_mutex_t g_shm_lock = PTHREAD_MUTEX_INITIALIZER;
// root + /tmp/.ddnatv-sysv-shm[/name]
static int shm_path(char *out, size_t outsz, const char *name) {
int n = snprintf(out, outsz, "%s%s%s%s", g_ddnatv_root, SHM_DIR, name ? "/" : "", name ? name : "");
return n > 0 && (size_t)n < outsz ? 0 : -1;
}
static int shm_open_file(const char *name, int flags, unsigned mode) {
char path[PATH_MAX];
if (shm_path(path, sizeof(path), name) != 0) return -1;
return (int)syscall(SYS_openat, AT_FDCWD, path, flags | O_CLOEXEC, mode);
}
static void shm_unlink_file(const char *name) {
char path[PATH_MAX];
if (shm_path(path, sizeof(path), name) == 0) syscall(SYS_unlinkat, AT_FDCWD, path, 0);
}
static int shm_ensure_dir(void) {
char path[PATH_MAX];
if (shm_path(path, sizeof(path), NULL) != 0) return -1;
if (syscall(SYS_mkdirat, AT_FDCWD, path, 0700) == 0 || errno == EEXIST) return 0;
// /tmp of the rootfs missing too (a rootfs being set up)
char tmp[PATH_MAX];
snprintf(tmp, sizeof(tmp), "%s/tmp", g_ddnatv_root);
syscall(SYS_mkdirat, AT_FDCWD, tmp, 01777);
return (syscall(SYS_mkdirat, AT_FDCWD, path, 0700) == 0 || errno == EEXIST) ? 0 : -1;
}
static int shm_read_small(const char *name, char *buf, size_t bufsz) {
int fd = shm_open_file(name, O_RDONLY, 0);
if (fd < 0) return -1;
ssize_t n = (ssize_t)syscall(SYS_read, fd, buf, bufsz - 1);
syscall(SYS_close, fd);
if (n < 0) return -1;
buf[n] = '\0';
return (int)n;
}
// The description of segment `id`; waits a moment for one being written. 0, or -1 (errno EINVAL).
static int shm_read_meta(int id, struct shm_meta *meta) {
char name[32], text[128];
snprintf(name, sizeof(name), "id-%d", id);
for (int attempt = 0; attempt < 50; attempt++) {
int n = shm_read_small(name, text, sizeof(text));
if (n < 0) break;
unsigned long size = 0;
if (n > 0 && sscanf(text, "%d %lx %o %lu", &meta->pid, &meta->key, &meta->mode, &size) == 4) {
meta->size = (size_t)size;
return 0;
}
struct timespec pause = { 0, 1000000 };
nanosleep(&pause, NULL);
}
errno = EINVAL;
return -1;
}
static int shm_process_alive(int pid) {
return pid > 0 && (kill(pid, 0) == 0 || errno == EPERM);
}
static void shm_remove(int id, long key) {
char name[32];
if (key != IPC_PRIVATE) {
// only when the key still names this segment
char text[32];
snprintf(name, sizeof(name), "key-%lx", key);
if (shm_read_small(name, text, sizeof(text)) > 0 && atoi(text) == id) shm_unlink_file(name);
}
snprintf(name, sizeof(name), "seg-%d", id);
shm_unlink_file(name);
snprintf(name, sizeof(name), "id-%d", id);
shm_unlink_file(name);
}
// Deletes the segments whose process has ended (a segment being written has no description yet and is
// left alone).
static void shm_collect(void) {
char path[PATH_MAX];
if (shm_path(path, sizeof(path), NULL) != 0) return;
int dfd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (dfd < 0) return;
char dents[4096];
int dead[64];
int ndead = 0;
for (;;) {
long n = syscall(SYS_getdents64, dfd, dents, sizeof(dents));
if (n <= 0) break;
for (long at = 0; at < n;) {
unsigned short reclen;
memcpy(&reclen, dents + at + 16, sizeof(reclen));
if (reclen == 0) break;
const char *entry = dents + at + 19;
if (strncmp(entry, "id-", 3) == 0 && ndead < 64) {
int id = atoi(entry + 3);
char text[128];
struct shm_meta meta;
if (shm_read_small(entry, text, sizeof(text)) > 0 &&
sscanf(text, "%d %lx %o", &meta.pid, &meta.key, &meta.mode) == 3 && !shm_process_alive(meta.pid)) {
dead[ndead++] = id;
}
}
at += reclen;
}
}
syscall(SYS_close, dfd);
for (int i = 0; i < ndead; i++) {
struct shm_meta meta;
if (shm_read_meta(dead[i], &meta) == 0) shm_remove(dead[i], meta.key);
}
}
// A new segment: claims an id, makes its memory, then writes its description. Returns the id or -1.
static int shm_create(long key, size_t size, unsigned mode) {
// a different sequence of ids for every call, also within one second and one process
static unsigned calls = 0;
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
unsigned seed = (unsigned)getpid() * 2654435761u ^ (unsigned)now.tv_nsec ^ (unsigned)now.tv_sec * 40503u ^
__atomic_add_fetch(&calls, 1, __ATOMIC_RELAXED) * 0x9e3779b9u;
for (int attempt = 0; attempt < 64; attempt++) {
seed = seed * 1103515245u + 12345u;
int id = (int)((seed >> 1) & 0x3fffffff);
if (id == 0) continue;
char name[32];
snprintf(name, sizeof(name), "id-%d", id);
int meta_fd = shm_open_file(name, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (meta_fd < 0) {
if (errno == EEXIST) continue;
return -1;
}
snprintf(name, sizeof(name), "seg-%d", id);
int seg_fd = shm_open_file(name, O_RDWR | O_CREAT | O_TRUNC, 0600);
long page = sysconf(_SC_PAGESIZE);
if (page <= 0) page = 4096;
if (size > (size_t)INTPTR_MAX - (size_t)page) {
// no file (and no mapping) can be that large
syscall(SYS_close, meta_fd);
shm_remove(id, IPC_PRIVATE);
errno = EINVAL;
return -1;
}
size_t rounded = (size + (size_t)page - 1) / (size_t)page * (size_t)page;
if (seg_fd < 0 || ftruncate(seg_fd, (off_t)rounded) != 0) {
int saved = errno;
if (seg_fd >= 0) syscall(SYS_close, seg_fd);
syscall(SYS_close, meta_fd);
shm_remove(id, IPC_PRIVATE);
errno = saved == EFBIG ? EINVAL : (saved ? saved : ENOMEM);
return -1;
}
syscall(SYS_close, seg_fd);
char text[128];
int len = snprintf(text, sizeof(text), "%d %lx %o %lu\n", getpid(), key, mode & 0777, (unsigned long)size);
ssize_t written = (ssize_t)syscall(SYS_write, meta_fd, text, (size_t)len);
syscall(SYS_close, meta_fd);
if (written != len) {
shm_remove(id, IPC_PRIVATE);
errno = ENOSPC;
return -1;
}
return id;
}
errno = ENOSPC;
return -1;
}
// Writes `text` to the file `name` at once: into "new-ID" first, then renamed over it (`exclusive`: only
// when `name` does not exist yet, else -1 with EEXIST). Readers see the old file or the whole new one.
static int shm_publish(const char *name, int id, const char *text, size_t len, int exclusive) {
char tmp_name[32], tmp[PATH_MAX], path[PATH_MAX];
snprintf(tmp_name, sizeof(tmp_name), "new-%d", id);
if (shm_path(tmp, sizeof(tmp), tmp_name) != 0 || shm_path(path, sizeof(path), name) != 0) {
errno = ENAMETOOLONG;
return -1;
}
int fd = (int)syscall(SYS_openat, AT_FDCWD, tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
if (fd < 0) return -1;
ssize_t written = (ssize_t)syscall(SYS_write, fd, text, len);
syscall(SYS_close, fd);
if (written != (ssize_t)len) {
syscall(SYS_unlinkat, AT_FDCWD, tmp, 0);
errno = ENOSPC;
return -1;
}
long rc;
if (exclusive) {
rc = syscall(SYS_renameat2, AT_FDCWD, tmp, AT_FDCWD, path, 1 /* RENAME_NOREPLACE */);
if (rc != 0 && (errno == ENOSYS || errno == EINVAL)) {
// a kernel or file system without RENAME_NOREPLACE: claim the name, then write it
int kfd = (int)syscall(SYS_openat, AT_FDCWD, path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600);
syscall(SYS_unlinkat, AT_FDCWD, tmp, 0);
if (kfd < 0) return -1;
written = (ssize_t)syscall(SYS_write, kfd, text, len);
syscall(SYS_close, kfd);
if (written == (ssize_t)len) return 0;
syscall(SYS_unlinkat, AT_FDCWD, path, 0);
errno = ENOSPC;
return -1;
}
} else {
rc = syscall(SYS_renameat2, AT_FDCWD, tmp, AT_FDCWD, path, 0);
#ifdef SYS_renameat
if (rc != 0 && errno == ENOSYS) rc = syscall(SYS_renameat, AT_FDCWD, tmp, AT_FDCWD, path);
#endif
}
if (rc != 0) {
int saved = errno;
syscall(SYS_unlinkat, AT_FDCWD, tmp, 0);
errno = saved;
return -1;
}
return 0;
}
int shmget(key_t key, size_t size, int shmflg) {
init_ddnatv_hook();
if (g_ddnatv_root[0] == '\0') {
errno = ENOSYS;
return -1;
}
if (shm_ensure_dir() != 0) return -1;
if (shmflg & IPC_CREAT) shm_collect();
if (key == IPC_PRIVATE) {
if (size == 0) {
errno = EINVAL;
return -1;
}
return shm_create(IPC_PRIVATE, size, (unsigned)shmflg);
}
char key_name[32];
snprintf(key_name, sizeof(key_name), "key-%lx", (long)key);
for (int attempt = 0; attempt < 8; attempt++) {
char text[32];
if (shm_read_small(key_name, text, sizeof(text)) > 0) {
int id = atoi(text);
struct shm_meta meta;
if (id > 0 && shm_read_meta(id, &meta) == 0) {
if ((shmflg & IPC_CREAT) && (shmflg & IPC_EXCL)) {
errno = EEXIST;
return -1;
}
if (size > meta.size) {
errno = EINVAL;
return -1;
}
return id;
}
shm_unlink_file(key_name); // names a segment that is gone
}
if (!(shmflg & IPC_CREAT)) {
errno = ENOENT;
return -1;
}
if (size == 0) {
errno = EINVAL;
return -1;
}
int id = shm_create((long)key, size, (unsigned)shmflg);
if (id < 0) return -1;
// The key file appears with its id in it, never empty: written under a name of its own, then
// renamed to the key's name unless another process made the key's segment meanwhile
int len = snprintf(text, sizeof(text), "%d\n", id);
int published = shm_publish(key_name, id, text, (size_t)len, 1);
if (published == 0) return id;
int saved = errno;
shm_remove(id, IPC_PRIVATE);
if (saved != EEXIST) {
errno = saved;
return -1;
}
// another process made the key's segment at the same time: use that one
}
errno = EAGAIN;
return -1;
}
void *shmat(int shmid, const void *shmaddr, int shmflg) {
init_ddnatv_hook();
struct shm_meta meta;
if (g_ddnatv_root[0] == '\0' || shm_read_meta(shmid, &meta) != 0) {
errno = EINVAL;
return (void *)-1;
}
int readonly = (shmflg & SHM_RDONLY) != 0;
char name[32];
snprintf(name, sizeof(name), "seg-%d", shmid);
int fd = shm_open_file(name, readonly ? O_RDONLY : O_RDWR, 0);
if (fd < 0) {
errno = EINVAL;
return (void *)-1;
}
void *want = (void *)shmaddr;
int flags = MAP_SHARED;
if (want) {
if (shmflg & SHM_RND) want = (void *)((uintptr_t)want & ~((uintptr_t)SHMLBA - 1));
else if ((uintptr_t)want & ((uintptr_t)sysconf(_SC_PAGESIZE) - 1)) {
syscall(SYS_close, fd);
errno = EINVAL;
return (void *)-1;
}
// an address in use is replaced only with SHM_REMAP, as on Linux (MAP_FIXED_NOREPLACE: a kernel
// older than 4.17 takes it as a hint, which the check below catches)
flags |= (shmflg & SHM_REMAP) ? MAP_FIXED : MAP_FIXED_NOREPLACE;
}
// a place in the table first, so that every attach can be detached
int slot = -1;
pthread_mutex_lock(&g_shm_lock);
for (int i = 0; i < SHM_MAX_ATTACH; i++) {
if (!g_shm_attach[i].addr && !g_shm_attach[i].size) {
g_shm_attach[i].size = 1; // reserved
slot = i;
break;
}
}
pthread_mutex_unlock(&g_shm_lock);
if (slot < 0) {
syscall(SYS_close, fd);
errno = EMFILE;
return (void *)-1;
}
void *addr = mmap(want, meta.size, readonly ? PROT_READ : (PROT_READ | PROT_WRITE), flags, fd, 0);
int saved = errno;
syscall(SYS_close, fd);
if (addr != MAP_FAILED && want && addr != want) {
munmap(addr, meta.size);
addr = MAP_FAILED;
saved = EINVAL;
}
pthread_mutex_lock(&g_shm_lock);
if (addr == MAP_FAILED) {
g_shm_attach[slot].size = 0;
} else {
g_shm_attach[slot].addr = addr;
g_shm_attach[slot].size = meta.size;
g_shm_attach[slot].id = shmid;
}
pthread_mutex_unlock(&g_shm_lock);
if (addr == MAP_FAILED) {
errno = saved == ENOMEM ? ENOMEM : EINVAL;
return (void *)-1;
}
return addr;
}
int shmdt(const void *shmaddr) {
pthread_mutex_lock(&g_shm_lock);
for (int i = 0; i < SHM_MAX_ATTACH; i++) {
if (g_shm_attach[i].addr && g_shm_attach[i].addr == shmaddr) {
void *addr = g_shm_attach[i].addr;
size_t size = g_shm_attach[i].size;
g_shm_attach[i].addr = NULL;
g_shm_attach[i].size = 0;
pthread_mutex_unlock(&g_shm_lock);
munmap(addr, size);
return 0;
}
}
pthread_mutex_unlock(&g_shm_lock);
errno = EINVAL;
return -1;
}
static int shm_attached_here(int id) {
int count = 0;
pthread_mutex_lock(&g_shm_lock);
for (int i = 0; i < SHM_MAX_ATTACH; i++) {
if (g_shm_attach[i].addr && g_shm_attach[i].id == id) count++;
}
pthread_mutex_unlock(&g_shm_lock);
return count;
}
int shmctl(int shmid, int cmd, struct shmid_ds *buf) {
init_ddnatv_hook();
if (g_ddnatv_root[0] == '\0') {
errno = ENOSYS;
return -1;
}
switch (cmd) {
case IPC_INFO:
case SHM_INFO:
if (buf) {
// the caller's buffer is the structure of the command (struct shminfo or struct shm_info)
memset(buf, 0, cmd == IPC_INFO ? sizeof(struct shminfo) : sizeof(struct shm_info));
if (cmd == IPC_INFO) {
struct shminfo *info = (struct shminfo *)buf;
info->shmmax = sizeof(unsigned long) > 4 ? (unsigned long)1 << 40 : 0x7fffffffUL;
info->shmmin = 1;
info->shmmni = 4096;
info->shmseg = 4096;
info->shmall = (unsigned long)1 << 30;
}
}
return 0;
case SHM_LOCK:
case SHM_UNLOCK:
return 0;
default:
break;
}
struct shm_meta meta;
if (shm_read_meta(shmid, &meta) != 0) {
errno = EINVAL;
return -1;
}
switch (cmd) {
case IPC_STAT:
case SHM_STAT:
case SHM_STAT_ANY:
if (!buf) {
errno = EFAULT;
return -1;
}
memset(buf, 0, sizeof(*buf));
buf->shm_perm.__key = (key_t)meta.key;
// The owner's rights for everyone of the app: X compares the uid of its client with the owner's,
// and the two can differ in The native userland (root emulated for one, not the other)
unsigned owner = meta.mode & 0600;
buf->shm_perm.mode = (unsigned short)(owner | (owner >> 3) | (owner >> 6));
buf->shm_perm.uid = buf->shm_perm.cuid = geteuid();
buf->shm_perm.gid = buf->shm_perm.cgid = getegid();
buf->shm_segsz = meta.size;
buf->shm_cpid = meta.pid;
buf->shm_lpid = getpid();
buf->shm_nattch = (shmatt_t)(shm_attached_here(shmid) + (meta.pid != getpid() ? 1 : 0));
buf->shm_ctime = time(NULL);
return cmd == IPC_STAT ? 0 : shmid;
case IPC_SET: {
if (!buf) {
errno = EFAULT;
return -1;
}
// the new rights are kept (owner and group stay the app's: there is no other user to give it to)
char name[32], text[128];
snprintf(name, sizeof(name), "id-%d", shmid);
int len = snprintf(text, sizeof(text), "%d %lx %o %lu\n", meta.pid, meta.key, buf->shm_perm.mode & 0777u,
(unsigned long)meta.size);
return shm_publish(name, shmid, text, (size_t)len, 0) == 0 ? 0 : -1;
}
case IPC_RMID:
shm_remove(shmid, meta.key);
return 0;
default:
errno = EINVAL;
return -1;
}
}
#endif /* !DDNATV_HOST_TEST */