diff --git a/.swiftlint.yml b/.swiftlint.yml index 84222407..9a842a9b 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -5,6 +5,8 @@ disabled_rules: excluded: - Carthage - Pods + - PlayChainHarness/.build + - PlayChain/.build identifier_name: allowed_symbols: ['_'] diff --git a/PlayChain/.gitignore b/PlayChain/.gitignore new file mode 100644 index 00000000..2d9f16e2 --- /dev/null +++ b/PlayChain/.gitignore @@ -0,0 +1,2 @@ +.build/ +.swiftpm/ diff --git a/PlayChain/Package.swift b/PlayChain/Package.swift new file mode 100644 index 00000000..03d447ed --- /dev/null +++ b/PlayChain/Package.swift @@ -0,0 +1,20 @@ +// swift-tools-version:5.9 +import PackageDescription + +let package = Package( + name: "PlayChain", + platforms: [.macOS(.v13), .iOS(.v15), .macCatalyst(.v15)], + products: [ + .library(name: "PlayChain", targets: ["PlayChain"]) + ], + targets: [ + .target( + name: "PlayChain", + linkerSettings: [ + .linkedLibrary("sqlite3"), + .linkedFramework("Security"), + .linkedFramework("CoreFoundation") + ] + ) + ] +) diff --git a/PlayChain/Sources/PlayChain/include/pc_keychain.h b/PlayChain/Sources/PlayChain/include/pc_keychain.h new file mode 100644 index 00000000..ceecf776 --- /dev/null +++ b/PlayChain/Sources/PlayChain/include/pc_keychain.h @@ -0,0 +1,32 @@ +#ifndef PC_KEYCHAIN_H +#define PC_KEYCHAIN_H + +#include +#include + +CF_ASSUME_NONNULL_BEGIN +CF_EXTERN_C_BEGIN + +typedef struct { + const char *db_path; // .../PlayChain/.v2.db, copied + CFStringRef default_group; // agrp for items added without one, retained + CFArrayRef _Nullable groups; // every group the app may name; NULL = no restriction + void (*_Nullable log)(const char *msg); // NULL = silent +} pc_config_t; + +/// Sets the configuration and closes any open database; the next call reopens it. Thread-safe. +void pc_configure(const pc_config_t *cfg); + +OSStatus pc_SecItemAdd(CFDictionaryRef attrs, CFTypeRef _Nullable * _Nullable result); +OSStatus pc_SecItemCopyMatching(CFDictionaryRef query, CFTypeRef _Nullable * _Nullable result); +OSStatus pc_SecItemUpdate(CFDictionaryRef query, CFDictionaryRef attrs); +OSStatus pc_SecItemDelete(CFDictionaryRef query); +SecKeyRef _Nullable pc_SecKeyCreateRandomKey(CFDictionaryRef params, + CFErrorRef _Nullable * _Nullable error) CF_RETURNS_RETAINED; +OSStatus pc_SecKeyGeneratePair(CFDictionaryRef params, SecKeyRef _Nullable * _Nullable pub, + SecKeyRef _Nullable * _Nullable priv); + +CF_EXTERN_C_END +CF_ASSUME_NONNULL_END + +#endif diff --git a/PlayChain/Sources/PlayChain/pc_internal.h b/PlayChain/Sources/PlayChain/pc_internal.h new file mode 100644 index 00000000..2980f48c --- /dev/null +++ b/PlayChain/Sources/PlayChain/pc_internal.h @@ -0,0 +1,101 @@ +#ifndef PC_INTERNAL_H +#define PC_INTERNAL_H + +#include +#include +#include "pc_keychain.h" + +CF_ASSUME_NONNULL_BEGIN + +typedef enum { PC_BLOB, PC_STR, PC_DATA, PC_NUM, PC_DATE } pc_kind; // BLOB: string or data, kept as given +enum { + PC_PRIMARY = 1 << 0, // part of the unique key + PC_DEFAULT = 1 << 1, // filled on add when missing ("" / 0 / empty data / epoch by kind) +}; +typedef struct { + CFStringRef name; + pc_kind kind; + uint32_t flags; +} pc_attr; +typedef struct { + char tag[5]; // "genp", also the class name and persistent-ref prefix + CFStringRef name; + const pc_attr *attrs; + size_t count; +} pc_class; + +const pc_class *_Nullable pc_class_find(CFStringRef name); +const pc_class *_Nullable pc_class_by_tag(const char *tag); +const pc_attr *_Nullable pc_class_attr(const pc_class *cls, CFStringRef name); +bool pc_class_is_password(const pc_class *cls); +/// Converts a caller value to the schema's storage type (bools → numbers for numeric attrs). Returns +1. +CFTypeRef pc_coerce(const pc_class *_Nullable cls, CFStringRef name, CFTypeRef value); +bool pc_string_int(CFStringRef text, int64_t *out); + +bool pc_truthy(CFTypeRef value); + +enum { PC_RET_DATA = 1, PC_RET_ATTRS = 2, PC_RET_REF = 4, PC_RET_PREF = 8 }; +typedef enum { PC_USE_ADD, PC_USE_SEARCH, PC_USE_CHANGES } pc_use; +typedef struct { + const pc_class *_Nullable cls; + CFMutableDictionaryRef match; // attribute name → coerced value (excludes sync) + unsigned ret; + CFIndex limit; // 1 = One (default), -1 = All, n + int sync; // 0, 1, or -1 = any (syna); default 0 + bool sync_given; + int64_t rowid; // from v_PersistentRef, 0 = none + CFDataRef _Nullable value_data; + CFTypeRef _Nullable value_ref; +} pc_query; + +OSStatus pc_query_parse(CFDictionaryRef dict, pc_use use, pc_query *q); +void pc_query_free(pc_query *q); + +typedef struct { + int64_t rowid; + CFMutableDictionaryRef attrs; // every attribute except v_Data + CFDataRef _Nullable data; +} pc_row; +typedef struct { + pc_row *_Nullable rows; + size_t count; +} pc_rows; + +OSStatus pc_store_open(const char *path); +void pc_store_close(void); +OSStatus pc_store_begin(void); +OSStatus pc_store_commit(void); +void pc_store_rollback(void); +/// Loads rows of `cls` in rowid order; `rowid` > 0 loads just that row. +OSStatus pc_store_load(const pc_class *cls, int64_t rowid, pc_rows *out); +OSStatus pc_store_insert(const pc_class *cls, CFDictionaryRef attrs, CFDataRef _Nullable data, int64_t *rowid); +OSStatus pc_store_update(const pc_class *cls, int64_t rowid, CFDictionaryRef attrs, CFDataRef _Nullable data); +OSStatus pc_store_delete(int64_t rowid); +const pc_class *_Nullable pc_store_class_of(int64_t rowid); +void pc_rows_free(pc_rows *rows); + +OSStatus pc_item_add(pc_query *q, CFTypeRef _Nullable *_Nullable result); +OSStatus pc_item_copy(pc_query *q, CFTypeRef _Nullable *_Nullable result); +OSStatus pc_item_update(pc_query *q, pc_query *changes); +OSStatus pc_item_delete(pc_query *q); +/// Stamps sha1 from the row's attributes and data, as securityd does on every write. +void pc_item_stamp_sha1(CFMutableDictionaryRef attrs, CFDataRef _Nullable data); + +CFDataRef pc_persistent_ref(const pc_class *cls, int64_t rowid); +bool pc_persistent_ref_parse(CFTypeRef value, char *tag, int64_t *rowid); // tag: 5 bytes +/// Builds the SecItem result for already-limited rows. `for_add` uses SecItemAdd's attribute set. +OSStatus pc_result_build(const pc_class *cls, pc_row *rows, size_t count, unsigned ret, CFIndex limit, + bool for_add, CFTypeRef _Nullable *_Nullable result); + +/// Fills a key add's attributes and data from the key itself (v_Ref, or v_Data + type/kcls). Every way a key +/// enters the keychain passes here, so a stored key always has its class, type, sizes and klbl. +OSStatus pc_key_prepare_add(pc_query *q); +SecKeyRef _Nullable pc_key_from_row(const pc_row *row) CF_RETURNS_RETAINED; + +CFStringRef pc_default_group(void); +CFArrayRef _Nullable pc_groups(void); +void pc_log(const char *fmt, ...) __attribute__((format(printf, 1, 2))); + +CF_ASSUME_NONNULL_END + +#endif diff --git a/PlayChain/Sources/PlayChain/pc_item.c b/PlayChain/Sources/PlayChain/pc_item.c new file mode 100644 index 00000000..204acd6c --- /dev/null +++ b/PlayChain/Sources/PlayChain/pc_item.c @@ -0,0 +1,255 @@ +#include +#include "pc_internal.h" + +static bool pc_number(CFTypeRef value, int64_t *out) { + CFTypeID type = CFGetTypeID(value); + if (type == CFBooleanGetTypeID()) { + *out = CFBooleanGetValue(value); + return true; + } + if (type == CFNumberGetTypeID()) return CFNumberGetValue(value, kCFNumberSInt64Type, out), true; + return false; +} + +static bool pc_value_equal(CFTypeRef stored, CFTypeRef wanted) { + int64_t a, b; + bool a_num = pc_number(stored, &a), b_num = pc_number(wanted, &b); + if (a_num && b_num) return a == b; + if (a_num != b_num) { + CFTypeRef text = a_num ? wanted : stored; + int64_t n; + return CFGetTypeID(text) == CFStringGetTypeID() && pc_string_int(text, &n) && n == (a_num ? a : b); + } + return CFEqual(stored, wanted); +} + +typedef struct { + const pc_row *row; + bool ok; +} pc_match_ctx; + +static void pc_match_entry(const void *key, const void *value, void *context) { + pc_match_ctx *ctx = context; + if (!ctx->ok) return; + CFTypeRef stored = CFDictionaryGetValue(ctx->row->attrs, key); + ctx->ok = stored && pc_value_equal(stored, value); +} + +static bool pc_in_groups(CFTypeRef agrp) { + CFArrayRef groups = pc_groups(); + if (!groups) return true; + if (!agrp) return false; + return CFEqual(agrp, pc_default_group()) || + CFArrayContainsValue(groups, CFRangeMake(0, CFArrayGetCount(groups)), agrp); +} + +static bool pc_row_matches(const pc_query *q, const pc_row *row) { + if (q->rowid && row->rowid != q->rowid) return false; + + // No kSecAttrSynchronizable means sync = 0 only (recorded), except a pure persistent-ref lookup. + int sync = q->sync_given ? q->sync : (q->rowid ? -1 : 0); + if (sync != -1) { + CFTypeRef stored = CFDictionaryGetValue(row->attrs, kSecAttrSynchronizable); + int64_t n = 0; + if (stored) pc_number(stored, &n); + if (n != sync) return false; + } + + if (!CFDictionaryContainsKey(q->match, kSecAttrAccessGroup) && + !pc_in_groups(CFDictionaryGetValue(row->attrs, kSecAttrAccessGroup))) { + return false; + } + + pc_match_ctx ctx = {row, true}; + CFDictionaryApplyFunction(q->match, pc_match_entry, &ctx); + return ctx.ok; +} + +static OSStatus pc_find(pc_query *q, pc_rows *out) { + *out = (pc_rows){0}; + const pc_class *cls = q->cls; + if (q->rowid < 0) return errSecSuccess; + if (!cls && q->rowid) cls = pc_store_class_of(q->rowid); + if (!cls) return errSecSuccess; + q->cls = cls; + + OSStatus status = pc_store_load(cls, q->rowid, out); + if (status != errSecSuccess) return status; + size_t kept = 0; + for (size_t i = 0; i < out->count; i++) { + if (pc_row_matches(q, &out->rows[i])) { + out->rows[kept++] = out->rows[i]; + } else { + CFRelease(out->rows[i].attrs); + if (out->rows[i].data) CFRelease(out->rows[i].data); + } + } + out->count = kept; + return errSecSuccess; +} + +void pc_item_stamp_sha1(CFMutableDictionaryRef attrs, CFDataRef data) { + CFMutableDictionaryRef hashed = CFDictionaryCreateMutableCopy(NULL, 0, attrs); + CFDictionaryRemoveValue(hashed, kSecAttrModificationDate); + CFDictionaryRemoveValue(hashed, CFSTR("sha1")); + CFDictionaryRemoveValue(hashed, CFSTR("UUID")); + CFDataRef plist = CFPropertyListCreateData(NULL, hashed, kCFPropertyListBinaryFormat_v1_0, 0, NULL); + CFRelease(hashed); + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" // SHA-1 is what securityd stores here + CC_SHA1_CTX ctx; + CC_SHA1_Init(&ctx); + if (plist) CC_SHA1_Update(&ctx, CFDataGetBytePtr(plist), (CC_LONG)CFDataGetLength(plist)); + if (data) CC_SHA1_Update(&ctx, CFDataGetBytePtr(data), (CC_LONG)CFDataGetLength(data)); + uint8_t digest[CC_SHA1_DIGEST_LENGTH]; + CC_SHA1_Final(digest, &ctx); +#pragma clang diagnostic pop + + if (plist) CFRelease(plist); + CFDataRef sha1 = CFDataCreate(NULL, digest, sizeof digest); + CFDictionarySetValue(attrs, CFSTR("sha1"), sha1); + CFRelease(sha1); +} + +static CFTypeRef _Nullable pc_default_value(const pc_attr *attr) { + static const int64_t zero = 0; + switch (attr->kind) { + case PC_BLOB: return CFRetain(CFSTR("")); + case PC_STR: return CFRetain(CFSTR("")); + case PC_DATA: return CFDataCreate(NULL, NULL, 0); + case PC_NUM: return CFNumberCreate(NULL, kCFNumberSInt64Type, &zero); + case PC_DATE: return CFDateCreate(NULL, 0); + } + return NULL; +} + +static void pc_set_now(CFMutableDictionaryRef attrs, CFStringRef key) { + CFDateRef now = CFDateCreate(NULL, CFAbsoluteTimeGetCurrent()); + CFDictionarySetValue(attrs, key, now); + CFRelease(now); +} + +static void pc_set_sync(CFMutableDictionaryRef attrs, int sync) { + int64_t n = sync; + CFNumberRef value = CFNumberCreate(NULL, kCFNumberSInt64Type, &n); + CFDictionarySetValue(attrs, kSecAttrSynchronizable, value); + CFRelease(value); +} + +OSStatus pc_item_add(pc_query *q, CFTypeRef *result) { + const pc_class *cls = q->cls; + if (CFEqual(cls->name, kSecClassKey)) { + OSStatus status = pc_key_prepare_add(q); + if (status != errSecSuccess) return status; + } + CFMutableDictionaryRef attrs = CFDictionaryCreateMutableCopy(NULL, 0, q->match); + pc_set_sync(attrs, q->sync); + for (size_t i = 0; i < cls->count; i++) { + const pc_attr *attr = &cls->attrs[i]; + if (!(attr->flags & PC_DEFAULT) || CFDictionaryContainsKey(attrs, attr->name)) continue; + CFTypeRef value = pc_default_value(attr); + if (value) CFDictionarySetValue(attrs, attr->name, value); + if (value) CFRelease(value); + } + if (!CFDictionaryContainsKey(attrs, kSecAttrAccessGroup)) { + CFDictionarySetValue(attrs, kSecAttrAccessGroup, pc_default_group()); + } + if (!CFDictionaryContainsKey(attrs, kSecAttrAccessible)) { + CFDictionarySetValue(attrs, kSecAttrAccessible, kSecAttrAccessibleWhenUnlocked); + } + pc_set_now(attrs, kSecAttrCreationDate); + pc_set_now(attrs, kSecAttrModificationDate); + CFUUIDRef uuid = CFUUIDCreate(NULL); + CFStringRef uuid_string = CFUUIDCreateString(NULL, uuid); + CFDictionarySetValue(attrs, CFSTR("UUID"), uuid_string); + CFRelease(uuid_string); + CFRelease(uuid); + pc_item_stamp_sha1(attrs, q->value_data); + + OSStatus status = pc_store_begin(); + pc_row row = {0, attrs, q->value_data}; + if (status == errSecSuccess) status = pc_store_insert(cls, attrs, q->value_data, &row.rowid); + if (status == errSecSuccess) status = pc_result_build(cls, &row, 1, q->ret, 1, true, result); + if (status == errSecSuccess) { + status = pc_store_commit(); + } else { + pc_store_rollback(); + } + if (status != errSecSuccess && result && *result) { // commit failed after the result was built + CFRelease(*result); + *result = NULL; + } + CFRelease(attrs); + return status; +} + +OSStatus pc_item_copy(pc_query *q, CFTypeRef *result) { + pc_rows rows; + OSStatus status = pc_find(q, &rows); + if (status != errSecSuccess) return status; + if (rows.count == 0) { + status = errSecItemNotFound; + } else { + size_t count = q->limit < 0 || (size_t)q->limit > rows.count ? rows.count : (size_t)q->limit; + status = pc_result_build(q->cls, rows.rows, count, q->ret, q->limit, false, result); + } + pc_rows_free(&rows); + return status; +} + +typedef struct { + const pc_class *cls; + CFMutableDictionaryRef attrs; +} pc_apply_ctx; + +static void pc_apply_change(const void *key, const void *value, void *context) { + pc_apply_ctx *ctx = context; + CFTypeRef coerced = pc_coerce(ctx->cls, key, value); + CFDictionarySetValue(ctx->attrs, key, coerced); + CFRelease(coerced); +} + +OSStatus pc_item_update(pc_query *q, pc_query *changes) { + OSStatus status = pc_store_begin(); + if (status != errSecSuccess) return status; + pc_rows rows; + status = pc_find(q, &rows); + if (status == errSecSuccess && rows.count == 0) status = errSecItemNotFound; + + for (size_t i = 0; status == errSecSuccess && i < rows.count; i++) { + pc_row *row = &rows.rows[i]; + pc_apply_ctx ctx = {q->cls, row->attrs}; + CFDictionaryApplyFunction(changes->match, pc_apply_change, &ctx); + if (changes->sync_given) pc_set_sync(row->attrs, changes->sync); + pc_set_now(row->attrs, kSecAttrModificationDate); + CFDataRef data = changes->value_data ? changes->value_data : row->data; + pc_item_stamp_sha1(row->attrs, data); + status = pc_store_update(q->cls, row->rowid, row->attrs, data); + } + + if (status == errSecSuccess) { + status = pc_store_commit(); + } else { + pc_store_rollback(); + } + pc_rows_free(&rows); + return status; +} + +OSStatus pc_item_delete(pc_query *q) { + OSStatus status = pc_store_begin(); + if (status != errSecSuccess) return status; + pc_rows rows; + status = pc_find(q, &rows); // recorded: kSecMatchLimit is ignored + if (status == errSecSuccess && rows.count == 0) status = errSecItemNotFound; + for (size_t i = 0; status == errSecSuccess && i < rows.count; i++) status = pc_store_delete(rows.rows[i].rowid); + + if (status == errSecSuccess) { + status = pc_store_commit(); + } else { + pc_store_rollback(); + } + pc_rows_free(&rows); + return status; +} diff --git a/PlayChain/Sources/PlayChain/pc_key.c b/PlayChain/Sources/PlayChain/pc_key.c new file mode 100644 index 00000000..51c8aaf1 --- /dev/null +++ b/PlayChain/Sources/PlayChain/pc_key.c @@ -0,0 +1,277 @@ +#include +#include +#include "pc_internal.h" + +static void pc_set_int(CFMutableDictionaryRef dict, CFStringRef key, int64_t value) { + CFNumberRef number = CFNumberCreate(NULL, kCFNumberSInt64Type, &value); + CFDictionarySetValue(dict, key, number); + CFRelease(number); +} + +static void pc_log_once(atomic_bool *flag, const char *msg) { + if (!atomic_exchange(flag, true)) pc_log("%s", msg); +} + +static bool pc_is_secure_enclave(CFDictionaryRef dict) { + CFTypeRef tkid = CFDictionaryGetValue(dict, kSecAttrTokenID); + return tkid && CFEqual(tkid, kSecAttrTokenIDSecureEnclave); +} + +/// The attributes a real keychain derives for a key (the Secure Enclave set when `se`). +static OSStatus pc_key_derive(SecKeyRef key, bool se, CFMutableDictionaryRef out) { + CFDictionaryRef info = SecKeyCopyAttributes(key); + if (!info) return errSecParam; + CFTypeRef type = CFDictionaryGetValue(info, kSecAttrKeyType); + CFTypeRef kcls = CFDictionaryGetValue(info, kSecAttrKeyClass); + CFTypeRef bsiz = CFDictionaryGetValue(info, kSecAttrKeySizeInBits); + CFTypeRef klbl = CFDictionaryGetValue(info, kSecAttrApplicationLabel); + if (!type || !kcls || !bsiz || !klbl) { + CFRelease(info); + return errSecParam; + } + bool is_private = CFEqual(kcls, kSecAttrKeyClassPrivate); + bool is_ec = CFEqual(type, kSecAttrKeyTypeECSECPrimeRandom); + + CFTypeRef type_n = pc_coerce(pc_class_find(kSecClassKey), kSecAttrKeyType, type); + CFTypeRef kcls_n = pc_coerce(pc_class_find(kSecClassKey), kSecAttrKeyClass, kcls); + CFDictionarySetValue(out, kSecAttrKeyType, type_n); + CFDictionarySetValue(out, kSecAttrKeyClass, kcls_n); + CFDictionarySetValue(out, kSecAttrKeySizeInBits, bsiz); + CFDictionarySetValue(out, kSecAttrEffectiveKeySize, bsiz); + CFDictionarySetValue(out, kSecAttrApplicationLabel, klbl); // Security's own klbl, so it matches by construction + CFRelease(type_n); + CFRelease(kcls_n); + CFRelease(info); + + pc_set_int(out, kSecAttrIsPermanent, 1); + pc_set_int(out, CFSTR("priv"), 1); // recorded: 1 for public keys too + pc_set_int(out, kSecAttrCanDecrypt, is_private && !se); + pc_set_int(out, kSecAttrCanDerive, is_private && is_ec); + pc_set_int(out, kSecAttrCanEncrypt, !is_private); + pc_set_int(out, kSecAttrCanSign, is_private); + pc_set_int(out, kSecAttrCanVerify, !is_private); + pc_set_int(out, kSecAttrCanWrap, !is_private); + pc_set_int(out, CFSTR("modi"), !se); + pc_set_int(out, kSecAttrIsExtractable, !se); + pc_set_int(out, CFSTR("next"), se); + if (!se) { + pc_set_int(out, kSecAttrCanUnwrap, is_private); + pc_set_int(out, kSecAttrIsSensitive, 0); + pc_set_int(out, CFSTR("asen"), 0); + pc_set_int(out, CFSTR("snrc"), 0); + pc_set_int(out, CFSTR("vyrc"), 0); + } + return errSecSuccess; +} + +static CFStringRef pc_string_of(CFTypeRef _Nullable value) { + if (!value) return NULL; + if (CFGetTypeID(value) == CFStringGetTypeID()) return CFRetain(value); + int64_t n = 0; + if (CFGetTypeID(value) != CFNumberGetTypeID() || !CFNumberGetValue(value, kCFNumberSInt64Type, &n)) return NULL; + return CFStringCreateWithFormat(NULL, NULL, CFSTR("%lld"), (long long)n); +} + +static CFDictionaryRef pc_rebuild_params(CFDictionaryRef attrs) { + CFMutableDictionaryRef params = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + CFStringRef type = pc_string_of(CFDictionaryGetValue(attrs, kSecAttrKeyType)); + CFStringRef kcls = pc_string_of(CFDictionaryGetValue(attrs, kSecAttrKeyClass)); + CFTypeRef bsiz = CFDictionaryGetValue(attrs, kSecAttrKeySizeInBits); + if (type) CFDictionarySetValue(params, kSecAttrKeyType, type); + // securityd defaults a missing kcls to public (0); SecKeyCreateWithData refuses to parse without one. + CFDictionarySetValue(params, kSecAttrKeyClass, kcls ? kcls : kSecAttrKeyClassPublic); + if (bsiz) CFDictionarySetValue(params, kSecAttrKeySizeInBits, bsiz); + if (type) CFRelease(type); + if (kcls) CFRelease(kcls); + return params; +} + +OSStatus pc_key_prepare_add(pc_query *q) { + SecKeyRef key = NULL; + if (q->value_ref) { + if (CFGetTypeID(q->value_ref) != SecKeyGetTypeID()) return errSecParam; + key = (SecKeyRef)CFRetain(q->value_ref); + } else if (q->value_data) { + CFDictionaryRef params = pc_rebuild_params(q->match); + key = SecKeyCreateWithData(q->value_data, params, NULL); + CFRelease(params); + if (!key) { + pc_log("key: SecItemAdd with unusable key data"); + return errSecParam; + } + } else { + return errSecSuccess; + } + + bool se = pc_is_secure_enclave(q->match); + CFMutableDictionaryRef derived = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + OSStatus status = pc_key_derive(key, se, derived); + CFDataRef data = status == errSecSuccess ? SecKeyCopyExternalRepresentation(key, NULL) : NULL; + CFRelease(key); + if (status == errSecSuccess && !data) status = errSecParam; + if (status != errSecSuccess) { + CFRelease(derived); + return status; + } + + // The caller's attributes win (tag, label, capability overrides), except what identifies the key. + CFStringRef identity[] = {kSecAttrKeyType, kSecAttrKeyClass, kSecAttrKeySizeInBits, kSecAttrEffectiveKeySize, + kSecAttrApplicationLabel}; + for (size_t i = 0; i < sizeof identity / sizeof identity[0]; i++) { + CFDictionarySetValue(q->match, identity[i], CFDictionaryGetValue(derived, identity[i])); + CFDictionaryRemoveValue(derived, identity[i]); + } + CFIndex count = CFDictionaryGetCount(derived); + const void **keys = malloc(sizeof(void *) * (size_t)count * 2); + const void **values = keys + count; + CFDictionaryGetKeysAndValues(derived, keys, values); + for (CFIndex i = 0; i < count; i++) { + if (!CFDictionaryContainsKey(q->match, keys[i])) CFDictionarySetValue(q->match, keys[i], values[i]); + } + free(keys); + CFRelease(derived); + if (se && !CFDictionaryContainsKey(q->match, kSecAttrAccessible)) { + CFDictionarySetValue(q->match, kSecAttrAccessible, CFSTR("dk")); + } + + if (q->value_data) CFRelease(q->value_data); + q->value_data = data; + return errSecSuccess; +} + +SecKeyRef pc_key_from_row(const pc_row *row) { + if (!row->data) return NULL; + CFDictionaryRef params = pc_rebuild_params(row->attrs); + CFErrorRef error = NULL; + SecKeyRef key = SecKeyCreateWithData(row->data, params, &error); + if (!key) pc_log("key: rebuild failed (%ld)", error ? (long)CFErrorGetCode(error) : 0L); + if (error) CFRelease(error); + CFRelease(params); + return key; +} + +static atomic_bool logged_se; + +static bool pc_wants_perm(CFDictionaryRef _Nullable dict) { + CFTypeRef perm = dict ? CFDictionaryGetValue(dict, kSecAttrIsPermanent) : NULL; + return perm && pc_truthy(perm); +} + +/// What the real generator gets: type and size only, so it makes a plain software key and never touches +/// the real keychain, a token or access control. +static CFDictionaryRef pc_generation_params(CFDictionaryRef params, bool se) { + CFMutableDictionaryRef gen = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + if (se) { + pc_log_once(&logged_se, "key: Secure Enclave requested; using a software P-256 key (it stays exportable)"); + int64_t bits = 256; + CFNumberRef size = CFNumberCreate(NULL, kCFNumberSInt64Type, &bits); + CFDictionarySetValue(gen, kSecAttrKeyType, kSecAttrKeyTypeECSECPrimeRandom); + CFDictionarySetValue(gen, kSecAttrKeySizeInBits, size); + CFRelease(size); + return gen; + } + CFTypeRef type = CFDictionaryGetValue(params, kSecAttrKeyType); + CFTypeRef bsiz = CFDictionaryGetValue(params, kSecAttrKeySizeInBits); + if (type) CFDictionarySetValue(gen, kSecAttrKeyType, type); + if (bsiz) CFDictionarySetValue(gen, kSecAttrKeySizeInBits, bsiz); + return gen; +} + +static OSStatus pc_key_store(SecKeyRef key, CFDictionaryRef params, CFDictionaryRef _Nullable half, + CFTypeRef _Nullable *_Nullable pref) { + CFMutableDictionaryRef add = CFDictionaryCreateMutableCopy(NULL, 0, params); + CFDictionaryRemoveValue(add, kSecPrivateKeyAttrs); + CFDictionaryRemoveValue(add, kSecPublicKeyAttrs); + if (half) { + CFIndex count = CFDictionaryGetCount(half); + const void **keys = malloc(sizeof(void *) * (size_t)count * 2); + const void **values = keys + count; + CFDictionaryGetKeysAndValues(half, keys, values); + for (CFIndex i = 0; i < count; i++) CFDictionarySetValue(add, keys[i], values[i]); + free(keys); + } + CFStringRef dropped[] = {kSecAttrIsPermanent, kSecAttrKeyType, kSecAttrKeySizeInBits}; + for (size_t i = 0; i < sizeof dropped / sizeof dropped[0]; i++) CFDictionaryRemoveValue(add, dropped[i]); + CFDictionarySetValue(add, kSecClass, kSecClassKey); + CFDictionarySetValue(add, kSecValueRef, key); + if (pref) CFDictionarySetValue(add, kSecReturnPersistentRef, kCFBooleanTrue); + OSStatus status = pc_SecItemAdd(add, pref); // takes the lock itself; generation ran outside it + CFRelease(add); + return status; +} + +static void pc_set_error(CFErrorRef *error, OSStatus status) { + if (error) *error = CFErrorCreate(NULL, kCFErrorDomainOSStatus, status, NULL); +} + +SecKeyRef pc_SecKeyCreateRandomKey(CFDictionaryRef params, CFErrorRef *error) { + if (error) *error = NULL; + bool se = pc_is_secure_enclave(params); + CFDictionaryRef gen = pc_generation_params(params, se); + SecKeyRef key = SecKeyCreateRandomKey(gen, error); + CFRelease(gen); + if (!key) return NULL; + + CFDictionaryRef priv = CFDictionaryGetValue(params, kSecPrivateKeyAttrs); + if (pc_wants_perm(params) || pc_wants_perm(priv)) { + // Recorded: only the private key is stored; the public half is derived from it on demand. + OSStatus status = pc_key_store(key, params, priv, NULL); + if (status != errSecSuccess) { + CFRelease(key); + pc_set_error(error, status); + return NULL; + } + } + return key; +} + +OSStatus pc_SecKeyGeneratePair(CFDictionaryRef params, SecKeyRef *pub_out, SecKeyRef *priv_out) { + if (pub_out) *pub_out = NULL; + if (priv_out) *priv_out = NULL; + bool se = pc_is_secure_enclave(params); + CFDictionaryRef gen = pc_generation_params(params, se); + CFErrorRef error = NULL; + SecKeyRef priv = SecKeyCreateRandomKey(gen, &error); + CFRelease(gen); + if (!priv) { + OSStatus status = error ? (OSStatus)CFErrorGetCode(error) : errSecParam; + if (error) CFRelease(error); + return status; + } + SecKeyRef pub = SecKeyCopyPublicKey(priv); + + CFDictionaryRef priv_attrs = CFDictionaryGetValue(params, kSecPrivateKeyAttrs); + CFDictionaryRef pub_attrs = CFDictionaryGetValue(params, kSecPublicKeyAttrs); + OSStatus status = errSecSuccess; + CFTypeRef priv_pref = NULL; + if (pc_wants_perm(params) || pc_wants_perm(priv_attrs)) { + status = pc_key_store(priv, params, priv_attrs, &priv_pref); + } + if (status == errSecSuccess && pub && (pc_wants_perm(params) || pc_wants_perm(pub_attrs))) { + status = pc_key_store(pub, params, pub_attrs, NULL); + } + if (priv_pref) { + if (status != errSecSuccess) { + const void *k = kSecValuePersistentRef, *v = priv_pref; + CFDictionaryRef del = CFDictionaryCreate(NULL, &k, &v, 1, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + pc_SecItemDelete(del); + CFRelease(del); + } + CFRelease(priv_pref); + } + if (status != errSecSuccess || !pub) { + CFRelease(priv); + if (pub) CFRelease(pub); + return status != errSecSuccess ? status : errSecInternalComponent; + } + + if (priv_out) *priv_out = priv; + else CFRelease(priv); + if (pub_out) *pub_out = pub; + else CFRelease(pub); + return errSecSuccess; +} diff --git a/PlayChain/Sources/PlayChain/pc_keychain.c b/PlayChain/Sources/PlayChain/pc_keychain.c new file mode 100644 index 00000000..c075d217 --- /dev/null +++ b/PlayChain/Sources/PlayChain/pc_keychain.c @@ -0,0 +1,109 @@ +#include +#include +#include +#include +#include +#include +#include "pc_internal.h" + +static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; +static struct { + char *db_path; + CFStringRef default_group; + CFArrayRef groups; + void (*_Atomic log)(const char *msg); // atomic: pc_log runs outside the lock +} config; + +void pc_configure(const pc_config_t *cfg) { + pthread_mutex_lock(&lock); + pc_store_close(); + free(config.db_path); + if (config.default_group) CFRelease(config.default_group); + if (config.groups) CFRelease(config.groups); + config.db_path = strdup(cfg->db_path); + config.default_group = CFRetain(cfg->default_group); + config.groups = cfg->groups ? CFRetain(cfg->groups) : NULL; + config.log = cfg->log; + pthread_mutex_unlock(&lock); +} + +// Callers hold the lock (pc_enter), so pc_configure can't free these underneath them. +CFStringRef pc_default_group(void) { return config.default_group; } +CFArrayRef pc_groups(void) { return config.groups; } + +void pc_log(const char *fmt, ...) { + void (*log)(const char *msg) = config.log; + if (!log) return; + char msg[1024]; + va_list args; + va_start(args, fmt); + vsnprintf(msg, sizeof msg, fmt, args); + va_end(args); + log(msg); +} + +/// Takes the lock and opens the store; on success the caller must unlock. +static OSStatus pc_enter(void) { + pthread_mutex_lock(&lock); + OSStatus status = config.db_path ? pc_store_open(config.db_path) : errSecNotAvailable; + if (status != errSecSuccess) { + if (!config.db_path) fprintf(stderr, "PlayChain: used before pc_configure\n"); + pthread_mutex_unlock(&lock); + } + return status; +} + +static void pc_leave(void) { pthread_mutex_unlock(&lock); } + +OSStatus pc_SecItemAdd(CFDictionaryRef attrs, CFTypeRef *result) { + if (result) *result = NULL; + pc_query q; + OSStatus status = pc_query_parse(attrs, PC_USE_ADD, &q); + if (status == errSecSuccess && (status = pc_enter()) == errSecSuccess) { + status = pc_item_add(&q, result); + pc_leave(); + } + pc_log("SecItemAdd → %d", (int)status); + pc_query_free(&q); + return status; +} + +OSStatus pc_SecItemCopyMatching(CFDictionaryRef query, CFTypeRef *result) { + if (result) *result = NULL; + pc_query q; + OSStatus status = pc_query_parse(query, PC_USE_SEARCH, &q); + if (status == errSecSuccess && (status = pc_enter()) == errSecSuccess) { + status = pc_item_copy(&q, result); + pc_leave(); + } + pc_log("SecItemCopyMatching → %d", (int)status); + pc_query_free(&q); + return status; +} + +OSStatus pc_SecItemUpdate(CFDictionaryRef query, CFDictionaryRef attrs) { + pc_query q, changes; + OSStatus status = pc_query_parse(query, PC_USE_SEARCH, &q); + OSStatus changes_status = pc_query_parse(attrs, PC_USE_CHANGES, &changes); + if (status == errSecSuccess) status = changes_status; + if (status == errSecSuccess && (status = pc_enter()) == errSecSuccess) { + status = pc_item_update(&q, &changes); + pc_leave(); + } + pc_log("SecItemUpdate → %d", (int)status); + pc_query_free(&q); + pc_query_free(&changes); + return status; +} + +OSStatus pc_SecItemDelete(CFDictionaryRef query) { + pc_query q; + OSStatus status = pc_query_parse(query, PC_USE_SEARCH, &q); + if (status == errSecSuccess && (status = pc_enter()) == errSecSuccess) { + status = pc_item_delete(&q); + pc_leave(); + } + pc_log("SecItemDelete → %d", (int)status); + pc_query_free(&q); + return status; +} diff --git a/PlayChain/Sources/PlayChain/pc_query.c b/PlayChain/Sources/PlayChain/pc_query.c new file mode 100644 index 00000000..7411f055 --- /dev/null +++ b/PlayChain/Sources/PlayChain/pc_query.c @@ -0,0 +1,139 @@ +#include +#include "pc_internal.h" + +static atomic_bool logged_accc; + +typedef struct { + pc_query *q; + pc_use use; + OSStatus status; +} pc_parse_ctx; + +bool pc_truthy(CFTypeRef value) { + if (CFGetTypeID(value) == CFBooleanGetTypeID()) return CFBooleanGetValue(value); + if (CFGetTypeID(value) == CFNumberGetTypeID()) { + int64_t n = 0; + CFNumberGetValue(value, kCFNumberSInt64Type, &n); + return n != 0; + } + return false; +} + +static bool pc_has_prefix(CFStringRef key, CFStringRef prefix) { + return CFStringHasPrefix(key, prefix); +} + +static void pc_parse_entry(const void *k, const void *v, void *context) { + pc_parse_ctx *ctx = context; + pc_query *q = ctx->q; + CFStringRef key = k; + CFTypeRef value = v; + if (ctx->status != errSecSuccess) return; + if (CFGetTypeID(key) != CFStringGetTypeID()) { + ctx->status = errSecParam; + return; + } + + bool is_return = pc_has_prefix(key, CFSTR("r_")); + if (ctx->use == PC_USE_CHANGES && + (CFEqual(key, kSecClass) || is_return || pc_has_prefix(key, CFSTR("m_")))) { + ctx->status = errSecNoSuchAttr; + return; + } + + if (CFEqual(key, kSecClass)) { + return; + } else if (CFEqual(key, kSecReturnData)) { + if (pc_truthy(value)) q->ret |= PC_RET_DATA; + } else if (CFEqual(key, kSecReturnAttributes)) { + if (pc_truthy(value)) q->ret |= PC_RET_ATTRS; + } else if (CFEqual(key, kSecReturnRef)) { + if (pc_truthy(value)) q->ret |= PC_RET_REF; + } else if (CFEqual(key, kSecReturnPersistentRef)) { + if (pc_truthy(value)) q->ret |= PC_RET_PREF; + } else if (is_return) { + return; + } else if (CFEqual(key, kSecMatchLimit)) { + if (CFEqual(value, kSecMatchLimitAll)) { + q->limit = -1; + } else if (CFEqual(value, kSecMatchLimitOne)) { + q->limit = 1; + } else if (CFGetTypeID(value) == CFNumberGetTypeID()) { + CFNumberGetValue(value, kCFNumberCFIndexType, &q->limit); + if (q->limit <= 0) ctx->status = errSecParam; + } else { + ctx->status = errSecParam; + } + } else if (pc_has_prefix(key, CFSTR("m_")) || pc_has_prefix(key, CFSTR("u_")) || + CFEqual(key, kSecUseDataProtectionKeychain)) { + return; // other match/use keys (case-insensitive, auth UI, …) are accepted and ignored; recorded + } else if (CFEqual(key, kSecValueData)) { + if (CFGetTypeID(value) != CFDataGetTypeID()) { + ctx->status = errSecParam; + return; + } + q->value_data = CFRetain(value); + } else if (CFEqual(key, kSecValueRef)) { + q->value_ref = CFRetain(value); + } else if (CFEqual(key, kSecValuePersistentRef)) { + char tag[5]; + if (!pc_persistent_ref_parse(value, tag, &q->rowid)) { + ctx->status = errSecParam; + return; + } + const pc_class *cls = pc_class_by_tag(tag); + if (q->cls && cls != q->cls) q->rowid = -1; + if (!q->cls) q->cls = cls; + } else if (pc_has_prefix(key, CFSTR("v_"))) { + return; + } else if (CFEqual(key, kSecAttrAccessControl)) { + // Not a plist value, so it can't be stored; results rebuild accc from pdmn. + if (!atomic_exchange(&logged_accc, true)) pc_log("kSecAttrAccessControl is accepted and dropped (no biometric gating)"); + return; + } else if (CFEqual(key, kSecAttrSynchronizable)) { + if (CFEqual(value, kSecAttrSynchronizableAny)) { + if (ctx->use != PC_USE_SEARCH) { + ctx->status = errSecParam; + return; + } + q->sync = -1; + } else { + q->sync = pc_truthy(value) ? 1 : 0; + } + q->sync_given = true; + } else { + CFTypeRef coerced = pc_coerce(q->cls, key, value); + CFDictionarySetValue(q->match, key, coerced); + CFRelease(coerced); + } +} + +OSStatus pc_query_parse(CFDictionaryRef dict, pc_use use, pc_query *q) { + *q = (pc_query){ + .match = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks), + .limit = 1, + }; + if (!dict || CFGetTypeID(dict) != CFDictionaryGetTypeID()) return errSecParam; + + CFTypeRef cls_name = CFDictionaryGetValue(dict, kSecClass); + if (cls_name && use != PC_USE_CHANGES) { + q->cls = pc_class_find(cls_name); + if (!q->cls) return errSecNoSuchClass; + } + + pc_parse_ctx ctx = {q, use, errSecSuccess}; + CFDictionaryApplyFunction(dict, pc_parse_entry, &ctx); + if (ctx.status != errSecSuccess) return ctx.status; + + // Recorded: a persistent ref alone is enough to copy or delete. + if (use != PC_USE_CHANGES && !q->cls && !(use == PC_USE_SEARCH && q->rowid)) return errSecParam; + return errSecSuccess; +} + +void pc_query_free(pc_query *q) { + if (q->match) CFRelease(q->match); + if (q->value_data) CFRelease(q->value_data); + if (q->value_ref) CFRelease(q->value_ref); + *q = (pc_query){0}; +} diff --git a/PlayChain/Sources/PlayChain/pc_result.c b/PlayChain/Sources/PlayChain/pc_result.c new file mode 100644 index 00000000..e2263a56 --- /dev/null +++ b/PlayChain/Sources/PlayChain/pc_result.c @@ -0,0 +1,153 @@ +#include +#include "pc_internal.h" + +// Persistent refs: 4-character class tag + big-endian rowid. + +CFDataRef pc_persistent_ref(const pc_class *cls, int64_t rowid) { + uint8_t bytes[12]; + memcpy(bytes, cls->tag, 4); + for (int i = 0; i < 8; i++) bytes[4 + i] = (uint8_t)(rowid >> (56 - 8 * i)); + return CFDataCreate(NULL, bytes, sizeof bytes); +} + +bool pc_persistent_ref_parse(CFTypeRef value, char *tag, int64_t *rowid) { + if (CFGetTypeID(value) != CFDataGetTypeID() || CFDataGetLength(value) != 12) return false; + const uint8_t *bytes = CFDataGetBytePtr(value); + memcpy(tag, bytes, 4); + tag[4] = 0; + *rowid = 0; + for (int i = 0; i < 8; i++) *rowid = (*rowid << 8) | bytes[4 + i]; + return pc_class_by_tag(tag) != NULL && *rowid > 0; +} + +/// The DER form securityd stores for a plain protection class: SET { SEQUENCE { "prot", } }. +static CFDataRef pc_accc_der(CFStringRef pdmn) { + char value[16] = {0}; + CFStringGetCString(pdmn, value, sizeof value, kCFStringEncodingUTF8); + uint8_t len = (uint8_t)strlen(value); + uint8_t bytes[32] = {0x31, len + 10, 0x30, len + 8, 0x0c, 4, 'p', 'r', 'o', 't', 0x0c, len}; + memcpy(bytes + 12, value, len); + return CFDataCreate(NULL, bytes, 12 + len); +} + +static CFMutableDictionaryRef pc_attr_dict(const pc_class *cls, const pc_row *row, unsigned ret, bool for_add) { + CFMutableDictionaryRef dict = CFDictionaryCreateMutableCopy(NULL, 0, row->attrs); + CFStringRef pdmn = CFDictionaryGetValue(row->attrs, kSecAttrAccessible); + + if (for_add) { + CFDictionaryRemoveValue(dict, CFSTR("UUID")); + CFDictionaryRemoveValue(dict, CFSTR("musr")); + CFDictionaryRemoveValue(dict, CFSTR("tomb")); + return dict; + } + + // Mac quirks, from the recordings: asking for a ref adds `UUID` and `class`; exactly Ref + PersistentRef + // adds `persistref`; exactly Data + PersistentRef reports `accc` as its raw DER instead of an object. + if (ret & PC_RET_REF) { + CFDictionarySetValue(dict, kSecClass, cls->name); + } else { + CFDictionaryRemoveValue(dict, CFSTR("UUID")); + } + if (ret == (PC_RET_REF | PC_RET_PREF)) { + CFDataRef pref = pc_persistent_ref(cls, row->rowid); + CFDictionarySetValue(dict, CFSTR("persistref"), pref); + CFRelease(pref); + } + if (pdmn && CFGetTypeID(pdmn) == CFStringGetTypeID()) { + CFTypeRef accc = ret == (PC_RET_DATA | PC_RET_PREF) + ? (CFTypeRef)pc_accc_der(pdmn) + : (CFTypeRef)SecAccessControlCreateWithFlags(NULL, pdmn, 0, NULL); + if (accc) CFDictionarySetValue(dict, kSecAttrAccessControl, accc); + if (accc) CFRelease(accc); + } + return dict; +} + +static OSStatus pc_ref(const pc_class *cls, const pc_row *row, CFTypeRef *out) { + if (pc_class_is_password(cls)) { + // The Mac returns a legacy SecKeychainItem here, which can't exist without the file keychain. + // Deliberate deviation: the persistent ref, which works anywhere a v_Ref is passed back in. + *out = pc_persistent_ref(cls, row->rowid); + return errSecSuccess; + } + if (CFEqual(cls->name, kSecClassKey)) { + *out = pc_key_from_row(row); + } else if (row->data) { + *out = SecCertificateCreateWithData(NULL, row->data); + } else { + *out = NULL; + } + if (*out) return errSecSuccess; + pc_log("result: cannot rebuild a ref for %s row %lld", cls->tag, row->rowid); + return errSecDecode; +} + +static OSStatus pc_item_value(const pc_class *cls, const pc_row *row, unsigned ret, bool for_add, CFTypeRef *out) { + *out = NULL; + switch (ret) { + case PC_RET_DATA: + *out = row->data ? CFRetain(row->data) : CFDataCreate(NULL, NULL, 0); + return errSecSuccess; + case PC_RET_ATTRS: + *out = pc_attr_dict(cls, row, ret, for_add); + return errSecSuccess; + case PC_RET_REF: + return pc_ref(cls, row, out); + case PC_RET_PREF: + *out = pc_persistent_ref(cls, row->rowid); + return errSecSuccess; + } + + // Two or more flags: one dictionary, always with the attributes (recorded). + CFMutableDictionaryRef dict = pc_attr_dict(cls, row, ret, for_add); + if (ret & PC_RET_DATA) { + CFDataRef data = row->data ? CFRetain(row->data) : CFDataCreate(NULL, NULL, 0); + CFDictionarySetValue(dict, kSecValueData, data); + CFRelease(data); + } + if (ret & PC_RET_REF) { + CFTypeRef ref = NULL; + OSStatus status = pc_ref(cls, row, &ref); + if (status != errSecSuccess) { + CFRelease(dict); + return status; + } + CFDictionarySetValue(dict, kSecValueRef, ref); + CFRelease(ref); + } + if (ret & PC_RET_PREF) { + CFDataRef pref = pc_persistent_ref(cls, row->rowid); + CFDictionarySetValue(dict, kSecValuePersistentRef, pref); + CFRelease(pref); + } + *out = dict; + return errSecSuccess; +} + +OSStatus pc_result_build(const pc_class *cls, pc_row *rows, size_t count, unsigned ret, CFIndex limit, bool for_add, + CFTypeRef *result) { + if (!result) return errSecSuccess; + *result = NULL; + bool single = for_add || limit == 1; + + if (ret == 0) { + // Recorded: no return flags gives no result for One, but an empty array for All. + if (!single) *result = CFArrayCreate(NULL, NULL, 0, &kCFTypeArrayCallBacks); + return errSecSuccess; + } + if (single) return pc_item_value(cls, &rows[0], ret, for_add, result); + + CFMutableArrayRef array = CFArrayCreateMutable(NULL, (CFIndex)count, &kCFTypeArrayCallBacks); + for (size_t i = 0; i < count; i++) { + CFTypeRef value = NULL; + OSStatus status = pc_item_value(cls, &rows[i], ret, false, &value); + if (status != errSecSuccess) { + CFRelease(array); + return status; + } + CFArrayAppendValue(array, value); + CFRelease(value); + } + *result = array; + return errSecSuccess; +} diff --git a/PlayChain/Sources/PlayChain/pc_schema.c b/PlayChain/Sources/PlayChain/pc_schema.c new file mode 100644 index 00000000..cf578068 --- /dev/null +++ b/PlayChain/Sources/PlayChain/pc_schema.c @@ -0,0 +1,151 @@ +#include +#include "pc_internal.h" + +#define P PC_PRIMARY +#define D PC_DEFAULT + +#define PC_COMMON_ATTRS \ + {CFSTR("agrp"), PC_STR, P}, /* default: the app's default group, set in pc_item.c */ \ + {CFSTR("sync"), PC_NUM, P | D}, \ + {CFSTR("vwht"), PC_STR, P}, \ + {CFSTR("tkid"), PC_STR, P}, \ + {CFSTR("musr"), PC_DATA, P | D}, \ + {CFSTR("ggrp"), PC_STR, P}, \ + {CFSTR("tomb"), PC_NUM, D}, \ + {CFSTR("pdmn"), PC_STR, 0}, /* default "ak", set in pc_item.c */ \ + {CFSTR("cdat"), PC_DATE, 0}, \ + {CFSTR("mdat"), PC_DATE, 0} + +static const pc_attr genp_attrs[] = { + {CFSTR("acct"), PC_BLOB, P | D}, + {CFSTR("svce"), PC_BLOB, P | D}, + {CFSTR("scrp"), PC_NUM, 0}, + {CFSTR("invi"), PC_NUM, 0}, + {CFSTR("nega"), PC_NUM, 0}, + {CFSTR("cusi"), PC_NUM, 0}, + {CFSTR("crtr"), PC_NUM, 0}, + {CFSTR("type"), PC_NUM, 0}, + PC_COMMON_ATTRS, +}; + +static const pc_attr inet_attrs[] = { + {CFSTR("acct"), PC_BLOB, P | D}, + {CFSTR("sdmn"), PC_BLOB, P | D}, + {CFSTR("srvr"), PC_BLOB, P | D}, + {CFSTR("ptcl"), PC_NUM, P | D}, + {CFSTR("atyp"), PC_BLOB, P | D}, + {CFSTR("port"), PC_NUM, P | D}, + {CFSTR("path"), PC_BLOB, P | D}, + {CFSTR("scrp"), PC_NUM, 0}, + {CFSTR("invi"), PC_NUM, 0}, + {CFSTR("nega"), PC_NUM, 0}, + {CFSTR("cusi"), PC_NUM, 0}, + {CFSTR("crtr"), PC_NUM, 0}, + {CFSTR("type"), PC_NUM, 0}, + PC_COMMON_ATTRS, +}; + +static const pc_attr cert_attrs[] = { + {CFSTR("ctyp"), PC_NUM, P | D}, + {CFSTR("issr"), PC_DATA, P | D}, + {CFSTR("slnr"), PC_DATA, P | D}, + {CFSTR("cenc"), PC_NUM, 0}, + PC_COMMON_ATTRS, +}; + +// kcls and type are stored as numbers (recorded); apps pass strings ("1", "73"), which pc_coerce converts. +static const pc_attr keys_attrs[] = { + {CFSTR("kcls"), PC_NUM, P | D}, + {CFSTR("klbl"), PC_DATA, P | D}, + {CFSTR("atag"), PC_BLOB, P | D}, + {CFSTR("crtr"), PC_NUM, P | D}, + {CFSTR("type"), PC_NUM, P | D}, + {CFSTR("bsiz"), PC_NUM, P | D}, + {CFSTR("esiz"), PC_NUM, P | D}, + {CFSTR("sdat"), PC_DATE, P | D}, + {CFSTR("edat"), PC_DATE, P | D}, + {CFSTR("perm"), PC_NUM, 0}, + {CFSTR("priv"), PC_NUM, 0}, + {CFSTR("modi"), PC_NUM, 0}, + {CFSTR("sens"), PC_NUM, 0}, + {CFSTR("asen"), PC_NUM, 0}, + {CFSTR("extr"), PC_NUM, 0}, + {CFSTR("next"), PC_NUM, 0}, + {CFSTR("encr"), PC_NUM, 0}, + {CFSTR("decr"), PC_NUM, 0}, + {CFSTR("drve"), PC_NUM, 0}, + {CFSTR("sign"), PC_NUM, 0}, + {CFSTR("vrfy"), PC_NUM, 0}, + {CFSTR("snrc"), PC_NUM, 0}, + {CFSTR("vyrc"), PC_NUM, 0}, + {CFSTR("wrap"), PC_NUM, 0}, + {CFSTR("unwp"), PC_NUM, 0}, + PC_COMMON_ATTRS, +}; + +#undef P +#undef D + +#define PC_CLASS(tag, attrs) {tag, CFSTR(tag), attrs, sizeof(attrs) / sizeof(attrs[0])} +static const pc_class classes[] = { + PC_CLASS("genp", genp_attrs), + PC_CLASS("inet", inet_attrs), + PC_CLASS("cert", cert_attrs), + PC_CLASS("keys", keys_attrs), +}; + +const pc_class *pc_class_find(CFStringRef name) { + if (CFGetTypeID(name) != CFStringGetTypeID()) return NULL; + for (size_t i = 0; i < sizeof(classes) / sizeof(classes[0]); i++) { + if (CFEqual(classes[i].name, name)) return &classes[i]; + } + return NULL; +} + +const pc_class *pc_class_by_tag(const char *tag) { + for (size_t i = 0; i < sizeof(classes) / sizeof(classes[0]); i++) { + if (strncmp(classes[i].tag, tag, 4) == 0) return &classes[i]; + } + return NULL; +} + +const pc_attr *pc_class_attr(const pc_class *cls, CFStringRef name) { + for (size_t i = 0; i < cls->count; i++) { + if (CFEqual(cls->attrs[i].name, name)) return &cls->attrs[i]; + } + return NULL; +} + +bool pc_class_is_password(const pc_class *cls) { + return cls == &classes[0] || cls == &classes[1]; +} + +bool pc_string_int(CFStringRef text, int64_t *out) { + int64_t n = CFStringGetIntValue(text); + CFStringRef back = CFStringCreateWithFormat(NULL, NULL, CFSTR("%lld"), (long long)n); + bool numeric = CFEqual(back, text); + CFRelease(back); + if (numeric) *out = n; + return numeric; +} + +CFTypeRef pc_coerce(const pc_class *cls, CFStringRef name, CFTypeRef value) { + const pc_attr *attr = cls ? pc_class_attr(cls, name) : NULL; + if (!attr) return CFRetain(value); + CFTypeID type = CFGetTypeID(value); + + if (attr->kind == PC_NUM && type == CFBooleanGetTypeID()) { + int64_t n = CFBooleanGetValue(value) ? 1 : 0; + return CFNumberCreate(NULL, kCFNumberSInt64Type, &n); + } + if (attr->kind == PC_NUM && type == CFStringGetTypeID()) { + int64_t n; + if (pc_string_int(value, &n)) return CFNumberCreate(NULL, kCFNumberSInt64Type, &n); + } + if (attr->kind == PC_STR && type == CFNumberGetTypeID()) { + int64_t n = 0; + CFNumberGetValue(value, kCFNumberSInt64Type, &n); + return CFStringCreateWithFormat(NULL, NULL, CFSTR("%lld"), (long long)n); + } + return CFRetain(value); +} diff --git a/PlayChain/Sources/PlayChain/pc_store.c b/PlayChain/Sources/PlayChain/pc_store.c new file mode 100644 index 00000000..f4fc8200 --- /dev/null +++ b/PlayChain/Sources/PlayChain/pc_store.c @@ -0,0 +1,229 @@ +#include +#include +#include +#include +#include +#include +#include "pc_internal.h" + +static sqlite3 *db; + +static const char *const schema_sql = + "PRAGMA journal_mode = WAL;" + "CREATE TABLE IF NOT EXISTS item (" + " rowid INTEGER PRIMARY KEY," + " class TEXT NOT NULL," + " pk BLOB NOT NULL," + " attrs BLOB NOT NULL," + " data BLOB," + " UNIQUE (class, pk));" + "CREATE INDEX IF NOT EXISTS item_class ON item(class);" + "PRAGMA user_version = 2;"; + +OSStatus pc_store_open(const char *path) { + if (db) return errSecSuccess; + char *dir = strdup(path); + if (mkdir(dirname(dir), 0755) != 0 && errno != EEXIST) pc_log("store: cannot create %s", dir); + free(dir); + + if (sqlite3_open_v2(path, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL) != SQLITE_OK) { + pc_log("store: cannot open %s: %s", path, db ? sqlite3_errmsg(db) : "out of memory"); + pc_store_close(); + return errSecNotAvailable; + } + sqlite3_busy_timeout(db, 2000); + char *err = NULL; + if (sqlite3_exec(db, schema_sql, NULL, NULL, &err) != SQLITE_OK) { + pc_log("store: schema failed: %s", err ? err : "?"); + sqlite3_free(err); + pc_store_close(); + return errSecNotAvailable; + } + return errSecSuccess; +} + +void pc_store_close(void) { + if (db) sqlite3_close(db); + db = NULL; +} + +static OSStatus pc_exec(const char *sql) { + if (sqlite3_exec(db, sql, NULL, NULL, NULL) == SQLITE_OK) return errSecSuccess; + pc_log("store: %s failed: %s", sql, sqlite3_errmsg(db)); + return errSecIO; +} + +OSStatus pc_store_begin(void) { return pc_exec("BEGIN IMMEDIATE"); } +OSStatus pc_store_commit(void) { return pc_exec("COMMIT"); } +void pc_store_rollback(void) { pc_exec("ROLLBACK"); } + +// pk: per primary attr, in schema order: kind tag, u32 length, canonical bytes. + +static void pc_append(CFMutableDataRef out, uint8_t tag, const void *bytes, uint32_t len) { + uint8_t be[4] = {len >> 24, len >> 16, len >> 8, len}; + CFDataAppendBytes(out, &tag, 1); + CFDataAppendBytes(out, be, 4); + if (len) CFDataAppendBytes(out, bytes, len); +} + +static void pc_encode_value(CFMutableDataRef out, CFTypeRef value) { + CFTypeID type = value ? CFGetTypeID(value) : 0; + if (!value) { + pc_append(out, 0, NULL, 0); + } else if (type == CFStringGetTypeID()) { + CFIndex max = CFStringGetMaximumSizeForEncoding(CFStringGetLength(value), kCFStringEncodingUTF8) + 1; + char *buf = malloc(max); + CFIndex used = 0; + CFStringGetBytes(value, CFRangeMake(0, CFStringGetLength(value)), kCFStringEncodingUTF8, 0, false, + (UInt8 *)buf, max, &used); + pc_append(out, 's', buf, (uint32_t)used); + free(buf); + } else if (type == CFDataGetTypeID()) { + pc_append(out, 'd', CFDataGetBytePtr(value), (uint32_t)CFDataGetLength(value)); + } else if (type == CFNumberGetTypeID() || type == CFBooleanGetTypeID()) { + int64_t n = 0; + if (type == CFBooleanGetTypeID()) n = CFBooleanGetValue(value); + else CFNumberGetValue(value, kCFNumberSInt64Type, &n); + uint8_t be[8]; + for (int i = 0; i < 8; i++) be[i] = (uint8_t)(n >> (56 - 8 * i)); + pc_append(out, 'n', be, 8); + } else if (type == CFDateGetTypeID()) { + double t = CFDateGetAbsoluteTime(value); + pc_append(out, 't', &t, sizeof t); + } else { + CFDataRef plist = CFPropertyListCreateData(NULL, value, kCFPropertyListBinaryFormat_v1_0, 0, NULL); + pc_append(out, 'p', plist ? CFDataGetBytePtr(plist) : NULL, plist ? (uint32_t)CFDataGetLength(plist) : 0); + if (plist) CFRelease(plist); + } +} + +static CFDataRef pc_encode_pk(const pc_class *cls, CFDictionaryRef attrs) { + CFMutableDataRef out = CFDataCreateMutable(NULL, 0); + for (size_t i = 0; i < cls->count; i++) { + if (cls->attrs[i].flags & PC_PRIMARY) pc_encode_value(out, CFDictionaryGetValue(attrs, cls->attrs[i].name)); + } + return out; +} + +static OSStatus pc_bind_blob(sqlite3_stmt *stmt, int index, CFDataRef _Nullable data) { + int rc = data ? sqlite3_bind_blob(stmt, index, CFDataGetBytePtr(data), (int)CFDataGetLength(data), + SQLITE_TRANSIENT) + : sqlite3_bind_null(stmt, index); + return rc == SQLITE_OK ? errSecSuccess : errSecIO; +} + +static OSStatus pc_write(const char *sql, const pc_class *cls, int64_t rowid, CFDictionaryRef attrs, + CFDataRef _Nullable data, int64_t *_Nullable out_rowid) { + CFDataRef plist = CFPropertyListCreateData(NULL, attrs, kCFPropertyListBinaryFormat_v1_0, 0, NULL); + if (!plist) { + pc_log("store: attributes are not a property list"); + return errSecParam; + } + CFDataRef pk = pc_encode_pk(cls, attrs); + sqlite3_stmt *stmt = NULL; + OSStatus status = errSecIO; + if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK && + sqlite3_bind_text(stmt, 1, cls->tag, 4, SQLITE_STATIC) == SQLITE_OK && + pc_bind_blob(stmt, 2, pk) == errSecSuccess && pc_bind_blob(stmt, 3, plist) == errSecSuccess && + pc_bind_blob(stmt, 4, data) == errSecSuccess && + (rowid == 0 || sqlite3_bind_int64(stmt, 5, rowid) == SQLITE_OK)) { + int rc = sqlite3_step(stmt); + if (rc == SQLITE_DONE) { + status = errSecSuccess; + if (out_rowid) *out_rowid = sqlite3_last_insert_rowid(db); + } else if ((rc & 0xff) == SQLITE_CONSTRAINT) { + status = errSecDuplicateItem; + } + } + if (status == errSecIO) pc_log("store: write failed: %s", sqlite3_errmsg(db)); + sqlite3_finalize(stmt); + CFRelease(pk); + CFRelease(plist); + return status; +} + +OSStatus pc_store_insert(const pc_class *cls, CFDictionaryRef attrs, CFDataRef data, int64_t *rowid) { + return pc_write("INSERT INTO item (class, pk, attrs, data) VALUES (?1, ?2, ?3, ?4)", cls, 0, attrs, data, + rowid); +} + +OSStatus pc_store_update(const pc_class *cls, int64_t rowid, CFDictionaryRef attrs, CFDataRef data) { + return pc_write("UPDATE item SET class = ?1, pk = ?2, attrs = ?3, data = ?4 WHERE rowid = ?5", cls, rowid, + attrs, data, NULL); +} + +OSStatus pc_store_delete(int64_t rowid) { + sqlite3_stmt *stmt = NULL; + OSStatus status = errSecIO; + if (sqlite3_prepare_v2(db, "DELETE FROM item WHERE rowid = ?1", -1, &stmt, NULL) == SQLITE_OK && + sqlite3_bind_int64(stmt, 1, rowid) == SQLITE_OK && sqlite3_step(stmt) == SQLITE_DONE) { + status = errSecSuccess; + } + sqlite3_finalize(stmt); + return status; +} + +const pc_class *pc_store_class_of(int64_t rowid) { + sqlite3_stmt *stmt = NULL; + const pc_class *cls = NULL; + if (sqlite3_prepare_v2(db, "SELECT class FROM item WHERE rowid = ?1", -1, &stmt, NULL) == SQLITE_OK && + sqlite3_bind_int64(stmt, 1, rowid) == SQLITE_OK && sqlite3_step(stmt) == SQLITE_ROW) { + const unsigned char *tag = sqlite3_column_text(stmt, 0); + if (tag) cls = pc_class_by_tag((const char *)tag); + } + sqlite3_finalize(stmt); + return cls; +} + +OSStatus pc_store_load(const pc_class *cls, int64_t rowid, pc_rows *out) { + *out = (pc_rows){0}; + const char *sql = rowid > 0 ? "SELECT rowid, attrs, data FROM item WHERE class = ?1 AND rowid = ?2" + : "SELECT rowid, attrs, data FROM item WHERE class = ?1 ORDER BY rowid"; + sqlite3_stmt *stmt = NULL; + if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK || + sqlite3_bind_text(stmt, 1, cls->tag, 4, SQLITE_STATIC) != SQLITE_OK || + (rowid > 0 && sqlite3_bind_int64(stmt, 2, rowid) != SQLITE_OK)) { + pc_log("store: load failed: %s", sqlite3_errmsg(db)); + sqlite3_finalize(stmt); + return errSecIO; + } + + size_t capacity = 0; + int rc; + while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) { + CFDataRef plist = CFDataCreate(NULL, sqlite3_column_blob(stmt, 1), sqlite3_column_bytes(stmt, 1)); + CFPropertyListRef attrs = CFPropertyListCreateWithData(NULL, plist, kCFPropertyListMutableContainers, + NULL, NULL); + CFRelease(plist); + if (!attrs || CFGetTypeID(attrs) != CFDictionaryGetTypeID()) { + pc_log("store: row %lld has unreadable attributes, skipped", sqlite3_column_int64(stmt, 0)); + if (attrs) CFRelease(attrs); + continue; + } + if (out->count == capacity) { + capacity = capacity ? capacity * 2 : 8; + out->rows = reallocf(out->rows, capacity * sizeof(pc_row)); + if (!out->rows) abort(); + } + CFDataRef data = sqlite3_column_type(stmt, 2) == SQLITE_NULL + ? NULL + : CFDataCreate(NULL, sqlite3_column_blob(stmt, 2), sqlite3_column_bytes(stmt, 2)); + out->rows[out->count++] = (pc_row){sqlite3_column_int64(stmt, 0), (CFMutableDictionaryRef)attrs, data}; + } + sqlite3_finalize(stmt); + if (rc != SQLITE_DONE) { + pc_log("store: load failed: %s", sqlite3_errmsg(db)); + pc_rows_free(out); + return errSecIO; + } + return errSecSuccess; +} + +void pc_rows_free(pc_rows *rows) { + for (size_t i = 0; i < rows->count; i++) { + CFRelease(rows->rows[i].attrs); + if (rows->rows[i].data) CFRelease(rows->rows[i].data); + } + free(rows->rows); + *rows = (pc_rows){0}; +} diff --git a/PlayChainHarness/.gitignore b/PlayChainHarness/.gitignore new file mode 100644 index 00000000..2d9f16e2 --- /dev/null +++ b/PlayChainHarness/.gitignore @@ -0,0 +1,2 @@ +.build/ +.swiftpm/ diff --git a/PlayChainHarness/Package.swift b/PlayChainHarness/Package.swift new file mode 100644 index 00000000..7f7ad233 --- /dev/null +++ b/PlayChainHarness/Package.swift @@ -0,0 +1,19 @@ +// swift-tools-version:5.9 +import PackageDescription + +let package = Package( + name: "PlayChainHarness", + platforms: [.macOS(.v13), .iOS(.v15), .macCatalyst(.v15)], + products: [ + .library(name: "HarnessCore", targets: ["HarnessCore"]) + ], + dependencies: [ + .package(path: "../PlayChain") + ], + targets: [ + .target(name: "HarnessCore", resources: [.copy("Scripts")]), + .testTarget(name: "PlayChainTests", dependencies: [ + "HarnessCore", .product(name: "PlayChain", package: "PlayChain") + ]) + ] +) diff --git a/PlayChainHarness/README.md b/PlayChainHarness/README.md new file mode 100644 index 00000000..d8ee181d --- /dev/null +++ b/PlayChainHarness/README.md @@ -0,0 +1,13 @@ +# PlayChain conformance harness + +The real keychain is the spec. Each `Sources/HarnessCore/Scripts/*.plist` is one case: a list of +`{op, dict, update?, save?, expect?}` steps using raw SecItem keys (`acct`, `r_Data`, `m_LimitAll`, …). +A string `"$name.path"` refers to an earlier step's saved result (`.pub` gives a key's public half). + +- **Record:** open `Recorder/PlayChainRecorder.xcodeproj`, run it as *My Mac (Mac Catalyst)* signed with + your team, press *Record all cases*, then copy the printed folder's `*.json` into `Transcripts/`. +- **Check:** `swift test` replays every script against PlayChain and diffs against `Transcripts/`. + +Dates, persistent refs, UUIDs, key material and the `agrp` team prefix are masked; `klbl`/`sha1` are +numbered per case. Status codes, result shapes and attribute key sets must match exactly. +Re-record only when cases are added or changed. diff --git a/PlayChainHarness/Recorder/PlayChainRecorder.xcodeproj/project.pbxproj b/PlayChainHarness/Recorder/PlayChainRecorder.xcodeproj/project.pbxproj new file mode 100644 index 00000000..e588c82c --- /dev/null +++ b/PlayChainHarness/Recorder/PlayChainRecorder.xcodeproj/project.pbxproj @@ -0,0 +1,233 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 60; + objects = { + +/* Begin PBXBuildFile section */ + AA0000000000000000000B01 /* RecorderApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0000000000000000000F01 /* RecorderApp.swift */; }; + AA0000000000000000000B02 /* HarnessCore in Frameworks */ = {isa = PBXBuildFile; productRef = AA0000000000000000000D01 /* HarnessCore */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + AA0000000000000000000F01 /* RecorderApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecorderApp.swift; sourceTree = ""; }; + AA0000000000000000000F02 /* PlayChainRecorder.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = PlayChainRecorder.app; sourceTree = BUILT_PRODUCTS_DIR; }; + ABC5FFCA30BBE6C1005F59F9 /* PlayChainRecorder.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = PlayChainRecorder.entitlements; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + AA0000000000000000000501 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + AA0000000000000000000B02 /* HarnessCore in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + AA0000000000000000000G00 = { + isa = PBXGroup; + children = ( + AA0000000000000000000G01 /* PlayChainRecorder */, + AA0000000000000000000G02 /* Products */, + ); + sourceTree = ""; + }; + AA0000000000000000000G01 /* PlayChainRecorder */ = { + isa = PBXGroup; + children = ( + ABC5FFCA30BBE6C1005F59F9 /* PlayChainRecorder.entitlements */, + AA0000000000000000000F01 /* RecorderApp.swift */, + ); + path = PlayChainRecorder; + sourceTree = ""; + }; + AA0000000000000000000G02 /* Products */ = { + isa = PBXGroup; + children = ( + AA0000000000000000000F02 /* PlayChainRecorder.app */, + ); + name = Products; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + AA0000000000000000000T01 /* PlayChainRecorder */ = { + isa = PBXNativeTarget; + buildConfigurationList = AA0000000000000000000C02 /* Build configuration list for PBXNativeTarget "PlayChainRecorder" */; + buildPhases = ( + AA0000000000000000000S01 /* Sources */, + AA0000000000000000000501 /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = PlayChainRecorder; + packageProductDependencies = ( + AA0000000000000000000D01 /* HarnessCore */, + ); + productName = PlayChainRecorder; + productReference = AA0000000000000000000F02 /* PlayChainRecorder.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + AA0000000000000000000P01 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 2700; + LastUpgradeCheck = 2700; + }; + buildConfigurationList = AA0000000000000000000C01 /* Build configuration list for PBXProject "PlayChainRecorder" */; + compatibilityVersion = "Xcode 15.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = AA0000000000000000000G00; + packageReferences = ( + AA0000000000000000000L01 /* XCLocalSwiftPackageReference ".." */, + ); + productRefGroup = AA0000000000000000000G02 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + AA0000000000000000000T01 /* PlayChainRecorder */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + AA0000000000000000000S01 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + AA0000000000000000000B01 /* RecorderApp.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + AA0000000000000000000E01 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ENABLE_MODULES = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_TESTABILITY = YES; + GCC_OPTIMIZATION_LEVEL = 0; + IPHONEOS_DEPLOYMENT_TARGET = 16.0; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + AA0000000000000000000E02 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ENABLE_MODULES = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + IPHONEOS_DEPLOYMENT_TARGET = 16.0; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + AA0000000000000000000E03 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_ENTITLEMENTS = PlayChainRecorder/PlayChainRecorder.entitlements; + "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = ""; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = io.playcover.PlayChainRecorder; + PRODUCT_NAME = "$(TARGET_NAME)"; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = YES; + SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2,6"; + }; + name = Debug; + }; + AA0000000000000000000E04 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_ENTITLEMENTS = PlayChainRecorder/PlayChainRecorder.entitlements; + "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = ""; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = io.playcover.PlayChainRecorder; + PRODUCT_NAME = "$(TARGET_NAME)"; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = YES; + SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2,6"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + AA0000000000000000000C01 /* Build configuration list for PBXProject "PlayChainRecorder" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + AA0000000000000000000E01 /* Debug */, + AA0000000000000000000E02 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + AA0000000000000000000C02 /* Build configuration list for PBXNativeTarget "PlayChainRecorder" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + AA0000000000000000000E03 /* Debug */, + AA0000000000000000000E04 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + AA0000000000000000000L01 /* XCLocalSwiftPackageReference ".." */ = { + isa = XCLocalSwiftPackageReference; + relativePath = ..; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + AA0000000000000000000D01 /* HarnessCore */ = { + isa = XCSwiftPackageProductDependency; + productName = HarnessCore; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = AA0000000000000000000P01 /* Project object */; +} diff --git a/PlayChainHarness/Recorder/PlayChainRecorder.xcodeproj/xcshareddata/xcschemes/PlayChainRecorder.xcscheme b/PlayChainHarness/Recorder/PlayChainRecorder.xcodeproj/xcshareddata/xcschemes/PlayChainRecorder.xcscheme new file mode 100644 index 00000000..9abb1527 --- /dev/null +++ b/PlayChainHarness/Recorder/PlayChainRecorder.xcodeproj/xcshareddata/xcschemes/PlayChainRecorder.xcscheme @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/PlayChainHarness/Recorder/PlayChainRecorder/PlayChainRecorder.entitlements b/PlayChainHarness/Recorder/PlayChainRecorder/PlayChainRecorder.entitlements new file mode 100644 index 00000000..fbad0237 --- /dev/null +++ b/PlayChainHarness/Recorder/PlayChainRecorder/PlayChainRecorder.entitlements @@ -0,0 +1,8 @@ + + + + + keychain-access-groups + + + diff --git a/PlayChainHarness/Recorder/PlayChainRecorder/RecorderApp.swift b/PlayChainHarness/Recorder/PlayChainRecorder/RecorderApp.swift new file mode 100644 index 00000000..b5c4b0e5 --- /dev/null +++ b/PlayChainHarness/Recorder/PlayChainRecorder/RecorderApp.swift @@ -0,0 +1,78 @@ +import SwiftUI +import Security +import HarnessCore + +/// Runs every harness script against the real keychain and writes one transcript per case. +/// Build as Mac Catalyst, signed with a team (the keychain needs the application-identifier entitlement), +/// then copy the output folder's contents into PlayChainHarness/Transcripts/. +@main +struct RecorderApp: App { + var body: some Scene { + WindowGroup { RecorderView() } + } +} + +struct RecorderView: View { + @State private var log: [String] = [] + @State private var running = false + + private let outDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] + .appendingPathComponent("PlayChainTranscripts") + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Button(running ? "Recording…" : "Record all cases", action: record).disabled(running) + Text("Output: \(outDir.path)").font(.caption).textSelection(.enabled) + ScrollView { + Text(log.joined(separator: "\n")) + .font(.system(.caption, design: .monospaced)) + .textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) + } + } + .padding() + .task { record() } + } + + private func record() { + running = true + log = [] + let dir = outDir + Task.detached { + let lines = Self.recordAll(to: dir) + await MainActor.run { + log = lines + running = false + } + } + } + + private nonisolated static func recordAll(to dir: URL) -> [String] { + var lines: [String] = [] + func say(_ line: String) { lines.append(line); print(line) } + + // Without the entitlement every call fails with -34018 and the transcripts would be garbage. + let probe = ["class": "genp", "acct": "playchain.probe", "v_Data": Data()] as CFDictionary + let status = SecItemAdd(probe, nil) + _ = SecItemDelete(["class": "genp", "acct": "playchain.probe"] as CFDictionary) + guard status == errSecSuccess || status == errSecDuplicateItem else { + say("Keychain unusable (status \(status)). Sign the app with a development team and run again.") + return lines + } + + do { + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + var runner = Runner(backend: .system) + runner.report = { say("note: \($0)") } + for script in try Script.loadAll() { + let transcript = try runner.run(script) + try transcript.write(to: dir.appendingPathComponent(script.name + ".json")) + say("recorded \(script.name) (\(script.steps.count) steps)") + } + say("Done. Copy \(dir.path)/*.json into PlayChainHarness/Transcripts/") + } catch { + say("error: \(error)") + } + return lines + } +} diff --git a/PlayChainHarness/Sources/HarnessCore/Normalizer.swift b/PlayChainHarness/Sources/HarnessCore/Normalizer.swift new file mode 100644 index 00000000..d99ca289 --- /dev/null +++ b/PlayChainHarness/Sources/HarnessCore/Normalizer.swift @@ -0,0 +1,107 @@ +import Foundation +import Security + +/// Turns a SecItem result into JSON that's stable across runs and machines. +/// Status codes, shapes and key sets stay exact; dates, persistent refs, UUIDs, the `agrp` team prefix and +/// key material are masked. `klbl` / `sha1` become numbered `$id`s so "same key" still shows. +public struct Normalizer { + public struct Context { + var isKeyClass: Bool + var isPassword: Bool + var onlyPersistentRef: Bool + var onlyRef: Bool + + init(_ operation: String, _ dict: [String: Any]) { + isKeyClass = dict["class"] as? String == "keys" + || operation == "createRandomKey" || operation == "generatePair" + isPassword = ["genp", "inet"].contains(dict["class"] as? String ?? "") + let flags = ["r_Data", "r_Attributes", "r_Ref", "r_PersistentRef"].filter { (dict[$0] as? Bool) == true } + onlyPersistentRef = flags == ["r_PersistentRef"] + onlyRef = flags == ["r_Ref"] + } + } + + private var ids: [String: [Data: Int]] = [:] + + public init() {} + + mutating func normalize(_ value: Any, context: Context, key: String? = nil) -> Any { + let ref = value as CFTypeRef + switch CFGetTypeID(ref) { + case CFBooleanGetTypeID(): return CFBooleanGetValue(unsafeBitCast(ref, to: CFBoolean.self)) + case CFNumberGetTypeID(): return value + case CFStringGetTypeID(): + let string = value as? String ?? "" + return key == "agrp" ? maskTeam(string) : string + case CFDateGetTypeID(): return ["$date": "*"] + case CFDataGetTypeID(): return normalize(data: value as? Data ?? Data(), context: context, key: key) + case CFArrayGetTypeID(): return normalize(array: value as? [Any] ?? [], context: context) + case CFDictionaryGetTypeID(): return normalize(dict: value as? [String: Any] ?? [:], context: context) + case SecKeyGetTypeID(): return normalize(key: unsafeBitCast(ref, to: SecKey.self), context: context) + case SecCertificateGetTypeID(): + return ["$cert": hex(SecCertificateCopyData(unsafeBitCast(ref, to: SecCertificate.self)) as Data)] + case let type: return ["$cftype": (CFCopyTypeIDDescription(type) as String?) ?? "?"] + } + } + + /// Limit All order is an artefact of securityd's SQLite indexes (recorded: it changes with the query's + /// attributes), so arrays are compared as sets: sorted by content, with `$id`s numbered after sorting. + private mutating func normalize(array: [Any], context: Context) -> [Any] { + func sortKey(_ element: Any) -> String { + var scratch = Normalizer() + let json = scratch.normalize(element, context: context) + let data = (try? JSONSerialization.data(withJSONObject: ["v": json], options: .sortedKeys)) ?? Data() + return String(data: data, encoding: .utf8) ?? "" + } + return array.map { (sortKey($0), $0) } + .sorted { $0.0 < $1.0 } + .map { normalize($0.1, context: context) } + } + + private mutating func normalize(dict: [String: Any], context: Context) -> [String: Any] { + var out: [String: Any] = [:] + for (name, value) in dict.sorted(by: { $0.key < $1.key }) { // sorted: `$id` numbering ignores hash order + out[name] = name == "UUID" ? ["$uuid": "*"] : normalize(value, context: context, key: name) + } + return out + } + + /// Only the fields both a real and an emulated (e.g. Secure Enclave fallback) key agree on. + private mutating func normalize(key: SecKey, context: Context) -> [String: Any] { + let attrs = SecKeyCopyAttributes(key) as? [String: Any] ?? [:] + var shape: [String: Any] = [:] + for name in ["type", "kcls", "bsiz"] { shape[name] = attrs[name].map { normalize($0, context: context) } } + return ["$key": shape] + } + + private mutating func normalize(data: Data, context: Context, key: String?) -> Any { + switch key { + case "klbl", "sha1": return ["$id": "\(key!)#\(id(key!, data))"] + case "v_PersistentRef", "persistref": return ["$pref": "*"] + // PlayChain returns the persistent ref where the Mac returns a SecKeychainItem (deliberate deviation). + case "v_Ref" where context.isPassword: return ["$cftype": "SecKeychainItem"] + case nil where context.isPassword && context.onlyRef: return ["$cftype": "SecKeychainItem"] + case "v_Data" where context.isKeyClass: return ["$keydata": "*"] + case nil where context.onlyPersistentRef: return ["$pref": "*"] + case nil where context.isKeyClass: return ["$keydata": "*"] + default: return ["$data": hex(data)] + } + } + + private mutating func id(_ kind: String, _ data: Data) -> Int { + if let existing = ids[kind]?[data] { return existing } + let next = (ids[kind]?.count ?? 0) + 1 + ids[kind, default: [:]][data] = next + return next + } + + /// "ABCDE12345.com.example" → "TEAMID.com.example" + private func maskTeam(_ group: String) -> String { + let parts = group.split(separator: ".", maxSplits: 1) + guard parts.count == 2, parts[0].count == 10, + parts[0].allSatisfy({ $0.isUppercase || $0.isNumber }) else { return group } + return "TEAMID." + parts[1] + } + + private func hex(_ data: Data) -> String { data.map { String(format: "%02x", $0) }.joined() } +} diff --git a/PlayChainHarness/Sources/HarnessCore/Runner.swift b/PlayChainHarness/Sources/HarnessCore/Runner.swift new file mode 100644 index 00000000..cc83401c --- /dev/null +++ b/PlayChainHarness/Sources/HarnessCore/Runner.swift @@ -0,0 +1,178 @@ +import Foundation +import Security + +/// The six entry points a keychain implementation must provide. `system` is the real Security.framework. +public struct Backend { + public var add: (CFDictionary) -> (OSStatus, CFTypeRef?) + public var copyMatching: (CFDictionary) -> (OSStatus, CFTypeRef?) + public var update: (CFDictionary, CFDictionary) -> OSStatus + public var delete: (CFDictionary) -> OSStatus + public var createRandomKey: (CFDictionary) -> (OSStatus, SecKey?) + // swiftlint:disable:next large_tuple + public var generatePair: (CFDictionary) -> (OSStatus, SecKey?, SecKey?) + + public init(add: @escaping (CFDictionary) -> (OSStatus, CFTypeRef?), + copyMatching: @escaping (CFDictionary) -> (OSStatus, CFTypeRef?), + update: @escaping (CFDictionary, CFDictionary) -> OSStatus, + delete: @escaping (CFDictionary) -> OSStatus, + createRandomKey: @escaping (CFDictionary) -> (OSStatus, SecKey?), + // swiftlint:disable:next large_tuple + generatePair: @escaping (CFDictionary) -> (OSStatus, SecKey?, SecKey?)) { + self.add = add + self.copyMatching = copyMatching + self.update = update + self.delete = delete + self.createRandomKey = createRandomKey + self.generatePair = generatePair + } + + public static let system = Backend( + add: { var out: CFTypeRef?; return (SecItemAdd($0, &out), out) }, + copyMatching: { var out: CFTypeRef?; return (SecItemCopyMatching($0, &out), out) }, + update: { SecItemUpdate($0, $1) }, + delete: { SecItemDelete($0) }, + createRandomKey: { + var err: Unmanaged? + let key = SecKeyCreateRandomKey($0, &err) + return (err.map { OSStatus(CFErrorGetCode($0.takeRetainedValue())) } ?? errSecSuccess, key) + }, + generatePair: { + var pub: SecKey?, priv: SecKey? + return (SecKeyGeneratePair($0, &pub, &priv), pub, priv) + } + ) +} + +public struct Script { + public struct Step { + public var operation: String // plist `op`: add, copy, update, delete, createRandomKey, generatePair + public var dict: [String: Any] + public var update: [String: Any]? + public var save: String? // name the result can be referred to by later, as "$name" + public var expect: OSStatus? // the script author's guess; only reported, never compared + } + public var name: String + public var steps: [Step] + + public static func loadAll() throws -> [Script] { + guard let dir = Bundle.module.url(forResource: "Scripts", withExtension: nil) else { return [] } + return try FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil) + .filter { $0.pathExtension == "plist" } + .sorted { $0.lastPathComponent < $1.lastPathComponent } + .map { try load($0) } + } + + public static func load(_ url: URL) throws -> Script { + let plist = try PropertyListSerialization.propertyList(from: Data(contentsOf: url), format: nil) + guard let raw = (plist as? [String: Any])?["steps"] as? [[String: Any]] else { + throw HarnessError.badScript(url.lastPathComponent, "missing `steps` array") + } + let steps = try raw.enumerated().map { index, step -> Step in + guard let operation = step["op"] as? String, Runner.operations.contains(operation), + let dict = step["dict"] as? [String: Any] else { + throw HarnessError.badScript(url.lastPathComponent, "step \(index) needs a known `op` and a `dict`") + } + return Step(operation: operation, dict: dict, update: step["update"] as? [String: Any], + save: step["save"] as? String, expect: (step["expect"] as? NSNumber)?.int32Value) + } + return Script(name: url.deletingPathExtension().lastPathComponent, steps: steps) + } +} + +public enum HarnessError: Error, CustomStringConvertible { + case badScript(String, String) + case unresolved(String) + + public var description: String { + switch self { + case let .badScript(file, why): return "\(file): \(why)" + case let .unresolved(ref): return "unresolved reference \(ref)" + } + } +} + +public struct Runner { + static let operations: Set = ["add", "copy", "update", "delete", "createRandomKey", "generatePair"] + static let classes = ["genp", "inet", "cert", "keys"] + + public var backend: Backend + public var report: (String) -> Void = { _ in } + + public init(backend: Backend) { self.backend = backend } + + public func reset() { + for cls in Runner.classes { + _ = backend.delete(["class": cls, "sync": "syna"] as CFDictionary) + } + } + + public func run(_ script: Script) throws -> Data { + reset() + defer { reset() } + var saved: [String: Any] = [:] + var normalizer = Normalizer() + var steps: [[String: Any]] = [] + + for (index, step) in script.steps.enumerated() { + let dict = try resolve(dict: step.dict, saved) + let (status, result) = try execute(step, dict, saved) + if let name = step.save, let result { saved[name] = result } + if let expect = step.expect, expect != status { + report("\(script.name) step \(index) (\(step.operation)): expected \(expect), got \(status)") + } + var entry: [String: Any] = ["op": step.operation, "status": Int(status)] + if let result { entry["result"] = normalizer.normalize(result, context: .init(step.operation, dict)) } + steps.append(entry) + } + let transcript: [String: Any] = ["case": script.name, "steps": steps] + return try JSONSerialization.data(withJSONObject: transcript, options: [.prettyPrinted, .sortedKeys]) + } + + private func execute(_ step: Script.Step, _ dict: [String: Any], + _ saved: [String: Any]) throws -> (OSStatus, Any?) { + let cfDict = dict as CFDictionary + switch step.operation { + case "add": return backend.add(cfDict) + case "copy": return backend.copyMatching(cfDict) + case "update": + let changes = try resolve(dict: step.update ?? [:], saved) + return (backend.update(cfDict, changes as CFDictionary), nil) + case "delete": return (backend.delete(cfDict), nil) + case "createRandomKey": return backend.createRandomKey(cfDict) + default: + let (status, pub, priv) = backend.generatePair(cfDict) + guard let pub, let priv else { return (status, nil) } + return (status, ["pub": pub, "priv": priv]) + } + } + + func resolve(dict: [String: Any], _ saved: [String: Any]) throws -> [String: Any] { + try dict.mapValues { try resolve($0, saved) } + } + + /// Replaces string values "$name" / "$name.path.to.value" with saved results. "$$" escapes a literal "$". + func resolve(_ value: Any, _ saved: [String: Any]) throws -> Any { + switch value { + case let dict as [String: Any]: return try resolve(dict: dict, saved) + case let array as [Any]: return try array.map { try resolve($0, saved) } + case let string as String where string.hasPrefix("$$"): return String(string.dropFirst()) + case let string as String where string.hasPrefix("$"): + var parts = string.dropFirst().split(separator: ".").map(String.init) + guard var current = saved[parts.removeFirst()] else { throw HarnessError.unresolved(string) } + for part in parts { + if let dict = current as? [String: Any], let next = dict[part] { + current = next + } else if let array = current as? [Any], let index = Int(part), array.indices.contains(index) { + current = array[index] + } else if part == "pub", CFGetTypeID(current as CFTypeRef) == SecKeyGetTypeID(), + let pub = SecKeyCopyPublicKey(unsafeBitCast(current as CFTypeRef, to: SecKey.self)) { + current = pub + } else { + throw HarnessError.unresolved(string) + } + } + return current + default: return value + } + } +} diff --git a/PlayChainHarness/Sources/HarnessCore/Scripts/errors.plist b/PlayChainHarness/Sources/HarnessCore/Scripts/errors.plist new file mode 100644 index 00000000..4e3646ab --- /dev/null +++ b/PlayChainHarness/Sources/HarnessCore/Scripts/errors.plist @@ -0,0 +1,68 @@ + + + + + steps + + + dict + + acct + a + v_Data + + eA== + + + expect + -50 + op + add + + + dict + + acct + a + class + zzzz + + expect + -50 + op + add + + + dict + + acct + a + + op + copy + + + dict + + acct + a + + op + delete + + + dict + + acct + missing + class + genp + + expect + -25300 + op + copy + + + + diff --git a/PlayChainHarness/Sources/HarnessCore/Scripts/genp_add_defaults.plist b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_add_defaults.plist new file mode 100644 index 00000000..fa375fe2 --- /dev/null +++ b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_add_defaults.plist @@ -0,0 +1,113 @@ + + + + + steps + + + dict + + acct + a + class + genp + svce + s + v_Data + + c2VjcmV0 + + + expect + 0 + op + add + + + dict + + acct + a + class + genp + svce + s + v_Data + + c2VjcmV0 + + + expect + -25299 + op + add + + + dict + + acct + a + class + genp + r_Attributes + + svce + s + + expect + 0 + op + copy + + + dict + + class + genp + r_Data + + svce + s + + expect + 0 + op + copy + + + dict + + class + genp + v_Data + + bm8gYWNjdCBvciBzdmNl + + + expect + 0 + op + add + + + dict + + acct + + class + genp + svce + + v_Data + + ZXhwbGljaXQgZW1wdHk= + + + expect + -25299 + op + add + + + + diff --git a/PlayChainHarness/Sources/HarnessCore/Scripts/genp_add_return.plist b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_add_return.plist new file mode 100644 index 00000000..5b383f4b --- /dev/null +++ b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_add_return.plist @@ -0,0 +1,146 @@ + + + + + steps + + + dict + + acct + r1 + class + genp + r_Attributes + + svce + s + v_Data + + c2VjcmV0 + + + op + add + + + dict + + acct + r2 + class + genp + r_Data + + svce + s + v_Data + + c2VjcmV0 + + + op + add + + + dict + + acct + r3 + class + genp + r_PersistentRef + + svce + s + v_Data + + c2VjcmV0 + + + op + add + + + dict + + acct + r4 + class + genp + r_Ref + + svce + s + v_Data + + c2VjcmV0 + + + op + add + + + dict + + acct + r5 + class + genp + r_Attributes + + r_Data + + svce + s + v_Data + + c2VjcmV0 + + + op + add + + + dict + + acct + r6 + class + genp + m_Limit + m_LimitOne + svce + s + v_Data + + c2VjcmV0 + + + op + add + + + dict + + acct + r7 + class + genp + m_Limit + m_LimitOne + r_Data + + svce + s + v_Data + + c2VjcmV0 + + + op + add + + + + diff --git a/PlayChainHarness/Sources/HarnessCore/Scripts/genp_default_limit.plist b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_default_limit.plist new file mode 100644 index 00000000..78ad160b --- /dev/null +++ b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_default_limit.plist @@ -0,0 +1,75 @@ + + + + + steps + + + dict + + acct + l1 + class + genp + svce + s + v_Data + + c2VjcmV0 + + + expect + 0 + op + add + + + dict + + acct + l2 + class + genp + svce + s + v_Data + + c2VjcmV0 + + + expect + 0 + op + add + + + dict + + class + genp + r_Attributes + + svce + s + + expect + 0 + op + copy + + + dict + + class + genp + svce + s + + expect + 0 + op + copy + + + + diff --git a/PlayChainHarness/Sources/HarnessCore/Scripts/genp_delete.plist b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_delete.plist new file mode 100644 index 00000000..9e1c4fd4 --- /dev/null +++ b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_delete.plist @@ -0,0 +1,118 @@ + + + + + steps + + + dict + + acct + d1 + class + genp + svce + s + v_Data + + c2VjcmV0 + + + expect + 0 + op + add + + + dict + + acct + d2 + class + genp + svce + s + v_Data + + c2VjcmV0 + + + expect + 0 + op + add + + + dict + + acct + d3 + class + genp + svce + s + v_Data + + c2VjcmV0 + + + expect + 0 + op + add + + + dict + + class + genp + m_Limit + m_LimitOne + svce + s + + op + delete + + + dict + + class + genp + svce + s + + expect + 0 + op + delete + + + dict + + class + genp + svce + s + + expect + -25300 + op + copy + + + dict + + class + genp + svce + s + + expect + -25300 + op + delete + + + + diff --git a/PlayChainHarness/Sources/HarnessCore/Scripts/genp_order.plist b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_order.plist new file mode 100644 index 00000000..49fcbb82 --- /dev/null +++ b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_order.plist @@ -0,0 +1,211 @@ + + + + + steps + + + dict + + acct + b + class + genp + svce + o + v_Data + + Yg== + + + op + add + + + dict + + acct + a + class + genp + svce + o + v_Data + + YQ== + + + op + add + + + dict + + acct + c + class + genp + svce + o + v_Data + + Yw== + + + op + add + + + dict + + acct + z + class + genp + svce + 2 + v_Data + + Mg== + + + op + add + + + dict + + acct + z + class + genp + svce + 1 + v_Data + + MQ== + + + op + add + + + dict + + acct + z + class + genp + svce + 3 + v_Data + + Mw== + + + op + add + + + dict + + class + genp + m_Limit + m_LimitAll + r_Data + + svce + o + + op + copy + + + dict + + class + genp + r_Data + + svce + o + + op + copy + + + dict + + acct + z + class + genp + m_Limit + m_LimitAll + r_Data + + + op + copy + + + dict + + acct + z + class + genp + r_Data + + + op + copy + + + dict + + class + genp + m_Limit + m_LimitAll + r_Data + + + op + copy + + + dict + + acct + b + class + genp + + op + update + update + + labl + touched + + + + dict + + class + genp + m_Limit + m_LimitAll + r_Data + + svce + o + + op + copy + + + + diff --git a/PlayChainHarness/Sources/HarnessCore/Scripts/genp_persistent_ref.plist b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_persistent_ref.plist new file mode 100644 index 00000000..1ec5709f --- /dev/null +++ b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_persistent_ref.plist @@ -0,0 +1,84 @@ + + + + + steps + + + dict + + acct + a + class + genp + r_PersistentRef + + svce + s + v_Data + + c2VjcmV0 + + + expect + 0 + op + add + save + p + + + dict + + r_Data + + v_PersistentRef + $p + + expect + 0 + op + copy + + + dict + + class + genp + r_Attributes + + v_PersistentRef + $p + + expect + 0 + op + copy + + + dict + + v_PersistentRef + $p + + expect + 0 + op + delete + + + dict + + r_Data + + v_PersistentRef + $p + + expect + -25300 + op + copy + + + + diff --git a/PlayChainHarness/Sources/HarnessCore/Scripts/genp_return_combos.plist b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_return_combos.plist new file mode 100644 index 00000000..84d8a934 --- /dev/null +++ b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_return_combos.plist @@ -0,0 +1,572 @@ + + + + + steps + + + dict + + acct + a + class + genp + svce + s + v_Data + + c2VjcmV0 + + + expect + 0 + op + add + + + dict + + class + genp + m_Limit + m_LimitOne + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitOne + r_Data + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitOne + r_Attributes + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitOne + r_Ref + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitOne + r_PersistentRef + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitOne + r_Attributes + + r_Data + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitOne + r_Data + + r_Ref + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitOne + r_Data + + r_PersistentRef + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitOne + r_Attributes + + r_Ref + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitOne + r_Attributes + + r_PersistentRef + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitOne + r_PersistentRef + + r_Ref + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitOne + r_Attributes + + r_Data + + r_Ref + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitOne + r_Attributes + + r_Data + + r_PersistentRef + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitOne + r_Data + + r_PersistentRef + + r_Ref + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitOne + r_Attributes + + r_PersistentRef + + r_Ref + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitOne + r_Attributes + + r_Data + + r_PersistentRef + + r_Ref + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitAll + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitAll + r_Data + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitAll + r_Attributes + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitAll + r_Ref + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitAll + r_PersistentRef + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitAll + r_Attributes + + r_Data + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitAll + r_Data + + r_Ref + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitAll + r_Data + + r_PersistentRef + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitAll + r_Attributes + + r_Ref + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitAll + r_Attributes + + r_PersistentRef + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitAll + r_PersistentRef + + r_Ref + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitAll + r_Attributes + + r_Data + + r_Ref + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitAll + r_Attributes + + r_Data + + r_PersistentRef + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitAll + r_Data + + r_PersistentRef + + r_Ref + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitAll + r_Attributes + + r_PersistentRef + + r_Ref + + svce + s + + op + copy + + + dict + + class + genp + m_Limit + m_LimitAll + r_Attributes + + r_Data + + r_PersistentRef + + r_Ref + + svce + s + + op + copy + + + + diff --git a/PlayChainHarness/Sources/HarnessCore/Scripts/genp_strings.plist b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_strings.plist new file mode 100644 index 00000000..56daf867 --- /dev/null +++ b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_strings.plist @@ -0,0 +1,88 @@ + + + + + steps + + + dict + + acct + o'brien ñ 日本 "q" + class + genp + svce + s + v_Data + + c2VjcmV0 + + + expect + 0 + op + add + + + dict + + acct + o'brien ñ 日本 "q" + class + genp + r_Attributes + + + expect + 0 + op + copy + + + dict + + acct + O'BRIEN Ñ 日本 "Q" + class + genp + r_Data + + + expect + -25300 + op + copy + + + dict + + acct + O'BRIEN Ñ 日本 "Q" + class + genp + m_CaseInsensitive + + r_Data + + + op + copy + + + dict + + acct + o'brien + class + genp + r_Data + + + expect + -25300 + op + copy + + + + diff --git a/PlayChainHarness/Sources/HarnessCore/Scripts/genp_sync.plist b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_sync.plist new file mode 100644 index 00000000..970816e2 --- /dev/null +++ b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_sync.plist @@ -0,0 +1,157 @@ + + + + + steps + + + dict + + acct + plain + class + genp + svce + s + v_Data + + c2VjcmV0 + + + expect + 0 + op + add + + + dict + + acct + synced + class + genp + svce + s + sync + + v_Data + + c2VjcmV0 + + + expect + 0 + op + add + + + dict + + class + genp + m_Limit + m_LimitAll + r_Attributes + + svce + s + + expect + 0 + op + copy + + + dict + + class + genp + m_Limit + m_LimitAll + r_Attributes + + svce + s + sync + + + expect + 0 + op + copy + + + dict + + class + genp + m_Limit + m_LimitAll + r_Attributes + + svce + s + sync + syna + + expect + 0 + op + copy + + + dict + + acct + plain + class + genp + svce + s + sync + + v_Data + + c2VjcmV0 + + + expect + 0 + op + add + + + dict + + class + genp + svce + s + + expect + 0 + op + delete + + + dict + + class + genp + m_Limit + m_LimitAll + r_Attributes + + svce + s + sync + syna + + expect + 0 + op + copy + + + + diff --git a/PlayChainHarness/Sources/HarnessCore/Scripts/genp_update.plist b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_update.plist new file mode 100644 index 00000000..1b67e8a4 --- /dev/null +++ b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_update.plist @@ -0,0 +1,175 @@ + + + + + steps + + + dict + + acct + a1 + class + genp + svce + s + v_Data + + c2VjcmV0 + + + expect + 0 + op + add + + + dict + + acct + a2 + class + genp + svce + s + v_Data + + c2VjcmV0 + + + expect + 0 + op + add + + + dict + + class + genp + svce + s + + expect + 0 + op + update + update + + labl + x + + + + dict + + class + genp + m_Limit + m_LimitAll + r_Attributes + + svce + s + + expect + 0 + op + copy + + + dict + + class + genp + svce + s + + expect + -50 + op + update + update + + class + genp + labl + y + + + + dict + + class + genp + svce + s + + expect + -50 + op + update + update + + labl + y + r_Data + + + + + dict + + class + genp + svce + nope + + expect + -25300 + op + update + update + + labl + y + + + + dict + + acct + a1 + class + genp + + expect + 0 + op + update + update + + v_Data + + bmV3 + + + + + dict + + acct + a1 + class + genp + r_Data + + + expect + 0 + op + copy + + + + diff --git a/PlayChainHarness/Sources/HarnessCore/Scripts/genp_update_collision.plist b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_update_collision.plist new file mode 100644 index 00000000..f14edf83 --- /dev/null +++ b/PlayChainHarness/Sources/HarnessCore/Scripts/genp_update_collision.plist @@ -0,0 +1,100 @@ + + + + + steps + + + dict + + acct + a1 + class + genp + svce + s + v_Data + + c2VjcmV0 + + + expect + 0 + op + add + + + dict + + acct + a2 + class + genp + svce + s + v_Data + + c2VjcmV0 + + + expect + 0 + op + add + + + dict + + acct + a1 + class + genp + + expect + -25299 + op + update + update + + acct + a2 + + + + dict + + class + genp + svce + s + + expect + -25299 + op + update + update + + acct + same + + + + dict + + class + genp + m_Limit + m_LimitAll + r_Attributes + + svce + s + + expect + 0 + op + copy + + + + diff --git a/PlayChainHarness/Sources/HarnessCore/Scripts/key_add_valueref.plist b/PlayChainHarness/Sources/HarnessCore/Scripts/key_add_valueref.plist new file mode 100644 index 00000000..a1b3910e --- /dev/null +++ b/PlayChainHarness/Sources/HarnessCore/Scripts/key_add_valueref.plist @@ -0,0 +1,111 @@ + + + + + steps + + + dict + + bsiz + 256 + private + + type + 73 + + expect + 0 + op + createRandomKey + save + k + + + dict + + atag + + YWRkZWQ= + + class + keys + v_Ref + $k + + expect + 0 + op + add + + + dict + + atag + + YWRkZWQ= + + class + keys + v_Ref + $k + + expect + -25299 + op + add + + + dict + + atag + + YWRkZWQ= + + class + keys + r_Attributes + + + expect + 0 + op + copy + + + dict + + atag + + YWRkZWQucHVi + + class + keys + v_Ref + $k.pub + + expect + 0 + op + add + + + dict + + atag + + YWRkZWQucHVi + + class + keys + r_Attributes + + + expect + 0 + op + copy + + + + diff --git a/PlayChainHarness/Sources/HarnessCore/Scripts/key_delete_regenerate.plist b/PlayChainHarness/Sources/HarnessCore/Scripts/key_delete_regenerate.plist new file mode 100644 index 00000000..cf626255 --- /dev/null +++ b/PlayChainHarness/Sources/HarnessCore/Scripts/key_delete_regenerate.plist @@ -0,0 +1,119 @@ + + + + + steps + + + dict + + bsiz + 256 + private + + atag + + cmVnZW4= + + perm + + + type + 73 + + expect + 0 + op + createRandomKey + + + dict + + atag + + cmVnZW4= + + class + keys + r_Attributes + + + expect + 0 + op + copy + + + dict + + atag + + cmVnZW4= + + class + keys + + expect + 0 + op + delete + + + dict + + atag + + cmVnZW4= + + class + keys + r_Attributes + + + expect + -25300 + op + copy + + + dict + + bsiz + 256 + private + + atag + + cmVnZW4= + + perm + + + type + 73 + + expect + 0 + op + createRandomKey + + + dict + + atag + + cmVnZW4= + + class + keys + r_Attributes + + + expect + 0 + op + copy + + + + diff --git a/PlayChainHarness/Sources/HarnessCore/Scripts/key_ec_permanent.plist b/PlayChainHarness/Sources/HarnessCore/Scripts/key_ec_permanent.plist new file mode 100644 index 00000000..dc44f1e2 --- /dev/null +++ b/PlayChainHarness/Sources/HarnessCore/Scripts/key_ec_permanent.plist @@ -0,0 +1,173 @@ + + + + + steps + + + dict + + bsiz + 256 + private + + atag + + a2V5X2VjX3Blcm1hbmVudA== + + labl + my key + perm + + + type + 73 + + expect + 0 + op + createRandomKey + save + k + + + dict + + atag + + a2V5X2VjX3Blcm1hbmVudA== + + class + keys + r_Attributes + + + expect + 0 + op + copy + save + a + + + dict + + atag + + a2V5X2VjX3Blcm1hbmVudA== + + class + keys + r_Ref + + + expect + 0 + op + copy + + + dict + + atag + + a2V5X2VjX3Blcm1hbmVudA== + + class + keys + r_Data + + + expect + 0 + op + copy + + + dict + + class + keys + klbl + $a.klbl + r_Attributes + + + expect + 0 + op + copy + + + dict + + class + keys + labl + my key + r_Attributes + + + expect + 0 + op + copy + + + dict + + atag + + a2V5X2VjX3Blcm1hbmVudA== + + class + keys + r_Attributes + + r_Data + + r_PersistentRef + + r_Ref + + + op + copy + + + dict + + atag + + a2V5X2VjX3Blcm1hbmVudA== + + class + keys + m_Limit + m_LimitAll + r_Attributes + + + op + copy + + + dict + + atag + + a2V5X2VjX3Blcm1hbmVudA== + + class + keys + kcls + 0 + r_Attributes + + + op + copy + + + + diff --git a/PlayChainHarness/Sources/HarnessCore/Scripts/key_generate_pair.plist b/PlayChainHarness/Sources/HarnessCore/Scripts/key_generate_pair.plist new file mode 100644 index 00000000..22720355 --- /dev/null +++ b/PlayChainHarness/Sources/HarnessCore/Scripts/key_generate_pair.plist @@ -0,0 +1,93 @@ + + + + + steps + + + dict + + bsiz + 256 + private + + atag + + cGFpci5wcml2 + + perm + + + public + + atag + + cGFpci5wdWI= + + perm + + + type + 73 + + expect + 0 + op + generatePair + save + p + + + dict + + atag + + cGFpci5wcml2 + + class + keys + r_Attributes + + + expect + 0 + op + copy + + + dict + + atag + + cGFpci5wdWI= + + class + keys + r_Attributes + + + expect + 0 + op + copy + + + dict + + atag + + cGFpci5wdWI= + + class + keys + r_Ref + + + expect + 0 + op + copy + + + + diff --git a/PlayChainHarness/Sources/HarnessCore/Scripts/key_limit_all_refs.plist b/PlayChainHarness/Sources/HarnessCore/Scripts/key_limit_all_refs.plist new file mode 100644 index 00000000..c6b82b6b --- /dev/null +++ b/PlayChainHarness/Sources/HarnessCore/Scripts/key_limit_all_refs.plist @@ -0,0 +1,117 @@ + + + + + steps + + + dict + + bsiz + 256 + private + + atag + + YQ== + + labl + trio + perm + + + type + 73 + + expect + 0 + op + createRandomKey + + + dict + + bsiz + 256 + private + + atag + + Yg== + + labl + trio + perm + + + type + 73 + + expect + 0 + op + createRandomKey + + + dict + + bsiz + 256 + private + + atag + + Yw== + + labl + trio + perm + + + type + 73 + + expect + 0 + op + createRandomKey + + + dict + + class + keys + labl + trio + m_Limit + m_LimitAll + r_Ref + + + expect + 0 + op + copy + + + dict + + class + keys + kcls + 1 + labl + trio + m_Limit + m_LimitAll + r_Ref + + + expect + 0 + op + copy + + + + diff --git a/PlayChainHarness/Sources/HarnessCore/Scripts/key_rsa_permanent.plist b/PlayChainHarness/Sources/HarnessCore/Scripts/key_rsa_permanent.plist new file mode 100644 index 00000000..5647cdea --- /dev/null +++ b/PlayChainHarness/Sources/HarnessCore/Scripts/key_rsa_permanent.plist @@ -0,0 +1,194 @@ + + + + + steps + + + dict + + bsiz + 2048 + private + + atag + + a2V5X3JzYV9wZXJtYW5lbnQ= + + labl + my key + perm + + + type + 42 + + expect + 0 + op + createRandomKey + save + k + + + dict + + atag + + a2V5X3JzYV9wZXJtYW5lbnQ= + + bsiz + 2048 + class + keys + r_Attributes + + + expect + 0 + op + copy + save + a + + + dict + + atag + + a2V5X3JzYV9wZXJtYW5lbnQ= + + class + keys + r_Ref + + + expect + 0 + op + copy + + + dict + + atag + + a2V5X3JzYV9wZXJtYW5lbnQ= + + class + keys + r_Data + + + expect + 0 + op + copy + + + dict + + class + keys + klbl + $a.klbl + r_Attributes + + + expect + 0 + op + copy + + + dict + + class + keys + labl + my key + r_Attributes + + + expect + 0 + op + copy + + + dict + + atag + + a2V5X3JzYV9wZXJtYW5lbnQ= + + class + keys + r_Attributes + + r_Data + + r_PersistentRef + + r_Ref + + + op + copy + + + dict + + atag + + a2V5X3JzYV9wZXJtYW5lbnQ= + + class + keys + m_Limit + m_LimitAll + r_Attributes + + + op + copy + + + dict + + atag + + a2V5X3JzYV9wZXJtYW5lbnQ= + + class + keys + kcls + 0 + r_Attributes + + + op + copy + + + dict + + atag + + a2V5X3JzYV9wZXJtYW5lbnQ= + + bsiz + 4096 + class + keys + r_Attributes + + + expect + -25300 + op + copy + + + + diff --git a/PlayChainHarness/Sources/HarnessCore/Scripts/key_secure_enclave.plist b/PlayChainHarness/Sources/HarnessCore/Scripts/key_secure_enclave.plist new file mode 100644 index 00000000..7a74d957 --- /dev/null +++ b/PlayChainHarness/Sources/HarnessCore/Scripts/key_secure_enclave.plist @@ -0,0 +1,69 @@ + + + + + steps + + + dict + + bsiz + 256 + private + + atag + + c2U= + + perm + + + tkid + com.apple.setoken + type + 73 + + expect + 0 + op + createRandomKey + + + dict + + atag + + c2U= + + class + keys + r_Ref + + tkid + com.apple.setoken + + expect + 0 + op + copy + + + dict + + atag + + c2U= + + class + keys + r_Attributes + + + expect + 0 + op + copy + + + + diff --git a/PlayChainHarness/Tests/PlayChainTests/ConformanceTests.swift b/PlayChainHarness/Tests/PlayChainTests/ConformanceTests.swift new file mode 100644 index 00000000..ee36e4d7 --- /dev/null +++ b/PlayChainHarness/Tests/PlayChainTests/ConformanceTests.swift @@ -0,0 +1,75 @@ +import XCTest +import HarnessCore +import PlayChain + +final class ConformanceTests: XCTestCase { + static let transcripts = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("Transcripts") + + /// Steps whose result isn't compared (status still is): Limit One over several matches, where the real + /// keychain's pick follows its SQLite index order and PlayChain deliberately takes the oldest item. + static let unorderedOne: [String: Set] = ["genp_order": [7]] + + func testMatchesRecordedTranscripts() throws { + var compared = 0 + for script in try Script.loadAll() { + let url = Self.transcripts.appendingPathComponent(script.name + ".json") + guard let expected = try? Data(contentsOf: url) else { continue } + let actual = try Runner(backend: .playChain(freshDatabase: script.name)).run(script) + let skip = Self.unorderedOne[script.name] ?? [] + XCTAssertEqual(try canonical(actual, skipping: skip), try canonical(expected, skipping: skip), + "\(script.name) differs from its recording") + compared += 1 + } + if compared == 0 { throw XCTSkip("no transcripts recorded yet") } + } + + private func canonical(_ transcript: Data, skipping: Set) throws -> String { + var json = try XCTUnwrap(JSONSerialization.jsonObject(with: transcript) as? [String: Any]) + var steps = try XCTUnwrap(json["steps"] as? [[String: Any]]) + for index in skipping where steps.indices.contains(index) { steps[index]["result"] = nil } + json["steps"] = steps + let data = try JSONSerialization.data(withJSONObject: json, options: [.prettyPrinted, .sortedKeys]) + return try XCTUnwrap(String(data: data, encoding: .utf8)) + } +} + +extension Backend { + static func playChain(freshDatabase name: String) -> Backend { + let path = FileManager.default.temporaryDirectory + .appendingPathComponent("PlayChainTests-\(ProcessInfo.processInfo.processIdentifier)") + .appendingPathComponent(name + ".db").path + for suffix in ["", "-wal", "-shm"] { try? FileManager.default.removeItem(atPath: path + suffix) } + let group = "ABCDE12345.io.playcover.PlayChainRecorder" as CFString + path.withCString { cPath in + var config = pc_config_t(db_path: cPath, default_group: Unmanaged.passUnretained(group), + groups: nil, log: nil) + pc_configure(&config) + } + return Backend( + add: { query in + var out: Unmanaged? + let status = pc_SecItemAdd(query, &out) + return (status, out?.takeRetainedValue()) + }, + copyMatching: { query in + var out: Unmanaged? + let status = pc_SecItemCopyMatching(query, &out) + return (status, out?.takeRetainedValue()) + }, + update: { pc_SecItemUpdate($0, $1) }, + delete: { pc_SecItemDelete($0) }, + createRandomKey: { params in + var error: Unmanaged? + let key = pc_SecKeyCreateRandomKey(params, &error) + return (error.map { OSStatus(CFErrorGetCode($0.takeRetainedValue())) } ?? errSecSuccess, key) + }, + generatePair: { params in + var pub: Unmanaged?, priv: Unmanaged? + let status = pc_SecKeyGeneratePair(params, &pub, &priv) + return (status, pub?.takeRetainedValue(), priv?.takeRetainedValue()) + } + ) + } +} diff --git a/PlayChainHarness/Tests/PlayChainTests/HarnessTests.swift b/PlayChainHarness/Tests/PlayChainTests/HarnessTests.swift new file mode 100644 index 00000000..d54f811b --- /dev/null +++ b/PlayChainHarness/Tests/PlayChainTests/HarnessTests.swift @@ -0,0 +1,70 @@ +import XCTest +import Security +@testable import HarnessCore + +final class HarnessTests: XCTestCase { + func testAllScriptsLoad() throws { + let scripts = try Script.loadAll() + XCTAssertGreaterThan(scripts.count, 0) + XCTAssertEqual(Set(scripts.map(\.name)).count, scripts.count) + } + + func testNormalizesVolatileValuesAndKeepsShape() throws { + let klbl = Data([1, 2, 3]) + let attrs: [String: Any] = [ + "class": "genp", "acct": "a", "sync": kCFBooleanFalse!, "bsiz": 256, + "cdat": Date(), "klbl": klbl, "agrp": "ABCDE12345.com.example", "v_Data": Data("pw".utf8), + "UUID": "1234" + ] + let backend = Backend( + add: { _ in (errSecSuccess, nil) }, + copyMatching: { query in + let wantsRef = (query as? [String: Any])?["r_PersistentRef"] != nil + return (errSecSuccess, wantsRef ? Data([9, 9]) as CFData : [attrs, attrs] as CFArray) + }, + update: { _, _ in errSecSuccess }, + delete: { _ in errSecItemNotFound }, + createRandomKey: { _ in (errSecParam, nil) }, + generatePair: { _ in (errSecParam, nil, nil) } + ) + let script = Script(name: "t", steps: [ + .init(operation: "copy", dict: ["class": "genp", "r_Attributes": true, "m_Limit": "m_LimitAll"], + save: "x"), + .init(operation: "copy", dict: ["class": "genp", "acct": "$x.0.acct", "r_PersistentRef": true]), + .init(operation: "createRandomKey", dict: [:]) + ]) + let data = try Runner(backend: backend).run(script) + let json = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + let steps = try XCTUnwrap(json["steps"] as? [[String: Any]]) + let rows = try XCTUnwrap(steps[0]["result"] as? [[String: Any]]) + let first = rows[0] + XCTAssertEqual(first["cdat"] as? [String: String], ["$date": "*"]) + XCTAssertEqual(first["klbl"] as? [String: String], ["$id": "klbl#1"]) + XCTAssertEqual(rows[1]["klbl"] as? [String: String], ["$id": "klbl#1"]) + XCTAssertEqual(first["agrp"] as? String, "TEAMID.com.example") + XCTAssertEqual(first["v_Data"] as? [String: String], ["$data": "7077"]) + XCTAssertEqual(first["UUID"] as? [String: String], ["$uuid": "*"]) + XCTAssertEqual(steps[1]["result"] as? [String: String], ["$pref": "*"]) + XCTAssertEqual(steps[2]["status"] as? Int, Int(errSecParam)) + XCTAssertNil(steps[2]["result"]) + + // Bools must stay bools in the JSON text, distinct from the number 0. + let text = try XCTUnwrap(String(data: data, encoding: .utf8)) + XCTAssertTrue(text.contains("\"sync\" : false")) + XCTAssertTrue(text.contains("\"bsiz\" : 256")) + } + + func testUnresolvedReferenceThrows() { + XCTAssertThrowsError(try Runner(backend: .system).resolve("$missing", [:])) + } + + func testKeyRefShape() throws { + var err: Unmanaged? + let key = try XCTUnwrap(SecKeyCreateRandomKey(["type": "73", "bsiz": 256] as CFDictionary, &err)) + var normalizer = Normalizer() + let normalized = normalizer.normalize(key, context: .init("copy", ["class": "keys"])) + let shape = try XCTUnwrap(normalized as? [String: [String: Any]]) + XCTAssertEqual(shape["$key"]?["type"] as? String, "73") + XCTAssertEqual(shape["$key"]?["bsiz"] as? Int, 256) + } +} diff --git a/PlayChainHarness/Tests/PlayChainTests/RegressionTests.swift b/PlayChainHarness/Tests/PlayChainTests/RegressionTests.swift new file mode 100644 index 00000000..66b100c8 --- /dev/null +++ b/PlayChainHarness/Tests/PlayChainTests/RegressionTests.swift @@ -0,0 +1,76 @@ +import XCTest +import Security +import HarnessCore +import PlayChain + +final class RegressionTests: XCTestCase { + override func setUp() { + _ = Backend.playChain(freshDatabase: "regression-\(name)") + } + + private func copy(_ query: [String: Any]) -> OSStatus { + var out: Unmanaged? + let status = pc_SecItemCopyMatching(query as CFDictionary, &out) + out?.release() + return status + } + + func testAddWithAccessControl() throws { + let accc = try XCTUnwrap(SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlocked, + .userPresence, nil)) + let item: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: "a", + kSecAttrAccessControl as String: accc, kSecValueData as String: Data("pw".utf8)] + XCTAssertEqual(pc_SecItemAdd(item as CFDictionary, nil), errSecSuccess) + let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: "a"] + let change: [String: Any] = [kSecAttrAccessControl as String: accc] + XCTAssertEqual(pc_SecItemUpdate(query as CFDictionary, change as CFDictionary), errSecSuccess) + XCTAssertEqual(copy(query), errSecSuccess) + } + + func testNonNumericStringDoesNotMatchZero() { + let item: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: "a", + kSecAttrType as String: 0] + XCTAssertEqual(pc_SecItemAdd(item as CFDictionary, nil), errSecSuccess) + var query = item + query[kSecAttrType as String] = "abc" + XCTAssertEqual(copy(query), errSecItemNotFound) + query[kSecAttrType as String] = "0" + XCTAssertEqual(copy(query), errSecSuccess) + } + + func testPermanentAsNumber() throws { + let tag = Data("perm-number".utf8) + let params: [String: Any] = [kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom, + kSecAttrKeySizeInBits as String: 256, + kSecAttrIsPermanent as String: NSNumber(value: 1), + kSecAttrApplicationTag as String: tag] + let key = pc_SecKeyCreateRandomKey(params as CFDictionary, nil) + XCTAssertNotNil(key) + XCTAssertEqual(copy([kSecClass as String: kSecClassKey, kSecAttrApplicationTag as String: tag]), + errSecSuccess) + } + + func testAddKeyDataWithoutClass() throws { + let priv = try XCTUnwrap(SecKeyCreateRandomKey([kSecAttrKeyType: kSecAttrKeyTypeRSA, + kSecAttrKeySizeInBits: 2048] as CFDictionary, nil)) + let der = try XCTUnwrap(SecKeyCopyExternalRepresentation(try XCTUnwrap(SecKeyCopyPublicKey(priv)), nil)) + let tag = Data("no-kcls".utf8) + let item: [String: Any] = [kSecClass as String: kSecClassKey, kSecAttrKeyType as String: kSecAttrKeyTypeRSA, + kSecAttrApplicationTag as String: tag, kSecValueData as String: der] + XCTAssertEqual(pc_SecItemAdd(item as CFDictionary, nil), errSecSuccess) + XCTAssertEqual(copy([kSecClass as String: kSecClassKey, kSecAttrApplicationTag as String: tag, + kSecReturnRef as String: true]), errSecSuccess) + } + + func testFailedPairLeavesNoPrivateKey() { + let tag = Data("half-pair".utf8) + let params: [String: Any] = [ + kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom, kSecAttrKeySizeInBits as String: 256, + kSecAttrIsPermanent as String: true, kSecAttrApplicationTag as String: tag, + kSecPublicKeyAttrs as String: [kSecMatchLimit as String: 0] // makes only the public add fail + ] + XCTAssertEqual(pc_SecKeyGeneratePair(params as CFDictionary, nil, nil), errSecParam) + XCTAssertEqual(copy([kSecClass as String: kSecClassKey, kSecAttrApplicationTag as String: tag]), + errSecItemNotFound) + } +} diff --git a/PlayChainHarness/Transcripts/.gitkeep b/PlayChainHarness/Transcripts/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/PlayChainHarness/Transcripts/errors.json b/PlayChainHarness/Transcripts/errors.json new file mode 100644 index 00000000..f23df7a4 --- /dev/null +++ b/PlayChainHarness/Transcripts/errors.json @@ -0,0 +1,25 @@ +{ + "case" : "errors", + "steps" : [ + { + "op" : "add", + "status" : -50 + }, + { + "op" : "add", + "status" : -25306 + }, + { + "op" : "copy", + "status" : -50 + }, + { + "op" : "delete", + "status" : -50 + }, + { + "op" : "copy", + "status" : -25300 + } + ] +} \ No newline at end of file diff --git a/PlayChainHarness/Transcripts/genp_add_defaults.json b/PlayChainHarness/Transcripts/genp_add_defaults.json new file mode 100644 index 00000000..980e321e --- /dev/null +++ b/PlayChainHarness/Transcripts/genp_add_defaults.json @@ -0,0 +1,55 @@ +{ + "case" : "genp_add_defaults", + "steps" : [ + { + "op" : "add", + "status" : 0 + }, + { + "op" : "add", + "status" : -25299 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0 + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "$data" : "736563726574" + }, + "status" : 0 + }, + { + "op" : "add", + "status" : 0 + }, + { + "op" : "add", + "status" : -25299 + } + ] +} \ No newline at end of file diff --git a/PlayChainHarness/Transcripts/genp_add_return.json b/PlayChainHarness/Transcripts/genp_add_return.json new file mode 100644 index 00000000..8297c749 --- /dev/null +++ b/PlayChainHarness/Transcripts/genp_add_return.json @@ -0,0 +1,80 @@ +{ + "case" : "genp_add_return", + "steps" : [ + { + "op" : "add", + "result" : { + "acct" : "r1", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0 + }, + "status" : 0 + }, + { + "op" : "add", + "result" : { + "$data" : "736563726574" + }, + "status" : 0 + }, + { + "op" : "add", + "result" : { + "$pref" : "*" + }, + "status" : 0 + }, + { + "op" : "add", + "result" : { + "$cftype" : "SecKeychainItem" + }, + "status" : 0 + }, + { + "op" : "add", + "result" : { + "acct" : "r5", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#2" + }, + "svce" : "s", + "sync" : 0, + "v_Data" : { + "$data" : "736563726574" + } + }, + "status" : 0 + }, + { + "op" : "add", + "status" : 0 + }, + { + "op" : "add", + "result" : { + "$data" : "736563726574" + }, + "status" : 0 + } + ] +} \ No newline at end of file diff --git a/PlayChainHarness/Transcripts/genp_default_limit.json b/PlayChainHarness/Transcripts/genp_default_limit.json new file mode 100644 index 00000000..75393216 --- /dev/null +++ b/PlayChainHarness/Transcripts/genp_default_limit.json @@ -0,0 +1,44 @@ +{ + "case" : "genp_default_limit", + "steps" : [ + { + "op" : "add", + "status" : 0 + }, + { + "op" : "add", + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "l1", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0 + }, + "status" : 0 + }, + { + "op" : "copy", + "status" : 0 + } + ] +} \ No newline at end of file diff --git a/PlayChainHarness/Transcripts/genp_delete.json b/PlayChainHarness/Transcripts/genp_delete.json new file mode 100644 index 00000000..8f1805ba --- /dev/null +++ b/PlayChainHarness/Transcripts/genp_delete.json @@ -0,0 +1,33 @@ +{ + "case" : "genp_delete", + "steps" : [ + { + "op" : "add", + "status" : 0 + }, + { + "op" : "add", + "status" : 0 + }, + { + "op" : "add", + "status" : 0 + }, + { + "op" : "delete", + "status" : 0 + }, + { + "op" : "delete", + "status" : -25300 + }, + { + "op" : "copy", + "status" : -25300 + }, + { + "op" : "delete", + "status" : -25300 + } + ] +} \ No newline at end of file diff --git a/PlayChainHarness/Transcripts/genp_order.json b/PlayChainHarness/Transcripts/genp_order.json new file mode 100644 index 00000000..23355153 --- /dev/null +++ b/PlayChainHarness/Transcripts/genp_order.json @@ -0,0 +1,116 @@ +{ + "case" : "genp_order", + "steps" : [ + { + "op" : "add", + "status" : 0 + }, + { + "op" : "add", + "status" : 0 + }, + { + "op" : "add", + "status" : 0 + }, + { + "op" : "add", + "status" : 0 + }, + { + "op" : "add", + "status" : 0 + }, + { + "op" : "add", + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "$data" : "61" + }, + { + "$data" : "62" + }, + { + "$data" : "63" + } + ], + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "$data" : "63" + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "$data" : "31" + }, + { + "$data" : "32" + }, + { + "$data" : "33" + } + ], + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "$data" : "32" + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "$data" : "31" + }, + { + "$data" : "32" + }, + { + "$data" : "33" + }, + { + "$data" : "61" + }, + { + "$data" : "62" + }, + { + "$data" : "63" + } + ], + "status" : 0 + }, + { + "op" : "update", + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "$data" : "61" + }, + { + "$data" : "62" + }, + { + "$data" : "63" + } + ], + "status" : 0 + } + ] +} \ No newline at end of file diff --git a/PlayChainHarness/Transcripts/genp_persistent_ref.json b/PlayChainHarness/Transcripts/genp_persistent_ref.json new file mode 100644 index 00000000..abc16798 --- /dev/null +++ b/PlayChainHarness/Transcripts/genp_persistent_ref.json @@ -0,0 +1,54 @@ +{ + "case" : "genp_persistent_ref", + "steps" : [ + { + "op" : "add", + "result" : { + "$pref" : "*" + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "$data" : "736563726574" + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0 + }, + "status" : 0 + }, + { + "op" : "delete", + "status" : 0 + }, + { + "op" : "copy", + "status" : -25300 + } + ] +} \ No newline at end of file diff --git a/PlayChainHarness/Transcripts/genp_return_combos.json b/PlayChainHarness/Transcripts/genp_return_combos.json new file mode 100644 index 00000000..9471f41b --- /dev/null +++ b/PlayChainHarness/Transcripts/genp_return_combos.json @@ -0,0 +1,928 @@ +{ + "case" : "genp_return_combos", + "steps" : [ + { + "op" : "add", + "status" : 0 + }, + { + "op" : "copy", + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "$data" : "736563726574" + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0 + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "$cftype" : "SecKeychainItem" + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "$pref" : "*" + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "v_Data" : { + "$data" : "736563726574" + } + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "class" : "genp", + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "UUID" : { + "$uuid" : "*" + }, + "v_Data" : { + "$data" : "736563726574" + }, + "v_Ref" : { + "$cftype" : "SecKeychainItem" + } + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$data" : "310c300a0c0470726f740c02616b" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "v_Data" : { + "$data" : "736563726574" + }, + "v_PersistentRef" : { + "$pref" : "*" + } + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "class" : "genp", + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "UUID" : { + "$uuid" : "*" + }, + "v_Ref" : { + "$cftype" : "SecKeychainItem" + } + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "v_PersistentRef" : { + "$pref" : "*" + } + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "class" : "genp", + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "persistref" : { + "$pref" : "*" + }, + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "UUID" : { + "$uuid" : "*" + }, + "v_PersistentRef" : { + "$pref" : "*" + }, + "v_Ref" : { + "$cftype" : "SecKeychainItem" + } + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "class" : "genp", + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "UUID" : { + "$uuid" : "*" + }, + "v_Data" : { + "$data" : "736563726574" + }, + "v_Ref" : { + "$cftype" : "SecKeychainItem" + } + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "v_Data" : { + "$data" : "736563726574" + }, + "v_PersistentRef" : { + "$pref" : "*" + } + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "class" : "genp", + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "UUID" : { + "$uuid" : "*" + }, + "v_Data" : { + "$data" : "736563726574" + }, + "v_PersistentRef" : { + "$pref" : "*" + }, + "v_Ref" : { + "$cftype" : "SecKeychainItem" + } + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "class" : "genp", + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "UUID" : { + "$uuid" : "*" + }, + "v_PersistentRef" : { + "$pref" : "*" + }, + "v_Ref" : { + "$cftype" : "SecKeychainItem" + } + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "class" : "genp", + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "UUID" : { + "$uuid" : "*" + }, + "v_Data" : { + "$data" : "736563726574" + }, + "v_PersistentRef" : { + "$pref" : "*" + }, + "v_Ref" : { + "$cftype" : "SecKeychainItem" + } + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + + ], + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "$data" : "736563726574" + } + ], + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0 + } + ], + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "$cftype" : "SecKeychainItem" + } + ], + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "$pref" : "*" + } + ], + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "v_Data" : { + "$data" : "736563726574" + } + } + ], + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "class" : "genp", + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "UUID" : { + "$uuid" : "*" + }, + "v_Data" : { + "$data" : "736563726574" + }, + "v_Ref" : { + "$cftype" : "SecKeychainItem" + } + } + ], + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "accc" : { + "$data" : "310c300a0c0470726f740c02616b" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "v_Data" : { + "$data" : "736563726574" + }, + "v_PersistentRef" : { + "$pref" : "*" + } + } + ], + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "class" : "genp", + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "UUID" : { + "$uuid" : "*" + }, + "v_Ref" : { + "$cftype" : "SecKeychainItem" + } + } + ], + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "v_PersistentRef" : { + "$pref" : "*" + } + } + ], + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "class" : "genp", + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "persistref" : { + "$pref" : "*" + }, + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "UUID" : { + "$uuid" : "*" + }, + "v_PersistentRef" : { + "$pref" : "*" + }, + "v_Ref" : { + "$cftype" : "SecKeychainItem" + } + } + ], + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "class" : "genp", + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "UUID" : { + "$uuid" : "*" + }, + "v_Data" : { + "$data" : "736563726574" + }, + "v_Ref" : { + "$cftype" : "SecKeychainItem" + } + } + ], + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "v_Data" : { + "$data" : "736563726574" + }, + "v_PersistentRef" : { + "$pref" : "*" + } + } + ], + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "class" : "genp", + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "UUID" : { + "$uuid" : "*" + }, + "v_Data" : { + "$data" : "736563726574" + }, + "v_PersistentRef" : { + "$pref" : "*" + }, + "v_Ref" : { + "$cftype" : "SecKeychainItem" + } + } + ], + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "class" : "genp", + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "UUID" : { + "$uuid" : "*" + }, + "v_PersistentRef" : { + "$pref" : "*" + }, + "v_Ref" : { + "$cftype" : "SecKeychainItem" + } + } + ], + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "class" : "genp", + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0, + "UUID" : { + "$uuid" : "*" + }, + "v_Data" : { + "$data" : "736563726574" + }, + "v_PersistentRef" : { + "$pref" : "*" + }, + "v_Ref" : { + "$cftype" : "SecKeychainItem" + } + } + ], + "status" : 0 + } + ] +} \ No newline at end of file diff --git a/PlayChainHarness/Transcripts/genp_strings.json b/PlayChainHarness/Transcripts/genp_strings.json new file mode 100644 index 00000000..5f30543b --- /dev/null +++ b/PlayChainHarness/Transcripts/genp_strings.json @@ -0,0 +1,48 @@ +{ + "case" : "genp_strings", + "steps" : [ + { + "op" : "add", + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "o'brien ñ 日本 \"q\"", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0 + }, + "status" : 0 + }, + { + "op" : "copy", + "status" : -25300 + }, + { + "op" : "copy", + "status" : -25300 + }, + { + "op" : "copy", + "status" : -25300 + } + ] +} \ No newline at end of file diff --git a/PlayChainHarness/Transcripts/genp_sync.json b/PlayChainHarness/Transcripts/genp_sync.json new file mode 100644 index 00000000..74fe6714 --- /dev/null +++ b/PlayChainHarness/Transcripts/genp_sync.json @@ -0,0 +1,183 @@ +{ + "case" : "genp_sync", + "steps" : [ + { + "op" : "add", + "status" : 0 + }, + { + "op" : "add", + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "plain", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0 + } + ], + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "synced", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#2" + }, + "svce" : "s", + "sync" : 1, + "tomb" : 0 + } + ], + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "plain", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0 + }, + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "synced", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#2" + }, + "svce" : "s", + "sync" : 1, + "tomb" : 0 + } + ], + "status" : 0 + }, + { + "op" : "add", + "status" : 0 + }, + { + "op" : "delete", + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "plain", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#3" + }, + "svce" : "s", + "sync" : 1, + "tomb" : 0 + }, + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "synced", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#2" + }, + "svce" : "s", + "sync" : 1, + "tomb" : 0 + } + ], + "status" : 0 + } + ] +} \ No newline at end of file diff --git a/PlayChainHarness/Transcripts/genp_update.json b/PlayChainHarness/Transcripts/genp_update.json new file mode 100644 index 00000000..703e0c7e --- /dev/null +++ b/PlayChainHarness/Transcripts/genp_update.json @@ -0,0 +1,94 @@ +{ + "case" : "genp_update", + "steps" : [ + { + "op" : "add", + "status" : 0 + }, + { + "op" : "add", + "status" : 0 + }, + { + "op" : "update", + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a1", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "labl" : "x", + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0 + }, + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a2", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "labl" : "x", + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#2" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0 + } + ], + "status" : 0 + }, + { + "op" : "update", + "status" : -25303 + }, + { + "op" : "update", + "status" : -25303 + }, + { + "op" : "update", + "status" : -25300 + }, + { + "op" : "update", + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "$data" : "6e6577" + }, + "status" : 0 + } + ] +} \ No newline at end of file diff --git a/PlayChainHarness/Transcripts/genp_update_collision.json b/PlayChainHarness/Transcripts/genp_update_collision.json new file mode 100644 index 00000000..016d1aff --- /dev/null +++ b/PlayChainHarness/Transcripts/genp_update_collision.json @@ -0,0 +1,73 @@ +{ + "case" : "genp_update_collision", + "steps" : [ + { + "op" : "add", + "status" : 0 + }, + { + "op" : "add", + "status" : 0 + }, + { + "op" : "update", + "status" : -25299 + }, + { + "op" : "update", + "status" : -25299 + }, + { + "op" : "copy", + "result" : [ + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a1", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#1" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0 + }, + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "acct" : "a2", + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "cdat" : { + "$date" : "*" + }, + "mdat" : { + "$date" : "*" + }, + "musr" : { + "$data" : "" + }, + "pdmn" : "ak", + "sha1" : { + "$id" : "sha1#2" + }, + "svce" : "s", + "sync" : 0, + "tomb" : 0 + } + ], + "status" : 0 + } + ] +} \ No newline at end of file diff --git a/PlayChainHarness/Transcripts/key_add_valueref.json b/PlayChainHarness/Transcripts/key_add_valueref.json new file mode 100644 index 00000000..674497d2 --- /dev/null +++ b/PlayChainHarness/Transcripts/key_add_valueref.json @@ -0,0 +1,144 @@ +{ + "case" : "key_add_valueref", + "steps" : [ + { + "op" : "createRandomKey", + "result" : { + "$key" : { + "bsiz" : 256, + "kcls" : "1", + "type" : "73" + } + }, + "status" : 0 + }, + { + "op" : "add", + "status" : 0 + }, + { + "op" : "add", + "status" : -25299 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "asen" : 0, + "atag" : { + "$data" : "6164646564" + }, + "bsiz" : 256, + "cdat" : { + "$date" : "*" + }, + "crtr" : 0, + "decr" : 1, + "drve" : 1, + "edat" : { + "$date" : "*" + }, + "encr" : 0, + "esiz" : 256, + "extr" : 1, + "kcls" : 1, + "klbl" : { + "$id" : "klbl#1" + }, + "mdat" : { + "$date" : "*" + }, + "modi" : 1, + "musr" : { + "$data" : "" + }, + "next" : 0, + "pdmn" : "ak", + "perm" : 1, + "priv" : 1, + "sdat" : { + "$date" : "*" + }, + "sens" : 0, + "sha1" : { + "$id" : "sha1#1" + }, + "sign" : 1, + "snrc" : 0, + "sync" : 0, + "tomb" : 0, + "type" : 73, + "unwp" : 1, + "vrfy" : 0, + "vyrc" : 0, + "wrap" : 0 + }, + "status" : 0 + }, + { + "op" : "add", + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "asen" : 0, + "atag" : { + "$data" : "61646465642e707562" + }, + "bsiz" : 256, + "cdat" : { + "$date" : "*" + }, + "crtr" : 0, + "decr" : 0, + "drve" : 0, + "edat" : { + "$date" : "*" + }, + "encr" : 1, + "esiz" : 256, + "extr" : 1, + "kcls" : 0, + "klbl" : { + "$id" : "klbl#1" + }, + "mdat" : { + "$date" : "*" + }, + "modi" : 1, + "musr" : { + "$data" : "" + }, + "next" : 0, + "pdmn" : "ak", + "perm" : 1, + "priv" : 1, + "sdat" : { + "$date" : "*" + }, + "sens" : 0, + "sha1" : { + "$id" : "sha1#2" + }, + "sign" : 0, + "snrc" : 0, + "sync" : 0, + "tomb" : 0, + "type" : 73, + "unwp" : 0, + "vrfy" : 1, + "vyrc" : 0, + "wrap" : 1 + }, + "status" : 0 + } + ] +} \ No newline at end of file diff --git a/PlayChainHarness/Transcripts/key_delete_regenerate.json b/PlayChainHarness/Transcripts/key_delete_regenerate.json new file mode 100644 index 00000000..4bdefbf5 --- /dev/null +++ b/PlayChainHarness/Transcripts/key_delete_regenerate.json @@ -0,0 +1,151 @@ +{ + "case" : "key_delete_regenerate", + "steps" : [ + { + "op" : "createRandomKey", + "result" : { + "$key" : { + "bsiz" : 256, + "kcls" : "1", + "type" : "73" + } + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "asen" : 0, + "atag" : { + "$data" : "726567656e" + }, + "bsiz" : 256, + "cdat" : { + "$date" : "*" + }, + "crtr" : 0, + "decr" : 1, + "drve" : 1, + "edat" : { + "$date" : "*" + }, + "encr" : 0, + "esiz" : 256, + "extr" : 1, + "kcls" : 1, + "klbl" : { + "$id" : "klbl#1" + }, + "mdat" : { + "$date" : "*" + }, + "modi" : 1, + "musr" : { + "$data" : "" + }, + "next" : 0, + "pdmn" : "ak", + "perm" : 1, + "priv" : 1, + "sdat" : { + "$date" : "*" + }, + "sens" : 0, + "sha1" : { + "$id" : "sha1#1" + }, + "sign" : 1, + "snrc" : 0, + "sync" : 0, + "tomb" : 0, + "type" : 73, + "unwp" : 1, + "vrfy" : 0, + "vyrc" : 0, + "wrap" : 0 + }, + "status" : 0 + }, + { + "op" : "delete", + "status" : 0 + }, + { + "op" : "copy", + "status" : -25300 + }, + { + "op" : "createRandomKey", + "result" : { + "$key" : { + "bsiz" : 256, + "kcls" : "1", + "type" : "73" + } + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "asen" : 0, + "atag" : { + "$data" : "726567656e" + }, + "bsiz" : 256, + "cdat" : { + "$date" : "*" + }, + "crtr" : 0, + "decr" : 1, + "drve" : 1, + "edat" : { + "$date" : "*" + }, + "encr" : 0, + "esiz" : 256, + "extr" : 1, + "kcls" : 1, + "klbl" : { + "$id" : "klbl#2" + }, + "mdat" : { + "$date" : "*" + }, + "modi" : 1, + "musr" : { + "$data" : "" + }, + "next" : 0, + "pdmn" : "ak", + "perm" : 1, + "priv" : 1, + "sdat" : { + "$date" : "*" + }, + "sens" : 0, + "sha1" : { + "$id" : "sha1#2" + }, + "sign" : 1, + "snrc" : 0, + "sync" : 0, + "tomb" : 0, + "type" : 73, + "unwp" : 1, + "vrfy" : 0, + "vyrc" : 0, + "wrap" : 0 + }, + "status" : 0 + } + ] +} \ No newline at end of file diff --git a/PlayChainHarness/Transcripts/key_ec_permanent.json b/PlayChainHarness/Transcripts/key_ec_permanent.json new file mode 100644 index 00000000..77739aaf --- /dev/null +++ b/PlayChainHarness/Transcripts/key_ec_permanent.json @@ -0,0 +1,352 @@ +{ + "case" : "key_ec_permanent", + "steps" : [ + { + "op" : "createRandomKey", + "result" : { + "$key" : { + "bsiz" : 256, + "kcls" : "1", + "type" : "73" + } + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "asen" : 0, + "atag" : { + "$data" : "6b65795f65635f7065726d616e656e74" + }, + "bsiz" : 256, + "cdat" : { + "$date" : "*" + }, + "crtr" : 0, + "decr" : 1, + "drve" : 1, + "edat" : { + "$date" : "*" + }, + "encr" : 0, + "esiz" : 256, + "extr" : 1, + "kcls" : 1, + "klbl" : { + "$id" : "klbl#1" + }, + "labl" : "my key", + "mdat" : { + "$date" : "*" + }, + "modi" : 1, + "musr" : { + "$data" : "" + }, + "next" : 0, + "pdmn" : "ak", + "perm" : 1, + "priv" : 1, + "sdat" : { + "$date" : "*" + }, + "sens" : 0, + "sha1" : { + "$id" : "sha1#1" + }, + "sign" : 1, + "snrc" : 0, + "sync" : 0, + "tomb" : 0, + "type" : 73, + "unwp" : 1, + "vrfy" : 0, + "vyrc" : 0, + "wrap" : 0 + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "$key" : { + "bsiz" : 256, + "kcls" : "1", + "type" : "73" + } + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "$keydata" : "*" + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "asen" : 0, + "atag" : { + "$data" : "6b65795f65635f7065726d616e656e74" + }, + "bsiz" : 256, + "cdat" : { + "$date" : "*" + }, + "crtr" : 0, + "decr" : 1, + "drve" : 1, + "edat" : { + "$date" : "*" + }, + "encr" : 0, + "esiz" : 256, + "extr" : 1, + "kcls" : 1, + "klbl" : { + "$id" : "klbl#1" + }, + "labl" : "my key", + "mdat" : { + "$date" : "*" + }, + "modi" : 1, + "musr" : { + "$data" : "" + }, + "next" : 0, + "pdmn" : "ak", + "perm" : 1, + "priv" : 1, + "sdat" : { + "$date" : "*" + }, + "sens" : 0, + "sha1" : { + "$id" : "sha1#1" + }, + "sign" : 1, + "snrc" : 0, + "sync" : 0, + "tomb" : 0, + "type" : 73, + "unwp" : 1, + "vrfy" : 0, + "vyrc" : 0, + "wrap" : 0 + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "asen" : 0, + "atag" : { + "$data" : "6b65795f65635f7065726d616e656e74" + }, + "bsiz" : 256, + "cdat" : { + "$date" : "*" + }, + "crtr" : 0, + "decr" : 1, + "drve" : 1, + "edat" : { + "$date" : "*" + }, + "encr" : 0, + "esiz" : 256, + "extr" : 1, + "kcls" : 1, + "klbl" : { + "$id" : "klbl#1" + }, + "labl" : "my key", + "mdat" : { + "$date" : "*" + }, + "modi" : 1, + "musr" : { + "$data" : "" + }, + "next" : 0, + "pdmn" : "ak", + "perm" : 1, + "priv" : 1, + "sdat" : { + "$date" : "*" + }, + "sens" : 0, + "sha1" : { + "$id" : "sha1#1" + }, + "sign" : 1, + "snrc" : 0, + "sync" : 0, + "tomb" : 0, + "type" : 73, + "unwp" : 1, + "vrfy" : 0, + "vyrc" : 0, + "wrap" : 0 + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "asen" : 0, + "atag" : { + "$data" : "6b65795f65635f7065726d616e656e74" + }, + "bsiz" : 256, + "cdat" : { + "$date" : "*" + }, + "class" : "keys", + "crtr" : 0, + "decr" : 1, + "drve" : 1, + "edat" : { + "$date" : "*" + }, + "encr" : 0, + "esiz" : 256, + "extr" : 1, + "kcls" : 1, + "klbl" : { + "$id" : "klbl#1" + }, + "labl" : "my key", + "mdat" : { + "$date" : "*" + }, + "modi" : 1, + "musr" : { + "$data" : "" + }, + "next" : 0, + "pdmn" : "ak", + "perm" : 1, + "priv" : 1, + "sdat" : { + "$date" : "*" + }, + "sens" : 0, + "sha1" : { + "$id" : "sha1#1" + }, + "sign" : 1, + "snrc" : 0, + "sync" : 0, + "tomb" : 0, + "type" : 73, + "unwp" : 1, + "UUID" : { + "$uuid" : "*" + }, + "v_Data" : { + "$keydata" : "*" + }, + "v_PersistentRef" : { + "$pref" : "*" + }, + "v_Ref" : { + "$key" : { + "bsiz" : 256, + "kcls" : "1", + "type" : "73" + } + }, + "vrfy" : 0, + "vyrc" : 0, + "wrap" : 0 + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "asen" : 0, + "atag" : { + "$data" : "6b65795f65635f7065726d616e656e74" + }, + "bsiz" : 256, + "cdat" : { + "$date" : "*" + }, + "crtr" : 0, + "decr" : 1, + "drve" : 1, + "edat" : { + "$date" : "*" + }, + "encr" : 0, + "esiz" : 256, + "extr" : 1, + "kcls" : 1, + "klbl" : { + "$id" : "klbl#1" + }, + "labl" : "my key", + "mdat" : { + "$date" : "*" + }, + "modi" : 1, + "musr" : { + "$data" : "" + }, + "next" : 0, + "pdmn" : "ak", + "perm" : 1, + "priv" : 1, + "sdat" : { + "$date" : "*" + }, + "sens" : 0, + "sha1" : { + "$id" : "sha1#1" + }, + "sign" : 1, + "snrc" : 0, + "sync" : 0, + "tomb" : 0, + "type" : 73, + "unwp" : 1, + "vrfy" : 0, + "vyrc" : 0, + "wrap" : 0 + } + ], + "status" : 0 + }, + { + "op" : "copy", + "status" : -25300 + } + ] +} \ No newline at end of file diff --git a/PlayChainHarness/Transcripts/key_generate_pair.json b/PlayChainHarness/Transcripts/key_generate_pair.json new file mode 100644 index 00000000..52d1e6f8 --- /dev/null +++ b/PlayChainHarness/Transcripts/key_generate_pair.json @@ -0,0 +1,152 @@ +{ + "case" : "key_generate_pair", + "steps" : [ + { + "op" : "generatePair", + "result" : { + "priv" : { + "$key" : { + "bsiz" : 256, + "kcls" : "1", + "type" : "73" + } + }, + "pub" : { + "$key" : { + "bsiz" : 256, + "kcls" : "0", + "type" : "73" + } + } + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "asen" : 0, + "atag" : { + "$data" : "706169722e70726976" + }, + "bsiz" : 256, + "cdat" : { + "$date" : "*" + }, + "crtr" : 0, + "decr" : 1, + "drve" : 1, + "edat" : { + "$date" : "*" + }, + "encr" : 0, + "esiz" : 256, + "extr" : 1, + "kcls" : 1, + "klbl" : { + "$id" : "klbl#1" + }, + "mdat" : { + "$date" : "*" + }, + "modi" : 1, + "musr" : { + "$data" : "" + }, + "next" : 0, + "pdmn" : "ak", + "perm" : 1, + "priv" : 1, + "sdat" : { + "$date" : "*" + }, + "sens" : 0, + "sha1" : { + "$id" : "sha1#1" + }, + "sign" : 1, + "snrc" : 0, + "sync" : 0, + "tomb" : 0, + "type" : 73, + "unwp" : 1, + "vrfy" : 0, + "vyrc" : 0, + "wrap" : 0 + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "asen" : 0, + "atag" : { + "$data" : "706169722e707562" + }, + "bsiz" : 256, + "cdat" : { + "$date" : "*" + }, + "crtr" : 0, + "decr" : 0, + "drve" : 0, + "edat" : { + "$date" : "*" + }, + "encr" : 1, + "esiz" : 256, + "extr" : 1, + "kcls" : 0, + "klbl" : { + "$id" : "klbl#1" + }, + "mdat" : { + "$date" : "*" + }, + "modi" : 1, + "musr" : { + "$data" : "" + }, + "next" : 0, + "pdmn" : "ak", + "perm" : 1, + "priv" : 1, + "sdat" : { + "$date" : "*" + }, + "sens" : 0, + "sha1" : { + "$id" : "sha1#2" + }, + "sign" : 0, + "snrc" : 0, + "sync" : 0, + "tomb" : 0, + "type" : 73, + "unwp" : 0, + "vrfy" : 1, + "vyrc" : 0, + "wrap" : 1 + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "$key" : { + "bsiz" : 256, + "kcls" : "0", + "type" : "73" + } + }, + "status" : 0 + } + ] +} \ No newline at end of file diff --git a/PlayChainHarness/Transcripts/key_limit_all_refs.json b/PlayChainHarness/Transcripts/key_limit_all_refs.json new file mode 100644 index 00000000..704b5928 --- /dev/null +++ b/PlayChainHarness/Transcripts/key_limit_all_refs.json @@ -0,0 +1,92 @@ +{ + "case" : "key_limit_all_refs", + "steps" : [ + { + "op" : "createRandomKey", + "result" : { + "$key" : { + "bsiz" : 256, + "kcls" : "1", + "type" : "73" + } + }, + "status" : 0 + }, + { + "op" : "createRandomKey", + "result" : { + "$key" : { + "bsiz" : 256, + "kcls" : "1", + "type" : "73" + } + }, + "status" : 0 + }, + { + "op" : "createRandomKey", + "result" : { + "$key" : { + "bsiz" : 256, + "kcls" : "1", + "type" : "73" + } + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "$key" : { + "bsiz" : 256, + "kcls" : "1", + "type" : "73" + } + }, + { + "$key" : { + "bsiz" : 256, + "kcls" : "1", + "type" : "73" + } + }, + { + "$key" : { + "bsiz" : 256, + "kcls" : "1", + "type" : "73" + } + } + ], + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "$key" : { + "bsiz" : 256, + "kcls" : "1", + "type" : "73" + } + }, + { + "$key" : { + "bsiz" : 256, + "kcls" : "1", + "type" : "73" + } + }, + { + "$key" : { + "bsiz" : 256, + "kcls" : "1", + "type" : "73" + } + } + ], + "status" : 0 + } + ] +} \ No newline at end of file diff --git a/PlayChainHarness/Transcripts/key_rsa_permanent.json b/PlayChainHarness/Transcripts/key_rsa_permanent.json new file mode 100644 index 00000000..abdf27e7 --- /dev/null +++ b/PlayChainHarness/Transcripts/key_rsa_permanent.json @@ -0,0 +1,356 @@ +{ + "case" : "key_rsa_permanent", + "steps" : [ + { + "op" : "createRandomKey", + "result" : { + "$key" : { + "bsiz" : 2048, + "kcls" : "1", + "type" : "42" + } + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "asen" : 0, + "atag" : { + "$data" : "6b65795f7273615f7065726d616e656e74" + }, + "bsiz" : 2048, + "cdat" : { + "$date" : "*" + }, + "crtr" : 0, + "decr" : 1, + "drve" : 0, + "edat" : { + "$date" : "*" + }, + "encr" : 0, + "esiz" : 2048, + "extr" : 1, + "kcls" : 1, + "klbl" : { + "$id" : "klbl#1" + }, + "labl" : "my key", + "mdat" : { + "$date" : "*" + }, + "modi" : 1, + "musr" : { + "$data" : "" + }, + "next" : 0, + "pdmn" : "ak", + "perm" : 1, + "priv" : 1, + "sdat" : { + "$date" : "*" + }, + "sens" : 0, + "sha1" : { + "$id" : "sha1#1" + }, + "sign" : 1, + "snrc" : 0, + "sync" : 0, + "tomb" : 0, + "type" : 42, + "unwp" : 1, + "vrfy" : 0, + "vyrc" : 0, + "wrap" : 0 + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "$key" : { + "bsiz" : 2048, + "kcls" : "1", + "type" : "42" + } + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "$keydata" : "*" + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "asen" : 0, + "atag" : { + "$data" : "6b65795f7273615f7065726d616e656e74" + }, + "bsiz" : 2048, + "cdat" : { + "$date" : "*" + }, + "crtr" : 0, + "decr" : 1, + "drve" : 0, + "edat" : { + "$date" : "*" + }, + "encr" : 0, + "esiz" : 2048, + "extr" : 1, + "kcls" : 1, + "klbl" : { + "$id" : "klbl#1" + }, + "labl" : "my key", + "mdat" : { + "$date" : "*" + }, + "modi" : 1, + "musr" : { + "$data" : "" + }, + "next" : 0, + "pdmn" : "ak", + "perm" : 1, + "priv" : 1, + "sdat" : { + "$date" : "*" + }, + "sens" : 0, + "sha1" : { + "$id" : "sha1#1" + }, + "sign" : 1, + "snrc" : 0, + "sync" : 0, + "tomb" : 0, + "type" : 42, + "unwp" : 1, + "vrfy" : 0, + "vyrc" : 0, + "wrap" : 0 + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "asen" : 0, + "atag" : { + "$data" : "6b65795f7273615f7065726d616e656e74" + }, + "bsiz" : 2048, + "cdat" : { + "$date" : "*" + }, + "crtr" : 0, + "decr" : 1, + "drve" : 0, + "edat" : { + "$date" : "*" + }, + "encr" : 0, + "esiz" : 2048, + "extr" : 1, + "kcls" : 1, + "klbl" : { + "$id" : "klbl#1" + }, + "labl" : "my key", + "mdat" : { + "$date" : "*" + }, + "modi" : 1, + "musr" : { + "$data" : "" + }, + "next" : 0, + "pdmn" : "ak", + "perm" : 1, + "priv" : 1, + "sdat" : { + "$date" : "*" + }, + "sens" : 0, + "sha1" : { + "$id" : "sha1#1" + }, + "sign" : 1, + "snrc" : 0, + "sync" : 0, + "tomb" : 0, + "type" : 42, + "unwp" : 1, + "vrfy" : 0, + "vyrc" : 0, + "wrap" : 0 + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "asen" : 0, + "atag" : { + "$data" : "6b65795f7273615f7065726d616e656e74" + }, + "bsiz" : 2048, + "cdat" : { + "$date" : "*" + }, + "class" : "keys", + "crtr" : 0, + "decr" : 1, + "drve" : 0, + "edat" : { + "$date" : "*" + }, + "encr" : 0, + "esiz" : 2048, + "extr" : 1, + "kcls" : 1, + "klbl" : { + "$id" : "klbl#1" + }, + "labl" : "my key", + "mdat" : { + "$date" : "*" + }, + "modi" : 1, + "musr" : { + "$data" : "" + }, + "next" : 0, + "pdmn" : "ak", + "perm" : 1, + "priv" : 1, + "sdat" : { + "$date" : "*" + }, + "sens" : 0, + "sha1" : { + "$id" : "sha1#1" + }, + "sign" : 1, + "snrc" : 0, + "sync" : 0, + "tomb" : 0, + "type" : 42, + "unwp" : 1, + "UUID" : { + "$uuid" : "*" + }, + "v_Data" : { + "$keydata" : "*" + }, + "v_PersistentRef" : { + "$pref" : "*" + }, + "v_Ref" : { + "$key" : { + "bsiz" : 2048, + "kcls" : "1", + "type" : "42" + } + }, + "vrfy" : 0, + "vyrc" : 0, + "wrap" : 0 + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : [ + { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "asen" : 0, + "atag" : { + "$data" : "6b65795f7273615f7065726d616e656e74" + }, + "bsiz" : 2048, + "cdat" : { + "$date" : "*" + }, + "crtr" : 0, + "decr" : 1, + "drve" : 0, + "edat" : { + "$date" : "*" + }, + "encr" : 0, + "esiz" : 2048, + "extr" : 1, + "kcls" : 1, + "klbl" : { + "$id" : "klbl#1" + }, + "labl" : "my key", + "mdat" : { + "$date" : "*" + }, + "modi" : 1, + "musr" : { + "$data" : "" + }, + "next" : 0, + "pdmn" : "ak", + "perm" : 1, + "priv" : 1, + "sdat" : { + "$date" : "*" + }, + "sens" : 0, + "sha1" : { + "$id" : "sha1#1" + }, + "sign" : 1, + "snrc" : 0, + "sync" : 0, + "tomb" : 0, + "type" : 42, + "unwp" : 1, + "vrfy" : 0, + "vyrc" : 0, + "wrap" : 0 + } + ], + "status" : 0 + }, + { + "op" : "copy", + "status" : -25300 + }, + { + "op" : "copy", + "status" : -25300 + } + ] +} \ No newline at end of file diff --git a/PlayChainHarness/Transcripts/key_secure_enclave.json b/PlayChainHarness/Transcripts/key_secure_enclave.json new file mode 100644 index 00000000..422f7638 --- /dev/null +++ b/PlayChainHarness/Transcripts/key_secure_enclave.json @@ -0,0 +1,81 @@ +{ + "case" : "key_secure_enclave", + "steps" : [ + { + "op" : "createRandomKey", + "result" : { + "$key" : { + "bsiz" : 256, + "kcls" : "1", + "type" : "73" + } + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "$key" : { + "bsiz" : 256, + "kcls" : "1", + "type" : "73" + } + }, + "status" : 0 + }, + { + "op" : "copy", + "result" : { + "accc" : { + "$cftype" : "SecAccessControl" + }, + "agrp" : "TEAMID.io.playcover.PlayChainRecorder", + "atag" : { + "$data" : "7365" + }, + "bsiz" : 256, + "cdat" : { + "$date" : "*" + }, + "crtr" : 0, + "decr" : 0, + "drve" : 1, + "edat" : { + "$date" : "*" + }, + "encr" : 0, + "esiz" : 256, + "extr" : 0, + "kcls" : 1, + "klbl" : { + "$id" : "klbl#1" + }, + "mdat" : { + "$date" : "*" + }, + "modi" : 0, + "musr" : { + "$data" : "" + }, + "next" : 1, + "pdmn" : "dk", + "perm" : 1, + "priv" : 1, + "sdat" : { + "$date" : "*" + }, + "sha1" : { + "$id" : "sha1#1" + }, + "sign" : 1, + "sync" : 0, + "tkid" : "com.apple.setoken", + "tomb" : 0, + "type" : 73, + "vrfy" : 0, + "wrap" : 0 + }, + "status" : 0 + } + ] +} \ No newline at end of file diff --git a/PlayTools.xcodeproj/project.pbxproj b/PlayTools.xcodeproj/project.pbxproj index 253c39eb..bf7f233b 100644 --- a/PlayTools.xcodeproj/project.pbxproj +++ b/PlayTools.xcodeproj/project.pbxproj @@ -78,16 +78,14 @@ AA818CB9287ABFB1000BEE9D /* IOKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AA818CB8287ABFB1000BEE9D /* IOKit.framework */; }; AB7DA47529B85BFB0034ACB2 /* PlayShadow.m in Sources */ = {isa = PBXBuildFile; fileRef = AB7DA47429B85BFB0034ACB2 /* PlayShadow.m */; }; AB7DA47729B8A78B0034ACB2 /* PlayShadow.h in Headers */ = {isa = PBXBuildFile; fileRef = AB7DA47629B8A78B0034ACB2 /* PlayShadow.h */; }; - ABCECEE629750BA600746595 /* PlayedApple.swift in Sources */ = {isa = PBXBuildFile; fileRef = ABCECEE529750BA600746595 /* PlayedApple.swift */; }; B127172528817C040025112B /* DiscordIPC.swift in Sources */ = {isa = PBXBuildFile; fileRef = B127172428817C040025112B /* DiscordIPC.swift */; }; B1271729288284BE0025112B /* DiscordActivity.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1271728288284BE0025112B /* DiscordActivity.swift */; }; B1E8CF8A28BBE2AB004340D3 /* Keymapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1E8CF8928BBE2AB004340D3 /* Keymapping.swift */; }; B444BB0D2F49C1D100ADCC5A /* ControllerFocus.m in Sources */ = {isa = PBXBuildFile; fileRef = B444BB0B2F49C1D100ADCC5A /* ControllerFocus.m */; }; B46C02C72C634AB5007637AB /* BatteryLevel.m in Sources */ = {isa = PBXBuildFile; fileRef = B46C02C62C634AB5007637AB /* BatteryLevel.m */; }; - B66E65002C936EA100E48FD0 /* PlayedAppleDBConstants.swift in Sources */ = {isa = PBXBuildFile; fileRef = B66E64FF2C936E9800E48FD0 /* PlayedAppleDBConstants.swift */; }; B6D774FF2ACFC3D900C0D9D8 /* SwordRPC in Frameworks */ = {isa = PBXBuildFile; productRef = B6D774FE2ACFC3D900C0D9D8 /* SwordRPC */; }; D04B12CA2EF6F3DD008FEC14 /* MediaVolume.m in Sources */ = {isa = PBXBuildFile; fileRef = D04B12C92EF6F3DD008FEC14 /* MediaVolume.m */; }; - EEB248592B81D074000C230A /* PlayedAppleDB.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEB248582B81D074000C230A /* PlayedAppleDB.swift */; }; + DC0000000000000000000002 /* PlayChain in Frameworks */ = {isa = PBXBuildFile; productRef = DC0000000000000000000003 /* PlayChain */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -180,17 +178,15 @@ AA818CBA287ABFD5000BEE9D /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk/System/iOSSupport/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; AB7DA47429B85BFB0034ACB2 /* PlayShadow.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = PlayShadow.m; sourceTree = ""; }; AB7DA47629B8A78B0034ACB2 /* PlayShadow.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = PlayShadow.h; sourceTree = ""; }; - ABCECEE529750BA600746595 /* PlayedApple.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayedApple.swift; sourceTree = ""; }; B127172428817C040025112B /* DiscordIPC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiscordIPC.swift; sourceTree = ""; }; B1271728288284BE0025112B /* DiscordActivity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiscordActivity.swift; sourceTree = ""; }; B1E8CF8928BBE2AB004340D3 /* Keymapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Keymapping.swift; sourceTree = ""; }; B444BB0B2F49C1D100ADCC5A /* ControllerFocus.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ControllerFocus.m; sourceTree = ""; }; B46C02C62C634AB5007637AB /* BatteryLevel.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = BatteryLevel.m; sourceTree = ""; }; B46C02C82C634C60007637AB /* BatteryLevel.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = BatteryLevel.h; sourceTree = ""; }; - B66E64FF2C936E9800E48FD0 /* PlayedAppleDBConstants.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayedAppleDBConstants.swift; sourceTree = ""; }; D04B12C92EF6F3DD008FEC14 /* MediaVolume.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MediaVolume.m; sourceTree = ""; }; D04B12CC2EF6F3F9008FEC14 /* MediaVolume.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MediaVolume.h; sourceTree = ""; }; - EEB248582B81D074000C230A /* PlayedAppleDB.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayedAppleDB.swift; sourceTree = ""; }; + DC0000000000000000000001 /* PlayChain */ = {isa = PBXFileReference; lastKnownFileType = wrapper; path = PlayChain; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -205,6 +201,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + DC0000000000000000000002 /* PlayChain in Frameworks */, B6D774FF2ACFC3D900C0D9D8 /* SwordRPC in Frameworks */, 6E84A14528D0F94E00BF7495 /* UIKit.framework in Frameworks */, AA818CB9287ABFB1000BEE9D /* IOKit.framework in Frameworks */, @@ -419,6 +416,7 @@ AA7196CE287A447700623C15 = { isa = PBXGroup; children = ( + DC0000000000000000000001 /* PlayChain */, 951D8277299D097C00D35B20 /* Playtools.strings */, AA7196DA287A447700623C15 /* PlayTools */, 6E76639928D0FA6F00DE4AF9 /* AKInterface */, @@ -543,9 +541,6 @@ ABCECEE729750BB100746595 /* MysticRunes */ = { isa = PBXGroup; children = ( - B66E64FF2C936E9800E48FD0 /* PlayedAppleDBConstants.swift */, - ABCECEE529750BA600746595 /* PlayedApple.swift */, - EEB248582B81D074000C230A /* PlayedAppleDB.swift */, AB7DA47429B85BFB0034ACB2 /* PlayShadow.m */, AB7DA47629B8A78B0034ACB2 /* PlayShadow.h */, ); @@ -618,6 +613,7 @@ name = PlayTools; packageProductDependencies = ( B6D774FE2ACFC3D900C0D9D8 /* SwordRPC */, + DC0000000000000000000003 /* PlayChain */, ); productName = PlayTools; productReference = AA7196D8287A447700623C15 /* PlayTools.framework */; @@ -725,7 +721,6 @@ AA7197A1287A481500623C15 /* CircleMenuLoader.swift in Sources */, 6E76639B28D0FAE700DE4AF9 /* Plugin.swift in Sources */, B1271729288284BE0025112B /* DiscordActivity.swift in Sources */, - EEB248592B81D074000C230A /* PlayedAppleDB.swift in Sources */, 954389CC2B39F03D00B063BB /* EditorView.swift in Sources */, 954389C22B38922400B063BB /* MouseArea.swift in Sources */, AA7197AB287A481500623C15 /* Element.swift in Sources */, @@ -750,7 +745,6 @@ 9562D1532AB484FD002C329D /* EventAdapter.swift in Sources */, AA7197A2287A481500623C15 /* CircleMenu.swift in Sources */, 954389CE2B39F26600B063BB /* ElementView.swift in Sources */, - B66E65002C936EA100E48FD0 /* PlayedAppleDBConstants.swift in Sources */, 9562D15A2AB4FBBB002C329D /* TransparentKeyboardEventAdapter.swift in Sources */, AA71978B287A480D00623C15 /* MenuController.swift in Sources */, 9562D1732AB52416002C329D /* EditorKeyboardEventAdapter.swift in Sources */, @@ -774,7 +768,6 @@ AA71986A287A81A000623C15 /* PTFakeMetaTouch.m in Sources */, 9562D15E2AB4FCB8002C329D /* TouchscreenControllerEventAdapter.swift in Sources */, 954389C62B3896E600B063BB /* ChildButton.swift in Sources */, - ABCECEE629750BA600746595 /* PlayedApple.swift in Sources */, AA71986C287A81A000623C15 /* NSObject+Swizzle.m in Sources */, AA71970F287A44D200623C15 /* PlayCover.swift in Sources */, B127172528817C040025112B /* DiscordIPC.swift in Sources */, @@ -1127,6 +1120,10 @@ package = B6D774FD2ACFC3D900C0D9D8 /* XCRemoteSwiftPackageReference "SwordRPC" */; productName = SwordRPC; }; + DC0000000000000000000003 /* PlayChain */ = { + isa = XCSwiftPackageProductDependency; + productName = PlayChain; + }; /* End XCSwiftPackageProductDependency section */ }; rootObject = AA7196CF287A447700623C15 /* Project object */; diff --git a/PlayTools/Controls/Backend/Toucher.swift b/PlayTools/Controls/Backend/Toucher.swift index 94bd55f9..4e18de4e 100644 --- a/PlayTools/Controls/Backend/Toucher.swift +++ b/PlayTools/Controls/Backend/Toucher.swift @@ -26,9 +26,12 @@ class Toucher { if tid != nil { return } + // No key window (focus or fullscreen transitions): drop the touch; tid stays nil so its + // moved/ended phases are ignored too. + guard let window = screen.keyWindow else { return } tid = -1 - keyWindow = screen.keyWindow - keyView = keyWindow!.hitTest(point, with: nil) + keyWindow = window + keyView = window.hitTest(point, with: nil) } else if tid == nil { return } diff --git a/PlayTools/Controls/PTFakeTouch/NSObject+Swizzle.m b/PlayTools/Controls/PTFakeTouch/NSObject+Swizzle.m index e50200fb..2fa79af4 100644 --- a/PlayTools/Controls/PTFakeTouch/NSObject+Swizzle.m +++ b/PlayTools/Controls/PTFakeTouch/NSObject+Swizzle.m @@ -201,6 +201,18 @@ + (NSArray *)hook_GCMouse_mice { return @[]; } +// macOS 15+ shields ~/Library/Group Containers from apps without a provisioned application-groups +// entitlement, which ad-hoc signed apps can't have; keep group data inside the app's own container. +- (NSURL *)hook_containerURLForSecurityApplicationGroupIdentifier:(NSString *)groupIdentifier { + if (groupIdentifier.length == 0) { + return [self hook_containerURLForSecurityApplicationGroupIdentifier:groupIdentifier]; + } + NSURL *url = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Group Containers"] isDirectory:YES]; + url = [url URLByAppendingPathComponent:groupIdentifier isDirectory:YES]; + [(NSFileManager *)self createDirectoryAtURL:url withIntermediateDirectories:YES attributes:nil error:nil]; + return url; +} + + (void)hook_Unity_KeyboardDelegate_Initialize { @try { [self hook_Unity_KeyboardDelegate_Initialize]; @@ -338,6 +350,10 @@ + (void)load { // [objc_getClass("UIDevice") swizzleInstanceMethod:@selector(userInterfaceIdiom) withMethod:@selector(hook_userInterfaceIdiom)]; // [objc_getClass("UITraitCollection") swizzleInstanceMethod:@selector(userInterfaceIdiom) withMethod:@selector(hook_userInterfaceIdiom)]; + if (@available(iOS 18.0, *)) { + [objc_getClass("NSFileManager") swizzleInstanceMethod:@selector(containerURLForSecurityApplicationGroupIdentifier:) withMethod:@selector(hook_containerURLForSecurityApplicationGroupIdentifier:)]; + } + [objc_getClass("VSSubscriptionRegistrationCenter") swizzleInstanceMethod:@selector(setCurrentSubscription:) withMethod:@selector(hook_setCurrentSubscription:)]; if (PlayInfo.isUnrealEngine) { diff --git a/PlayTools/MysticRunes/PlayedApple.swift b/PlayTools/MysticRunes/PlayedApple.swift deleted file mode 100644 index ef0de9b5..00000000 --- a/PlayTools/MysticRunes/PlayedApple.swift +++ /dev/null @@ -1,383 +0,0 @@ -// -// PlayWeRuinedIt.swift -// PlayTools -// -// Created by Venti on 16/01/2023. -// - -import Foundation -import Security - -// Implementation for PlayKeychain -// World's Most Advanced Keychain Replacement Solution:tm: -// This is a joke, don't take it seriously - -public class PlayKeychain: NSObject { - static let shared = PlayKeychain() - private static let playChainDB = PlayKeychainDB.shared - - @objc public static func debugLogger(_ logContent: String) { - if PlaySettings.shared.settingsData.playChainDebugging { - NSLog("PC-DEBUG: \(logContent)") - } - } - - private static func flag(_ dictionary: NSDictionary, _ key: CFString) -> Bool { - let value = dictionary[key as String] - if let value = value as? Bool { - return value - } - if let value = value as? NSNumber { - return value.boolValue - } - return false - } - // Emulates SecItemAdd, SecItemUpdate, SecItemDelete and SecItemCopyMatching - // Store the entire dictionary as a plist - // SecItemAdd(CFDictionaryRef attributes, CFTypeRef *result) - @objc static public func add(_ attributes: NSDictionary, - result: UnsafeMutablePointer?>?) -> OSStatus { - guard let keychainDict = playChainDB.insert(attributes) else { - debugLogger("Failed to write keychain file") - return errSecIO - } - debugLogger("Wrote keychain item to db") - - let wantsReturn = - flag(attributes, kSecReturnAttributes) || - flag(attributes, kSecReturnData) || - flag(attributes, kSecReturnRef) || - flag(attributes, kSecReturnPersistentRef) - - guard wantsReturn, result != nil else { - return errSecSuccess - } - - return addResult(attributes, keychainDict: keychainDict, result: result) - } - - private static func addResult(_ attributes: NSDictionary, - keychainDict: NSMutableDictionary, - result: UnsafeMutablePointer?>?) -> OSStatus { - // Place v_Data in the result - guard let vData = attributes["v_Data"] as? CFTypeRef else { - return errSecSuccess - } - - if attributes["r_Attributes"] as? Int == 1 { - // Create a dummy dictionary and return it - let dummyDict = keychainDict - if attributes["r_Data"] as? Int != 1 { - dummyDict.removeObject(forKey: kSecValueData) - dummyDict.removeObject(forKey: kSecValueRef) - dummyDict.removeObject(forKey: kSecValuePersistentRef) - } - result?.pointee = Unmanaged.passRetained(dummyDict) - return errSecSuccess - } - - if flag(attributes, kSecReturnData) && - !flag(attributes, kSecReturnRef) && - !flag(attributes, kSecReturnPersistentRef) { - result?.pointee = Unmanaged.passRetained(vData) - return errSecSuccess - } - - if attributes["class"] as? String == "keys" { - if let keyDataValue = vData as? Data { - // kSecAttrKeyType is stored as `type` in the dictionary - // kSecAttrKeyClass is stored as `kcls` in the dictionary - let keyAttributesDictionary = [ - kSecAttrKeyType: attributes["type"] as? String - ?? (attributes[kSecAttrKeyType as String] as? String), - kSecAttrKeyClass: attributes["kcls"] as? String - ?? (attributes[kSecAttrKeyType as String] as? String) - ] - if let key = SecKeyCreateWithData( - keyDataValue as CFData, - keyAttributesDictionary as CFDictionary, - nil - ) { - result?.pointee = Unmanaged.passRetained(key) - return errSecSuccess - } - } - return errSecBadReq - } - result?.pointee = Unmanaged.passRetained(vData) - return errSecSuccess - } - - // SecItemUpdate(CFDictionaryRef query, CFDictionaryRef attributesToUpdate) - @objc static public func update(_ query: NSDictionary, attributesToUpdate: NSDictionary) -> OSStatus { - guard let keychainDict = playChainDB.query(query)?.first else { - debugLogger("Keychain item not found in db") - return errSecItemNotFound - } - debugLogger("Select keychain item from db") - // Reconstruct the dictionary (subscripting won't work as assignment is not allowed) - let newKeychainDict = NSMutableDictionary() - for (key, value) in keychainDict { - newKeychainDict.setValue(value, forKey: key as! String) // swiftlint:disable:this force_cast - } - // Update the dictionary - for (key, value) in attributesToUpdate { - newKeychainDict.setValue(value, forKey: key as! String) // swiftlint:disable:this force_cast - } - guard playChainDB.update(newKeychainDict) else { - debugLogger("Failed to update keychain item to db") - return errSecIO - } - - return errSecSuccess - } - - // SecItemDelete(CFDictionaryRef query) - @objc static public func delete(_ query: NSDictionary) -> OSStatus { - guard playChainDB.query(query)?.first != nil else { - debugLogger("Failed to find keychain item") - return errSecItemNotFound - } - guard playChainDB.delete(query) else { - debugLogger("Failed to delete keychain item") - return errSecIO - } - debugLogger("Deleted keychain item in db") - return errSecSuccess - } - - @objc static public func keyCreateRandomKey(_ parameters: NSDictionary, - error: UnsafeMutablePointer?>?) - -> Unmanaged? { - // Check if kSecAttrIsPermanent is set to 1 in kSecPrivateKeyAttrs. - // If it is, set it to 0 before fowarding the call to SecKeyCreateRandomKey, - // and then add the key to the keychain db with the original attributes (with kSecAttrIsPermanent set to 1) - var privateKeyAttrs = parameters[kSecPrivateKeyAttrs as String] as? [String: Any] ?? [:] - let isPermanent = privateKeyAttrs[kSecAttrIsPermanent as String] as? Bool ?? false - if isPermanent { - privateKeyAttrs[kSecAttrIsPermanent as String] = false - } - var parametersCopy = parameters as! [String: Any] // swiftlint:disable:this force_cast - parametersCopy[kSecPrivateKeyAttrs as String] = privateKeyAttrs - var error: Unmanaged? - guard let key = SecKeyCreateRandomKey(parametersCopy as CFDictionary, &error) else { - debugLogger("Failed to create random key: \(error!.takeRetainedValue())") - return nil - } - if isPermanent { - // Add the key to the keychain db with the original attributes - var keychainDict = [String: Any]() - keychainDict[kSecClass as String] = kSecClassKey - keychainDict[kSecAttrKeyType as String] = parameters[kSecAttrKeyType as String] - keychainDict[kSecAttrKeyClass as String] = parameters[kSecAttrKeyClass as String] - keychainDict["type"] = parameters[kSecAttrKeyType as String] - keychainDict["kcls"] = parameters[kSecAttrKeyClass as String] - keychainDict["v_Data"] = SecKeyCopyExternalRepresentation(key, nil) as? Data - keychainDict["r_Attributes"] = 1 - guard playChainDB.insert(keychainDict as NSDictionary) != nil else { - debugLogger("Failed to write keychain file") - return nil - } - } - return Unmanaged.passRetained(key) - } - - // swiftlint:disable:next function_body_length - @objc static public func keyGeneratePair(_ parameters: NSDictionary, - publicKey: UnsafeMutablePointer?>?, - privateKey: UnsafeMutablePointer?>?) -> OSStatus { - // Same as above but we need to disable kSecAttrIsPermanent for both the public and private key. - var isPermanent = parameters[kSecAttrIsPermanent as String] as? Bool ?? false - var privateKeyAttrs = parameters[kSecPrivateKeyAttrs as String] as? [String: Any] ?? [:] - let isPrivatePermanent = privateKeyAttrs[kSecAttrIsPermanent as String] as? Bool ?? false - if isPrivatePermanent { - privateKeyAttrs[kSecAttrIsPermanent as String] = false - isPermanent = true - } - var publicKeyAttrs = parameters[kSecPublicKeyAttrs as String] as? [String: Any] ?? [:] - let isPublicPermanent = (publicKeyAttrs[kSecAttrIsPermanent as String] as? Bool) ?? false - if isPublicPermanent { - publicKeyAttrs[kSecAttrIsPermanent as String] = false - isPermanent = true - } - var parametersCopy = parameters as! [String: Any] // swiftlint:disable:this force_cast - parametersCopy.removeValue(forKey: kSecAttrIsPermanent as String) - parametersCopy[kSecPrivateKeyAttrs as String] = privateKeyAttrs - parametersCopy[kSecPublicKeyAttrs as String] = publicKeyAttrs - var newPublicKey: SecKey? - var newPrivateKey: SecKey? - guard SecKeyGeneratePair(parametersCopy as CFDictionary, &newPublicKey, &newPrivateKey) == 0 else { - debugLogger("Failed to generate key pair.") - return errSecMissingEntitlement - } - if let newPublicKey = newPublicKey { - publicKey?.pointee = Unmanaged.passRetained(newPublicKey) - } - if let newPrivateKey = newPrivateKey { - privateKey?.pointee = Unmanaged.passRetained(newPrivateKey) - } - if isPermanent { - // Add the keys to the keychain db with the original attributes - let publicKeyRef = newPublicKey - let privateKeyRef = newPrivateKey - var publicKeyDict = [String: Any]() - publicKeyDict[kSecClass as String] = kSecClassKey - publicKeyDict[kSecAttrKeyType as String] = parameters[kSecAttrKeyType as String] - publicKeyDict[kSecAttrKeyClass as String] = kSecAttrKeyClassPublic - publicKeyDict["type"] = parameters[kSecAttrKeyType as String] - publicKeyDict["kcls"] = kSecAttrKeyClassPublic - publicKeyDict["v_Data"] = SecKeyCopyExternalRepresentation(publicKeyRef!, nil) as? Data - publicKeyDict["r_Attributes"] = 1 - guard playChainDB.insert(publicKeyDict as NSDictionary) != nil else { - debugLogger("Failed to write public key to keychain db") - return errSecMissingEntitlement - } - var privateKeyDict = [String: Any]() - privateKeyDict[kSecClass as String] = kSecClassKey - privateKeyDict[kSecAttrKeyType as String] = parameters[kSecAttrKeyType as String] - privateKeyDict[kSecAttrKeyClass as String] = kSecAttrKeyClassPrivate - privateKeyDict["type"] = parameters[kSecAttrKeyType as String] - privateKeyDict["kcls"] = kSecAttrKeyClassPrivate - privateKeyDict["v_Data"] = SecKeyCopyExternalRepresentation(privateKeyRef!, nil) as? Data - privateKeyDict["r_Attributes"] = 1 - guard playChainDB.insert(privateKeyDict as NSDictionary) != nil else { - debugLogger("Failed to write private key to keychain db") - return errSecMissingEntitlement - } - } - return errSecSuccess - } -} - -extension PlayKeychain { - // SecItemCopyMatching(CFDictionaryRef query, CFTypeRef *result) - // swiftlint:disable:next function_body_length - @objc static public func copyMatching(_ query: NSDictionary, - result: UnsafeMutablePointer?>?) -> OSStatus { - guard let keychainDicts = playChainDB.query(query), - let keychainDict = keychainDicts.first else { - debugLogger("Keychain item not found in db") - return errSecItemNotFound - } - - let wantsAttributes = flag(query, kSecReturnAttributes) - let wantsData = flag(query, kSecReturnData) - let wantsRef = flag(query, kSecReturnRef) - let wantsPersistentRef = flag(query, kSecReturnPersistentRef) - - if query[kSecMatchLimit as String] as? String == kSecMatchLimitAll as String { - return copyAllMatches(keychainDicts, query: query, result: result) - } - // Check the `r_Attributes` key. If it is set to 1 in the query - let classType = query[kSecClass as String] as? String ?? "" - - if wantsAttributes { - // Create a dummy dictionary and return it - let dummyDict = keychainDict - if !wantsData { - dummyDict.removeObject(forKey: kSecValueData) - dummyDict.removeObject(forKey: kSecValueRef) - dummyDict.removeObject(forKey: kSecValuePersistentRef) - } - result?.pointee = Unmanaged.passRetained(dummyDict) - return errSecSuccess - } - - // kSecReturnData asks for the stored bytes, even for kSecClassKey. - if wantsData && !wantsRef && !wantsPersistentRef { - guard let vData = keychainDict[kSecValueData] else { - return errSecItemNotFound - } - result?.pointee = Unmanaged.passRetained(vData as CFTypeRef) - return errSecSuccess - } - - // A query without return flags is an existence check. - if !wantsAttributes && !wantsData && !wantsRef && !wantsPersistentRef { - return errSecSuccess - } - - if wantsRef { - return copyReference(keychainDict, result: result) - } - - // Return v_Data if it exists - if let vData = keychainDict[kSecValueData] { - debugLogger("Read keychain file from db") - // Check the class type, if it is a key we need to return the data - // as SecKeyRef, otherwise we can return it as a CFTypeRef - if classType == "keys" { - // kSecAttrKeyType is stored as `type` in the dictionary - // kSecAttrKeyClass is stored as `kcls` in the dictionary - let keyAttributes = [ - kSecAttrKeyType: keychainDict[kSecAttrKeyType] as! CFString, // swiftlint:disable:this force_cast - kSecAttrKeyClass: keychainDict[kSecAttrKeyClass] as! CFString // swiftlint:disable:this force_cast - ] - let keyData = vData as! Data // swiftlint:disable:this force_cast - let key = SecKeyCreateWithData(keyData as CFData, keyAttributes as CFDictionary, nil) - result?.pointee = Unmanaged.passRetained(key!) - return errSecSuccess - } - result?.pointee = Unmanaged.passRetained(vData as CFTypeRef) - return errSecSuccess - } - - return errSecItemNotFound - } - - private static func copyAllMatches(_ keychainDicts: [NSMutableDictionary], query: NSDictionary, - result: UnsafeMutablePointer?>?) -> OSStatus { - let wantsData = flag(query, kSecReturnData) - let wantsAttributes = flag(query, kSecReturnAttributes) - let wantsRef = flag(query, kSecReturnRef) - let wantsPersistentRef = flag(query, kSecReturnPersistentRef) - if wantsData && !wantsAttributes && !wantsRef && !wantsPersistentRef { - let values = keychainDicts.compactMap({ $0[kSecValueData] }) - guard values.count == keychainDicts.count else { - return errSecItemNotFound - } - result?.pointee = Unmanaged.passRetained(values as CFTypeRef) - return errSecSuccess - } - - result?.pointee = Unmanaged.passRetained(keychainDicts.map({ - if !wantsData { - $0.removeObject(forKey: kSecValueData) - } - $0.removeObject(forKey: kSecValueRef) - $0.removeObject(forKey: kSecValuePersistentRef) - return $0 - }) as CFTypeRef) - return errSecSuccess - } - - private static func copyReference(_ keychainDict: NSMutableDictionary, - result: UnsafeMutablePointer?>?) -> OSStatus { - // Return the data on v_PersistentRef or v_Data if they exist - var key: CFTypeRef? - if let vData = keychainDict[kSecValueData] { - NSLog("found v_Data") - debugLogger("Read keychain item from db") - key = vData as CFTypeRef - } - if let vPersistentRef = keychainDict[kSecValuePersistentRef] { - NSLog("found persistent ref") - debugLogger("Read keychain item from db") - key = vPersistentRef as CFTypeRef - } - - if key == nil { - debugLogger("Keychain item not found in db") - return errSecItemNotFound - } - - let dummyKeyAttrs = [ - kSecAttrKeyType: keychainDict[kSecAttrKeyType] ?? kSecAttrKeyTypeRSA, - kSecAttrKeyClass: keychainDict[kSecAttrKeyClass] ?? kSecAttrKeyClassPublic - ] as CFDictionary - - let secKey = SecKeyCreateWithData(key as! CFData, dummyKeyAttrs, nil) // swiftlint:disable:this force_cast - result?.pointee = Unmanaged.passRetained(secKey!) - return errSecSuccess - } -} diff --git a/PlayTools/MysticRunes/PlayedAppleDB.swift b/PlayTools/MysticRunes/PlayedAppleDB.swift deleted file mode 100644 index 06103b65..00000000 --- a/PlayTools/MysticRunes/PlayedAppleDB.swift +++ /dev/null @@ -1,308 +0,0 @@ -// -// PlayedAppleBackend.swift -// PlayTools -// -// Created by Ryu-ga on 2/20/24. -// - -import Foundation -import Security -import SQLite3 - -class PlayKeychainDB: NSObject { - public static let shared = PlayKeychainDB() - - private var dbLock: DispatchSemaphore = .init(value: 1) - private var dbVersion: Int = 1 - - func query(_ attributes: NSDictionary) -> [NSMutableDictionary]? { - guard let tableName = attributes[kSecClass] as? String, - let primaryColumns = PlayedAppleDBConstants.primaries[tableName as CFString] else { - return nil - } - - let selectWhere = primaryColumns.compactMap({ - guard let attr = attributes[$0] else { return nil } // use only requested ones - if CFGetTypeID(attr as CFTypeRef) == CFDataGetTypeID(), - let string = (attr as? Data).map({ String(data: $0, encoding: .utf8) }) { - return "\($0) LIKE '\(string!)'" // non null-termination in db - } - return "\($0) = '\(attr)'" - }).joined(separator: " AND ") - guard selectWhere.count > 0 else { return nil } - let selectLimit = attributes[kSecMatchLimit] as? String == kSecMatchLimitOne as String ? 1 : Int.max - - let selectQuery = "SELECT * FROM \(tableName) WHERE \(selectWhere) LIMIT \(selectLimit)" - var stmt: OpaquePointer? - - var dictArr: [NSMutableDictionary] = [] - guard usingDB({ sqlite3DB in - defer { sqlite3_finalize(stmt) } - guard sqlite3_prepare(sqlite3DB, selectQuery, -1, &stmt, nil) == SQLITE_OK, - let stmt = stmt else { - PlayKeychain.debugLogger("Failed query \(selectQuery)") - PlayKeychain.debugLogger("Failed to query to db table: \(String(cString: sqlite3_errmsg(sqlite3DB)))") - return false - } - - while sqlite3_step(stmt) == SQLITE_ROW && dictArr.count < selectLimit { - let newDict: NSMutableDictionary = [:] - let columns = sqlite3_column_count(stmt) - newDict[kSecClass] = tableName - newDict[kSecAttrSynchronizable] = attributes[kSecAttrSynchronizable] - for index in 0.. NSMutableDictionary? { - guard let tableName = attributes[kSecClass] as? String, - let primaryColumns = PlayedAppleDBConstants.primaries[tableName as CFString], - let secondaryColumns = PlayedAppleDBConstants.attributes[tableName as CFString] else { - return nil - } - - var columnsQuery = primaryColumns.map({ "\($0)" }) - columnsQuery.append(contentsOf: secondaryColumns.compactMap({ - attributes[$0] != nil ? "\($0)" : nil - })) - columnsQuery.append(contentsOf: PlayedAppleDBConstants.values.compactMap({ - attributes[$0] != nil ? "\($0)" : nil - })) - - let insertValues = columnsQuery.map({ attributes[$0] as CFTypeRef }) - - let insertColumns = columnsQuery.joined(separator: ", ") - let insertPlaceholders = Array(repeating: "?", count: insertValues.count).joined(separator: ", ") - - let insertQuery = "INSERT INTO \(tableName) (\(insertColumns)) VALUES (\(insertPlaceholders))" - var stmt: OpaquePointer? - - let newDict: NSMutableDictionary = [:] - newDict[kSecClassKey] = tableName - for column in columnsQuery { - newDict[column] = attributes[column] - } - - guard usingDB({ sqlite3DB in - defer { sqlite3_finalize(stmt) } - guard sqlite3_prepare(sqlite3DB, insertQuery, -1, &stmt, nil) == SQLITE_OK, - let stmt = stmt else { - let errorMessage = String(cString: sqlite3_errmsg(sqlite3DB)) - PlayKeychain.debugLogger("Failed query \(insertQuery)") - PlayKeychain.debugLogger("Failed to make query: \(errorMessage)") - return false - } - - for (index, value) in insertValues.enumerated() - where !encodeData(stmt: stmt, index: Int32(index + 1), value: value) { - let erorrMessage = String(cString: sqlite3_errmsg(sqlite3DB)) - PlayKeychain.debugLogger("Failed to insert into db: \(erorrMessage)") - return false - } - - return sqlite3_step(stmt) == SQLITE_DONE - }) else { return nil } - - return newDict - } - - func update(_ attributes: NSDictionary) -> Bool { - guard let tableName = attributes[kSecClass] as? String, - let primaryColumns = PlayedAppleDBConstants.primaries[tableName as CFString], - let secondaryColumns = PlayedAppleDBConstants.attributes[tableName as CFString] else { - return false - } - - var columnsQuery = primaryColumns.map({ "\($0)" }) - columnsQuery.append(contentsOf: secondaryColumns.compactMap({ - attributes[$0] != nil ? "\($0)" : nil - })) - columnsQuery.append(contentsOf: PlayedAppleDBConstants.values.compactMap({ - attributes[$0] != nil ? "\($0)" : nil - })) - - let updateValues = columnsQuery.map({ attributes[$0] as CFTypeRef }) - - let updateColumns = columnsQuery.map({ return "\($0) = ?" }).joined(separator: ", ") - let updateWhere = primaryColumns.compactMap({ - guard let attr = attributes[$0] else { return nil } - if CFGetTypeID(attr as CFTypeRef) == CFDataGetTypeID(), - let string = (attr as? Data).map({ return String(data: $0, encoding: .utf8) }) { - return "\($0) LIKE '\(string!)'" // \0 does not exists in db due to casting - } - return "\($0) = '\(attr)'" - }).joined(separator: " AND ") - - let updateQuery = "UPDATE \(tableName) SET \(updateColumns) WHERE \(updateWhere)" - var stmt: OpaquePointer? - - guard usingDB({ sqlite3DB in - defer { sqlite3_finalize(stmt) } - guard sqlite3_prepare(sqlite3DB, updateQuery, -1, &stmt, nil) == SQLITE_OK, - let stmt = stmt else { - let errorMessage = String(cString: sqlite3_errmsg(sqlite3DB)) - PlayKeychain.debugLogger("Failed query \(updateQuery)") - PlayKeychain.debugLogger("Failed to make query: \(errorMessage)") - return false - } - - for (index, value) in updateValues.enumerated() - where !encodeData(stmt: stmt, index: Int32(index + 1), value: value) { - let errorMessage = String(cString: sqlite3_errmsg(sqlite3DB)) - PlayKeychain.debugLogger("Failed to update into db: \(errorMessage)") - return false - } - - return sqlite3_step(stmt) == SQLITE_DONE - }) else { return false } - - return true - } - - func delete(_ attributes: NSDictionary) -> Bool { - guard let tableName = attributes[kSecClass] as? String, - let primaryColumns = PlayedAppleDBConstants.primaries[tableName as CFString] else { - return false - } - - let deleteWhere = primaryColumns.compactMap({ - guard let attr = attributes[$0] else { return nil } // use only requested ones - if CFGetTypeID(attr as CFTypeRef) == CFDataGetTypeID(), - let string = (attr as? Data).map({ return String(data: $0, encoding: .utf8) }) { - return "\($0) LIKE '\(string!)'" // non null-termination in db - } - return "\($0) = '\(attr)'" - }).joined(separator: " AND ") - - let deleteQuery = "DELETE FROM \(tableName) where \(deleteWhere)" - var stmt: OpaquePointer? - - guard usingDB({ sqlite3DB in - defer { sqlite3_finalize(stmt) } - guard sqlite3_prepare(sqlite3DB, deleteQuery, -1, &stmt, nil) == SQLITE_OK, - let stmt = stmt else { - let errorMessage = String(cString: sqlite3_errmsg(sqlite3DB)) - PlayKeychain.debugLogger("Failed query \(deleteQuery)") - PlayKeychain.debugLogger("Failed to delte items from db table: \(errorMessage)") - return false - } - - return sqlite3_step(stmt) == SQLITE_OK - }) else { return false } - - return true - } - - private func structDB(_ sqlite3DB: OpaquePointer) -> Bool { - for (key, value) in PlayedAppleDBConstants.primaries { - var columns: [CFString] = value - columns.append(contentsOf: PlayedAppleDBConstants.attributes[key]!) - columns.append(contentsOf: PlayedAppleDBConstants.values) - let columnsSetting = columns.map({ return "\($0) TEXT" }).joined(separator: ", ") - let primaryKeysSetting = "PRIMARY KEY (\(value.map({ return "\($0)" }).joined(separator: ", ")))" - let createTableQuery = "CREATE TABLE IF NOT EXISTS \(key) (\(columnsSetting), \(primaryKeysSetting));" - guard sqlite3_exec(sqlite3DB, createTableQuery, nil, nil, nil) == SQLITE_OK else { - let errorMessage = String(cString: sqlite3_errmsg(sqlite3DB)) - PlayKeychain.debugLogger("Failed query \(createTableQuery)") - PlayKeychain.debugLogger("Failed to create db table: \(errorMessage)") - return false - } - } - - sqlite3_exec(sqlite3DB, "PRAGMA user_version = \(dbVersion)", nil, nil, nil) - - return true - } - - private func usingDB(_ callback: (OpaquePointer) -> Bool) -> Bool { - dbLock.wait() - defer { dbLock.signal() } - - guard let sqlite3DB = connectToDB() else { return false } - let result = callback(sqlite3DB) - guard disconnectFromDB(sqlite3DB) else { return false } - return result - } - - private func connectToDB() -> OpaquePointer? { - var sqlite3DB: OpaquePointer? - let bundleID = Bundle.main.infoDictionary?["CFBundleIdentifier"] as? String ?? "Shared" - let keychainDB = URL(fileURLWithPath: "/Users/\(NSUserName())/Library/Containers/io.playcover.PlayCover") - .appendingPathComponent("PlayChain") - .appendingPathComponent("\(bundleID).db") - - let alreadyCreated = FileManager.default.fileExists(atPath: keychainDB.path) - - guard sqlite3_open(keychainDB.path, &sqlite3DB) == SQLITE_OK, - let sqlite3DB = sqlite3DB else { - PlayKeychain.debugLogger("Failed to connect to DB") - return nil - } - - if !alreadyCreated || !structDB(sqlite3DB) { - _ = disconnectFromDB(sqlite3DB) - return nil - } - - return sqlite3DB - } - - private func disconnectFromDB(_ sqlite3DB: OpaquePointer?) -> Bool { - guard sqlite3_close(sqlite3DB) == SQLITE_OK else { - PlayKeychain.debugLogger("Failed to disconnect from DB") - return false - } - - return true - } - - private func encodeData(stmt: OpaquePointer, index: Int32, value: CFTypeRef) -> Bool { - let sqliteTransient = unsafeBitCast(-1, to: sqlite3_destructor_type.self) - var result = SQLITE_FAIL - switch CFGetTypeID(value) { - case CFStringGetTypeID(): - let string = value as! String // swiftlint:disable:this force_cast - result = sqlite3_bind_text(stmt, index, string, -1, sqliteTransient) - case CFDataGetTypeID(): - let data = value as! CFData // swiftlint:disable:this force_cast - let ptr = CFDataGetBytePtr(data) - let size = CFDataGetLength(data) - result = sqlite3_bind_blob(stmt, index, ptr, Int32(size), sqliteTransient) - case CFNullGetTypeID(): - result = sqlite3_bind_null(stmt, index) - default: - PlayKeychain.debugLogger("Cannot encode this data type: \(CFGetTypeID(value))") - result = sqlite3_bind_null(stmt, index) - } - - return result == SQLITE_OK - } - - private func decodeData(stmt: OpaquePointer, index: Int32) -> CFTypeRef? { - switch sqlite3_column_type(stmt, index) { - case SQLITE_TEXT: - guard let ptr = sqlite3_column_text(stmt, index) else { return nil } - return CFStringCreateWithCString(nil, ptr, kCFStringEncodingASCII) - case SQLITE_BLOB: - guard let ptr = sqlite3_column_blob(stmt, index) else { return nil } - let size = sqlite3_column_bytes(stmt, index) - return CFDataCreate(nil, ptr, CFIndex(size)) - case SQLITE_NULL: - return nil - default: - PlayKeychain.debugLogger("Cannot decode this data \(sqlite3_column_type(stmt, index))") - return nil - } - } -} diff --git a/PlayTools/MysticRunes/PlayedAppleDBConstants.swift b/PlayTools/MysticRunes/PlayedAppleDBConstants.swift deleted file mode 100644 index c1f1533d..00000000 --- a/PlayTools/MysticRunes/PlayedAppleDBConstants.swift +++ /dev/null @@ -1,115 +0,0 @@ -// -// PlayedAppleDBConstants.swift -// PlayTools -// -// Created by TheMoonThatRises on 9/12/24. -// - -struct PlayedAppleDBConstants { - // https://developer.apple.com/documentation/security/keychain_services/keychain_items/item_class_keys_and_values - // Synchronizable does not matter. - static let primaries = [ - kSecClassGenericPassword: [ - kSecAttrAccessGroup, - kSecAttrAccount, - kSecAttrService - // kSecAttrSynchronizable - ], - kSecClassInternetPassword: [ - kSecAttrAccessGroup, - kSecAttrAccount, - kSecAttrAuthenticationType, - kSecAttrPath, - kSecAttrPort, - kSecAttrProtocol, - kSecAttrSecurityDomain, - kSecAttrServer - // kSecAttrSynchronizable - ], - kSecClassCertificate: [ - kSecAttrAccessGroup, - kSecAttrCertificateType, - kSecAttrIssuer, - kSecAttrSerialNumber - // kSecAttrSynchronizable - ], - kSecClassKey: [ - kSecAttrAccessGroup, - kSecAttrApplicationLabel, - kSecAttrApplicationTag, - kSecAttrEffectiveKeySize, - kSecAttrKeyClass, - kSecAttrKeySizeInBits, - kSecAttrKeyType - // kSecAttrSynchronizable - ], - kSecClassIdentity: [ - kSecAttrAccessGroup, - kSecAttrCertificateType, - kSecAttrIssuer, - kSecAttrSerialNumber - // kSecAttrSynchronizable - ] - ] - static let attributes = [ - kSecClassGenericPassword: [ - kSecAttrAccessControl, - kSecAttrAccessible, - kSecAttrCreationDate, - kSecAttrModificationDate, - kSecAttrDescription, - kSecAttrComment, - kSecAttrCreator, - kSecAttrType, - kSecAttrLabel, - kSecAttrIsInvisible, - kSecAttrIsNegative, - kSecAttrGeneric - ], - kSecClassInternetPassword: [ - kSecAttrAccessControl, - kSecAttrAccessible, - kSecAttrCreationDate, - kSecAttrModificationDate, - kSecAttrDescription, - kSecAttrComment, - kSecAttrCreator, - kSecAttrType, - kSecAttrLabel, - kSecAttrIsInvisible, - kSecAttrIsNegative, - kSecAttrGeneric - ], - kSecClassCertificate: [ - kSecAttrCertificateEncoding, - kSecAttrLabel, - kSecAttrSubject, - kSecAttrSubjectKeyID, - kSecAttrPublicKeyHash - ], - kSecClassKey: [ - kSecAttrAccessible, - kSecAttrLabel, - kSecAttrIsPermanent, - kSecAttrCanEncrypt, - kSecAttrCanDecrypt, - kSecAttrCanDerive, - kSecAttrCanSign, - kSecAttrCanVerify, - kSecAttrCanWrap, - kSecAttrCanUnwrap - ], - kSecClassIdentity: [ - kSecAttrCertificateEncoding, - kSecAttrLabel, - kSecAttrSubject, - kSecAttrSubjectKeyID, - kSecAttrPublicKeyHash - ] - ] - static let values = [ - kSecValueData, - kSecValueRef, - kSecValuePersistentRef - ] -} diff --git a/PlayTools/PlayLoader.m b/PlayTools/PlayLoader.m index ca928d69..f66b94c6 100644 --- a/PlayTools/PlayLoader.m +++ b/PlayTools/PlayLoader.m @@ -6,12 +6,20 @@ #include #include #include +#include +#include #import "PlayLoader.h" #import #import #import "NSObject+Swizzle.h" #import +#import +#import +#import +#import + +@import PlayChain; @import MachO; @@ -107,104 +115,117 @@ static int pt_sysctlbyname(const char *name, void *oldp, size_t *oldlenp, void * DYLD_INTERPOSE(pt_sysctlbyname, sysctlbyname) DYLD_INTERPOSE(pt_sysctl, sysctl) -// Interpose Apple Keychain functions (SecItemCopyMatching, SecItemAdd, SecItemUpdate, SecItemDelete) -// This allows us to intercept keychain requests and return our own data +// Interpose Apple Keychain functions. With PlayChain on, they go to the PlayChain core (PlayChain/), +// which is linked statically into this image, so its own Security calls reach the real API. + +#define PC_DEBUG(...) do { if ([[PlaySettings shared] playChainDebugging]) NSLog(@"PC-DEBUG: " __VA_ARGS__); } while (0) + +static void pt_playchain_log(const char *msg) { + NSLog(@"PC-DEBUG: %s", msg); +} + +// A stable, made-up team prefix for the default access group: apps that split `agrp` to find their +// team ID still get a well-formed one. The IPA's real prefix isn't available after re-signing. +static NSString *pt_playchain_default_group(NSString *bundleID) { + static const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + const char *utf8 = bundleID.UTF8String; + uint8_t digest[CC_SHA256_DIGEST_LENGTH]; + CC_SHA256(utf8, (CC_LONG)strlen(utf8), digest); + char prefix[11] = {0}; + for (int i = 0; i < 10; i++) prefix[i] = alphabet[digest[i] % 32]; + return [NSString stringWithFormat:@"%s.%@", prefix, bundleID]; +} + +// Configured on first use rather than at load, since keychain calls can arrive before PlayTools' setup. +static void pt_playchain_configure(void) { + static dispatch_once_t once; + dispatch_once(&once, ^{ + NSString *bundleID = NSBundle.mainBundle.bundleIdentifier ?: @"Shared"; + // Fresh database next to the old .db, which is left untouched. + NSString *path = [NSString stringWithFormat:@"/Users/%@/Library/Containers/io.playcover.PlayCover/PlayChain/%@.v2.db", + NSUserName(), bundleID]; + NSString *group = pt_playchain_default_group(bundleID); + pc_config_t config = { + .db_path = path.fileSystemRepresentation, + .default_group = (__bridge CFStringRef)group, + .groups = NULL, + .log = [[PlaySettings shared] playChainDebugging] ? pt_playchain_log : NULL, + }; + pc_configure(&config); + }); +} -// Use the implementations from PlayKeychain static OSStatus pt_SecItemCopyMatching(CFDictionaryRef query, CFTypeRef *result) { - OSStatus retval; + OSStatus status; if ([[PlaySettings shared] playChain]) { - retval = [PlayKeychain copyMatching:(__bridge NSDictionary * _Nonnull)(query) result:result]; + pt_playchain_configure(); + status = pc_SecItemCopyMatching(query, result); } else { - retval = SecItemCopyMatching(query, result); + status = SecItemCopyMatching(query, result); } - if (result != NULL) { - if ([[PlaySettings shared] playChainDebugging]) { - [PlayKeychain debugLogger:[NSString stringWithFormat:@"SecItemCopyMatching: %@", query]]; - [PlayKeychain debugLogger:[NSString stringWithFormat:@"SecItemCopyMatching result: %@", *result]]; - } - } - return retval; + PC_DEBUG(@"SecItemCopyMatching %@ → %d, %@", query, (int)status, result ? (__bridge id)*result : nil); + return status; } static OSStatus pt_SecItemAdd(CFDictionaryRef attributes, CFTypeRef *result) { - OSStatus retval; + OSStatus status; if ([[PlaySettings shared] playChain]) { - retval = [PlayKeychain add:(__bridge NSDictionary * _Nonnull)(attributes) result:result]; + pt_playchain_configure(); + status = pc_SecItemAdd(attributes, result); } else { - retval = SecItemAdd(attributes, result); + status = SecItemAdd(attributes, result); } - if (result != NULL) { - if ([[PlaySettings shared] playChainDebugging]) { - [PlayKeychain debugLogger: [NSString stringWithFormat:@"SecItemAdd: %@", attributes]]; - [PlayKeychain debugLogger: [NSString stringWithFormat:@"SecItemAdd result: %@", *result]]; - } - } - return retval; + PC_DEBUG(@"SecItemAdd %@ → %d, %@", attributes, (int)status, result ? (__bridge id)*result : nil); + return status; } static OSStatus pt_SecItemUpdate(CFDictionaryRef query, CFDictionaryRef attributesToUpdate) { - OSStatus retval; + OSStatus status; if ([[PlaySettings shared] playChain]) { - retval = [PlayKeychain update:(__bridge NSDictionary * _Nonnull)(query) attributesToUpdate:(__bridge NSDictionary * _Nonnull)(attributesToUpdate)]; + pt_playchain_configure(); + status = pc_SecItemUpdate(query, attributesToUpdate); } else { - retval = SecItemUpdate(query, attributesToUpdate); + status = SecItemUpdate(query, attributesToUpdate); } - if (attributesToUpdate != NULL) { - if ([[PlaySettings shared] playChainDebugging]) { - [PlayKeychain debugLogger: [NSString stringWithFormat:@"SecItemUpdate: %@", query]]; - [PlayKeychain debugLogger: [NSString stringWithFormat:@"SecItemUpdate attributesToUpdate: %@", attributesToUpdate]]; - } - } - return retval; - + PC_DEBUG(@"SecItemUpdate %@ with %@ → %d", query, attributesToUpdate, (int)status); + return status; } static OSStatus pt_SecItemDelete(CFDictionaryRef query) { - OSStatus retval; + OSStatus status; if ([[PlaySettings shared] playChain]) { - retval = [PlayKeychain delete:(__bridge NSDictionary * _Nonnull)(query)]; + pt_playchain_configure(); + status = pc_SecItemDelete(query); } else { - retval = SecItemDelete(query); + status = SecItemDelete(query); } - if ([[PlaySettings shared] playChainDebugging]) { - [PlayKeychain debugLogger: [NSString stringWithFormat:@"SecItemDelete: %@", query]]; - } - return retval; + PC_DEBUG(@"SecItemDelete %@ → %d", query, (int)status); + return status; } static SecKeyRef pt_SecKeyCreateRandomKey(CFDictionaryRef parameters, CFErrorRef *error) { - SecKeyRef result; + SecKeyRef key; if ([[PlaySettings shared] playChain]) { - result = [PlayKeychain keyCreateRandomKey:(__bridge NSDictionary * _Nonnull)(parameters) error:error]; + pt_playchain_configure(); + key = pc_SecKeyCreateRandomKey(parameters, error); } else { - result = SecKeyCreateRandomKey(parameters, (void *)error); + key = SecKeyCreateRandomKey(parameters, error); } - - if ([[PlaySettings shared] playChainDebugging]) { - [PlayKeychain debugLogger: [NSString stringWithFormat:@"SecKeyCreateRandomKey: %@", parameters]]; - [PlayKeychain debugLogger: [NSString stringWithFormat:@"SecKeyCreateRandomKey result: %@", result]]; - } - - return result; + PC_DEBUG(@"SecKeyCreateRandomKey %@ → %@", parameters, (__bridge id)key); + return key; } // Deprecated, but some apps might still use it. static OSStatus pt_SecKeyGeneratePair(CFDictionaryRef parameters, SecKeyRef *publicKey, SecKeyRef *privateKey) { - OSStatus retval; + OSStatus status; if ([[PlaySettings shared] playChain]) { - retval = [PlayKeychain keyGeneratePair:(__bridge NSDictionary * _Nonnull)(parameters) publicKey:(void *)publicKey privateKey:(void *)privateKey]; + pt_playchain_configure(); + status = pc_SecKeyGeneratePair(parameters, publicKey, privateKey); } else { - retval = SecKeyGeneratePair(parameters, (void *)publicKey, (void *)privateKey); + status = SecKeyGeneratePair(parameters, publicKey, privateKey); } - - if ([[PlaySettings shared] playChainDebugging]) { - [PlayKeychain debugLogger: [NSString stringWithFormat:@"SecKeyGeneratePair: %@", parameters]]; - [PlayKeychain debugLogger: [NSString stringWithFormat:@"SecKeyGeneratePair public key result: %@", publicKey != NULL ? *publicKey : nil]]; - [PlayKeychain debugLogger: [NSString stringWithFormat:@"SecKeyGeneratePair private key result: %@", privateKey != NULL ? *privateKey : nil]]; - } - - return retval; + PC_DEBUG(@"SecKeyGeneratePair %@ → %d", parameters, (int)status); + return status; } DYLD_INTERPOSE(pt_SecItemCopyMatching, SecItemCopyMatching) @@ -214,6 +235,41 @@ static OSStatus pt_SecKeyGeneratePair(CFDictionaryRef parameters, SecKeyRef *pub DYLD_INTERPOSE(pt_SecKeyCreateRandomKey, SecKeyCreateRandomKey) DYLD_INTERPOSE(pt_SecKeyGeneratePair, SecKeyGeneratePair) +// iOS-only memory entitlements have no macOS meaning (no jetsam limit to raise), so claim them. +// SecTask isn't in the iOS SDK headers but Security exports it. +typedef struct CF_BRIDGED_TYPE(id) __SecTask *SecTaskRef; +CFTypeRef SecTaskCopyValueForEntitlement(SecTaskRef task, CFStringRef entitlement, CFErrorRef *error); +CFDictionaryRef SecTaskCopyValuesForEntitlements(SecTaskRef task, CFArrayRef entitlements, CFErrorRef *error); + +static bool pt_isSpoofedEntitlement(CFStringRef key) { + return key && (CFEqual(key, CFSTR("com.apple.developer.kernel.increased-memory-limit")) || + CFEqual(key, CFSTR("com.apple.developer.kernel.extended-virtual-addressing"))); +} + +static CFTypeRef pt_SecTaskCopyValueForEntitlement(SecTaskRef task, CFStringRef entitlement, CFErrorRef *error) { + if (pt_isSpoofedEntitlement(entitlement)) return kCFBooleanTrue; // CFBoolean constants ignore retain/release + return SecTaskCopyValueForEntitlement(task, entitlement, error); +} + +static CFDictionaryRef pt_SecTaskCopyValuesForEntitlements(SecTaskRef task, CFArrayRef entitlements, CFErrorRef *error) { + CFDictionaryRef real = SecTaskCopyValuesForEntitlements(task, entitlements, error); + if (!entitlements) return real; + CFMutableDictionaryRef out = real ? CFDictionaryCreateMutableCopy(NULL, 0, real) + : CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + bool hadReal = real != NULL; + if (real) CFRelease(real); + for (CFIndex i = 0; i < CFArrayGetCount(entitlements); i++) { + CFStringRef key = CFArrayGetValueAtIndex(entitlements, i); + if (pt_isSpoofedEntitlement(key)) CFDictionarySetValue(out, key, kCFBooleanTrue); + } + if (!hadReal && !CFDictionaryGetCount(out)) { CFRelease(out); return NULL; } // keep the real failure as-is + if (error && *error) { CFRelease(*error); *error = NULL; } + return out; +} + +DYLD_INTERPOSE(pt_SecTaskCopyValueForEntitlement, SecTaskCopyValueForEntitlement) +DYLD_INTERPOSE(pt_SecTaskCopyValuesForEntitlements, SecTaskCopyValuesForEntitlements) + static uint8_t ue_status = 0; static char const* ue_fix_filename(char const* filename) { @@ -327,9 +383,31 @@ static int pt_usleep(useconds_t time) { DYLD_INTERPOSE(pt_unlink, unlink) DYLD_INTERPOSE(pt_usleep, usleep) +static void patchCryptid(void) { + const struct mach_header_64 *mh = (const struct mach_header_64 *)_dyld_get_image_header(0); + if (!mh || mh->magic != MH_MAGIC_64) return; + const uint8_t *p = (const uint8_t *)(mh + 1); + for (uint32_t i = 0; i < mh->ncmds; i++, p += ((const struct load_command *)p)->cmdsize) { + if (((const struct load_command *)p)->cmd != LC_ENCRYPTION_INFO_64) continue; + struct encryption_info_command_64 *eic = (struct encryption_info_command_64 *)p; + if (eic->cryptid) return; + vm_address_t addr = (vm_address_t)&eic->cryptid; + kern_return_t kr = vm_protect(mach_task_self(), addr, sizeof(eic->cryptid), false, + VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY); + if (kr != KERN_SUCCESS) { + NSLog(@"[PlayTools] cryptid patch: vm_protect failed %#x", kr); + return; + } + eic->cryptid = 1; + vm_protect(mach_task_self(), addr, sizeof(eic->cryptid), false, VM_PROT_READ | VM_PROT_EXECUTE); + return; + } +} + @implementation PlayLoader static void __attribute__((constructor)) initialize(void) { + patchCryptid(); [PlayCover launch]; if (ue_status == 0) { @@ -339,7 +417,7 @@ static void __attribute__((constructor)) initialize(void) { } if (ue_status == 2) { - [PlayKeychain debugLogger: [NSString stringWithFormat:@"UnrealEngine Hooked"]]; + PC_DEBUG(@"UnrealEngine Hooked"); } if ([[PlaySettings shared] blockSleepSpamming]) {