From 3c98b5c255472bb53c241205760a9f8950c6eee9 Mon Sep 17 00:00:00 2001 From: Jaakko Palvaila Date: Thu, 5 Nov 2026 17:39:35 +0000 Subject: [PATCH 1/8] Request two-factor codes by SMS for accounts without a trusted device Bumps upstream_repo to ac02e35 (AltServer-Windows branch sms-2fa): GrandSlam's "secondaryAuth" now gets an SMS code through the JSON endpoints from rileytestut/AltSign#62 and isideload, instead of being mistaken for an account without 2FA. README-NG documents it as Fix 7, experimental until it has signed in against Apple. Built for x86_64; not yet tried against Apple. --- README-NG.md | 17 +++++++++++++++++ upstream_repo | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/README-NG.md b/README-NG.md index a51c8e2..a4aa11e 100644 --- a/README-NG.md +++ b/README-NG.md @@ -158,6 +158,23 @@ 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 (experimental) + +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 shows Apple's message. + +This has not been verified against Apple yet. Try it once, and if it fails, stop and read the log +(`-d`) before trying again; see the account-lock warning above. + ## Prebuilt binaries Static binaries for x86_64, aarch64, armv7 and i586 are attached to the diff --git a/upstream_repo b/upstream_repo index 7358c74..eb4a690 160000 --- a/upstream_repo +++ b/upstream_repo @@ -1 +1 @@ -Subproject commit 7358c74bcdce5855bf05a4dc3586241953fc110a +Subproject commit eb4a6909a929da26156b32204b2c1ccbb3c37ac4 From 12dd3945ca2824b45040c213d1a347ce970365df Mon Sep 17 00:00:00 2001 From: Jaakko Palvaila Date: Thu, 5 Nov 2026 17:44:26 +0000 Subject: [PATCH 2/8] SMS 2FA: ALTSERVER_2FA=sms for accounts reported as trusted-device Bumps upstream_repo to 151d8a2 (AltServer-Windows sms-2fa). A sign-in on 2026-11-05 showed that an account without a trusted device can get trustedDeviceSecondaryAuth, whose validation answers an SMS code with 200 without accepting it. ALTSERVER_2FA=sms forces the SMS endpoints; 2xx answers with serviceErrors no longer count as success, and the log shows au, hsc and which SMS code to enter. README-NG's Fix 7 describes it. Built for x86_64; not yet tried against Apple. --- README-NG.md | 10 +++++++++- upstream_repo | 2 +- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/README-NG.md b/README-NG.md index a4aa11e..9094d41 100644 --- a/README-NG.md +++ b/README-NG.md @@ -170,7 +170,15 @@ endpoints that rileytestut/AltSign#62 proposes and [isideload](https://github.co `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 shows Apple's message. +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. Set `ALTSERVER_2FA=sms` for such an account. AltServer then skips +the trusted-device request and uses the SMS endpoints whenever a code is needed. The log shows `au` and +`hsc` of the sign-in response and which SMS code to enter. This has not been verified against Apple yet. Try it once, and if it fails, stop and read the log (`-d`) before trying again; see the account-lock warning above. diff --git a/upstream_repo b/upstream_repo index eb4a690..f3da5d3 160000 --- a/upstream_repo +++ b/upstream_repo @@ -1 +1 @@ -Subproject commit eb4a6909a929da26156b32204b2c1ccbb3c37ac4 +Subproject commit f3da5d31cbee8c5e4e2d179aceb09d55856ef717 From bbafd031bcab50aa5cc68f97db3ed38e3434a8f3 Mon Sep 17 00:00:00 2001 From: Jaakko Palvaila Date: Thu, 5 Nov 2026 17:51:33 +0000 Subject: [PATCH 3/8] SMS 2FA: keep one anisette identity through the sign-in Bumps upstream_repo to f76225d (AltServer-Windows sms-2fa). The 2026-11-05 SMS test validated the code, but new.ani.sidestore.io gives a new identity on every request, so the second sign-in came from another device and Apple asked for 2FA again. Anisette refreshes are now kept only when they return the same device, and the Device-Id is logged at each step. README-NG's Fix 7 describes it. Built for x86_64; not yet tried against Apple. --- README-NG.md | 7 +++++++ upstream_repo | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/README-NG.md b/README-NG.md index 9094d41..2b5e9ff 100644 --- a/README-NG.md +++ b/README-NG.md @@ -180,6 +180,13 @@ required two-factor authentication. Set `ALTSERVER_2FA=sms` for such an account. the trusted-device request and uses the SMS endpoints whenever a code is needed. The log shows `au` and `hsc` of the sign-in response 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. + This has not been verified against Apple yet. Try it once, and if it fails, stop and read the log (`-d`) before trying again; see the account-lock warning above. diff --git a/upstream_repo b/upstream_repo index f3da5d3..635cd3f 160000 --- a/upstream_repo +++ b/upstream_repo @@ -1 +1 @@ -Subproject commit f3da5d31cbee8c5e4e2d179aceb09d55856ef717 +Subproject commit 635cd3f63d92347f5f967d1e288a8ef0a6a916a5 From 97824a4ec8fa486d2043a09bdf4c6c5fdac615c9 Mon Sep 17 00:00:00 2001 From: Jaakko Palvaila Date: Thu, 5 Nov 2026 18:41:31 +0000 Subject: [PATCH 4/8] Bump AltSign: automatic 2FA method, no secrets in the log upstream_repo moves to 63e0b36 (AltServer-Windows ng-2026-11): - ed1317c removes the GSA token, the decrypted sign-in response, SRP byte dumps, SMS response bodies and anisette values from the log; - 63e0b36 makes ALTSERVER_2FA default to auto, which reads Apple's 2FA info and takes the SMS path for accounts without trusted devices, without requesting a second code. --- upstream_repo | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/upstream_repo b/upstream_repo index 635cd3f..5224db7 160000 --- a/upstream_repo +++ b/upstream_repo @@ -1 +1 @@ -Subproject commit 635cd3f63d92347f5f967d1e288a8ef0a6a916a5 +Subproject commit 5224db7b0c19015126ff678c88b83a3cbfeecd42 From 1ddf5c60fab59c24025cba3d17c58cb433c5de6a Mon Sep 17 00:00:00 2001 From: Jaakko Palvaila Date: Thu, 5 Nov 2026 18:41:31 +0000 Subject: [PATCH 5/8] Anisette v3 client, and anisette values out of the log A v1 anisette server hands out whatever identity it likes, and 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 2FA code each time. An anisette v3 server instead provisions one identity, whose keychain identifier and adi.pb stay on this computer. src/AnisetteV3.cpp speaks SideStore's anisette-v3-server protocol, as omnisette's remote_anisette_v3.rs does: - GET /v3/client_info for the client info and User-Agent; - provisioning: Apple's lookup for the midStartProvisioning and midFinishProvisioning URLs, then the /v3/provisioning_session websocket (GiveIdentifier, spim, cpim -> ptm/tk, adi_pb), relaying the Apple requests as the device (MD-LU = SHA-256 of the identifier, Device-Id = the identifier as a UUID); - POST /v3/get_headers for the one-time password, machine ID and routing info; -45061 means provision again. The identity is kept in $XDG_CONFIG_HOME (or ~/.config) /AltServer/anisette-v3/.json, mode 600 in a 700 directory, written to a temporary file and renamed. cpprestsdk's websocket client, already in the builder image, carries the websocket; HTTPS_PROXY is honoured for the anisette and provisioning requests. ALTSERVER_ANISETTE_PROTOCOL selects v3, v1 or auto (the default): v3 when the server answers /v3/client_info. A server that can't be reached is an error, not a reason to fall back to v1. The client info filter (ALTSERVER_CLIENT_INFO, Xcode sanitizer) is shared by both protocols. The v1 path no longer logs the anisette JSON or its values; the log shows the protocol, the client info and the first 8 characters of the device ID. Tested in the sandbox against new.ani.sidestore.io up to Apple's lookup, which the sandbox network policy blocks: auto selects v3, client info is read, a new identity is created. Websocket provisioning and get_headers are not yet tested end to end. --- src/AnisetteDataManager.cpp | 123 ++++--- src/AnisetteV3.cpp | 636 ++++++++++++++++++++++++++++++++++++ src/AnisetteV3.h | 22 ++ 3 files changed, 730 insertions(+), 51 deletions(-) create mode 100644 src/AnisetteV3.cpp create mode 100644 src/AnisetteV3.h diff --git a/src/AnisetteDataManager.cpp b/src/AnisetteDataManager.cpp index 4eab8ad..6475819 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()); } @@ -80,18 +83,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 +183,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 +214,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..7055a3c --- /dev/null +++ b/src/AnisetteV3.cpp @@ -0,0 +1,636 @@ +#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 "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; + } + + // HTTPS_PROXY / https_proxy, when set, for the anisette server and the provisioning requests. + std::optional EnvironmentProxy() + { + for (const char* name : { "HTTPS_PROXY", "https_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()) + { + 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) + { + 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."); + } + + return { json.at("client_info").as_string(), json.at("user_agent").as_string() }; + } + + // /AltServer/anisette-v3/.json, where is $XDG_CONFIG_HOME or ~/.config. + 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()); + } + + 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(); + } + + // 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()) + { + config.set_proxy(*proxy); + } + + web::websockets::client::websocket_client connection(config); + connection.connect(socketURL).wait(); + + 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()); + connection.close().wait(); + break; + } + else + { + std::string detail = message.has_field("message") && message.at("message").is_string() ? ": " + message.at("message").as_string() : ""; + connection.close().wait(); + throw V3Error("Provisioning failed, the server answered " + (result.empty() ? std::string("without a result") : result) + detail + "."); + } + } + + 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) << "."); + } + + // 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(); + auto json = response.extract_json(true).get(); + + 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); + + static std::map clientInfoByURL; + if (clientInfoByURL.count(url) == 0) + { + clientInfoByURL[url] = FetchClientInfo(url); + } + ClientInfo clientInfo = clientInfoByURL[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); + RAND_bytes(state.identifier.data(), (int)state.identifier.size()); + } + + 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); +} From 75ada64ac9eab10912adddbb0aa4a854d7eda2d0 Mon Sep 17 00:00:00 2001 From: Jaakko Palvaila Date: Thu, 5 Nov 2026 18:42:07 +0000 Subject: [PATCH 6/8] Default to new.ani.sidestore.io; document Fixes 7 and 8 The default anisette server was armconverter.com, which predates the Mac anisette requirement. It is now https://new.ani.sidestore.io, which provides Mac anisette and speaks v3, so a user who sets nothing gets one stable identity. An empty ALTSERVER_ANISETTE_SERVER also means the default. README-NG: - Fix 5: mac-ani.jkcoxson.com now gets -80043; new.ani is the default. - Fix 7: verified with ALTSERVER_2FA=sms; documents ALTSERVER_2FA auto | sms | trusteddevice and "resend". - Fix 8 (new): anisette v3, ALTSERVER_ANISETTE_PROTOCOL, where the identity is kept. - Log output: what the log shows and never shows. - Running: no mac-ani; sanity checks for Fixes 7 and 8. --- README-NG.md | 69 +++++++++++++++++++++++++++++++------ src/AnisetteDataManager.cpp | 5 +-- 2 files changed, 62 insertions(+), 12 deletions(-) diff --git a/README-NG.md b/README-NG.md index 2b5e9ff..092eae3 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,7 +162,7 @@ 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 (experimental) +## 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 @@ -176,9 +180,21 @@ 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. Set `ALTSERVER_2FA=sms` for such an account. AltServer then skips -the trusted-device request and uses the SMS endpoints whenever a code is needed. The log shows `au` and -`hsc` of the sign-in response and which SMS code to enter. +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`: always the trusted-device path, as before Fix 7. + +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 @@ -187,8 +203,39 @@ when it returns the same device; otherwise the sign-in keeps its original aniset 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. -This has not been verified against Apple yet. Try it once, and if it fails, stop and read the log -(`-d`) before trying again; see the account-lock warning above. +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. Delete that file to start over with a new identity. `HTTPS_PROXY` is honoured for the anisette +server and the provisioning requests. + +`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. + +## 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 @@ -213,24 +260,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 6475819..563aae9 100644 --- a/src/AnisetteDataManager.cpp +++ b/src/AnisetteDataManager.cpp @@ -56,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 From 7e47ce381cb5141a6c212f7301c7a628c4f22658 Mon Sep 17 00:00:00 2001 From: Jaakko Palvaila Date: Thu, 5 Nov 2026 18:46:28 +0000 Subject: [PATCH 7/8] README-NG: anisette v3 verified in the sandbox With gsa.apple.com allowed, the v3 client provisioned an identity through new.ani.sidestore.io's websocket and Apple's midStart/ midFinishProvisioning, saved it with mode 600, reused it on the next run, and Apple answered a made-up account with -20970 both times. --- README-NG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README-NG.md b/README-NG.md index 092eae3..7eaa7cf 100644 --- a/README-NG.md +++ b/README-NG.md @@ -230,6 +230,10 @@ 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 From 947bb102fb1309f0c49845360102d440d39ce986 Mon Sep 17 00:00:00 2001 From: Jaakko Palvaila Date: Thu, 5 Nov 2026 19:26:52 +0000 Subject: [PATCH 8/8] Anisette v3: review fixes From the review of ng..ng-2026-11: - The proxy follows the URL: HTTPS_PROXY for https/wss, HTTP_PROXY for http/ws, and none for hosts NO_PROXY lists. Before, HTTPS_PROXY was used for every request, so a local v3 server at http://localhost failed on a host with a proxy set. - The provisioning websocket is closed on every failure (missing spim/ptm, parse errors, failed sends), not only when the server reports one. The session loop moves to RunProvisioningSession(). - A get_headers answer that isn't JSON (a 502 page) now says "answered HTTP 502 without JSON" instead of a bare JSON error. - A failed RAND_bytes stops instead of leaving an all-zero identifier. - /v3/client_info is cached per server, so auto detection and the first fetch no longer request it twice. - A path in the server URL is added to the identity file's name, so two servers on one host don't share an identity. A URL without a path keeps its file name, so existing identities stay valid. - README-NG: ALTSERVER_2FA=trusteddevice still uses SMS for au=secondaryAuth, which has no trusted device; only the v3 client uses a proxy. Rebuilt for x86_64 and aarch64; v3 provisioning, identity reuse and the log checks repeated on both. --- README-NG.md | 8 ++- src/AnisetteV3.cpp | 134 ++++++++++++++++++++++++++++++++++++--------- 2 files changed, 114 insertions(+), 28 deletions(-) diff --git a/README-NG.md b/README-NG.md index 7eaa7cf..2a9b5f4 100644 --- a/README-NG.md +++ b/README-NG.md @@ -190,7 +190,8 @@ So the method is chosen from the account's 2FA info. `ALTSERVER_2FA` selects it: 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`: always the trusted-device path, as before Fix 7. +- `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 @@ -220,8 +221,9 @@ An anisette v3 server provisions one identity instead, and the identity's keycha `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. Delete that file to start over with a new identity. `HTTPS_PROXY` is honoured for the anisette -server and the provisioning requests. +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 diff --git a/src/AnisetteV3.cpp b/src/AnisetteV3.cpp index 7055a3c..af085d7 100644 --- a/src/AnisetteV3.cpp +++ b/src/AnisetteV3.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -77,10 +78,43 @@ namespace return url; } - // HTTPS_PROXY / https_proxy, when set, for the anisette server and the provisioning requests. - std::optional EnvironmentProxy() + // 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) { - for (const char* name : { "HTTPS_PROXY", "https_proxy" }) + 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) @@ -97,7 +131,7 @@ namespace http_client_config config; config.set_validate_certificates(validateCertificates); config.set_timeout(std::chrono::seconds(60)); - if (auto proxy = EnvironmentProxy()) + if (auto proxy = EnvironmentProxy(url)) { config.set_proxy(*proxy); } @@ -147,6 +181,15 @@ namespace 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) @@ -160,10 +203,12 @@ namespace throw V3Error(serverURL + "/v3/client_info has no client_info and user_agent."); } - return { json.at("client_info").as_string(), json.at("user_agent").as_string() }; + 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. + // /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"); @@ -195,6 +240,15 @@ namespace 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"; } @@ -429,6 +483,8 @@ namespace 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) @@ -457,7 +513,7 @@ namespace } web::websockets::client::websocket_client_config config; - if (auto proxy = EnvironmentProxy()) + if (auto proxy = EnvironmentProxy(socketURL)) { config.set_proxy(*proxy); } @@ -465,6 +521,36 @@ namespace 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)); @@ -493,23 +579,14 @@ namespace 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()); - connection.close().wait(); - break; + return; } else { std::string detail = message.has_field("message") && message.at("message").is_string() ? ": " + message.at("message").as_string() : ""; - connection.close().wait(); throw V3Error("Provisioning failed, the server answered " + (result.empty() ? std::string("without a result") : result) + detail + "."); } } - - 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) << "."); } // Headers from /v3/get_headers, or nothing when the server says the identity isn't provisioned (-45061). @@ -521,7 +598,16 @@ namespace auto client = MakeClient(serverURL, true); auto response = client.request(methods::POST, "/v3/get_headers", body).get(); - auto json = response.extract_json(true).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") @@ -571,12 +657,7 @@ std::shared_ptr AnisetteV3::FetchAnisetteData(const std::string& s std::string url = TrimmedURL(serverURL); - static std::map clientInfoByURL; - if (clientInfoByURL.count(url) == 0) - { - clientInfoByURL[url] = FetchClientInfo(url); - } - ClientInfo clientInfo = clientInfoByURL[url]; + 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); @@ -592,7 +673,10 @@ std::shared_ptr AnisetteV3::FetchAnisetteData(const std::string& s else { state.identifier.resize(16); - RAND_bytes(state.identifier.data(), (int)state.identifier.size()); + 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())