diff --git a/tools/nativeguest/gosys/gosys.c b/tools/nativeguest/gosys/gosys.c index fb8230ce4a..4a38cf4364 100644 --- a/tools/nativeguest/gosys/gosys.c +++ b/tools/nativeguest/gosys/gosys.c @@ -37,7 +37,10 @@ enum { NR_CHDIR = 49, NR_CHROOT = 51, NR_FCHMODAT = 53, NR_FCHOWNAT = 54, NR_OPENAT = 56, NR_READLINKAT = 78, NR_NEWFSTATAT = 79, NR_UTIMENSAT = 88, NR_BIND = 200, NR_CONNECT = 203, NR_EXECVE = 221, NR_NAME_TO_HANDLE_AT = 264, NR_RENAMEAT2 = 276, NR_STATX = 291, - NR_OPENAT2 = 437, NR_FACCESSAT2 = 439, NR_FCHMODAT2 = 452, + NR_OPENAT2 = 437, NR_FACCESSAT2 = 439, NR_FCHMODAT2 = 452, NR_SETREGID = 143, NR_SETGID = 144, + NR_SETREUID = 145, NR_SETUID = 146, NR_SETRESUID = 147, NR_GETRESUID = 148, NR_SETRESGID = 149, + NR_GETRESGID = 150, NR_SETGROUPS = 159, NR_GETUID = 174, NR_GETEUID = 175, NR_GETGID = 176, + NR_GETEGID = 177, }; __attribute__((section(".hdr"), used)) @@ -459,6 +462,9 @@ static i64 handle(const struct gosys_hdr *h, u32 *held, i64 nr, i64 a0, i64 a1, case NR_SETXATTR: case NR_LSETXATTR: case NR_GETXATTR: case NR_LGETXATTR: case NR_LISTXATTR: case NR_LLISTXATTR: case NR_REMOVEXATTR: case NR_LREMOVEXATTR: case NR_RENAMEAT: case NR_RENAMEAT2: case NR_LINKAT: case NR_SYMLINKAT: case NR_GETCWD: case NR_BIND: case NR_CONNECT: case NR_EXECVE: + case NR_GETUID: case NR_GETEUID: case NR_GETGID: case NR_GETEGID: case NR_GETRESUID: case NR_GETRESGID: + case NR_SETUID: case NR_SETGID: case NR_SETREUID: case NR_SETREGID: case NR_SETRESUID: case NR_SETRESGID: + case NR_SETGROUPS: // The calls that carry paths: not mapped where the rootfs is not in its own place (above) if (!rewriting(h)) return sc(nr, a0, a1, a2, a3, a4, a5); break; @@ -483,6 +489,14 @@ static i64 handle(const struct gosys_hdr *h, u32 *held, i64 nr, i64 a0, i64 a1, i64 r = sc(nr, a0, a1, 0, 0, 0, 0); return r > 0 ? unmap_prefix(h, (char *)a0, r, 1) : r; } + case NR_GETUID: case NR_GETEUID: case NR_GETGID: case NR_GETEGID: case NR_SETUID: case NR_SETGID: + case NR_SETREUID: case NR_SETREGID: case NR_SETRESUID: case NR_SETRESGID: case NR_SETGROUPS: + return 0; + case NR_GETRESUID: case NR_GETRESGID: { + i64 r = sc(nr, a0, a1, a2, 0, 0, 0); + if (r == 0) *(u32 *)a0 = *(u32 *)a1 = *(u32 *)a2 = 0; + return r; + } case NR_BIND: case NR_CONNECT: return with_sockaddr(h, held, nr, a0, a1, a2); case NR_EXECVE: { diff --git a/tools/nativeguest/gosys/gosys_abi.h b/tools/nativeguest/gosys/gosys_abi.h index e0c4807d34..d06a4f5c8b 100644 --- a/tools/nativeguest/gosys/gosys_abi.h +++ b/tools/nativeguest/gosys/gosys_abi.h @@ -15,7 +15,7 @@ #include #ifndef GOSYS_VERSION -#define GOSYS_VERSION 3u // raised when the code or its header changes: patched programs are patched again +#define GOSYS_VERSION 4u // raised when the code or its header changes: patched programs are patched again #endif // The scratch memory for rewritten paths: a small state area and 64 slots, in zero-filled memory the diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index e9c115d477..555ce7fc21 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -407,7 +407,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e if (probe.is_elf && !probe.is_dynamic) static_elf = elf_target; // A Go program built for Android asks for Android's linker, so it is started like the dynamic // ones, but it makes its own system calls: it gets the code of the static Go programs (#42) - if (probe.is_dynamic && probe.android_interp) prepare_static_program_ex(elf_target, 1); + if (probe.is_dynamic) prepare_static_program_ex(elf_target, 1); // 1. Transparently route dynamically linked glibc ELF binaries through ld.so // Note: Statically linked binaries (PT_INTERP absent, e.g. Meta Muse Code) must execute directly! @@ -959,7 +959,7 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path, int ret = -1; if (via_ld_so) { ensure_exec_bit(elf_target, probe.mode); - if (probe.android_interp) prepare_static_program_ex(elf_target, 1); // a Go program built for Android (#42) + prepare_static_program_ex(elf_target, 1); // a Go program built for Android (#42) char hook_buf[PATH_MAX]; const char *hook_so = ddnatv_hook_library(hook_buf, sizeof(hook_buf)); diff --git a/tools/nativeguest/hook/go_programs.c b/tools/nativeguest/hook/go_programs.c index 987d0132ee..5bb6f627f6 100644 --- a/tools/nativeguest/hook/go_programs.c +++ b/tools/nativeguest/hook/go_programs.c @@ -70,14 +70,20 @@ static int go_read_phdrs(int fd, struct go_ph *ph, uint16_t *etype, uint16_t *ma static const uint32_t k_go_syscall6[7] = { 0xf94007e8u, 0xf9400be0u, 0xf9400fe1u, 0xf94013e2u, 0xf94017e3u, 0xf9401be4u, 0xf9401fe5u, }; +static const uint32_t k_go_raw_no_error[7] = { + 0xf9400be0u, 0xf9400fe1u, 0xf94013e2u, 0xaa1f03e3u, 0xaa1f03e4u, 0xaa1f03e5u, 0xf94007e8u, +}; #define GO_SVC 0xd4000001u #define GO_CMN_X0_4095 0xb13ffc1fu +#define GO_STR_X0_SP40 0xf90017e0u +#define GO_THUNK_STRIDE 32u +#define GO_QUIET_MAX 4 +_Static_assert(GO_THUNK_STRIDE * (GO_QUIET_MAX + 1) <= GOSYS_THUNK_BYTES, "the thunks fit"); // 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; +static int go_find_calls(int fd, const struct go_ph *ph, int n, const uint32_t *code, uint32_t after, int64_t *at, int max) { + int found = 0; enum { CHUNK = 1 << 20, KEEP = 36 }; unsigned char *buf = (unsigned char *)malloc(CHUNK + KEEP); if (!buf) return -1; @@ -90,19 +96,19 @@ static int64_t go_find_syscall6(int fd, const struct go_ph *ph, int n, int *foun 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; + if (rd32(buf + o) != code[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)++; + for (int k = 1; k < 7 && same; k++) same = rd32(buf + o + 4 * k) == code[k]; + if (!same || rd32(buf + o + 32) != after) continue; + if (found < max) at[found] = (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; + return found; } // "b " / "bl " for a distance in bytes, or 0 when it does not fit @@ -179,13 +185,7 @@ static int go_open_for_write(int fd, const struct stat *st, const char *path, in // 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; +static void go_write_thunk(unsigned char *th, uint32_t to_entry, uint32_t back) { 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) @@ -193,6 +193,15 @@ static void go_build_image(unsigned char *img, const struct gosys_hdr *strings, wr32(th + 16, 0xf94003feu); // ldr x30, [sp] wr32(th + 20, 0x910043ffu); // add sp, sp, #16 wr32(th + 24, back); // b +} + +static void go_build_image(unsigned char *img, const struct gosys_hdr *strings, uint64_t cave_v, uint64_t scratch_v, + const uint32_t *to_entry, const uint32_t *back, int sites, 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)); + for (int k = 0; k < sites; k++) go_write_thunk(img + GOSYS_THUNKS_OFF + GO_THUNK_STRIDE * (uint64_t)k, to_entry[k], back[k]); struct gosys_trailer t; memcpy(&t, img + GOSYS_BLOB_SIZE - sizeof(t), sizeof(t)); t.version = GOSYS_VERSION; @@ -220,11 +229,12 @@ static uint32_t go_blob_fingerprint(void) { // 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) { +static int go_undo(int wfd, struct go_ph *ph, int cave_seg, const struct gosys_trailer *tr, const int64_t *site_off, int sites) { 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; + for (int k = sites - 1; k >= 0; k--) + if (go_pwrite_all(wfd, word, 4, (uint64_t)site_off[k]) != 0) return -1; unsigned char sz[16]; go_wr64(sz, tr->text_orig_filesz); go_wr64(sz + 8, tr->text_orig_filesz); @@ -253,14 +263,30 @@ static int go_disabled(void) { // 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; +static int go_branches(uint64_t cave_v, uint64_t site_v, int k, uint32_t *to_thunk, uint32_t *to_entry, uint32_t *back) { + uint64_t thunk_v = cave_v + GOSYS_THUNKS_OFF + GO_THUNK_STRIDE * (uint64_t)k; *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; } +static int go_links(uint64_t cave_v, const uint64_t *site_v, int sites, uint32_t *to_thunk, uint32_t *to_entry, uint32_t *back) { + if (!go_branches(cave_v, site_v[0], 0, &to_thunk[0], &to_entry[0], &back[0])) return 0; + for (int k = 1; k < sites; k++) + if (!go_branches(cave_v, site_v[k], k, &to_thunk[k], &to_entry[k], &back[k])) return 1; + return sites; +} + +static int go_write_sites(int wfd, const int64_t *site_off, const uint32_t *to_thunk, int sites) { + unsigned char word[4]; + for (int k = sites - 1; k >= 0; k--) { + wr32(word, to_thunk[k]); + if (go_pwrite_all(wfd, word, 4, (uint64_t)site_off[k]) != 0) return -1; + } + return 0; +} + // 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). @@ -271,9 +297,11 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { 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) + int64_t site_off[GO_QUIET_MAX + 1]; + if (go_find_calls(fd, ph, n, k_go_syscall6, GO_CMN_X0_4095, site_off, 1) != 1) return 0; // not a Go of 1.19 or newer (or its function is not there once) + int quiet = go_find_calls(fd, ph, n, k_go_raw_no_error, GO_STR_X0_SP40, site_off + 1, GO_QUIET_MAX); + if (quiet < 0) return -1; + int sites = 1 + (quiet <= GO_QUIET_MAX ? quiet : 0); // The loadable segments, by address int order[GO_MAX_PH], nl = 0; @@ -289,13 +317,16 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { 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); + uint64_t site_v[GO_QUIET_MAX + 1] = { 0 }; + for (int k = 0; k < sites; k++) { + 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[k] >= s->offset && (uint64_t)site_off[k] < s->offset + s->filesz) + site_v[k] = s->vaddr + ((uint64_t)site_off[k] - s->offset); + } + if (site_v[k] == 0) sites = k; } - if (site_v == 0) return 0; + if (sites == 0) return 0; struct gosys_hdr strings; memset(&strings, 0, sizeof(strings)); @@ -333,7 +364,7 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { if (wfd < 0) { rc = -1; } else { - rc = go_undo(wfd, ph, cave_seg, &tr, site_off); + rc = go_undo(wfd, ph, cave_seg, &tr, site_off, sites); changed = rc == 0; } } @@ -343,19 +374,20 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { 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; + int same = 0, site_ok = 0, linked = 0; + uint32_t to_thunk[GO_QUIET_MAX + 1], to_entry[GO_QUIET_MAX + 1], back[GO_QUIET_MAX + 1]; // 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)) { + (linked = go_links(cave_v, site_v, sites, to_thunk, to_entry, back)) > 0) { 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); + go_build_image(img, &strings, cave_v, scratch_v, to_entry, back, linked, &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; + site_ok = same; + for (int k = 0; k < linked && site_ok; k++) site_ok = pread(fd, cur, 4, (off_t)site_off[k]) == 4 && rd32(cur) == to_thunk[k]; if (same && site_ok) goto done; wfd = go_open_for_write(fd, st, path, &made_writable); @@ -365,13 +397,12 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { } 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); + rc = go_write_sites(wfd, site_off, to_thunk, linked); 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) { + if (go_undo(wfd, ph, cave_seg, &tr, site_off, sites) != 0) { rc = -1; goto done; } @@ -394,7 +425,7 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { 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 (v + total > (nx->vaddr & ~0x3fffull)) 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; @@ -410,8 +441,9 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { } } 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; + uint32_t to_thunk[GO_QUIET_MAX + 1], to_entry[GO_QUIET_MAX + 1], back[GO_QUIET_MAX + 1]; + int linked = text < 0 ? 0 : go_links(cave_v, site_v, sites, to_thunk, to_entry, back); + if (text < 0 || !(ph[rw].flags & GO_PF_W) || rw == text || linked == 0) goto done; uint64_t scratch_v = go_align_up(ph[rw].vaddr + ph[rw].memsz, 64); struct gosys_trailer info; @@ -421,8 +453,8 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { 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); + info.site_file_off = (uint64_t)site_off[0]; + go_build_image(img, &strings, cave_v, scratch_v, to_entry, back, linked, &info); wfd = go_open_for_write(fd, st, path, &made_writable); if (wfd < 0) { @@ -442,10 +474,7 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { 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); - } + if (rc == 0) rc = go_write_sites(wfd, site_off, to_thunk, linked); changed = rc == 0; done: diff --git a/tools/nativeguest/hook/static_programs.c b/tools/nativeguest/hook/static_programs.c index 406fca0da9..0e10cd6ad7 100644 --- a/tools/nativeguest/hook/static_programs.c +++ b/tools/nativeguest/hook/static_programs.c @@ -212,9 +212,15 @@ static int read_elf_phdrs(int fd, uint16_t *machine, struct ddnatv_phdr *ph, int 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; + for (uint64_t at = 0; at + 16 <= ph[i].filesz;) { + unsigned char note[16]; + if (pread(fd, note, sizeof(note), (off_t)(ph[i].offset + at)) != (ssize_t)sizeof(note)) break; + uint32_t namesz = rd32(note), descsz = rd32(note + 4); + if (namesz == 4 && memcmp(note + 12, "Go\0\0", 4) == 0) return 1; + uint64_t next = at + 12 + (((uint64_t)namesz + 3) & ~3ull) + (((uint64_t)descsz + 3) & ~3ull); + if (next <= at || next > ph[i].filesz) break; + at = next; + } } return 0; } diff --git a/tools/tests/test_native_hook_go_identity.py b/tools/tests/test_native_hook_go_identity.py new file mode 100644 index 0000000000..3ebc1d53df --- /dev/null +++ b/tools/tests/test_native_hook_go_identity.py @@ -0,0 +1,147 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +MAIN = r""" +package main + +import ( + "fmt" + "probe/quiet" + "syscall" +) + +func main() { + _, _, errno := syscall.RawSyscall(syscall.SYS_SETREUID, ^uintptr(0), 0, 0) + euid, _ := quiet.Call(syscall.SYS_GETEUID, 0, 0, 0) + fmt.Println(syscall.Getuid(), syscall.Getgid(), int(euid), errno == 0) +} +""" + +QUIET = """#include "textflag.h" + +TEXT ·Call(SB),NOSPLIT,$0-48 +\tMOVD\ta1+8(FP), R0 +\tMOVD\ta2+16(FP), R1 +\tMOVD\ta3+24(FP), R2 +\tMOVD\t$0, R3 +\tMOVD\t$0, R4 +\tMOVD\t$0, R5 +\tMOVD\ttrap+0(FP), R8 +\tSVC +\tMOVD\tR0, r1+32(FP) +\tMOVD\tR1, r2+40(FP) +\tRET +""" + +QUIET_GO = """package quiet + +func Call(trap, a1, a2, a3 uintptr) (r1, r2 uintptr) +""" + +CGO = """package main + +import "C" +""" + +LAUNCHER = r""" +#include + +int main(int argc, char **argv) { + execv(argv[1], argv + 1); + return 0; +} +""" + + +class NativeHookGoIdentityTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + if not shutil.which("go"): + raise unittest.SkipTest("no Go toolchain") + cls.tmp = tempfile.TemporaryDirectory(dir="/tmp") + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "launcher.c").write_text(LAUNCHER) + cls.launcher = tmp / "launcher" + subprocess.run([cls.cc, "-O1", "-o", str(cls.launcher), str(tmp / "launcher.c")], check=True) + src = tmp / "src" + src.mkdir() + (src / "go.mod").write_text("module probe\n\ngo 1.19\n") + (src / "main.go").write_text(MAIN) + (src / "quiet").mkdir() + (src / "quiet/quiet.go").write_text(QUIET_GO) + (src / "quiet/quiet_arm64.s").write_text(QUIET) + (src / "cgo.go").write_text(CGO) + cls.root = tmp / "root" + (cls.root / "usr/bin").mkdir(parents=True) + cls.go_env = {**os.environ, "GOOS": "linux", "GOARCH": "arm64", "GOCACHE": str(tmp / "gocache"), + "GOPATH": str(tmp / "gopath"), "GOFLAGS": "-buildvcs=false", "GOTOOLCHAIN": "local"} + cls.static = cls.root / "usr/bin/go-static" + subprocess.run(["go", "build", "-o", str(cls.static), "."], cwd=src, check=True, capture_output=True, + env={**cls.go_env, "CGO_ENABLED": "0"}) + cls.dynamic = cls.root / "usr/bin/go-dynamic" + built = subprocess.run(["go", "build", "-o", str(cls.dynamic), "."], cwd=src, capture_output=True, + env={**cls.go_env, "CGO_ENABLED": "1", "CC": cls.cc}) + if built.returncode != 0: + cls.dynamic = None + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def prepare(self, program): + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")} + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + subprocess.run(cmd + [str(self.launcher), str(program)], env=env, capture_output=True, timeout=120) + return b"CXGOSYS1" in program.read_bytes() + + def run_go(self, program): + cmd = list(self.prefix) + [str(program)] + result = subprocess.run(cmd, capture_output=True, text=True, timeout=120) + self.assertEqual(result.returncode, 0, result.stderr) + return result.stdout.split() + + def check_identity(self, program): + before = self.run_go(program) + if os.getuid() != 0: + self.assertNotEqual(before[0], "0") + self.assertEqual(before[3], "false") + self.assertTrue(self.prepare(program)) + self.assertEqual(self.run_go(program), ["0", "0", "0", "true"]) + moved = self.root.with_name("root-away") + self.root.rename(moved) + try: + away = self.run_go(moved / program.relative_to(self.root)) + finally: + moved.rename(self.root) + if os.getuid() != 0: + self.assertEqual(away, before) + + def test_static_go_program_sees_the_session_identity(self): + self.check_identity(self.static) + + def test_dynamic_go_program_sees_the_session_identity(self): + if self.dynamic is None: + self.skipTest("no cgo cross build") + self.check_identity(self.dynamic) + + +if __name__ == "__main__": + unittest.main()