Files
DroidDeck/tools/tests/test_named_semaphores_preload.py

141 lines
5.5 KiB
Python

from pathlib import Path
import os
import platform
import shutil
import subprocess
import sys
import tempfile
import unittest
from tools.tests.test_native_hook_named_semaphores import CALLS, KEEP, PROBE
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
DENY_LINKS = r"""
#define _GNU_SOURCE
#include <errno.h>
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <stddef.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <unistd.h>
int main(int argc, char **argv) {
struct sock_filter filter[] = {
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_link, 1, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_linkat, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | EPERM),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
struct sock_fprog prog = {sizeof(filter) / sizeof(filter[0]), filter};
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) || prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)) return 125;
execvp(argv[1], argv + 1);
return 126;
}
"""
OPEN_EXISTING = r"""
#include <fcntl.h>
#include <semaphore.h>
#include <stdlib.h>
int main(int argc, char **argv) {
sem_t *sem = sem_open(argv[1], 0);
int value;
if (sem == SEM_FAILED || sem_getvalue(sem, &value) || value != atoi(argv[2])) return 1;
return sem_trywait(sem) || sem_close(sem);
}
"""
PYTHON_PROBE = '''
import multiprocessing as mp
import _multiprocessing
import os
import sys
def square(n):
return n * n
if __name__ == "__main__":
name = "/dd-py-sem-" + str(os.getpid())
sem = _multiprocessing.SemLock(1, 1, 1, name, True)
assert sem.acquire(False)
assert not sem.acquire(False)
sem.release()
for method in mp.get_all_start_methods():
ctx = mp.get_context(method)
lock = ctx.Lock()
with lock:
assert not lock.acquire(False)
queue = ctx.Queue()
queue.put(7)
assert queue.get(timeout=10) == 7
queue.close()
queue.join_thread()
with ctx.Pool(2) as pool:
assert pool.map(square, [1, 2, 3]) == [1, 4, 9]
print(method, flush=True)
'''
@unittest.skipUnless(platform.machine() == "x86_64" and shutil.which("cc"), "needs an x86-64 compiler and host")
class NamedSemaphoresPreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.TemporaryDirectory()
cls.addClassCleanup(cls.tmp.cleanup)
cls.root = Path(cls.tmp.name)
cls.lib = cls.root / "semaphores.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-Werror", "-pthread", "-o", str(cls.lib),
str(PRELOAD / "named_semaphores.c")], check=True)
for name, source in (("deny", DENY_LINKS), ("probe", PROBE), ("keep", KEEP), ("existing", OPEN_EXISTING)):
path = cls.root / (name + ".c")
path.write_text(source)
subprocess.run(["cc", "-pthread", "-o", str(cls.root / name), str(path)], check=True)
cls.script = cls.root / "pool.py"
cls.script.write_text(PYTHON_PROBE)
def run_program(self, args, hooked=True, denied=True):
env = dict(os.environ)
env.pop("LD_PRELOAD", None)
if hooked:
env["LD_PRELOAD"] = str(self.lib)
command = ([str(self.root / "deny")] if denied else []) + list(map(str, args))
return subprocess.run(command, env=env, text=True, capture_output=True, timeout=60)
def test_glibc_semlock_fails_when_hard_links_are_denied(self):
result = self.run_program([sys.executable, "-c",
"import multiprocessing; multiprocessing.Lock()"], hooked=False)
self.assertNotEqual(0, result.returncode)
self.assertIn("PermissionError: [Errno 1]", result.stderr)
def test_named_semaphore_contract_with_and_without_hard_links(self):
for denied in (True, False):
with self.subTest(denied=denied):
result = self.run_program([self.root / "probe", f"/dd-preload-{os.getpid()}-{int(denied)}"], denied=denied)
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual({call: "1" for call in CALLS}, dict(line.split("\t") for line in result.stdout.splitlines()))
def test_semaphores_remain_compatible_with_glibc_and_keep_the_requested_mode(self):
for hooked in (True, False):
with self.subTest(creator_hooked=hooked):
name = f"/dd-preload-existing-{os.getpid()}-{int(hooked)}"
path = Path("/dev/shm/sem." + name[1:])
self.addCleanup(path.unlink, missing_ok=True)
result = self.run_program([self.root / "keep", name], hooked=hooked, denied=hooked)
self.assertEqual(0, result.returncode, result.stderr)
umask = os.umask(0)
os.umask(umask)
self.assertEqual(0o640 & ~umask, path.stat().st_mode & 0o777)
for reader, value in ((not hooked, 3), (hooked, 2)):
result = self.run_program([self.root / "existing", name, value], hooked=reader, denied=reader)
self.assertEqual(0, result.returncode, result.stderr)
def test_python_semlock_queues_and_explicit_pool_contexts(self):
for denied in (True, False):
with self.subTest(denied=denied):
result = self.run_program([sys.executable, self.script], denied=denied)
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual({"fork", "forkserver", "spawn"}, set(result.stdout.splitlines()))