Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.
C
Sileo: the way to an installed package, and the two gates in the kernel that stood on it
vcvkk7358e95682e1
diff --git a/README.md b/README.mdindex 2958014..9ca2fe6 100644--- a/README.md+++ b/README.md@@ -435,6 +435,18 @@ Sileo работает от него и держит там свою базу.Из-за этого apt под своим `_apt` не доходил ни до сертификата, ни до связки ключей, а Sileo (он работает отmobile) не находил свои папки. Теперь режим каталога запоминается до обхода.+И ещё три, без которых Sileo открывается, но ничего не делает:+- **setuid-помощник**: всё, что Sileo меняет в системе (apt, dpkg, свой каталог индексов), он делает, запуская+ `giveMeRoot` из своего бандла, а тот в пакете лежит как `-rwsr-xr-x root/root`. Распаковка архива обычным+ пользователем бит setuid теряет, и без него Sileo читает репозитории, собирает очередь — и останавливается+ на этом. `mk-jb.sh` возвращает бит (в образе файл принадлежит root, так что он значит ровно то, что написано).+- **свой каталог индексов**: Sileo зовёт apt с `-oDir::State::lists=sileolists/`, то есть+ `/var/jb/var/lib/apt/sileolists`, которого в бутстрапе нет. Создаёт его init и отдаёт mobile, иначе Sileo+ показывает «The folder … doesn't exist» и видит только установленные пакеты вместо витрины.+- **`nsurlsessiond`**: фоновые загрузки URLSession выполняет этот демон iOS, а он стоял в `DENY` в+ `userland/mkjobs.py` вместе со службами Apple-аккаунта. Без него загрузка пакета не начинается и не+ обрывается — Sileo вечно показывает «Queued», без единой ошибки.+Проверка: `RC_JOBS=rc.jobs.sileo` — подготовка, версии dpkg и apt, `apt-get update` и установка пакета из сети,потом свайп по локскрину и `uiopen sileo://`. Данные не переживают перезагрузку (как и всё в `/private/var`):поставленное в префикс после перезапуска ядра придётся ставить снова.diff --git a/prebuilt/SHA256SUMS b/prebuilt/SHA256SUMSindex ed60c74..801c5b5 100644--- a/prebuilt/SHA256SUMS+++ b/prebuilt/SHA256SUMS@@ -1,4 +1,4 @@-Built 2026-10-17 14:49 from this tree.+Built 2026-10-17 20:32 from this tree.9d021e94b58c0d2d29a97266fc51d85a03801a60fbf2b925137c6b0891b68821 prebuilt/mach.development.bcm2837be79494078fff9c94e2747838388c759cef8318a2ba4d943380245a0744d00ef prebuilt/loader.efi@@ -6,7 +6,7 @@ d2a35a4a1d6658ffb3696914f727661b52c9333de8a3af8a31642b8023ce03ac prebuilt/userl1a413befd511384052e1962c1394adce20f718e1f2657ce63ab09828ebc4bd1b prebuilt/userland/cpu_testdb564073effc31e7ab1679a7ffe0631ec22c3030ad347c927028f3e53c8583c3 prebuilt/userland/helloa8baa9ab38333280369b0824aafaf92c7aa6a85851ff0b2551a4c711dbe59cfd prebuilt/userland/hello_dyn-fccc35453a56a42106d0bd49158f78485e5b591972d0aef3f21677393cb5acfc prebuilt/userland/init+3c6dbc99774d6c58981e80deaffa2937846fe37dfa5f7458bef525d447cdcbf0 prebuilt/userland/inite7bfd718aeef8340d3cf087973b2cf2f8c30022336478179a44287cf612ee410 prebuilt/userland/libredwood.dylib740cad8601732d327715ff7babb5233717bd7c0d50787a61c4c72c48170f4f40 prebuilt/userland/libredwood-media.dylib2e367913df16cb8daee0e9cba7e59ac70b26b25b490376fe2edb7a005eaf4393 prebuilt/userland/libredwood-sb.dylibdiff --git a/prebuilt/userland/init b/prebuilt/userland/initindex 5589524..8bcdfe5 100755Binary files a/prebuilt/userland/init and b/prebuilt/userland/init differdiff --git a/tools/mk-jb.sh b/tools/mk-jb.shindex b85a1c6..de975f4 100755--- a/tools/mk-jb.sh+++ b/tools/mk-jb.sh@@ -40,6 +40,13 @@ tar -C "$OUT/root" -xf "$TMP"/data.tar.* 2>/dev/null ||zstd -dc "$TMP/data.tar.zst" | tar -C "$OUT/root" -xf -[ -d "$OUT/root/var/jb/Applications/Sileo.app" ] || { echo "mk-jb.sh: no Sileo.app in the package" >&2; exit 1; }+# The package ships Sileo's root helper as -rwsr-xr-x root/root: everything Sileo does to the system+# (apt, dpkg, making its own list directory) it does by spawning giveMeRoot, which is set-user-ID.+# Unpacking the archive as an ordinary user drops that bit, and without it Sileo can read the+# repositories and queue packages but install nothing. In the image the file belongs to root, so the+# bit means what it says there.+chmod 4755 "$OUT/root/var/jb/Applications/Sileo.app/giveMeRoot"+# dpkg is to know that Sileo is installed, or Sileo itself will offer to install it againmkdir -p "$TMP/control" && tar -C "$TMP/control" -xf "$TMP"/control.tar.* 2>/dev/null ||zstd -dc "$TMP/control.tar.zst" | tar -C "$TMP/control" -xf -@@ -92,6 +99,37 @@ for package in shshd libkrw0 libdimentio0; domv "$OUT/root/var/jb/Library/dpkg/status.new" "$OUT/root/var/jb/Library/dpkg/status"done+# The dependency on "firmware" is taken out of the records of the packages that carry it. That+# package is not a package: usr/libexec/firmware writes it straight into dpkg's database (the iOS+# version, "firmware 16.5"), no repository has it and nothing provides it. apt on the command line+# is content with that -- but Sileo asks apt with an index of its own making (it writes a reduced+# Packages file into var/lib/apt/sileolists and runs "apt-get -sqf ... -oDir::State::lists=+# sileolists/"), and against that index apt calls the same firmware "not installable" and reports+# org.coolstar.sileo and snaputil as broken. Sileo then shows those as errors and refuses to install+# anything at all. What the dependency says -- "this iOS is new enough" -- is true here by+# construction: the system is iOS 16.5 and cannot be anything else.+python3 - "$OUT/root/var/jb/Library/dpkg/status" <<'EOF'+import re, sys++path = sys.argv[1]+stanzas = open(path, encoding='utf-8').read().split('\n\n')+changed = 0+for i, stanza in enumerate(stanzas):+ lines = stanza.split('\n')+ for k, line in enumerate(lines):+ if not line.startswith('Depends: '):+ continue+ groups = [g for g in line[len('Depends: '):].split(', ')+ if not re.match(r'^\s*firmware\s*[( ]|^\s*firmware$', g.split(' | ')[0])]+ if len(groups) != len(line[len('Depends: '):].split(', ')):+ lines[k] = 'Depends: ' + ', '.join(groups) if groups else None+ changed += 1+ lines = [line for line in lines if line is not None]+ stanzas[i] = '\n'.join(lines)+open(path, 'w', encoding='utf-8').write('\n\n'.join(stanzas))+print(f"mk-jb.sh: the dependency on \"firmware\" taken out of {changed} records")+EOF+# What the bootstrap's own prep_bootstrap.sh does, less what this port has no use for: it asks for a# terminal password through a window of its own, and sets login shells in an /etc that is made anew# at every boot anyway. What is left matters: usr/libexec/firmware puts a package named "firmware"diff --git a/userland/build.sh b/userland/build.shindex b651630..0902b21 100755--- a/userland/build.sh+++ b/userland/build.sh@@ -214,6 +214,11 @@ if [ -d $IOS/rootfs/usr/lib ]; thendone >> root/etc/var.skelcp ${RC:-rc.launchd} root/etc/rccp ${RC_JOBS:-rc.jobs} root/etc/rc.jobs+ # QUIET=1: launchd's own standard error goes nowhere (src/init.c). It says a few thousand+ # lines about its own business in the first minutes and pushes everything else out of the+ # kernel's log; the daemons keep their own standard error on the console all the same.+ rm -f root/etc/quiet+ [ -n "$QUIET" ] && : > root/etc/quiet# the jobs the iOS launchd will see (/System/Library/LaunchDaemons is a symlink to this directory)cp com.redwood.demo.plist com.redwood.wifi.plist root/LaunchDaemons/[ -n "$IOS_JOBS" ] && OSLOG=${OSLOG-com.apple.backboardd} ./mkjobs.py ${REST:+--rest} $IOS/rootfs root/LaunchDaemons $IOS_JOBSdiff --git a/userland/mkjobs.py b/userland/mkjobs.pyindex 325b24c..88e09c2 100755--- a/userland/mkjobs.py+++ b/userland/mkjobs.py@@ -26,14 +26,18 @@ import osimport plistlibimport sys-# substrings of labels. (mediaserverd is not among them, for all that there is neither sound nor a camera:+# substrings of labels. (nsurlsessiond is not among them either, for all that it belongs to the same+# family of Apple's own services: it is the daemon that carries out background URLSession downloads,+# and without it an application's download never starts and never fails -- Sileo sits on "Queued"+# for ever, see «Sileo» in README.md.)+# (mediaserverd is not among them, for all that there is neither sound nor a camera:# it is where VideoToolbox decodes for every other process, a HEIC picture included; see src/inject_media.c.)DENY = ('watchdog', 'CommCenter', 'wifi', 'WiFi', 'bluetooth', 'BTServer', 'locationd', 'softwareupdate','datamigrator', 'backupd', 'thermalmonitord', 'keybagd', 'nfcd', 'biometrickitd', 'pearld','obliterat', 'storage_mounter', 'com.apple.fud', 'sepd', 'seputil', 'camera', 'ReportCrash','osanalytics', 'lockdown', 'audio', 'jetsamproperties', 'mobileactivationd','installcoordinationd', 'purplebuddy', 'restore', 'usb', 'accessoryd',- 'mobileassetd', 'nsurlsessiond', 'apsd', 'itunesstored', 'appstored', 'cloudd', 'bird',+ 'mobileassetd', 'apsd', 'itunesstored', 'appstored', 'cloudd', 'bird',# these start, crash and are asked for again, over and over. (aggregated, which was among them, is where# iOS 16 keeps its power log -- com.apple.powerlog.plxpclogger.xpc and the rest -- that Settings > Battery# waits for; it now runs through a session.)diff --git a/userland/rc.jobs.sileo b/userland/rc.jobs.sileoindex 96153b3..60ca8fa 100644--- a/userland/rc.jobs.sileo+++ b/userland/rc.jobs.sileo@@ -1,21 +1,15 @@# Commands run by the launchd job com.redwood.demo (see com.redwood.demo.plist).-# Sileo, the package manager (RC_JOBS=rc.jobs.sileo): the Procursus prefix is grafted onto /var/jb by-# init (tools/mk-jb.sh puts it in the image), so first the preparation the bootstrap wants once per-# boot (the package "firmware" that every other package depends on), then a word from dpkg and apt-# that they run at all, then a package installed from the repository over the network to prove the-# prefix takes one. Then the lock screen is swiped away and Sileo -- a system application here, so-# that LaunchServices finds it by walking /Applications as it does for every other -- is opened;-# "xl screenshot" shows what came of it. At the end, what the user's corner of the prefix holds.+# Sileo, the package manager (RC_JOBS=rc.jobs.sileo): the prefix is grafted onto /var/jb by init+# (tools/mk-jb.sh puts it in the image). The preparation the bootstrap wants once per boot, a fresh+# index, and then the whole way a person goes: the package's own page is opened by URL (no typing),+# GET puts it in the queue, Confirm installs it. At the end, what dpkg has to say about it./redwood/bin/sound_test springboard/var/jb/bin/sh /var/jb/prep.sh-/var/jb/usr/bin/dpkg --version-/var/jb/usr/bin/apt-get --version-/var/jb/usr/bin/dpkg-query -W -f${binary:Package}_${Version}_${Status}\n org.coolstar.sileo firmware/var/jb/usr/bin/apt-get update-/var/jb/usr/bin/apt-get install -y tree+/redwood/bin/rwtouch wait 4 swipe 0.5 0.985 0.5 0.3 200 wait 6+/var/jb/usr/bin/uiopen sileo://package/tree+/redwood/bin/rwtouch wait 14 tap 0.32 0.59 wait 3 tap 0.5 0.826 wait 6+/redwood/bin/rwtouch tap 0.86 0.303 wait 5 tap 0.2 0.862 wait 6 tap 0.5 0.85 wait 60+/var/jb/bin/cat /var/jb/var/log/apt/term.log+/var/jb/usr/bin/dpkg-query -W -f${binary:Package}_${Version}_${Status}\n tree/var/jb/usr/bin/tree -L 1 /var/jb-/redwood/bin/rwtouch wait 4 swipe 0.5 0.985 0.5 0.3 200 wait 8-/var/jb/usr/bin/uiopen sileo://-# its first screen: the notifications it asks for, and the analytics it offers-/redwood/bin/rwtouch wait 14 tap 0.32 0.59 wait 3 tap 0.5 0.826 wait 25 tap 0.5 0.93 wait 60-/var/jb/usr/bin/find /var/jb/var/mobile -maxdepth 4diff --git a/userland/src/init.c b/userland/src/init.cindex cac1274..8fd173b 100644--- a/userland/src/init.c+++ b/userland/src/init.c@@ -620,10 +620,18 @@ mount_writable(void)static const char *const mobiles[] = { "/private/var/jb/var/mobile", "/private/var/jb/var/mobile/Library","/private/var/jb/var/mobile/Library/Caches","/private/var/jb/var/mobile/Library/Preferences",- "/private/var/jb/var/mobile/Documents" };+ "/private/var/jb/var/mobile/Documents",+ /*+ * Sileo keeps the indexes of its repositories apart from+ * apt's own (it runs apt with -oDir::State::lists=+ * sileolists/), and it is mobile who writes them.+ */+ "/private/var/jb/var/lib/apt/sileolists",+ "/private/var/jb/var/lib/apt/sileolists/partial" };for (unsigned i = 0; i < sizeof(mobiles) / sizeof(mobiles[0]); i++) {mkdir(mobiles[i], 0755);+ grafted = chown(mobiles[i], 501, 501) == 0 && grafted;}grafted = own_tree("/private/var/jb/var/mobile", 501) && grafted;printf(" /var/jb: %d directories, %d files and links\n", dirs, entries);@@ -785,6 +793,7 @@ run_command(char *line)char *envp[] = { "PATH=/var/jb/usr/bin:/var/jb/bin:/var/jb/usr/sbin:/var/jb/sbin:/bin:/sbin:/usr/bin:/usr/sbin","HOME=/var/mobile", "TERM=dumb", NULL };int argc = 0, status = 0, background = 0;+ struct stat st;pid_t pid;for (char *p = line; *p && argc < 63;) {@@ -816,6 +825,21 @@ run_command(char *line)/* "exec program args": become that program, keeping process number 1 */if (strcmp(argv[0], "exec") == 0 && argc > 1) {+ /*+ * With etc/quiet in our image (build.sh QUIET=1), what this program says on its+ * standard error is dropped. It is meant for launchd, which says a few thousand lines+ * about its own business in a couple of minutes and pushes everything else out of the+ * kernel's log; the daemons it starts keep their own standard error on the console+ * (mkjobs.py sets it), and so does everything the job runner runs.+ */+ if (stat(in_image("/etc/quiet"), &st) == 0) {+ int null = open("/dev/null", O_WRONLY, 0);++ if (null >= 0) {+ dup2(null, 2);+ close(null);+ }+ }execve(argv[1], argv + 1, envp);printf("%s: %s\n", argv[1], strerror(errno));return;diff --git a/userland/src/inject_app.c b/userland/src/inject_app.cindex 687e836..facc0fe 100644--- a/userland/src/inject_app.c+++ b/userland/src/inject_app.c@@ -8,6 +8,11 @@* and says the frames of the stack when a signal kills it, under the dyld shared cache's slide,* which `ipsw dyld a2s <cache> <address>` turns back into names.*/+#include <dispatch/dispatch.h>+#include <spawn.h>+#include <sys/stat.h>+#include <objc/message.h>+#include <objc/runtime.h>#include <execinfo.h>#include <fcntl.h>#include <mach-o/dyld.h>@@ -54,6 +59,135 @@ killed(int number, siginfo_t *info, void *context)raise(number);}+/*+ * Two things an application does on its way to a download, said out loud. Sileo queues a package and+ * nothing happens: no connection is made and no error is shown, so the question is how far it gets --+ * does it ask UIKit for a background task (a round trip to another daemon, which can wait for ever if+ * that daemon does not answer), and does it ever start a URL session task, for what address.+ */+static unsigned long (*begin_task)(id, SEL, id);+static void (*resume_task)(id, SEL);++static unsigned long+watched_begin_task(id self, SEL cmd, id handler)+{+ unsigned long task;+ char line[160];+ int n;++ n = snprintf(line, sizeof(line), "redwood: %s: asking UIKit for a background task\n", who);+ say(line, (size_t)(n > 0 ? n : 0));+ task = begin_task(self, cmd, handler);+ n = snprintf(line, sizeof(line), "redwood: %s: the background task is %lu\n", who, task);+ say(line, (size_t)(n > 0 ? n : 0));+ return task;+}++static void+watched_resume_task(id self, SEL cmd)+{+ const char *(*string)(id, SEL) = (const char *(*)(id, SEL))objc_msgSend;+ id (*get)(id, SEL) = (id (*)(id, SEL))objc_msgSend;+ const char *url = "?";+ char line[700];+ id request, address, text;+ int n;++ request = get(self, sel_registerName("originalRequest"));+ address = request != NULL ? get(request, sel_registerName("URL")) : NULL;+ text = address != NULL ? get(address, sel_registerName("absoluteString")) : NULL;+ if (text != NULL) {+ url = string(text, sel_registerName("UTF8String"));+ }+ n = snprintf(line, sizeof(line), "redwood: %s: starting a session task for %s\n", who,+ url != NULL ? url : "?");+ say(line, (size_t)(n > 0 ? n : 0));+ resume_task(self, cmd);+}++/*+ * One setting of Sileo's, set for it at every start: "Show Packages From Canister" (ShowProvisional,+ * on by default). Canister is the search service Sileo asks about packages, and where its servers+ * cannot be reached the asking never stops -- 3810 session tasks in two minutes in one run here,+ * and the download of a package never gets its turn among them. With the setting off Sileo keeps to+ * the repositories themselves, which work. The prefix lives in memory and is new at every boot, so+ * there is nowhere to keep this but here. It is done on the main queue, not here in the library's+ * own initializer: at that point Foundation is loaded but has not run its own initializers yet, and+ * asking it for the defaults then kills the application before it says a word.+ */+static void+keep_to_the_repositories(void)+{+ id (*get)(id, SEL) = (id (*)(id, SEL))objc_msgSend;+ id (*from_text)(id, SEL, const char *) = (id (*)(id, SEL, const char *))objc_msgSend;+ void (*set_bool)(id, SEL, signed char, id) = (void (*)(id, SEL, signed char, id))objc_msgSend;+ id defaults = (id)objc_getClass("NSUserDefaults");+ id key = from_text((id)objc_getClass("NSString"), sel_registerName("stringWithUTF8String:"), "ShowProvisional");++ if (defaults == NULL || key == NULL) {+ return;+ }+ defaults = get(defaults, sel_registerName("standardUserDefaults"));+ if (defaults != NULL) {+ set_bool(defaults, sel_registerName("setBool:forKey:"), 0, key);+ say("redwood: Sileo: its Canister search is turned off (it is not reachable here)\n", 73);+ }+}++/*+ * Every program the application starts, with its arguments. Sileo does everything to the system by+ * spawning its set-user-ID helper, which execs apt or dpkg; the arguments are the whole question+ * when apt's answer to Sileo differs from apt's answer on the command line.+ */+static int+watched_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *actions,+ const posix_spawnattr_t *attr, char *const argv[], char *const envp[])+{+ char line[1200];+ int n = snprintf(line, sizeof(line), "redwood: %s: (uid %d) spawns %s", who, (int)getuid(),+ path != NULL ? path : "?");++ for (int i = 0; argv != NULL && argv[i] != NULL && n < (int)sizeof(line) - 40; i++) {+ n += snprintf(line + n, sizeof(line) - (size_t)n, " %s", argv[i]);+ }+ /*+ * The size of what it is about to move, while the file is still there: apt refuses the+ * package Sileo puts in its archives ("Unable to fetch some archives") and takes the very+ * same package when apt itself fetched it, so the first thing to know is whether the file+ * is whole.+ */+ if (argv != NULL && argv[0] != NULL && strcmp(argv[0], "mv") == 0 && argv[1] != NULL) {+ struct stat st;++ if (stat(argv[1], &st) == 0) {+ n += snprintf(line + n, sizeof(line) - (size_t)n, " [%lld bytes]", (long long)st.st_size);+ } else {+ n += snprintf(line + n, sizeof(line) - (size_t)n, " [no such file]");+ }+ }+ n += snprintf(line + n, sizeof(line) - (size_t)n, "\n");+ say(line, (size_t)n);+ return posix_spawn(pid, path, actions, attr, argv, envp);+}++__attribute__((used)) static struct {+ const void *ours, *theirs;+} spawn_interpose __attribute__((section("__DATA,__interpose"))) = {+ (const void *)watched_spawn, (const void *)posix_spawn+};++/* Put ours in the place of a method, keeping the one that was there. */+static void+watch(const char *name, const char *selector, IMP ours, void *theirs)+{+ Class class = objc_getClass(name);+ Method method = class != NULL ? class_getInstanceMethod(class, sel_registerName(selector)) : NULL;++ if (method != NULL && method_getImplementation(method) != ours) {+ *(IMP *)theirs = method_setImplementation(method, ours);+ }+}+__attribute__((constructor))static voidredwood_app_init(void)@@ -84,6 +218,16 @@ redwood_app_init(void)for (unsigned i = 0; i < sizeof(signals) / sizeof(signals[0]); i++) {sigaction(signals[i], &action, NULL);}- n = snprintf(line, sizeof(line), "redwood: %s: started, watching for what kills it\n", name);+ if (strcmp(name, "Sileo") == 0) {+ dispatch_async(dispatch_get_main_queue(), ^{ keep_to_the_repositories(); });+ }+ watch("UIApplication", "beginBackgroundTaskWithExpirationHandler:", (IMP)watched_begin_task, &begin_task);+ /*+ * NSURLSessionTask alone: its subclasses inherit the very same method, and watching it twice+ * would leave ours as the "original" of itself -- a call that never returns.+ */+ watch("NSURLSessionTask", "resume", (IMP)watched_resume_task, &resume_task);+ n = snprintf(line, sizeof(line), "redwood: %s: started as uid %d (effective %d), watching for what kills it\n",+ name, (int)getuid(), (int)geteuid());say(line, (size_t)(n > 0 ? n : 0));}diff --git a/xnu/redwood.patch b/xnu/redwood.patchindex eada4c3..e0032ce 100644--- a/xnu/redwood.patch+++ b/xnu/redwood.patch@@ -337,7 +337,7 @@ index 95192dd62449..b00da803b5b4 100644/*diff --git a/bsd/kern/kern_exec.c b/bsd/kern/kern_exec.c-index 1d71c66629fb..828cb840fba1 100644+index 1d71c66629fb..84b1e1eaebf3 100644--- a/bsd/kern/kern_exec.c+++ b/bsd/kern/kern_exec.c@@ -1157,6 +1157,9 @@ SYSCTL_PROC(_vm, OID_AUTO, shared_region_control,@@ -437,7 +437,86 @@ index 1d71c66629fb..828cb840fba1 100644imgp->ip_vfs_context);error = open1(imgp->ip_vfs_context, ndp,-@@ -5586,10 +5646,61 @@ bad:+@@ -3094,10 +3154,16 @@ spawn_validate_persona(struct _posix_spawn_persona_info *px_persona)+ int error = 0;+ struct persona *persona = NULL;++- if (!IOCurrentTaskHasEntitlement( PERSONA_MGMT_ENTITLEMENT)) {+- return EPERM;+- }+-++ /*++ * redwood: two of the three checks below cannot be passed in this port, and both stand in++ * the way of something ordinary. The entitlement is one nobody carries here (nothing is++ * signed, AMFI is a stub), and the persona is one nobody makes -- yet a package manager++ * becomes root by asking for exactly this: Sileo spawns apt and dpkg into persona 99 with++ * the uid it wants (its APTWrapper). Refused here, the spawn failed before the program was++ * ever started, and the application waited for an answer that could not come. The check++ * that still means something -- the size of the group list -- stays; see++ * spawn_persona_adopt() below for what happens then.++ */+ if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_GROUPS) {+ if (px_persona->pspi_ngroups > NGROUPS_MAX) {+ return EINVAL;+@@ -3105,12 +3171,6 @@ spawn_validate_persona(struct _posix_spawn_persona_info *px_persona)+ }++ persona = persona_lookup(px_persona->pspi_id);+- if (!persona) {+- error = ESRCH;+- goto out;+- }+-+-out:+ if (persona) {+ persona_put(persona);+ }+@@ -3130,9 +3190,6 @@ spawn_persona_adopt(proc_t p, struct _posix_spawn_persona_info *px_persona)+ * the kauth with a different UID/GID combo+ */+ persona = persona_lookup(px_persona->pspi_id);+- if (!persona) {+- return ESRCH;+- }++ cred = kauth_cred_proc_ref(p);++@@ -3158,6 +3215,34 @@ spawn_persona_adopt(proc_t p, struct _posix_spawn_persona_info *px_persona)+ px_persona->pspi_gmuid);+ }+++ if (persona == NULL) {++ /*++ * redwood: there are no personas in this port -- nothing makes them, and++ * kpersona_find_by_type() answers "no such process" to everyone who asks. iOS's own++ * programs get along without them, but a package manager becomes root by way of one:++ * Sileo asks posix_spawn for persona 99 with OVERRIDE and uid 0 (its APTWrapper), and++ * that is how it runs apt and dpkg. With the persona missing the lookup failed, the++ * whole spawn failed with ESRCH, and the application sat for ever waiting for an++ * answer from a program that was never started. What the caller is after is the++ * credential, not the persona, so the credential is what it gets: the uid, gid and++ * groups it asked for, set on the process being spawned.++ *++ * The thread's own credential is not touched here: the thread running this is the++ * parent's, and the new process gets its credential when its image is activated.++ */++ __block kauth_cred_t new_cred = cred;++++ (void)proc_update_label(p, true, ^kauth_cred_t (kauth_cred_t cur_cred) {++ if (new_cred != cur_cred) {++ kauth_cred_ref(new_cred);++ kauth_cred_unref(&cur_cred);++ }++ return new_cred;++ });++ kauth_cred_unref(&cred);++ return 0;++ }+++ ret = persona_proc_adopt(p, persona, cred);++ kauth_cred_unref(&cred);+@@ -5586,10 +5671,61 @@ bad:* Note: The argument and environment vectors are user space pointers* to arrays of user space pointers.*/@@ -499,7 +578,7 @@ index 1d71c66629fb..828cb840fba1 100644int error = 0;int ptr_size = (imgp->ip_flags & IMGPF_WAS_64BIT_ADDR) ? 8 : 4;int new_ptr_size = (imgp->ip_flags & IMGPF_IS_64BIT_ADDR) ? 8 : 4;-@@ -5759,6 +5870,33 @@ exec_extract_strings(struct image_params *imgp)+@@ -5759,6 +5895,33 @@ exec_extract_strings(struct image_params *imgp)imgp->ip_envc++;}@@ -533,7 +612,7 @@ index 1d71c66629fb..828cb840fba1 100644/* Save space for envv[] NULL terminator */if (imgp->ip_argspace < new_ptr_size) {error = E2BIG;-@@ -6636,7 +6774,23 @@ handle_mac_transition:+@@ -6636,7 +6799,23 @@ handle_mac_transition:}/* Update the process' identity version and set the security token */@@ -558,7 +637,7 @@ index 1d71c66629fb..828cb840fba1 100644task_set_uniqueid(task);set_security_token_task_internal(p, task);-@@ -7538,6 +7692,11 @@ process_signature(proc_t p, struct image_params *imgp)+@@ -7538,6 +7717,11 @@ process_signature(proc_t p, struct image_params *imgp)}done:@@ -632,6 +711,30 @@ index 1750d3a52d3c..9947cb2421da 100644#endif}+diff --git a/bsd/kern/kern_priv.c b/bsd/kern/kern_priv.c+index 88adf2dda936..2b2f528d2273 100644+--- a/bsd/kern/kern_priv.c++++ b/bsd/kern/kern_priv.c+@@ -82,6 +82,19 @@ priv_check_cred(kauth_cred_t cred, int priv, int flags)+ #endif+ int error;+++ /*++ * redwood: nothing is signed here and no process carries an entitlement (AMFI is a stub), so++ * every privilege that an entitlement would answer for is refused -- and iOS leans on one of++ * them for ordinary work. A daemon that goes to the network on behalf of an application++ * (trustd checking the certificate for whoever opened the connection, nsurlsessiond carrying++ * out its downloads) describes the connection to NECP as delegated, and without this++ * privilege the kernel refuses it with EPERM: the download then never starts and never fails.++ * These daemons run as mobile, so the "root gets everything" rule below does not reach them.++ */++ if (priv == PRIV_NET_PRIVILEGED_SOCKET_DELEGATE) {++ return 0;++ }+++ /*+ * We first evaluate policies that may deny the granting of+ * privilege unilaterally.diff --git a/bsd/kern/kern_sig.c b/bsd/kern/kern_sig.cindex ae4a5f33df1e..986b517dfd18 100644--- a/bsd/kern/kern_sig.c