Skip to content

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

store_test: the storefront cannot be put on this device from outside, and why

vcvkkf2bbc2a62104
diff --git a/README.md b/README.md
index f16c389..48837c4 100644
--- a/README.md
+++ b/README.md
@@ -1676,6 +1676,35 @@ fetch local account. This will prevent initial bag requests from specifying stor
отвечает: в журнале видно и подключение `appstored` к нему, и его транзакции `AMSDCookieService.getCookies`.
Сценарий — `userland/rc.jobs.store`.
+**Витрину руками положить некуда.** Раз сервер выдал номер именно этому устройству
+(`x-set-apple-store-front: 143469-2,8`), оставалось проверить, не в нём ли одном дело: положить его на
+учётную запись самим. Для этого есть `userland/src/store_test.m` — он подписан теми же правами, что и
+`appstored` (`ldid -e` с его двоичного файла: `com.apple.accounts.appleaccount.fullaccess`,
+`com.apple.private.accounts.allaccounts`), сам загружает AppleMediaServices и зовёт её же методы.
+Ответ отрицательный, и он много объясняет:
+
+```
+store_test: uid 501, euid 501; AppleMediaServices loaded
+store_test: before: ams_localiTunesAccount: user local
+store_test: before: ams_localiTunesAccount: id 7BA65770-7DC2-488D-8B57-81B17A8B12F0
+store_test: before: ams_localiTunesAccount: STOREFRONT (null)
+store_test: set: in memory now 143469-2,8
+store_test: set: ams_saveAccount: done
+store_test: after: ams_localiTunesAccount: STOREFRONT (null)
+```
+
+Установщик работает, значение не сохраняется. В `accountsd` нет ни одной записи типа
+`com.apple.account.iTunesStore` — для телефона, в который не входили, это правильно, — а та «местная»
+учётная запись, которую отдаёт AMS, не её строка: её идентификатор каждый раз новый (в трёх сеансах
+`appstored` это 143B8A92…, 8D31AF5C…, C976F334…, у нас 7BA65770…). То есть она создаётся заново при
+каждой загрузке, с пустой витриной, и записать её негде: единственное, что её заполняет, — ответ
+сервера мешка (`_setStorefrontFromURLResponse:bagData:`), тот самый запрос, которого не происходит.
+
+Значит, снаружи процесса витрину этому устройству не отдать, и следующее место — внутри `appstored`:
+в порту уже есть механизм подсадки своей библиотеки в штатные программы (`INJECT` в `build.sh`,
+`src/inject_sb.c` и соседние). Она и положила бы витрину на ту самую учётную запись, которой
+пользуется AMS, и заодно показала бы, строится ли запрос мешка вообще.
+
**`mobileactivationd` — ещё одна служба из списка «никогда не пробовали».** Её спрашивал как раз
`appstored` (четыре ненайденных обращения за сеанс и двадцать строк «[HRNSupport] Failed to copy activation
record ... MobileActivation.ErrorDomain Code=-1 "IPC Error"» из каждого потока, который трогает мешок).
diff --git a/userland/build.sh b/userland/build.sh
index e3d272e..7837f69 100755
--- a/userland/build.sh
+++ b/userland/build.sh
@@ -159,6 +159,10 @@ if [ -d $IOS/rootfs/usr/lib ]; then
$DYN -framework CoreFoundation -framework CoreGraphics -framework ImageIO -o obj/snap_test src/snap_test.c
$DYN -framework CoreFoundation -framework CoreGraphics -framework CoreText -o obj/font_test src/font_test.c
$DYN -fobjc-arc -framework Foundation -framework SystemConfiguration -o obj/net_test src/net_test.m
+ # (the account database answers only a client with the entitlements its own daemons hold: src/store_test.m)
+ $DYN -fobjc-arc -framework Foundation -framework Accounts -o obj/store_test src/store_test.m &&
+ { ${LDID:-ldid} -Ssrc/store_test.entitlements obj/store_test 2>/dev/null ||
+ echo "build.sh: no ldid: store_test is unsigned, and accountsd will not show it the accounts"; }
# (with an entitlement for "battery_test open URL", if ldid is there: src/battery_test.c)
$DYN -framework CoreFoundation -framework IOKit -lsqlite3 -o obj/battery_test src/battery_test.c &&
{ ${LDID:-ldid} -Ssrc/battery_test.entitlements obj/battery_test 2>/dev/null ||
@@ -212,6 +216,7 @@ if [ -d $IOS/rootfs/usr/lib ]; then
[ -f obj/snap_test ] && cp obj/snap_test root/bin/
[ -f obj/font_test ] && cp obj/font_test root/bin/
[ -f obj/net_test ] && cp obj/net_test root/bin/
+ [ -f obj/store_test ] && cp obj/store_test root/bin/
[ -f obj/battery_test ] && cp obj/battery_test root/bin/
[ -f obj/keychain_test ] && cp obj/keychain_test root/bin/
[ -f obj/wifipw_test ] && cp obj/wifipw_test root/bin/
diff --git a/userland/rc.jobs.store b/userland/rc.jobs.store
index f807675..935813d 100644
--- a/userland/rc.jobs.store
+++ b/userland/rc.jobs.store
@@ -20,6 +20,20 @@
# And no second DHCP: configd configures en0 by itself here (the job com.redwood.wifi, with wifi=1),
# so "dhcp en0" asks IPConfiguration for a service that is already being made. Wait for the address.
#
+# Two things are asked at once here, because one window answers both. The storefront is put on the
+# local account with store_test, which is not an invention: it is the value bag.itunes.apple.com
+# returned for this device when asked with none (x-set-apple-store-front: 143469-2,8), a region and
+# not an account. If the store lists applications with it in place, then "AMS will not bootstrap its
+# own storefront" is the whole of what is left, and the store already does what was asked of it --
+# browse without an Apple ID, and no way to install, there being nothing to buy with.
+# The other half is the kernel's command line: atm_diagnostic_config=0x20000000
+# (ATM_ENABLE_LEGACY_LOGGING, osfmk/atm/atm_types.h) is what libtrace reads out of the boot
+# arguments to turn on full logging, and it is the only way in to AMS's own account-side lines --
+# "Attempted a bag load but an account wasn't provided", "Failed to fetch local account. This will
+# prevent initial bag requests from specifying storefront" -- which sit below the level
+# OS_ACTIVITY_DT_MODE prints. Only the jobs named in OSLOG print to the console, so the extra volume
+# is the one daemon's and not the whole system's.
+#
# QUIET=1 is not enough by itself, measured: launchd's lines keep coming (7755 in a 320 s run against
# 8013 in a 263 s one without it), and of five net_test steps run early only the last printed. So the
# steps wait out the start first -- the flood is heaviest while launchd spawns its two hundred
@@ -28,10 +42,11 @@
# that is what emptied the first run of this file.
/redwood/bin/rwtouch wait 55 swipe 0.5 0.985 0.5 0.3 250 wait 20
/redwood/bin/net_test waitaddr en0 60
-/redwood/bin/net_test fetch https://www.apple.com/library/test/success.html
-/redwood/bin/net_test resolve bag.itunes.apple.com reach bag.itunes.apple.com
/redwood/bin/net_test fetch https://bag.itunes.apple.com/bag.xml
-/redwood/bin/net_test fetch https://init.itunes.apple.com/bag.xml
+# the account as it stands, then the number the bag server gave THIS device, by AMS's own setter.
+# (Answered, and the answer is no: the value sets in memory and does not keep, because AMS's local
+# account is made fresh every boot and accountsd has no iTunes account at all. See src/store_test.m.)
+/redwood/bin/store_test user 501 set 143469-2,8
# and only then the store, open long enough to time out (30 s) and try again
/redwood/bin/rwtouch tap 0.615 0.59 wait 95
/bin/ps -A
diff --git a/userland/src/store_test.entitlements b/userland/src/store_test.entitlements
new file mode 100644
index 0000000..d3b3b0e
--- /dev/null
+++ b/userland/src/store_test.entitlements
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <!-- what appstored's own signature carries for the account database (ldid -e on its binary) -->
+ <key>com.apple.accounts.appleaccount.fullaccess</key>
+ <true/>
+ <key>com.apple.private.accounts.allaccounts</key>
+ <true/>
+ <key>application-identifier</key>
+ <string>hackios.store-test</string>
+ <key>keychain-access-groups</key>
+ <array>
+ <string>hackios.store-test</string>
+ <string>com.apple.itunes</string>
+ </array>
+</dict>
+</plist>
diff --git a/userland/src/store_test.m b/userland/src/store_test.m
new file mode 100644
index 0000000..e337ec1
--- /dev/null
+++ b/userland/src/store_test.m
@@ -0,0 +1,179 @@
+/*
+ * store_test: the iTunes Store account this device has, and the storefront on it.
+ *
+ * usage: store_test show
+ * store_test set STOREFRONT (e.g. "143469-2,8")
+ *
+ * Why it exists. The App Store's front page is a "bag" -- AppleMediaServices' configuration, fetched
+ * from bag.itunes.apple.com -- and AMS will not load one until it knows the storefront, the number
+ * that says which country's store this device belongs to. A stock iPhone with no SIM and no account
+ * gets that number from the bag server itself: it asks with none, the server picks one from the
+ * address the request came from and returns it in an X-Set-Apple-Store-Front header, and AMS writes
+ * it onto the local account. The first half works here -- net_test fetches the bag and the header
+ * comes back (rc.jobs.store) -- and the second never happens: appstored opens no socket at all, AMS
+ * reads an empty cache in its first 40 ms and stops. So: put the number the server gave THIS phone
+ * on the account by hand, with AMS's own setter, and see whether that is the only thing missing.
+ *
+ * Nothing here is invented. The value to pass is the one bag.itunes.apple.com returned for this
+ * device, and it is a region, not an account: no Apple ID is signed in, none can be, and the store
+ * must still refuse to install anything -- there is nothing to buy with.
+ *
+ * How. The account AMS talks about is not an ordinary one: asking accountsd for accounts of type
+ * com.apple.account.iTunesStore returns none, while appstored prints a local account with a stable
+ * identifier every boot (username = local, storefront = (null)). AppleMediaServices keeps its own
+ * notion of it, so this uses AMS's own calls rather than guessing at the database:
+ * ACAccountStore's ams_localiTunesAccount, and ams_localiTunesAccountAfterUpdatingStorefront:,
+ * which is the call AMS itself makes when the bag server returns an x-set-apple-store-front header.
+ * Everything is guarded by respondsToSelector and every answer is printed, so a run says which of
+ * them this build of AMS actually has.
+ * accountsd answers only a client that holds the entitlements its own daemons hold
+ * (store_test.entitlements, taken from appstored's own signature with ldid -e:
+ * com.apple.accounts.appleaccount.fullaccess, com.apple.private.accounts.allaccounts), so build.sh
+ * signs this one with ldid.
+ *
+ * WHAT IT ANSWERED, and it is not what was hoped for. As mobile (uid 501, "user 501" below: init runs
+ * this as root and appstored is mobile's):
+ * store_test: before: ams_localiTunesAccount: user local
+ * store_test: before: ams_localiTunesAccount: id 7BA65770-7DC2-488D-8B57-81B17A8B12F0
+ * store_test: before: ams_localiTunesAccount: STOREFRONT (null)
+ * store_test: set: in memory now 143469-2,8
+ * store_test: set: ams_saveAccount: done
+ * store_test: after: ams_localiTunesAccount: STOREFRONT (null)
+ * The setter works and the value does not keep. accountsd has no account of type
+ * com.apple.account.iTunesStore at all -- which is right for a signed-out iPhone -- and the local
+ * account AMS hands out is not one of its rows: its identifier is a different one every boot
+ * (143B8A92..., 8D31AF5C..., C976F334... in three runs of appstored, 7BA65770... here), so it is made
+ * fresh each time with a null storefront and there is nothing on disk to write to. The only thing
+ * that ever fills it is the bag response itself (_setStorefrontFromURLResponse:bagData:), which is
+ * the fetch that never happens.
+ * So a storefront cannot be put on this device from another process, and the next place to try is
+ * inside appstored -- the port already puts a library of ours into stock programs (INJECT in
+ * build.sh, src/inject_sb.c and its kin), which would both set the storefront on the account AMS is
+ * really using and show whether a bag request is ever built at all.
+ * This tool stays because the three facts it establishes are worth keeping: AMS's local account is
+ * per boot, accountsd holds no iTunes account, and ams_setStorefront: does not persist.
+ */
+#import <Accounts/Accounts.h>
+#import <Foundation/Foundation.h>
+#include <dlfcn.h>
+#include <stdio.h>
+#include <unistd.h>
+
+@interface ACAccount (AppleMediaServices)
+- (NSString *)ams_storefront;
+- (void)ams_setStorefront:(NSString *)storefront;
+- (BOOL)ams_isLocalAccount;
+@end
+
+@interface ACAccountStore (AppleMediaServices)
++ (instancetype)ams_sharedAccountStore;
+- (ACAccount *)ams_localiTunesAccount;
+- (ACAccount *)ams_localiTunesAccountAfterUpdatingStorefront:(NSString *)storefront;
+- (void)ams_saveAccount:(ACAccount *)account;
+@end
+
+static NSString *const kiTunesStore = @"com.apple.account.iTunesStore";
+
+/* one field a line: the console drops long ones (see rc.jobs.store), and the storefront is the point */
+static void
+describe(const char *what, ACAccount *account)
+{
+ if (account == nil) {
+ printf("store_test: %s: (none)\n", what);
+ return;
+ }
+ printf("store_test: %s: user %s\n", what, account.username.UTF8String ?: "(null)");
+ printf("store_test: %s: id %s\n", what, account.identifier.UTF8String ?: "(null)");
+ printf("store_test: %s: STOREFRONT %s\n", what,
+ [account respondsToSelector:@selector(ams_storefront)] ? (account.ams_storefront.UTF8String ?: "(null)") : "?");
+}
+
+static void
+show(ACAccountStore *store, const char *when)
+{
+ ACAccountType *type = [store accountTypeWithAccountTypeIdentifier:kiTunesStore];
+ NSArray<ACAccount *> *accounts = type != nil ? [store accountsWithAccountType:type] : nil;
+ char what[64];
+
+ printf("store_test: %s: accountsd has %lu account(s) of type %s\n", when, (unsigned long)accounts.count,
+ kiTunesStore.UTF8String);
+ for (ACAccount *account in accounts) {
+ snprintf(what, sizeof(what), "%s: accountsd", when);
+ describe(what, account);
+ }
+ if ([store respondsToSelector:@selector(ams_localiTunesAccount)]) {
+ snprintf(what, sizeof(what), "%s: ams_localiTunesAccount", when);
+ describe(what, store.ams_localiTunesAccount);
+ } else {
+ printf("store_test: %s: this AMS has no ams_localiTunesAccount\n", when);
+ }
+}
+
+int
+main(int argc, char **argv)
+{
+ @autoreleasepool {
+ const char *action = argc > 1 ? argv[1] : "show";
+ /* appstored is mobile's, and so is the account database; init runs this as root, so step down */
+ if (argc > 2 && strcmp(argv[1], "user") == 0) {
+ uid_t who = (uid_t)atoi(argv[2]);
+
+ if (setgid(who) != 0 || setuid(who) != 0) {
+ printf("store_test: could not become %d\n", who);
+ }
+ action = argc > 3 ? argv[3] : "show";
+ argv += 2;
+ argc -= 2;
+ }
+ /* the categories with the storefront live in this framework, which nothing has loaded for us */
+ void *ams = dlopen("/System/Library/PrivateFrameworks/AppleMediaServices.framework/AppleMediaServices", RTLD_LAZY);
+ ACAccountStore *store;
+
+ setvbuf(stdout, NULL, _IOLBF, 0);
+ printf("store_test: uid %d, euid %d; AppleMediaServices %s\n", getuid(), geteuid(),
+ ams != NULL ? "loaded" : dlerror());
+ store = [ACAccountStore respondsToSelector:@selector(ams_sharedAccountStore)] ?
+ ACAccountStore.ams_sharedAccountStore : [ACAccountStore new];
+ printf("store_test: account store = %s\n", [store description].UTF8String ?: "(null)");
+ show(store, "before");
+ if (strcmp(action, "set") == 0 && argc > 2) {
+ NSString *wanted = @(argv[2]);
+
+ /* what AMS itself does when the bag server returns an x-set-apple-store-front header */
+ if ([store respondsToSelector:@selector(ams_localiTunesAccountAfterUpdatingStorefront:)]) {
+ describe("set: ams_localiTunesAccountAfterUpdatingStorefront:",
+ [store ams_localiTunesAccountAfterUpdatingStorefront:wanted]);
+ } else {
+ printf("store_test: set: this AMS has no ams_localiTunesAccountAfterUpdatingStorefront:\n");
+ }
+ /* and the long way round, in case that one only answers and does not keep */
+ if ([store respondsToSelector:@selector(ams_localiTunesAccount)]) {
+ ACAccount *local = store.ams_localiTunesAccount;
+
+ if (local != nil && [local respondsToSelector:@selector(ams_setStorefront:)]) {
+ [local ams_setStorefront:wanted];
+ printf("store_test: set: in memory now %s\n", local.ams_storefront.UTF8String ?: "(null)");
+ if ([store respondsToSelector:@selector(ams_saveAccount:)]) {
+ [store ams_saveAccount:local];
+ printf("store_test: set: ams_saveAccount: done\n");
+ } else {
+ dispatch_semaphore_t done = dispatch_semaphore_create(0);
+
+ [store saveAccount:local withCompletionHandler:^(BOOL saved, NSError *error) {
+ printf("store_test: set: saveAccount: %s%s%s\n", saved ? "saved" : "NOT SAVED",
+ error != nil ? ", error = " : "",
+ error != nil ? error.description.UTF8String : "");
+ dispatch_semaphore_signal(done);
+ }];
+ if (dispatch_semaphore_wait(done, dispatch_time(DISPATCH_TIME_NOW, 30 * NSEC_PER_SEC)) != 0) {
+ printf("store_test: set: accountsd did not answer in 30 s\n");
+ }
+ }
+ }
+ }
+ show([ACAccountStore respondsToSelector:@selector(ams_sharedAccountStore)] ?
+ ACAccountStore.ams_sharedAccountStore : [ACAccountStore new], "after");
+ }
+ }
+ return 0;
+}