Files
GameLauncher/Services/Codecs/Es3/Es3PasswordResolver.cs
T

560 lines
22 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace GameLauncher.Services.Codecs.Es3
{
/// <summary>
/// "どの段階でパスワードが判明したか" を表す解決手段の種別。
/// </summary>
public enum Es3PasswordSource
{
/// <summary>学習キャッシュ(過去に解決済みのパスワード)から復元。</summary>
LearnedCache,
/// <summary>呼び出し元が明示指定したパスワード。</summary>
Explicit,
/// <summary>ゲーム内のマネージドアセンブリ(Assembly-CSharp.dll 等)の文字列リテラルから抽出。</summary>
GameBinaryStrings,
/// <summary>ゲーム内バイナリ(IL2CPP の GameAssembly.dll / global-metadata.dat)から抽出。</summary>
GameIl2CppMetadata,
/// <summary>ユーザー辞書ファイル/既定の候補リストからの探索。</summary>
Dictionary,
/// <summary>平文のまま(暗号化されていない)。</summary>
PlainText
}
/// <summary>
/// ES3 パスワード解決の結果。<see cref="Success"/> が false の場合は <see cref="Diagnostics"/> に理由が入ります。
/// </summary>
public sealed class Es3PasswordResolution
{
/// <summary>解決に成功したか。</summary>
public bool Success { get; init; }
/// <summary>解決したパスワード(平文・暗号化なしの場合は空文字)。</summary>
public string Password { get; init; } = string.Empty;
/// <summary>解決手段の種別。</summary>
public Es3PasswordSource Source { get; init; }
/// <summary>試行した候補数。</summary>
public int TriedCandidates { get; init; }
/// <summary>診断用のメッセージ一覧(失敗理由・各段階の結果)。</summary>
public IReadOnlyList<string> Diagnostics { get; init; } = [];
/// <summary>失敗結果を生成します。</summary>
public static Es3PasswordResolution Fail(List<string> diagnostics, int tried)
=> new() { Success = false, Diagnostics = diagnostics, TriedCandidates = tried };
/// <summary>成功結果を生成します。</summary>
public static Es3PasswordResolution Ok(string password, Es3PasswordSource source, int tried)
=> new() { Success = true, Password = password, Source = source, TriedCandidates = tried };
}
/// <summary>
/// ES3 (Easy Save 3) の暗号化セーブデータからパスワードを多段フォールバックで特定する汎用リゾルバ。
///
/// 解決順序:
/// 1. 学習キャッシュ(<see cref="Es3PasswordStore"/>)
/// 2. 呼び出し元の明示指定
/// 3. ゲームのマネージドアセンブリ文字列リテラル抽出(Mono)
/// 4. 既定候補 + ユーザー辞書による探索
///
/// すべての候補は実際に AES 復号して妥当性を検証し、成功したものだけを採用します。
/// これにより「誤ったパスワードで復号して壊れたデータを書く」事故を防止します。
/// </summary>
public sealed class Es3PasswordResolver
{
/// <summary>ES3 が AES 暗号化時にファイル先頭へ埋め込む IV の長さ(バイト)。</summary>
public const int AesIvLength = 16;
/// <summary>復号結果が「ES3 の平文 JSON」らしいかを判定する際の最小文字数。</summary>
private const int MinimumPlainTextLength = 2;
private readonly Es3PasswordStore _store;
/// <summary>
/// 既定のストアを用いて <see cref="Es3PasswordResolver"/> を初期化します。
/// </summary>
public Es3PasswordResolver()
: this(Es3PasswordStore.Instance)
{
}
/// <summary>
/// 任意のストアを指定して <see cref="Es3PasswordResolver"/> を初期化します(テスト用途を含む)。
/// </summary>
/// <param name="store">学習済みパスワードの永続ストア</param>
public Es3PasswordResolver(Es3PasswordStore store)
{
this._store = store ?? throw new ArgumentNullException(nameof(store));
}
/// <summary>
/// 既定のシングルトンインスタンス。
/// </summary>
public static Es3PasswordResolver Instance { get; } = new();
/// <summary>
/// ES3 のファイルが暗号化されているかどうかを統計的に判定します。
/// 平文 JSON / Gzip はもちろん「暗号化されていない」と判定します。
/// </summary>
/// <param name="bytes">ファイル全体のバイト列</param>
/// <returns>暗号化されている可能性が高い場合 true</returns>
public static bool LooksEncrypted(byte[] bytes)
{
if (bytes == null || bytes.Length < AesIvLength * 2)
{
return false;
}
// 平文 JSON はそのまま読める
if (IsLikelyJson(bytes))
{
return false;
}
// Gzip マジック
if (bytes[0] == 0x1F && bytes[1] == 0x8B)
{
return false;
}
// AES ブロック境界に一致し、かつ高エントロピーなら暗号化とみなす
if (bytes.Length % AesIvLength != 0)
{
return false;
}
return CalculateEntropy(bytes) >= 7.5;
}
/// <summary>
/// パスワードを多段フォールバックで解決します。
/// </summary>
/// <param name="saveFilePath">対象の .es3 ファイルの絶対パス</param>
/// <param name="gameRootDirectory">ゲームのルートディレクトリ(文字列抽出元の探索に使用)</param>
/// <param name="gameKey">学習キャッシュのキー(通常はゲームのルートディレクトリ)</param>
/// <param name="explicitPassword">呼び出し元が既に知っているパスワード(任意)</param>
/// <param name="userDictionaryPath">追加候補を列挙したテキストファイルのパス(任意)</param>
/// <returns>解決結果</returns>
public Es3PasswordResolution Resolve(
string saveFilePath,
string? gameRootDirectory = null,
string? gameKey = null,
string? explicitPassword = null,
string? userDictionaryPath = null)
{
var diagnostics = new List<string>();
int tried = 0;
byte[] fileBytes;
try
{
fileBytes = File.ReadAllBytes(saveFilePath);
}
catch (Exception ex)
{
diagnostics.Add($"セーブファイルを読み込めません: {ex.Message}");
return Es3PasswordResolution.Fail(diagnostics, tried);
}
if (fileBytes.Length == 0)
{
diagnostics.Add("セーブファイルが空です。");
return Es3PasswordResolution.Fail(diagnostics, tried);
}
// 暗号化されていない場合はパスワード不要
if (!LooksEncrypted(fileBytes))
{
diagnostics.Add("暗号化は検出されませんでした(平文または Gzip)。");
return Es3PasswordResolution.Ok(string.Empty, Es3PasswordSource.PlainText, tried);
}
diagnostics.Add($"暗号化を検出しました({fileBytes.Length} bytes / AES-128-CBC 相当)。");
// ---- 段階 1: 学習キャッシュ ----
var cacheKey = this.BuildCacheKey(gameKey, saveFilePath);
if (!string.IsNullOrEmpty(cacheKey))
{
var learned = this._store.TryGet(cacheKey);
if (!string.IsNullOrEmpty(learned))
{
tried++;
if (this.VerifyPassword(fileBytes, learned, out _))
{
diagnostics.Add("学習キャッシュのパスワードで復号に成功しました。");
return Es3PasswordResolution.Ok(learned, Es3PasswordSource.LearnedCache, tried);
}
diagnostics.Add("学習キャッシュのパスワードは無効でした(破棄します)。");
this._store.Remove(cacheKey);
}
}
// ---- 段階 2: 明示指定 ----
if (!string.IsNullOrEmpty(explicitPassword))
{
tried++;
if (this.VerifyPassword(fileBytes, explicitPassword, out _))
{
diagnostics.Add("指定されたパスワードで復号に成功しました。");
this.Remember(cacheKey, explicitPassword);
return Es3PasswordResolution.Ok(explicitPassword, Es3PasswordSource.Explicit, tried);
}
diagnostics.Add("指定されたパスワードでは復号できませんでした。");
}
// ---- 段階 3: ゲームバイナリの文字列リテラル抽出 ----
if (!string.IsNullOrEmpty(gameRootDirectory) && Directory.Exists(gameRootDirectory))
{
var extracted = Es3PasswordExtractor.ExtractCandidates(gameRootDirectory, diagnostics);
foreach (var candidate in extracted)
{
tried++;
if (this.VerifyPassword(fileBytes, candidate, out _))
{
diagnostics.Add($"ゲームバイナリから抽出した候補で復号に成功しました(候補: {Mask(candidate)})。");
this.Remember(cacheKey, candidate);
return Es3PasswordResolution.Ok(candidate, Es3PasswordSource.GameBinaryStrings, tried);
}
}
if (extracted.Count == 0)
{
diagnostics.Add("ゲームバイナリから有効なパスワード候補を抽出できませんでした。");
}
}
// ---- 段階 4: 既定候補 + ユーザー辞書 ----
foreach (var candidate in this.EnumerateDictionaryCandidates(userDictionaryPath, diagnostics))
{
tried++;
if (this.VerifyPassword(fileBytes, candidate, out _))
{
diagnostics.Add($"辞書探索で復号に成功しました(候補: {Mask(candidate)})。");
this.Remember(cacheKey, candidate);
return Es3PasswordResolution.Ok(candidate, Es3PasswordSource.Dictionary, tried);
}
}
diagnostics.Add($"すべての段階で復号に失敗しました(試行候補数: {tried})。パスワードを手動で入力してください。");
return Es3PasswordResolution.Fail(diagnostics, tried);
}
/// <summary>
/// 指定パスワードで ES3 ファイルを復号し、平文 JSON 文字列を取得します。
/// </summary>
/// <param name="fileBytes">ファイル全体のバイト列</param>
/// <param name="password">パスワード</param>
/// <param name="plainText">復号された平文 JSON</param>
/// <returns>復号に成功した場合 true</returns>
public bool VerifyPassword(byte[] fileBytes, string password, out string plainText)
{
plainText = string.Empty;
var plain = TryDecrypt(fileBytes, password);
if (plain == null)
{
return false;
}
plainText = plain;
return true;
}
/// <summary>
/// ES3 の AES-128-CBC 形式で復号を試みます。
/// ファイル先頭 16 バイトを IV、残りを暗号文として扱い、鍵はパスワード UTF-8 の先頭 16 バイトをゼロ埋めします。
/// </summary>
/// <param name="fileBytes">ファイル全体のバイト列</param>
/// <param name="password">パスワード</param>
/// <returns>復号された平文 JSON。失敗時は null</returns>
public static string? TryDecrypt(byte[] fileBytes, string password)
{
if (fileBytes == null || fileBytes.Length <= AesIvLength)
{
return null;
}
try
{
var iv = new byte[AesIvLength];
Array.Copy(fileBytes, 0, iv, 0, AesIvLength);
var cipher = new byte[fileBytes.Length - AesIvLength];
Array.Copy(fileBytes, AesIvLength, cipher, 0, cipher.Length);
using var aes = Aes.Create();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = DeriveKey(password);
aes.IV = iv;
using var decryptor = aes.CreateDecryptor();
var plain = decryptor.TransformFinalBlock(cipher, 0, cipher.Length);
var text = Encoding.UTF8.GetString(plain);
return IsPlausiblePlainText(text) ? text : null;
}
catch
{
return null;
}
}
/// <summary>
/// 平文バイト列を ES3 の AES-128-CBC 形式で暗号化します(IV を先頭に付与)。
/// </summary>
/// <param name="plainBytes">平文バイト列</param>
/// <param name="password">パスワード</param>
/// <returns>IV + 暗号文のバイト列</returns>
public static byte[] Encrypt(byte[] plainBytes, string password)
{
using var aes = Aes.Create();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = DeriveKey(password);
aes.GenerateIV();
using var encryptor = aes.CreateEncryptor();
var cipher = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
var result = new byte[aes.IV.Length + cipher.Length];
Array.Copy(aes.IV, 0, result, 0, aes.IV.Length);
Array.Copy(cipher, 0, result, aes.IV.Length, cipher.Length);
return result;
}
/// <summary>
/// パスワード文字列から AES-128 用の 16 バイト鍵を導出します。
/// </summary>
/// <param name="password">パスワード</param>
/// <returns>16 バイトの鍵</returns>
private static byte[] DeriveKey(string password)
{
var raw = Encoding.UTF8.GetBytes(password ?? string.Empty);
var key = new byte[16];
Array.Copy(raw, key, Math.Min(raw.Length, key.Length));
return key;
}
/// <summary>
/// 復号結果が ES3 の平文として妥当かを判定します。
/// </summary>
/// <param name="text">復号された文字列</param>
/// <returns>妥当な場合 true</returns>
private static bool IsPlausiblePlainText(string text)
{
if (string.IsNullOrWhiteSpace(text) || text.Length < MinimumPlainTextLength)
{
return false;
}
var trimmed = text.TrimStart();
if (trimmed.StartsWith('{') || trimmed.StartsWith('['))
{
return true;
}
// ES3 の内部シリアライズ形式は "__type" を必ず含む
return text.Contains("__type", StringComparison.Ordinal);
}
/// <summary>
/// バイト列が平文 JSON かどうかを判定します。
/// </summary>
/// <param name="bytes">対象バイト列</param>
/// <returns>平文 JSON と判断できる場合 true</returns>
private static bool IsLikelyJson(byte[] bytes)
{
try
{
int length = Math.Min(bytes.Length, 64);
var head = Encoding.UTF8.GetString(bytes, 0, length).TrimStart();
return head.StartsWith('{') || head.StartsWith('[');
}
catch
{
return false;
}
}
/// <summary>
/// バイト列のシャノンエントロピー(bits/byte)を算出します。
/// </summary>
/// <param name="bytes">対象バイト列</param>
/// <returns>エントロピー値</returns>
private static double CalculateEntropy(byte[] bytes)
{
var frequency = new int[256];
foreach (var b in bytes)
{
frequency[b]++;
}
double entropy = 0.0;
foreach (var count in frequency)
{
if (count == 0)
{
continue;
}
double p = (double)count / bytes.Length;
entropy -= p * Math.Log2(p);
}
return entropy;
}
/// <summary>
/// 学習キャッシュ用のキーを生成します。
/// </summary>
/// <param name="gameKey">ゲーム識別キー</param>
/// <param name="saveFilePath">セーブファイルパス</param>
/// <returns>キャッシュキー</returns>
private string BuildCacheKey(string? gameKey, string saveFilePath)
{
var key = !string.IsNullOrWhiteSpace(gameKey)
? gameKey!
: Path.GetDirectoryName(saveFilePath) ?? string.Empty;
return key.Trim();
}
/// <summary>
/// 解決済みパスワードを学習キャッシュへ保存します。
/// </summary>
/// <param name="cacheKey">キャッシュキー</param>
/// <param name="password">パスワード</param>
private void Remember(string? cacheKey, string password)
{
if (string.IsNullOrEmpty(cacheKey))
{
return;
}
this._store.Set(cacheKey, password);
}
/// <summary>
/// 辞書段階で試行する候補列挙子を返します(既定候補 → ユーザー辞書の順)。
/// </summary>
/// <param name="userDictionaryPath">ユーザー辞書ファイルのパス</param>
/// <param name="diagnostics">診断メッセージの追加先</param>
/// <returns>候補の列挙</returns>
private IEnumerable<string> EnumerateDictionaryCandidates(string? userDictionaryPath, List<string> diagnostics)
{
var seen = new HashSet<string>(StringComparer.Ordinal);
foreach (var candidate in GetBuiltInCandidates())
{
if (seen.Add(candidate))
{
yield return candidate;
}
}
if (string.IsNullOrWhiteSpace(userDictionaryPath))
{
yield break;
}
if (!File.Exists(userDictionaryPath))
{
diagnostics.Add($"ユーザー辞書が見つかりません: {userDictionaryPath}");
yield break;
}
string[] lines;
try
{
lines = File.ReadAllLines(userDictionaryPath, Encoding.UTF8);
}
catch (Exception ex)
{
diagnostics.Add($"ユーザー辞書の読み込みに失敗しました: {ex.Message}");
yield break;
}
diagnostics.Add($"ユーザー辞書を適用します({lines.Length} 行): {userDictionaryPath}");
foreach (var line in lines)
{
var candidate = line.Trim();
if (candidate.Length == 0 || candidate.StartsWith('#'))
{
continue;
}
if (seen.Add(candidate))
{
yield return candidate;
}
}
}
/// <summary>
/// Easy Save 3 でよく使われる既定のパスワード候補を返します。
/// </summary>
/// <returns>既定候補の並び</returns>
private static IEnumerable<string> GetBuiltInCandidates()
{
// 空文字(パスワード未設定のまま暗号化されたケース)を最初に試す
yield return string.Empty;
yield return "password";
yield return "Password";
yield return "PASSWORD";
yield return "Moodkie";
yield return "moodkie";
yield return "EasySave";
yield return "easysave";
yield return "EasySave3";
yield return "es3";
yield return "ES3";
yield return "SaveData";
yield return "savedata";
yield return "Save";
yield return "save";
yield return "secret";
yield return "Secret";
yield return "123456";
yield return "1234567890";
yield return "admin";
yield return "test";
yield return "game";
yield return "Game";
}
/// <summary>
/// 診断ログ用にパスワードをマスクします(先頭 2 文字のみ残す)。
/// </summary>
/// <param name="password">パスワード</param>
/// <returns>マスク済み文字列</returns>
private static string Mask(string password)
{
if (string.IsNullOrEmpty(password))
{
return "(空)";
}
if (password.Length <= 2)
{
return new string('*', password.Length);
}
return password[..2] + new string('*', Math.Min(password.Length - 2, 8));
}
}
}