diff --git a/README-NG.md b/README-NG.md index a51c8e2..2a9b5f4 100644 --- a/README-NG.md +++ b/README-NG.md @@ -150,6 +150,10 @@ What that means for AltServer-Linux: Verified on 2026-10-27: with this anisette, AltStore Classic signed in to a new free Apple ID through AltServer-Linux and installed an app on iOS 27. +**Since 2026-11-05 Apple answers `mac-ani.jkcoxson.com`'s identity with `-80043`**, even for a made-up +account. `https://new.ani.sidestore.io` provides Mac anisette with the same client info and is now the +default anisette server, spoken to with the v3 protocol (Fix 8). + **Protect your Apple account.** Repeated failed sign-ins make Apple lock the account. While these errors were being worked out, the maintainer's account was locked twice in four days. Stop after one or two failures and find the cause first. After a lock or a password reset Apple can answer @@ -158,6 +162,87 @@ during that period. If `iforgot.apple.com` says the account cannot be unlocked o Settings on an Apple device that is signed in with it. Use a separate free Apple ID for sideloading, so a lock never hits your main account. +## Fix 7 — SMS codes for accounts without a trusted device + +An Apple ID with no trusted Apple device gets its verification code by SMS. GrandSlam then answers +the password step with `au` = `secondaryAuth`. AltSign recognised only `trustedDeviceSecondaryAuth`, so +it treated such an account as having no two-factor authentication and the sign-in failed later. + +`AltSign/AppleAPI+Authentication.cpp` now requests the code by SMS and validates it with the JSON +endpoints that rileytestut/AltSign#62 proposes and [isideload](https://github.com/nab138/isideload) uses: +`PUT /auth/verify/phone` with `{"phoneNumber":{"id":1},"mode":"sms"}`, then +`POST /auth/verify/phone/securitycode` with the code. The code goes to the account's first trusted +phone number (id 1). AltServer prints `Enter two factor code` and reads the code from standard input. +If Apple says a code was already sent and is still valid (HTTP 412, or `-22979` / `-22981`), no new +SMS is requested. A wrong code is `-21669`; any other error, also inside a 2xx answer, shows Apple's +message. + +GrandSlam does not always report such an account as `secondaryAuth`. On 2026-11-05 an account without +a trusted device got `trustedDeviceSecondaryAuth`: the trusted-device code request made Apple send an +SMS, the trusted-device validation answered that code with HTTP 200, and the second sign-in still +required two-factor authentication. + +So the method is chosen from the account's 2FA info. `ALTSERVER_2FA` selects it: + +- `auto` (default): when a code is needed, AltServer reads the 2FA info (`GET /auth`, which sends + nothing). With `noTrustedDevices` it takes the SMS path for the `trustedPhoneNumber`. Apple sends that + SMS on its own, so AltServer requests no second one. `au` = `secondaryAuth` also takes the SMS path, + requesting the code with `PUT`. Any other account keeps the trusted-device path. `pushMode` doesn't + decide, because it is `sms` for the phone numbers of trusted-device accounts too. +- `sms`: always the SMS path, requesting the code with `PUT`. +- `trusteddevice`: the trusted-device path, as before Fix 7, except for `au` = `secondaryAuth`, which + has no trusted device to send a code to. + +At the SMS code prompt, `resend` requests one new SMS, for when the expected one doesn't arrive. The +log shows `au` and `hsc` of the sign-in response, the 2FA info (without the phone number), the chosen +method and which SMS code to enter. + +Apple ties the code to the anisette identity it was validated with. `new.ani.sidestore.io` returns a new +identity (Device-Id, MD-LU, MD-M) on every request, so the anisette refreshes added in Fix 4 made the +second sign-in come from another device than the one that validated the code. A refresh is now used only +when it returns the same device; otherwise the sign-in keeps its original anisette data. The log names +the Device-Id (first 8 characters) at each step. With such a server every sign-in is still a new device +to Apple, so it asks for a code every time. + +Verified on 2026-11-05: an account without trusted devices signed in with `ALTSERVER_2FA=sms` and +v1 anisette from `new.ani.sidestore.io`, and AltServer installed an app. The `auto` choice has not been +tried against Apple yet. If a sign-in fails, stop and read the log before trying again; see the +account-lock warning above. + +## Fix 8 — anisette v3: one identity, a code only once + +A v1 anisette server (`GET /`) hands out whatever identity it likes. `new.ani.sidestore.io` hands out a +new one on every request, so Apple sees a new device at every sign-in and asks for a code each time. +An anisette v3 server provisions one identity instead, and the identity's keychain identifier and +`adi.pb` stay on this computer. After the first sign-in with a code, Apple knows the device. + +`src/AnisetteV3.cpp` speaks SideStore's anisette-v3-server protocol, as omnisette and Sideloader do: +`GET /v3/client_info`, provisioning over the `/v3/provisioning_session` websocket with Apple's +`midStartProvisioning` and `midFinishProvisioning` (relayed by this computer as the device), and +`POST /v3/get_headers` for each set of anisette data. The identity is kept in +`$XDG_CONFIG_HOME/AltServer/anisette-v3/.json` (default `~/.config/...`), readable by its owner +only. A port or path in the server URL is added to the file name. Delete that file to start over with a +new identity. The v3 client's requests (anisette server and provisioning) honour `HTTPS_PROXY`, +`HTTP_PROXY` and `NO_PROXY`; the v1 client and the Apple sign-in itself do not use a proxy. + +`ALTSERVER_ANISETTE_PROTOCOL` selects the protocol: `auto` (default) uses v3 when the server answers +`/v3/client_info` and v1 otherwise; `v3` and `v1` force one. A server that can't be reached is an +error, not a reason to fall back to v1. The log shows the protocol, whether the identity was +provisioned or loaded, and the first 8 characters of its device ID. + +AltStore receives the same identity when it asks AltServer for anisette data. + +Verified on 2026-11-05 against `new.ani.sidestore.io` with a made-up account: the first run provisioned +an identity and saved it (mode 600), the second run reused it without provisioning, and both times +Apple answered the password step with `-20970`, so the v3 anisette passed every check before it. + +## Log output + +The log, with or without `-d`, shows the steps, status codes, `au`/`hsc` and the first 8 characters +of the anisette device ID. It does not show passwords, verification codes, GSA tokens, the decrypted +sign-in response or anisette secrets (one-time password, machine ID, local user ID, `adi.pb`). `-d` +also turns on libimobiledevice's own debug output for the device connection. + ## Prebuilt binaries Static binaries for x86_64, aarch64, armv7 and i586 are attached to the @@ -181,24 +266,26 @@ docker run --rm --platform linux/amd64 -v "$PWD:/workdir" -w /workdir \ The result is a statically linked `build/AltServer-x86_64`. Other architectures use the `altserver_builder_alpine_{aarch64,armv7,i386}` images. -Sanity-check that all three fixes are present: +Sanity-check that the fixes are present: ```bash strings build/AltServer-x86_64 | grep -c "missing path separator" # Fix 1, new ldid -> 1 strings build/AltServer-x86_64 | grep -c "Sanitized client info" # Fix 2, sign-in -> 1 grep -c idevice_sockaddr_len libraries/libimobiledevice/src/idevice.c # Fix 3, netmuxd -> >= 1 +strings build/AltServer-x86_64 | grep -c "noTrustedDevices" # Fix 7, 2FA choice -> >= 1 +strings build/AltServer-x86_64 | grep -c "/v3/provisioning_session" # Fix 8, anisette v3 -> 1 ``` ## Running ```bash USBMUXD_SOCKET_ADDRESS=127.0.0.1:27015 \ -ALTSERVER_ANISETTE_SERVER=https://mac-ani.jkcoxson.com \ ./AltServer-x86_64 -d -u -a -p AltStore.ipa ``` -`-d` enables debug output. Wi-Fi installs need netmuxd listening on that address (see Fix 3). Any -anisette server that provides Mac anisette works; see Fix 5 before you choose one. +`-d` enables debug output. Wi-Fi installs need netmuxd listening on that address (see Fix 3). The +default anisette server is `https://new.ani.sidestore.io` with the v3 protocol (Fix 8); +`ALTSERVER_ANISETTE_SERVER` selects another one, which must provide Mac anisette (Fix 5). To check sign-in without real credentials, run it with a throwaway account. HTTP 503 means Apple's edge is blocking, `-80045` means the client info does not match the anisette provisioning (Fix 4), diff --git a/src/AnisetteDataManager.cpp b/src/AnisetteDataManager.cpp index 4eab8ad..563aae9 100644 --- a/src/AnisetteDataManager.cpp +++ b/src/AnisetteDataManager.cpp @@ -4,6 +4,8 @@ #include "Error.hpp" #include "ServerError.hpp" +#include +#include #include #include #include @@ -12,6 +14,7 @@ #include "AnisetteData.h" #include "AltServerApp.h" +#include "AnisetteV3.h" #define odslog(msg) { std::stringstream ss; ss << msg << std::endl; OutputDebugStringA(ss.str().c_str()); } @@ -53,10 +56,11 @@ using namespace web::http::client; // HTTP client features std::string GetAnisetteURL() { const char *server = getenv("ALTSERVER_ANISETTE_SERVER"); - if (server) { + if (server && strlen(server) > 0) { return server; } - return U("https://armconverter.com/anisette/irGb3Quww8zrhgqnzmrx"); + // Provides Mac anisette (README-NG, Fix 5) and speaks anisette v3 (Fix 8). + return U("https://new.ani.sidestore.io"); } // Apple rejects any gsa.apple.com request whose X-Mme-Client-Info (aka @@ -80,18 +84,76 @@ std::string SanitizeClientInfo(const std::string& clientInfo) return result; } -std::shared_ptr AnisetteDataManager::FetchAnisetteData() +// Client info sent to Apple as X-Mme-Client-Info (and handed to AltStore with the anisette data). +// Default: the anisette server's own value. Since 2026-10-21 Apple accepts only a client info that +// matches the platform the anisette data was provisioned as, and only Mac anisette at the 2FA/apptokens +// steps (README-NG, Fix 5). ALTSERVER_CLIENT_INFO overrides it: "windows" selects the Windows AuthKit +// identity AltServer for Windows uses, any other non-empty value is sent as is. Any value still goes +// through SanitizeClientInfo, because gsa.apple.com rejects every client info containing com.apple.dt.Xcode. +std::string FilterClientInfo(const std::string& serverClientInfo) { - // auto client = web::http::client::http_client(U("https://armconverter.com")); - // std::string wideURI = ("/anisette/irGb3Quww8zrhgqnzmrx"); - - // auto encodedURI = web::uri::encode_uri(wideURI); - // uri_builder builder(encodedURI); + std::string clientInfo = serverClientInfo; + const char* envClientInfo = getenv("ALTSERVER_CLIENT_INFO"); + if (envClientInfo && strlen(envClientInfo) > 0) + { + std::string value(envClientInfo); + if (value == "windows") + { + clientInfo = " "; + } + else if (value != "anisette" && value != "original") + { + clientInfo = value; + } + } - // http_request request(methods::GET); - // request.set_request_uri(builder.to_string()); + std::string sanitizedClientInfo = SanitizeClientInfo(clientInfo); + odslog("Sanitized client info: " << sanitizedClientInfo); + return sanitizedClientInfo; +} + +// ALTSERVER_ANISETTE_PROTOCOL: "v3", "v1", or "auto" (the default), which uses v3 when the server answers +// /v3/client_info. v3 keeps one provisioned identity on this computer; v1 takes whatever identity the +// server hands out, which for some servers (new.ani.sidestore.io) is a new one on every request. +bool UsesAnisetteV3(const std::string& serverURL) +{ + const char* value = getenv("ALTSERVER_ANISETTE_PROTOCOL"); + std::string protocol = (value != nullptr && strlen(value) > 0) ? value : "auto"; + + if (protocol == "v3" || protocol == "v1") + { + return protocol == "v3"; + } + + if (protocol != "auto") + { + odslog("Unknown ALTSERVER_ANISETTE_PROTOCOL value " << protocol << ", using auto."); + } - auto client = web::http::client::http_client(GetAnisetteURL()); + static std::mutex mutex; + static std::map supportsV3; + + std::lock_guard lock(mutex); + if (supportsV3.count(serverURL) == 0) + { + supportsV3[serverURL] = AnisetteV3::IsSupported(serverURL); + odslog("Anisette server " << serverURL << ": using " << (supportsV3[serverURL] ? "v3" : "v1") << " (auto)."); + } + + return supportsV3[serverURL]; +} + +std::shared_ptr AnisetteDataManager::FetchAnisetteData() +{ + std::string serverURL = GetAnisetteURL(); + if (UsesAnisetteV3(serverURL)) + { + auto anisetteData = AnisetteV3::FetchAnisetteData(serverURL, FilterClientInfo); + odslog(*anisetteData); + return anisetteData; + } + + auto client = web::http::client::http_client(serverURL); http_request request(methods::GET); std::map headers = { @@ -122,24 +184,8 @@ std::shared_ptr AnisetteDataManager::FetchAnisetteData() }) .then([&anisetteData](pplx::task previousTask) { - odslog("parse anisette data ret"); + // The values are anisette secrets (machine ID, one-time password), so they stay out of the log. json::value jsonVal = previousTask.get(); - odslog("Got anisetteData json: " << jsonVal); - std::vector keys = { - "X-Apple-I-MD-M", - "X-Apple-I-MD", - "X-Apple-I-MD-LU", - "X-Apple-I-MD-RINFO", - "X-Mme-Device-Id", - "X-Apple-I-SRL-NO", - "X-MMe-Client-Info", - "X-Apple-I-Client-Time", - "X-Apple-Locale", - "X-Apple-I-TimeZone" - }; - for (auto &key : keys) { - odslog(key << ": " << jsonVal.at(key).as_string().c_str()); - } // X-Apple-I-Client-Time is UTC, for example 2026-09-26T12:34:56Z. Some anisette servers add // fractional seconds or leave out the Z; both name the same UTC instant. Any other value, @@ -169,32 +215,8 @@ std::shared_ptr AnisetteDataManager::FetchAnisetteData() tv.tv_sec = ts; tv.tv_usec = 0; - // Client info sent to Apple as X-Mme-Client-Info (and handed to AltStore with the - // anisette data). Default: the anisette server's own value. Since 2026-10-21 Apple - // accepts only a client info that matches the platform the anisette data was - // provisioned as, and only Mac anisette at the 2FA/apptokens steps (README-NG, Fix 5). - // ALTSERVER_CLIENT_INFO overrides it: "windows" selects the Windows AuthKit identity - // AltServer for Windows uses, any other non-empty value is sent as is. Any value - // still goes through SanitizeClientInfo, because gsa.apple.com rejects every client - // info containing com.apple.dt.Xcode. - std::string clientInfo = jsonVal.at("X-MMe-Client-Info").as_string(); - const char* envClientInfo = getenv("ALTSERVER_CLIENT_INFO"); - if (envClientInfo && strlen(envClientInfo) > 0) - { - std::string value(envClientInfo); - if (value == "windows") - { - clientInfo = " "; - } - else if (value != "anisette" && value != "original") - { - clientInfo = value; - } - } - std::string sanitizedClientInfo = SanitizeClientInfo(clientInfo); - odslog("Sanitized client info: " << sanitizedClientInfo); + std::string sanitizedClientInfo = FilterClientInfo(jsonVal.at("X-MMe-Client-Info").as_string()); - odslog("Building anisetteData obj..."); anisetteData = std::make_shared( jsonVal.at("X-Apple-I-MD-M").as_string(), jsonVal.at("X-Apple-I-MD").as_string(), diff --git a/src/AnisetteV3.cpp b/src/AnisetteV3.cpp new file mode 100644 index 0000000..af085d7 --- /dev/null +++ b/src/AnisetteV3.cpp @@ -0,0 +1,720 @@ +#include "AnisetteV3.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "AnisetteData.h" +#include "ServerError.hpp" + +#define odslog(msg) { std::stringstream ss; ss << msg << std::endl; OutputDebugStringA(ss.str().c_str()); } + +using namespace web; +using namespace web::http; +using namespace web::http::client; + +// The identity's keychain identifier and adi.pb are as good as a password for this device, and the +// one-time password and machine ID are anisette secrets: none of them goes to the log. The device ID +// is shown by its first 8 characters only. +namespace +{ + std::mutex stateMutex; + + struct ClientInfo + { + std::string clientInfo; + std::string userAgent; + }; + + struct State + { + std::vector identifier; // 16 random bytes + std::vector adiPB; // empty until provisioned + }; + + struct Headers + { + std::string machineID; // X-Apple-I-MD-M + std::string oneTimePassword; // X-Apple-I-MD + std::string routingInfo; // X-Apple-I-MD-RINFO + }; + + ServerError V3Error(std::string message) + { + odslog("Anisette v3: " << message); + return ServerError(ServerErrorCode::InvalidAnisetteData, { + { LocalizedFailureErrorKey, "Anisette v3: " + message } + }); + } + + std::string TrimmedURL(std::string url) + { + while (!url.empty() && url.back() == '/') + { + url.pop_back(); + } + + return url; + } + + // The proxy the environment names for url, for the anisette server and the provisioning requests: + // HTTPS_PROXY for https and wss, HTTP_PROXY for http and ws, unless NO_PROXY lists the host ("*", the + // host itself, or a domain it is in). + std::optional EnvironmentProxy(const std::string& url) + { + uri target(url); + std::string host = target.host(); + + for (const char* name : { "NO_PROXY", "no_proxy" }) + { + const char* value = getenv(name); + if (value == nullptr) + { + continue; + } + + std::stringstream entries(value); + std::string entry; + while (std::getline(entries, entry, ',')) + { + entry.erase(0, entry.find_first_not_of(" \t")); + entry.erase(entry.find_last_not_of(" \t") + 1); + if (!entry.empty() && entry[0] == '.') + { + entry.erase(0, 1); + } + + bool isInDomain = host.size() > entry.size() && host.compare(host.size() - entry.size() - 1, std::string::npos, "." + entry) == 0; + if (entry == "*" || (!entry.empty() && (host == entry || isInDomain))) + { + return std::nullopt; + } + } + } + + bool isSecure = target.scheme() == "https" || target.scheme() == "wss"; + for (const char* name : isSecure ? std::vector{ "HTTPS_PROXY", "https_proxy" } : std::vector{ "HTTP_PROXY", "http_proxy" }) + { + const char* value = getenv(name); + if (value != nullptr && strlen(value) > 0) + { + return web_proxy(uri(value)); + } + } + + return std::nullopt; + } + + http_client MakeClient(std::string url, bool validateCertificates) + { + http_client_config config; + config.set_validate_certificates(validateCertificates); + config.set_timeout(std::chrono::seconds(60)); + if (auto proxy = EnvironmentProxy(url)) + { + config.set_proxy(*proxy); + } + + return http_client(url, config); + } + + std::string Hex(const unsigned char* bytes, size_t length) + { + std::ostringstream stream; + for (size_t i = 0; i < length; i++) + { + stream << std::hex << std::setw(2) << std::setfill('0') << (int)bytes[i]; + } + + return stream.str(); + } + + // X-Apple-I-MD-LU: SHA-256 of the identifier in hex, as omnisette sends it. + std::string LocalUserID(const State& state) + { + unsigned char digest[SHA256_DIGEST_LENGTH]; + SHA256(state.identifier.data(), state.identifier.size(), digest); + return Hex(digest, sizeof(digest)); + } + + // X-Mme-Device-Id: the identifier as an upper-case UUID. + std::string DeviceID(const State& state) + { + std::string hex = Hex(state.identifier.data(), state.identifier.size()); + for (auto& c : hex) + { + c = toupper((unsigned char)c); + } + + return hex.substr(0, 8) + "-" + hex.substr(8, 4) + "-" + hex.substr(12, 4) + "-" + hex.substr(16, 4) + "-" + hex.substr(20, 12); + } + + std::string UTCTime(time_t time) + { + char buffer[32]; + struct tm tm; + gmtime_r(&time, &tm); + strftime(buffer, sizeof(buffer), "%Y-%m-%dT%H:%M:%SZ", &tm); + return buffer; + } + + ClientInfo FetchClientInfo(const std::string& serverURL) + { + static std::mutex mutex; + static std::map clientInfoByURL; + + std::lock_guard lock(mutex); + if (clientInfoByURL.count(serverURL) > 0) + { + return clientInfoByURL[serverURL]; + } + + auto client = MakeClient(serverURL, true); + auto response = client.request(methods::GET, "/v3/client_info").get(); + if (response.status_code() != status_codes::OK) + { + throw V3Error(serverURL + "/v3/client_info answered HTTP " + std::to_string(response.status_code()) + "."); + } + + auto json = response.extract_json(true).get(); + if (!json.has_field("client_info") || !json.at("client_info").is_string() || !json.has_field("user_agent") || !json.at("user_agent").is_string()) + { + throw V3Error(serverURL + "/v3/client_info has no client_info and user_agent."); + } + + clientInfoByURL[serverURL] = { json.at("client_info").as_string(), json.at("user_agent").as_string() }; + return clientInfoByURL[serverURL]; + } + + // /AltServer/anisette-v3/.json, where is $XDG_CONFIG_HOME or ~/.config. A port or + // path in the server URL is added to the name, so each server keeps its own identity. + std::string StateDirectory() + { + const char* xdgConfigHome = getenv("XDG_CONFIG_HOME"); + const char* home = getenv("HOME"); + + std::string base; + if (xdgConfigHome != nullptr && strlen(xdgConfigHome) > 0) + { + base = xdgConfigHome; + } + else if (home != nullptr && strlen(home) > 0) + { + base = std::string(home) + "/.config"; + } + else + { + throw V3Error("Neither XDG_CONFIG_HOME nor HOME is set, so there is nowhere to keep the anisette identity."); + } + + return base + "/AltServer/anisette-v3"; + } + + std::string StatePath(const std::string& serverURL) + { + uri serverURI(serverURL); + std::string name = serverURI.host(); + if (!serverURI.is_port_default()) + { + name += "_" + std::to_string(serverURI.port()); + } + + std::string path = serverURI.path(); + if (path != "" && path != "/") + { + for (auto c : path) + { + name += isalnum((unsigned char)c) || c == '-' || c == '.' ? c : '_'; + } + } + + return StateDirectory() + "/" + name + ".json"; + } + + void MakeDirectories(const std::string& path) + { + for (size_t position = 1; position <= path.size(); position++) + { + if (position == path.size() || path[position] == '/') + { + std::string directory = path.substr(0, position); + if (mkdir(directory.c_str(), 0700) != 0 && errno != EEXIST) + { + throw V3Error("Couldn't create " + directory + ": " + strerror(errno)); + } + } + } + } + + std::optional LoadState(const std::string& path) + { + std::ifstream file(path); + if (!file) + { + return std::nullopt; + } + + try + { + std::stringstream contents; + contents << file.rdbuf(); + auto json = json::value::parse(contents.str()); + + State state; + state.identifier = utility::conversions::from_base64(json.at("identifier").as_string()); + if (json.has_field("adi_pb") && json.at("adi_pb").is_string()) + { + state.adiPB = utility::conversions::from_base64(json.at("adi_pb").as_string()); + } + + if (state.identifier.size() != 16) + { + throw std::runtime_error("identifier isn't 16 bytes"); + } + + return state; + } + catch (std::exception& exception) + { + odslog("Anisette v3: ignoring unreadable " << path << " (" << exception.what() << "), provisioning a new identity."); + return std::nullopt; + } + } + + // Writes the state readable by its owner only (mode 600), replacing the old file in one step. + void SaveState(const std::string& path, const State& state) + { + MakeDirectories(path.substr(0, path.find_last_of('/'))); + + auto json = json::value::object(); + json["identifier"] = json::value::string(utility::conversions::to_base64(state.identifier)); + json["adi_pb"] = json::value::string(utility::conversions::to_base64(state.adiPB)); + std::string contents = json.serialize(); + + std::string temporaryPath = path + ".tmp"; + int fd = open(temporaryPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600); + if (fd < 0) + { + throw V3Error("Couldn't write " + temporaryPath + ": " + strerror(errno)); + } + + fchmod(fd, 0600); + bool written = write(fd, contents.data(), contents.size()) == (ssize_t)contents.size() && fsync(fd) == 0; + close(fd); + + if (!written || rename(temporaryPath.c_str(), path.c_str()) != 0) + { + unlink(temporaryPath.c_str()); + throw V3Error("Couldn't save " + path + ": " + strerror(errno)); + } + } + + std::string PlistString(plist_t dictionary, const char* key) + { + plist_t node = dictionary != nullptr ? plist_dict_get_item(dictionary, key) : nullptr; + if (node == nullptr || plist_get_node_type(node) != PLIST_STRING) + { + return ""; + } + + char* value = nullptr; + plist_get_string_val(node, &value); + std::string result = value != nullptr ? value : ""; + free(value); + return result; + } + + // Sends a provisioning request to Apple as the identity's device and returns the response plist, which + // the caller frees. gsa.apple.com uses Apple's own CA, so like AltSign's GSA client this doesn't validate it. + plist_t AppleRequest(method httpMethod, const std::string& url, plist_t body, const ClientInfo& clientInfo, const State& state) + { + uri requestURI(url); + auto client = MakeClient(requestURI.scheme() + "://" + requestURI.host() + (requestURI.is_port_default() ? "" : ":" + std::to_string(requestURI.port())), false); + + http_request request(httpMethod); + request.set_request_uri(requestURI.resource()); + + if (body != nullptr) + { + char* xml = nullptr; + uint32_t length = 0; + plist_to_xml(body, &xml, &length); + request.set_body(std::string(xml, length), "text/x-xml-plist"); + free(xml); + } + + std::map headers = { + { "X-Mme-Client-Info", clientInfo.clientInfo }, + { "User-Agent", clientInfo.userAgent }, + { "Content-Type", "text/x-xml-plist" }, + { "X-Apple-I-MD-LU", LocalUserID(state) }, + { "X-Mme-Device-Id", DeviceID(state) }, + { "X-Apple-I-Client-Time", UTCTime(time(nullptr)) }, + { "X-Apple-I-TimeZone", "UTC" }, + { "X-Apple-Locale", "en_US" }, + }; + + for (auto& pair : headers) + { + request.headers().remove(pair.first); + request.headers().add(pair.first, pair.second); + } + + auto response = client.request(request).get(); + auto data = response.extract_vector().get(); + + plist_t plist = nullptr; + if (!data.empty()) + { + plist_from_memory((const char*)data.data(), (uint32_t)data.size(), &plist); + } + + if (response.status_code() != status_codes::OK || plist == nullptr || plist_get_node_type(plist) != PLIST_DICT) + { + if (plist != nullptr) + { + plist_free(plist); + } + + throw V3Error(requestURI.path() + " answered HTTP " + std::to_string(response.status_code()) + "."); + } + + return plist; + } + + // Apple's answer to midStartProvisioning or midFinishProvisioning: the Response dictionary's keys. + std::map ProvisioningResponse(const std::string& url, plist_t requestBody, std::vector keys, const ClientInfo& clientInfo, const State& state) + { + plist_t plist = AppleRequest(methods::POST, url, requestBody, clientInfo, state); + plist_t response = plist_dict_get_item(plist, "Response"); + + std::map values; + for (auto& key : keys) + { + values[key] = PlistString(response, key.c_str()); + } + + plist_t status = response != nullptr ? plist_dict_get_item(response, "Status") : nullptr; + std::string message = PlistString(status, "em"); + plist_free(plist); + + for (auto& key : keys) + { + if (values[key].empty()) + { + throw V3Error("Apple's provisioning answer has no " + key + (message.empty() ? "." : ": " + message)); + } + } + + return values; + } + + plist_t ProvisioningBody(std::map request) + { + plist_t body = plist_new_dict(); + plist_dict_set_item(body, "Header", plist_new_dict()); + + plist_t requestDictionary = plist_new_dict(); + for (auto& pair : request) + { + plist_dict_set_item(requestDictionary, pair.first.c_str(), plist_new_string(pair.second.c_str())); + } + plist_dict_set_item(body, "Request", requestDictionary); + + return body; + } + + std::string ReceiveText(web::websockets::client::websocket_client& connection) + { + auto task = connection.receive(); + + auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(60); + while (!task.is_done()) + { + if (std::chrono::steady_clock::now() > deadline) + { + connection.close().wait(); + throw V3Error("The provisioning session timed out."); + } + + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } + + auto message = task.get(); + if (message.message_type() != web::websockets::client::websocket_message_type::text_message) + { + throw V3Error("The provisioning session ended early."); + } + + return message.extract_string().get(); + } + + void SendJSON(web::websockets::client::websocket_client& connection, std::map fields) + { + auto json = json::value::object(); + for (auto& pair : fields) + { + json[pair.first] = json::value::string(pair.second); + } + + web::websockets::client::websocket_outgoing_message message; + message.set_utf8_message(json.serialize()); + connection.send(message).wait(); + } + + void RunProvisioningSession(web::websockets::client::websocket_client& connection, const std::string& startURL, const std::string& finishURL, const ClientInfo& clientInfo, State& state); + + // Provisions the identity: the server drives Apple's midStartProvisioning/midFinishProvisioning over + // the /v3/provisioning_session websocket, and this computer relays the Apple requests as the device. + void Provision(const std::string& serverURL, const ClientInfo& clientInfo, State& state) + { + odslog("Anisette v3: provisioning device " << DeviceID(state).substr(0, 8) << " with " << serverURL << "..."); + + plist_t lookup = AppleRequest(methods::GET, "https://gsa.apple.com/grandslam/GsService2/lookup", nullptr, clientInfo, state); + plist_t urls = plist_dict_get_item(lookup, "urls"); + std::string startURL = PlistString(urls, "midStartProvisioning"); + std::string finishURL = PlistString(urls, "midFinishProvisioning"); + plist_free(lookup); + + if (startURL.empty() || finishURL.empty()) + { + throw V3Error("Apple's lookup has no provisioning URLs."); + } + + std::string socketURL = serverURL + "/v3/provisioning_session"; + if (socketURL.rfind("https://", 0) == 0) + { + socketURL.replace(0, 8, "wss://"); + } + else if (socketURL.rfind("http://", 0) == 0) + { + socketURL.replace(0, 7, "ws://"); + } + + web::websockets::client::websocket_client_config config; + if (auto proxy = EnvironmentProxy(socketURL)) + { + config.set_proxy(*proxy); + } + + web::websockets::client::websocket_client connection(config); + connection.connect(socketURL).wait(); + + try + { + RunProvisioningSession(connection, startURL, finishURL, clientInfo, state); + connection.close().wait(); + } + catch (...) + { + // Close the session on every failure, so the server isn't left waiting for its timeout. + try + { + connection.close().wait(); + } + catch (...) + { + } + + throw; + } + + if (state.adiPB.empty()) + { + throw V3Error("The server's provisioning result has no adi.pb."); + } + + odslog("Anisette v3: provisioned device " << DeviceID(state).substr(0, 8) << "."); + } + + // The /v3/provisioning_session conversation, until the server sends the provisioned adi.pb. + void RunProvisioningSession(web::websockets::client::websocket_client& connection, const std::string& startURL, const std::string& finishURL, const ClientInfo& clientInfo, State& state) + { + while (true) + { + auto message = json::value::parse(ReceiveText(connection)); + std::string result = message.has_field("result") && message.at("result").is_string() ? message.at("result").as_string() : ""; + + if (result == "GiveIdentifier") + { + SendJSON(connection, { { "identifier", utility::conversions::to_base64(state.identifier) } }); + } + else if (result == "GiveStartProvisioningData") + { + plist_t body = ProvisioningBody({}); + auto response = ProvisioningResponse(startURL, body, { "spim" }, clientInfo, state); + plist_free(body); + + SendJSON(connection, { { "spim", response["spim"] } }); + } + else if (result == "GiveEndProvisioningData" && message.has_field("cpim") && message.at("cpim").is_string()) + { + plist_t body = ProvisioningBody({ { "cpim", message.at("cpim").as_string() } }); + auto response = ProvisioningResponse(finishURL, body, { "ptm", "tk" }, clientInfo, state); + plist_free(body); + + SendJSON(connection, { { "ptm", response["ptm"] }, { "tk", response["tk"] } }); + } + else if (result == "ProvisioningSuccess" && message.has_field("adi_pb") && message.at("adi_pb").is_string()) + { + state.adiPB = utility::conversions::from_base64(message.at("adi_pb").as_string()); + return; + } + else + { + std::string detail = message.has_field("message") && message.at("message").is_string() ? ": " + message.at("message").as_string() : ""; + throw V3Error("Provisioning failed, the server answered " + (result.empty() ? std::string("without a result") : result) + detail + "."); + } + } + } + + // Headers from /v3/get_headers, or nothing when the server says the identity isn't provisioned (-45061). + std::optional FetchHeaders(const std::string& serverURL, const State& state) + { + auto body = json::value::object(); + body["identifier"] = json::value::string(utility::conversions::to_base64(state.identifier)); + body["adi_pb"] = json::value::string(utility::conversions::to_base64(state.adiPB)); + + auto client = MakeClient(serverURL, true); + auto response = client.request(methods::POST, "/v3/get_headers", body).get(); + + json::value json; + try + { + json = response.extract_json(true).get(); + } + catch (json::json_exception&) + { + throw V3Error(serverURL + "/v3/get_headers answered HTTP " + std::to_string(response.status_code()) + " without JSON."); + } + + std::string result = json.has_field("result") && json.at("result").is_string() ? json.at("result").as_string() : ""; + if (result == "Headers") + { + for (auto key : { "X-Apple-I-MD-M", "X-Apple-I-MD", "X-Apple-I-MD-RINFO" }) + { + if (!json.has_field(key) || !json.at(key).is_string()) + { + throw V3Error(serverURL + "/v3/get_headers answered without " + key + "."); + } + } + + return Headers{ json.at("X-Apple-I-MD-M").as_string(), json.at("X-Apple-I-MD").as_string(), json.at("X-Apple-I-MD-RINFO").as_string() }; + } + + std::string message = json.has_field("message") && json.at("message").is_string() ? json.at("message").as_string() : ""; + if (result == "GetHeadersError" && message.find("-45061") != std::string::npos) + { + return std::nullopt; + } + + throw V3Error(serverURL + "/v3/get_headers answered HTTP " + std::to_string(response.status_code()) + " " + result + (message.empty() ? "" : ": " + message) + "."); + } +} + +bool AnisetteV3::IsSupported(const std::string& serverURL) +{ + try + { + FetchClientInfo(TrimmedURL(serverURL)); + return true; + } + catch (ServerError& error) + { + // The server answered, but not with v3 client info. + return false; + } + catch (web::json::json_exception& exception) + { + return false; + } +} + +std::shared_ptr AnisetteV3::FetchAnisetteData(const std::string& serverURL, std::function clientInfoFilter) +{ + std::lock_guard lock(stateMutex); + + std::string url = TrimmedURL(serverURL); + + ClientInfo clientInfo = FetchClientInfo(url); + + // Provisioning goes to Apple too, so it already sends the client info Apple will see later. + clientInfo.clientInfo = clientInfoFilter(clientInfo.clientInfo); + + std::string path = StatePath(url); + auto savedState = LoadState(path); + + State state; + if (savedState.has_value()) + { + state = *savedState; + } + else + { + state.identifier.resize(16); + if (RAND_bytes(state.identifier.data(), (int)state.identifier.size()) != 1) + { + throw V3Error("Couldn't generate a random identifier for a new identity."); + } + } + + if (state.adiPB.empty()) + { + Provision(url, clientInfo, state); + SaveState(path, state); + odslog("Anisette v3: saved the identity to " << path << "."); + } + + auto headers = FetchHeaders(url, state); + if (!headers.has_value()) + { + odslog("Anisette v3: the server no longer accepts device " << DeviceID(state).substr(0, 8) << ", provisioning it again."); + state.adiPB.clear(); + Provision(url, clientInfo, state); + SaveState(path, state); + + headers = FetchHeaders(url, state); + if (!headers.has_value()) + { + throw V3Error("The server rejects the identity right after provisioning it."); + } + } + + odslog("Anisette v3: headers for device " << DeviceID(state).substr(0, 8) << "."); + + struct timeval now = { 0 }; + now.tv_sec = time(nullptr); + + return std::make_shared( + headers->machineID, + headers->oneTimePassword, + LocalUserID(state), + std::strtoull(headers->routingInfo.c_str(), nullptr, 10), + DeviceID(state), + "0", + clientInfo.clientInfo, + now, + "en_US", + "UTC"); +} diff --git a/src/AnisetteV3.h b/src/AnisetteV3.h new file mode 100644 index 0000000..93689f4 --- /dev/null +++ b/src/AnisetteV3.h @@ -0,0 +1,22 @@ +#pragma once + +#include +#include +#include + +class AnisetteData; + +// Client for anisette v3 servers (SideStore's anisette-v3-server protocol, as omnisette's +// remote_anisette_v3.rs and Sideloader speak it). The server provisions an identity once, and its +// keychain identifier and adi.pb stay on this computer, so Apple sees the same device at every +// sign-in instead of a new one each time. +namespace AnisetteV3 +{ + // Whether serverURL answers GET /v3/client_info. A server that answers without v3 support gives false; + // a server that can't be reached throws, so a network problem doesn't quietly select v1. + bool IsSupported(const std::string& serverURL); + + // Anisette data for this computer's identity on serverURL, provisioned first if there is none yet. + // clientInfoFilter turns the server's client info into the X-Mme-Client-Info sent to Apple. + std::shared_ptr FetchAnisetteData(const std::string& serverURL, std::function clientInfoFilter); +} diff --git a/upstream_repo b/upstream_repo index 7358c74..5224db7 160000 --- a/upstream_repo +++ b/upstream_repo @@ -1 +1 @@ -Subproject commit 7358c74bcdce5855bf05a4dc3586241953fc110a +Subproject commit 5224db7b0c19015126ff678c88b83a3cbfeecd42