| r231 vs r232 | ||
|---|---|---|
| ... | ... | |
| 434 | 434 | using UnityEngine; |
| 435 | 435 | using System.Diagnostics; |
| 436 | 436 | using System.Runtime.CompilerServices; |
| 437 | using System.Collections.Generic; | |
| 437 | 438 | |
| 438 | 439 | [Serializable] |
| 439 | 440 | public class PlayerData |
| ... | ... | |
| 444 | 445 | |
| 445 | 446 | public enum DevLogLevel { Trace = 0, Info = 1, Warning = 2, Error = 3, Critical = 4 } |
| 446 | 447 | |
| 448 | public struct SecureMetrics | |
| 449 | { | |
| 450 | public long TotalSaveTimeMs; | |
| 451 | public long TotalLoadTimeMs; | |
| 452 | public int SaveCount; | |
| 453 | public int LoadCount; | |
| 454 | public string SessionNonceStatus; | |
| 455 | public bool IsTamperingForced; | |
| 456 | public bool IsEnvironmentTampered; | |
| 457 | } | |
| 458 | ||
| 447 | 459 | public class SecureManager : MonoBehaviour |
| 448 | 460 | { |
| 449 | 461 | public static SecureManager Instance { get; private set; } |
| 450 | 462 | |
| 463 | [Header("보안 강화 제어")] | |
| 451 | 464 | public bool EnableHardening = true; |
| 452 | 465 | public bool EnableAntiDebugChecks = true; |
| 453 | 466 | public bool EnableRootDetection = true; |
| 454 | 467 | public bool EnableDummyMix = true; |
| 455 | 468 | public bool EnableFileNameObfuscation = true; |
| 456 | 469 | public bool EnableRotation = true; |
| 470 | ||
| 471 | [Header("개발자 진단 및 로깅")] | |
| 457 | 472 | public bool EnableDeveloperLogging = true; |
| 458 | 473 | public DevLogLevel DeveloperLogLevel = DevLogLevel.Info; |
| 474 | [Tooltip("안티-치트 로직 테스트를 위해 강제로 Tampered 상태를 주입합니다.")] | |
| 475 | public bool ForceTamperingForTest = false; | |
| 476 | ||
| 477 | [Header("데이터 및 I/O 설정")] | |
| 459 | 478 | public bool EnableTimeValidation = true; |
| 460 | 479 | public long MaxAllowedTimeJumpSeconds = 3600 * 6; |
| 480 | [Tooltip("비동기 I/O 사용 여부 (권장)")] | |
| 461 | 481 | public bool UseAsyncIO = true; |
| 462 | 482 | public byte CurrentVersion = 1; |
| 483 | [Tooltip("어셈블리 해시 검증을 위한 16진수 문자열. 비어 있으면 검증하지 않습니다.")] | |
| 463 | 484 | public string ExpectedAssemblyHashHex = ""; |
| 464 | 485 | |
| 465 | 486 | private const int SaltLenDefault = 16; |
| ... | ... | |
| 479 | 500 | |
| 480 | 501 | private string filePath; |
| 481 | 502 | private byte[] sessionNonce; |
| 503 | private bool nonceLoadedSecurely = false; | |
| 504 | ||
| 482 | 505 | private Stopwatch perfSave = new Stopwatch(); |
| 483 | 506 | private Stopwatch perfLoad = new Stopwatch(); |
| 484 | 507 | private long totalSaveMs = 0; |
| ... | ... | |
| 486 | 509 | private int saveCount = 0; |
| 487 | 510 | private int loadCount = 0; |
| 488 | 511 | private string devLogFilePath; |
| 489 | ||
| 512 | ||
| 490 | 513 | private static class Obf |
| 491 | 514 | { |
| 492 | 515 | public static string Decode(byte[] cipher, byte key) |
| ... | ... | |
| 508 | 531 | } |
| 509 | 532 | Instance = this; |
| 510 | 533 | DontDestroyOnLoad(gameObject); |
| 534 | ||
| 511 | 535 | sessionNonce = LoadOrCreateSessionNonce(); |
| 536 | PrintSecurityStatus(); | |
| 537 | ||
| 512 | 538 | filePath = Path.Combine(Application.persistentDataPath, ResolveFileName("playerData")); |
| 513 | 539 | devLogFilePath = Path.Combine(Application.persistentDataPath, "securemanager_devlog.txt"); |
| 540 | ||
| 514 | 541 | if (!string.IsNullOrEmpty(ExpectedAssemblyHashHex)) |
| 515 | 542 | { |
| 516 | 543 | try |
| 517 | 544 | { |
| 518 | 545 | string calc = CalculateAssemblyHashPartial(out bool ok); |
| 519 | if (!ok) | |
| 520 | ||
| 521 | ||
| 522 | ||
| 546 | if (!ok) DevLog("Assembly hash verification not applicable on this platform.", DevLogLevel.Warning); | |
| 523 | 547 | else |
| 524 | 548 | { |
| 525 | ||
| 526 | ||
| 527 | ||
| 528 | ||
| 529 | ||
| 530 | ||
| 531 | ||
| 532 | ||
| 549 | if (!VerifyAssemblyHash(ExpectedAssemblyHashHex)) DevLog($"Assembly hash mismatch.", DevLogLevel.Critical); | |
| 550 | else DevLog($"Assembly hash verified OK.", DevLogLevel.Info); | |
| 533 | 551 | } |
| 534 | 552 | } |
| 535 | catch (Exception ex) | |
| 536 | ||
| 537 | ||
| 538 | ||
| 553 | catch (Exception ex) { DevLog("Assembly verify failed due to exception.", DevLogLevel.Error, ex); } | |
| 539 | 554 | } |
| 540 | DevLog(" | |
| 555 | DevLog("최종 데이터 경로: " + filePath, DevLogLevel.Info); | |
| 541 | 556 | DevLogEnvironmentSnapshot(); |
| 542 | 557 | } |
| 543 | 558 | |
| ... | ... | |
| 545 | 560 | { |
| 546 | 561 | DevLog($"Platform={Application.platform}, OS={SystemInfo.operatingSystem}, Device={SystemInfo.deviceModel}, CPU={SystemInfo.processorType}, Memory={SystemInfo.systemMemorySize}MB", DevLogLevel.Info); |
| 547 | 562 | } |
| 563 | ||
| 564 | public void PrintSecurityStatus() | |
| 565 | { | |
| 566 | string status = nonceLoadedSecurely | |
| 567 | ? "SUCCESS: 세션 논스 안전하게 로드됨 (ProtectedData/Native)." | |
| 568 | : "WARNING: 세션 논스가 OS 보호 없이 저장됨 (초기 생성 또는 폴백 사용)."; | |
| 569 | ||
| 570 | DevLog($"--- 보안 상태 보고서 ---", DevLogLevel.Info); | |
| 571 | DevLog($"[논스 상태] {status}", nonceLoadedSecurely ? DevLogLevel.Info : DevLogLevel.Warning); | |
| 572 | DevLog($"[강화 설정] 활성: {EnableHardening}, 디버그 방어: {EnableAntiDebugChecks}, 루팅 감지: {EnableRootDetection}", DevLogLevel.Info); | |
| 573 | DevLog($"[변조 강제] 강제 테스트 상태: {ForceTamperingForTest}", ForceTamperingForTest ? DevLogLevel.Warning : DevLogLevel.Info); | |
| 574 | DevLog($"----------------------------", DevLogLevel.Info); | |
| 575 | } | |
| 548 | 576 | |
| 549 | 577 | private byte[] LoadOrCreateSessionNonce() |
| 550 | 578 | { |
| 551 | 579 | const string key = "SecureManager_SessionNonce_v4"; |
| 580 | byte[] newNonce = GenerateRandomBytes(16); | |
| 581 | ||
| 552 | 582 | try |
| 553 | 583 | { |
| 554 | 584 | if (PlayerPrefs.HasKey(key)) |
| ... | ... | |
| 560 | 590 | { |
| 561 | 591 | byte[] enc = Convert.FromBase64String(b64); |
| 562 | 592 | byte[] dec = TryProtectedUnprotect(enc); |
| 563 | if (dec != null && dec.Length > 0) return dec; | |
| 564 | return enc; | |
| 593 | ||
| 594 | if (dec != null && dec.Length > 0) | |
| 595 | { | |
| 596 | nonceLoadedSecurely = true; | |
| 597 | DevLog("Session Nonce successfully loaded and unprotected. [Recovery: Success]", DevLogLevel.Trace); | |
| 598 | return dec; | |
| 599 | } | |
| 600 | ||
| 601 | DevLog("ProtectedData Unprotect returned null or failed. [Recovery: Regenerate Nonce]", DevLogLevel.Warning); | |
| 602 | throw new CryptographicException("DPAPI/OS protection failed."); | |
| 565 | 603 | } |
| 566 | catch { } | |
| 604 | catch (FormatException ex) { DevLog("Failed to decode session nonce from Base64. [Recovery: Regenerate Nonce]", DevLogLevel.Warning, ex); } | |
| 605 | catch (CryptographicException ex) { DevLog("ProtectedData unprotect failed. [Recovery: Regenerate Nonce]", DevLogLevel.Warning, ex); } | |
| 606 | catch (Exception ex) { DevLog("Unexpected error during Session Nonce loading/unprotecting.", DevLogLevel.Error, ex); } | |
| 567 | 607 | } |
| 568 | 608 | } |
| 569 | 609 | } |
| 570 | catch (Exception ex) | |
| 571 | ||
| 572 | ||
| 573 | ||
| 574 | ||
| 610 | catch (Exception ex) { DevLog("Load session nonce failed (PlayerPrefs read error). [Recovery: Regenerate Nonce]", DevLogLevel.Warning, ex); } | |
| 611 | ||
| 612 | nonceLoadedSecurely = false; | |
| 613 | DevLog("Creating new Session Nonce (Fallback/Initial).", DevLogLevel.Info); | |
| 614 | ||
| 575 | 615 | try |
| 576 | 616 | { |
| 577 | byte[] protectedBytes = TryProtectedProtect(nonce); | |
| 578 | string toStore = protectedBytes != null ? Convert.ToBase64String(protectedBytes) : Convert.ToBase64String(nonce); | |
| 617 | byte[] protectedBytes = TryProtectedProtect(newNonce); | |
| 618 | string toStore = protectedBytes != null | |
| 619 | ? Convert.ToBase64String(protectedBytes) | |
| 620 | : Convert.ToBase64String(newNonce); | |
| 621 | ||
| 579 | 622 | PlayerPrefs.SetString(key, toStore); |
| 580 | 623 | PlayerPrefs.Save(); |
| 624 | if (protectedBytes == null) DevLog("New nonce saved without OS protection. [Recovery: Fallback to PlayerPrefs]", DevLogLevel.Warning); | |
| 625 | else DevLog("New nonce saved with OS protection.", DevLogLevel.Trace); | |
| 581 | 626 | } |
| 582 | catch (Exception ex) | |
| 583 | ||
| 584 | ||
| 585 | ||
| 586 | return nonce; | |
| 627 | catch (Exception ex) { DevLog("Save new session nonce failed. [Defense: Use in-memory nonce]", DevLogLevel.Critical, ex); } | |
| 628 | return newNonce; | |
| 587 | 629 | } |
| 588 | 630 | |
| 589 | 631 | [MethodImpl(MethodImplOptions.NoInlining)] |
| ... | ... | |
| 671 | 713 | byte[] secret = GetSecretBytes(); |
| 672 | 714 | string secretStr = EnableHardening ? Convert.ToBase64String(secret) + Application.identifier : Encoding.UTF8.GetString(secret) + Application.identifier; |
| 673 | 715 | Array.Clear(secret, 0, secret.Length); |
| 674 | ||
| 716 | try | |
| 675 | 717 | { |
| 676 | ||
| 677 | ||
| 718 | using (var kdf = new Rfc2898DeriveBytes(secretStr, salt, Pbkdf2Iterations, HashAlgorithmName.SHA256)) | |
| 678 | 719 | { |
| 679 | for (int i = 0; i < km.Length; i++) km[i] ^= rotationNonce[i % rotationNonce.Length]; | |
| 720 | byte[] km = kdf.GetBytes(KeyMaterialLen); | |
| 721 | if (EnableHardening && EnableRotation && rotationNonce != null) | |
| 722 | { | |
| 723 | for (int i = 0; i < km.Length; i++) km[i] ^= rotationNonce[i % rotationNonce.Length]; | |
| 724 | } | |
| 725 | byte[] aesKey = new byte[AesKeyLen]; | |
| 726 | byte[] hmacKey = new byte[HmacKeyLen]; | |
| 727 | Buffer.BlockCopy(km, 0, aesKey, 0, AesKeyLen); | |
| 728 | Buffer.BlockCopy(km, AesKeyLen, hmacKey, 0, HmacKeyLen); | |
| 729 | Array.Clear(km, 0, km.Length); | |
| 730 | return (aesKey, hmacKey); | |
| 680 | 731 | } |
| 681 | byte[] aesKey = new byte[AesKeyLen]; | |
| 682 | byte[] hmacKey = new byte[HmacKeyLen]; | |
| 683 | Buffer.BlockCopy(km, 0, aesKey, 0, AesKeyLen); | |
| 684 | Buffer.BlockCopy(km, AesKeyLen, hmacKey, 0, HmacKeyLen); | |
| 685 | Array.Clear(km, 0, km.Length); | |
| 686 | DevLog($"DeriveKeysRotating called. EnableDummyMix={EnableDummyMix}, EnableRotation={EnableRotation}", DevLogLevel.Trace); | |
| 687 | return (aesKey, hmacKey); | |
| 688 | 732 | } |
| 733 | catch (Exception ex) | |
| 734 | { | |
| 735 | DevLog("Key derivation failed. [Defense: Throw]", DevLogLevel.Critical, ex); | |
| 736 | throw new InvalidOperationException("Key derivation failed, cannot proceed with crypto operations.", ex); | |
| 737 | } | |
| 689 | 738 | } |
| 690 | 739 | |
| 691 | public void Save<T>(T data) where T : class | |
| 692 | { | |
| 693 | if (UseAsyncIO) SaveAsync(data).GetAwaiter().GetResult(); | |
| 694 | else SaveInternal(data); | |
| 695 | } | |
| 696 | ||
| 697 | public T Load<T>() where T : class | |
| 698 | { | |
| 699 | if (UseAsyncIO) return LoadAsync<T>().GetAwaiter().GetResult(); | |
| 700 | return LoadInternal<T>(); | |
| 701 | } | |
| 702 | ||
| 703 | 740 | public Task SaveAsync<T>(T data) where T : class |
| 704 | 741 | { |
| 742 | if (!UseAsyncIO) | |
| 743 | { | |
| 744 | string json = JsonUtility.ToJson(data); | |
| 745 | SaveInternalFromJson(json); | |
| 746 | return Task.CompletedTask; | |
| 747 | } | |
| 748 | ||
| 705 | 749 | string json = JsonUtility.ToJson(data); |
| 706 | 750 | return Task.Run(() => SaveInternalFromJson(json)); |
| 707 | 751 | } |
| 708 | 752 | |
| 709 | 753 | public async Task<T> LoadAsync<T>() where T : class |
| 710 | 754 | { |
| 711 | string json = await Task.Run(() => LoadInternalGetJson()); | |
| 755 | string json = null; | |
| 756 | ||
| 757 | if (!UseAsyncIO) json = LoadInternalGetJson(); | |
| 758 | else json = await Task.Run(() => LoadInternalGetJson()); | |
| 759 | ||
| 712 | 760 | if (json == null) return default; |
| 713 | 761 | T obj = null; |
| 714 | 762 | try |
| 715 | 763 | { |
| 716 | 764 | obj = JsonUtility.FromJson<T>(json); |
| 717 | DevLog("JSON deserialized on main thread.", DevLogLevel.Trace); | |
| 718 | 765 | } |
| 766 | catch (ArgumentException ex) | |
| 767 | { | |
| 768 | DevLog($"JSON deserialization failed for type {typeof(T).Name}. [Defense: Return Default]", DevLogLevel.Error, ex); | |
| 769 | return default; | |
| 770 | } | |
| 719 | 771 | catch (Exception ex) |
| 720 | 772 | { |
| 721 | DevLog("Js | |
| 773 | DevLog($"JSON deserialization failed for type {typeof(T).Name}. [Defense: Return Default]", DevLogLevel.Error, ex); | |
| 722 | 774 | return default; |
| 723 | 775 | } |
| 724 | 776 | return obj; |
| 725 | 777 | } |
| 726 | 778 | |
| 727 | private void SaveInternal<T>(T data) where T : class | |
| 728 | { | |
| 729 | string json = JsonUtility.ToJson(data); | |
| 730 | SaveInternalFromJson(json); | |
| 731 | } | |
| 732 | ||
| 733 | 779 | private void SaveInternalFromJson(string json) |
| 734 | 780 | { |
| 735 | if ( | |
| 781 | if (IsTamperedOrDebug(out string reason)) | |
| 736 | 782 | { |
| 737 | ||
| 738 | ||
| 739 | ||
| 740 | ||
| 741 | ||
| 742 | ||
| 783 | DevLog($"Save aborted: Tamper/Debug detected - {reason}. [Defense: Abort Save]", DevLogLevel.Warning); | |
| 784 | return; | |
| 743 | 785 | } |
| 744 | 786 | perfSave.Restart(); |
| 745 | 787 | try |
| ... | ... | |
| 752 | 794 | byte[] plain = Encoding.UTF8.GetBytes(json); |
| 753 | 795 | byte[] iv; |
| 754 | 796 | byte[] cipher; |
| 755 | ||
| 797 | ||
| 798 | try | |
| 756 | 799 | { |
| 757 | aes.KeySize = 256; | |
| 758 | aes.Mode = CipherMode.CBC; | |
| 759 | aes.Padding = PaddingMode.PKCS7; | |
| 760 | aes.Key = aesKey; | |
| 761 | aes.GenerateIV(); | |
| 762 | iv = aes.IV; | |
| 763 | using (var enc = aes.CreateEncryptor(aes.Key, iv)) | |
| 764 | cipher = enc.TransformFinalBlock(plain, 0, plain.Length); | |
| 800 | using (Aes aes = Aes.Create()) | |
| 801 | { | |
| 802 | aes.KeySize = 256; | |
| 803 | aes.Mode = CipherMode.CBC; | |
| 804 | aes.Padding = PaddingMode.PKCS7; | |
| 805 | aes.Key = aesKey; | |
| 806 | aes.GenerateIV(); | |
| 807 | iv = aes.IV; | |
| 808 | using (var enc = aes.CreateEncryptor(aes.Key, iv)) | |
| 809 | cipher = enc.TransformFinalBlock(plain, 0, plain.Length); | |
| 810 | } | |
| 765 | 811 | } |
| 812 | catch (CryptographicException ex) { DevLog("AES Encryption failed. [Defense: Abort Save]", DevLogLevel.Critical, ex); return; } | |
| 813 | catch (Exception ex) { DevLog("AES Encryption failed. [Defense: Abort Save]", DevLogLevel.Critical, ex); return; } | |
| 814 | ||
| 766 | 815 | long ticks = DateTime.UtcNow.Ticks; |
| 767 | 816 | byte[] ticksBytes = BitConverter.GetBytes(ticks); |
| 768 | 817 | byte[] hmacInput = new byte[salt.Length + rotation.Length + iv.Length + cipher.Length + ticksBytes.Length]; |
| ... | ... | |
| 775 | 824 | byte[] hmac; |
| 776 | 825 | using (var h = new HMACSHA256(hmacKey)) hmac = h.ComputeHash(hmacInput); |
| 777 | 826 | byte[] magicBytes = Encoding.ASCII.GetBytes(Obf.Decode(ObfMagicBytes, ObfMagicKey)); |
| 827 | ||
| 828 | byte[] outBytes; | |
| 778 | 829 | using (MemoryStream ms = new MemoryStream()) |
| 779 | 830 | using (BinaryWriter bw = new BinaryWriter(ms)) |
| 780 | 831 | { |
| ... | ... | |
| 791 | 842 | bw.Write(cipher); |
| 792 | 843 | bw.Write(hmac); |
| 793 | 844 | bw.Write(ticksBytes); |
| 794 | ||
| 795 | ||
| 796 | ||
| 797 | ||
| 798 | ||
| 799 | ||
| 800 | ||
| 801 | ||
| 802 | ||
| 803 | ||
| 804 | ||
| 805 | ||
| 806 | ||
| 807 | ||
| 808 | ||
| 809 | ||
| 810 | ||
| 811 | ||
| 812 | ||
| 813 | ||
| 814 | ||
| 815 | ||
| 816 | ||
| 817 | ||
| 818 | ||
| 845 | outBytes = ms.ToArray(); | |
| 819 | 846 | } |
| 820 | ||
| 821 | ||
| 822 | ||
| 823 | ||
| 824 | ||
| 825 | ClearBytes(hmac | |
| 826 | ClearBytes(hmac); | |
| 827 | ||
| 828 | ||
| 847 | ||
| 848 | string bak = filePath + ".bak"; | |
| 849 | try | |
| 850 | { | |
| 851 | if (File.Exists(filePath)) File.Copy(filePath, bak, true); | |
| 852 | } | |
| 853 | catch (Exception ex) { DevLog($"Backup creation failed. [Recovery: Continue with Main Write]", DevLogLevel.Warning, ex); } | |
| 854 | ||
| 855 | try | |
| 856 | { | |
| 857 | File.WriteAllBytes(filePath, outBytes); | |
| 858 | FileInfo fi = new FileInfo(filePath); | |
| 859 | DevLog($"Save successful: {filePath} ({fi.Length} bytes)", DevLogLevel.Info); | |
| 860 | } | |
| 861 | catch (IOException ex) { DevLog($"File write failed to {filePath}. [Defense: Throw]", DevLogLevel.Critical, ex); throw; } | |
| 862 | catch (Exception ex) { DevLog($"File write failed to {filePath}. [Defense: Throw]", DevLogLevel.Critical, ex); throw; } | |
| 863 | ||
| 864 | ClearBytes(aesKey); ClearBytes(hmacKey); ClearBytes(plain); ClearBytes(iv); ClearBytes(cipher); | |
| 865 | ClearBytes(hmacInput); ClearBytes(hmac); ClearBytes(salt); ClearBytes(rotation); | |
| 866 | ||
| 829 | 867 | perfSave.Stop(); |
| 830 | 868 | saveCount++; |
| 831 | 869 | totalSaveMs += perfSave.ElapsedMilliseconds; |
| 832 | DevLog($"Save | |
| 870 | DevLog($"Save completed in {perfSave.ElapsedMilliseconds} ms", DevLogLevel.Info); | |
| 833 | 871 | } |
| 834 | catch (Exception ex) | |
| 835 | ||
| 836 | ||
| 837 | ||
| 872 | catch (Exception ex) { DevLog("Save operation failed (Critical Catch).", DevLogLevel.Critical, ex); } | |
| 838 | 873 | } |
| 839 | 874 | |
| 840 | 875 | private string LoadInternalGetJson() |
| 841 | 876 | { |
| 842 | if ( | |
| 877 | if (IsTamperedOrDebug(out string reason)) | |
| 843 | 878 | { |
| 844 | ||
| 845 | ||
| 846 | ||
| 847 | ||
| 848 | ||
| 849 | ||
| 879 | DevLog($"Load aborted: Tamper/Debug detected - {reason}. [Defense: Abort Load]", DevLogLevel.Warning); | |
| 880 | return null; | |
| 850 | 881 | } |
| 882 | ||
| 851 | 883 | perfLoad.Restart(); |
| 852 | i | |
| 884 | string json = TryLoadFile(filePath, false); | |
| 885 | ||
| 886 | if (json == null) | |
| 853 | 887 | { |
| 854 | DevLog("No file to load: " + filePath, DevLogLevel.Info); | |
| 855 | return null; | |
| 856 | } | |
| 857 | byte[] total; | |
| 858 | try | |
| 859 | { | |
| 860 | total = File.ReadAllBytes(filePath); | |
| 861 | } | |
| 862 | catch (Exception ex) | |
| 863 | { | |
| 864 | DevLog("Read failed: " + ex.Message, DevLogLevel.Warning); | |
| 865 | 888 | string bak = filePath + ".bak"; |
| 866 | 889 | if (File.Exists(bak)) |
| 867 | 890 | { |
| 868 | try | |
| 891 | DevLog("Main file load failed. Attempting to load from backup. [Recovery: Try Backup]", DevLogLevel.Warning); | |
| 892 | json = TryLoadFile(bak, true); | |
| 893 | ||
| 894 | if (json != null) | |
| 869 | 895 | { |
| 870 | t | |
| 871 | DevLog(" | |
| 896 | try | |
| 897 | { | |
| 898 | File.Copy(bak, filePath, true); | |
| 899 | DevLog("Main file restored from backup. [Recovery: Success]", DevLogLevel.Trace); | |
| 900 | } | |
| 901 | catch (IOException ex) | |
| 902 | { | |
| 903 | DevLog("Failed to restore main file from backup. [Recovery: Continue with JSON]", DevLogLevel.Warning, ex); | |
| 904 | } | |
| 872 | 905 | } |
| 873 | ||
| 906 | else | |
| 874 | 907 | { |
| 875 | DevLog("Backup | |
| 876 | ||
| 908 | DevLog("Backup file also failed to load. [Defense: Return Null]", DevLogLevel.Error); | |
| 877 | 909 | } |
| 878 | 910 | } |
| 879 | else return | |
| 911 | else | |
| 912 | { | |
| 913 | DevLog("No main file or backup found to load. [Defense: Return Null]", DevLogLevel.Info); | |
| 914 | } | |
| 880 | 915 | } |
| 916 | ||
| 917 | perfLoad.Stop(); | |
| 918 | if (json != null) | |
| 919 | { | |
| 920 | loadCount++; | |
| 921 | totalLoadMs += perfLoad.ElapsedMilliseconds; | |
| 922 | DevLog($"Load successful. Load time: {perfLoad.ElapsedMilliseconds} ms", DevLogLevel.Info); | |
| 923 | } | |
| 924 | ||
| 925 | return json; | |
| 926 | } | |
| 927 | ||
| 928 | private string TryLoadFile(string path, bool isBackup) | |
| 929 | { | |
| 930 | if (!File.Exists(path)) return null; | |
| 931 | byte[] total = null; | |
| 932 | ||
| 881 | 933 | try |
| 882 | 934 | { |
| 935 | total = File.ReadAllBytes(path); | |
| 936 | } | |
| 937 | catch (IOException ex) { DevLog($"File read failed for {path}. [Defense: Reject File]", DevLogLevel.Warning, ex); return null; } | |
| 938 | ||
| 939 | try | |
| 940 | { | |
| 883 | 941 | using (MemoryStream ms = new MemoryStream(total)) |
| 884 | 942 | using (BinaryReader br = new BinaryReader(ms)) |
| 885 | 943 | { |
| 886 | 944 | byte[] magic = br.ReadBytes(4); |
| 887 | 945 | string mag = Encoding.ASCII.GetString(magic); |
| 888 | 946 | string expectedMagic = Obf.Decode(ObfMagicBytes, ObfMagicKey); |
| 889 | if (mag != expectedMagic) | |
| 890 | ||
| 891 | ||
| 892 | ||
| 893 | ||
| 947 | ||
| 948 | if (mag != expectedMagic) { DevLog($"Magic mismatch in {path}. [Defense: Reject Load]", DevLogLevel.Warning); return null; } | |
| 949 | ||
| 894 | 950 | byte ver = br.ReadByte(); |
| 895 | if (ver != CurrentVersion) | |
| 896 | ||
| 897 | ||
| 898 | ||
| 899 | ||
| 951 | if (ver != CurrentVersion) { DevLog($"Version mismatch in {path}: File Version {ver} != Current Version {CurrentVersion}. [Defense: Reject Load]", DevLogLevel.Warning); return null; } | |
| 952 | ||
| 900 | 953 | int saltLen = br.ReadByte(); |
| 901 | if (saltLen <= 0 || saltLen > 64) { DevLog("Bad salt length.", DevLogLevel.Warning); return null; } | |
| 954 | if (saltLen <= 0 || saltLen > 64) { DevLog($"Bad salt length ({saltLen}) in {path}. [Defense: Reject Load]", DevLogLevel.Warning); return null; } | |
| 902 | 955 | byte[] salt = br.ReadBytes(saltLen); |
| 956 | ||
| 903 | 957 | int rotationLen = br.ReadByte(); |
| 904 | 958 | byte[] rotation = rotationLen > 0 ? br.ReadBytes(rotationLen) : new byte[16]; |
| 959 | ||
| 905 | 960 | byte[] iv = br.ReadBytes(IvLen); |
| 961 | ||
| 906 | 962 | int cipherLen = br.ReadInt32(); |
| 907 | 963 | if (!BitConverter.IsLittleEndian) cipherLen = System.Net.IPAddress.NetworkToHostOrder(cipherLen); |
| 908 | if (cipherLen <= 0 || cipherLen > total.Length) { DevLog("Bad cipher length.", DevLogLevel.Warning); return null; } | |
| 964 | if (cipherLen <= 0 || cipherLen > total.Length) { DevLog($"Bad cipher length ({cipherLen}) in {path}. [Defense: Reject Load]", DevLogLevel.Warning); return null; } | |
| 909 | 965 | byte[] cipher = br.ReadBytes(cipherLen); |
| 966 | ||
| 910 | 967 | byte[] hmac = br.ReadBytes(HmacLen); |
| 911 | 968 | byte[] ticksBytes = br.ReadBytes(8); |
| 969 | ||
| 912 | 970 | long ticks = BitConverter.ToInt64(ticksBytes, 0); |
| 971 | ||
| 913 | 972 | byte[] hmacInput = new byte[salt.Length + rotation.Length + iv.Length + cipher.Length + ticksBytes.Length]; |
| 914 | 973 | int pos = 0; |
| 915 | 974 | Buffer.BlockCopy(salt, 0, hmacInput, pos, salt.Length); pos += salt.Length; |
| ... | ... | |
| 917 | 976 | Buffer.BlockCopy(iv, 0, hmacInput, pos, iv.Length); pos += iv.Length; |
| 918 | 977 | Buffer.BlockCopy(cipher, 0, hmacInput, pos, cipher.Length); pos += cipher.Length; |
| 919 | 978 | Buffer.BlockCopy(ticksBytes, 0, hmacInput, pos, ticksBytes.Length); |
| 979 | ||
| 920 | 980 | var keys = DeriveKeysRotating(salt, (EnableRotation ? rotation : null)); |
| 921 | 981 | byte[] aesKey = keys.aesKey; |
| 922 | 982 | byte[] hmacKey = keys.hmacKey; |
| 923 | byte[] expected; | |
| 924 | using (var h = new HMACSHA256(hmacKey)) expected = h.ComputeHash(hmacInput); | |
| 925 | ||
| 926 | ||
| 983 | byte[] expectedHmac; | |
| 984 | using (var h = new HMACSHA256(hmacKey)) expectedHmac = h.ComputeHash(hmacInput); | |
| 985 | ||
| 986 | if (!CryptographicOperations.FixedTimeEquals(expectedHmac, hmac)) | |
| 927 | 987 | { |
| 928 | DevLog("HMAC mismatch | |
| 929 | ClearBytes(aesKey); | |
| 930 | ||
| 931 | ||
| 988 | DevLog($"HMAC mismatch in {path} (data tamper). [Defense: Reject Load and Clear Keys]", DevLogLevel.Critical); | |
| 989 | ClearBytes(aesKey); ClearBytes(hmacKey); ClearBytes(expectedHmac); | |
| 932 | 990 | return null; |
| 933 | 991 | } |
| 992 | ||
| 934 | 993 | if (EnableTimeValidation && ticks > 0) |
| 935 | 994 | { |
| 936 | 995 | long nowTicks = DateTime.UtcNow.Ticks; |
| 937 | 996 | long diffSec = Math.Abs(nowTicks - ticks) / TimeSpan.TicksPerSecond; |
| 938 | DevLog($"Saved timestamp: {new DateTime(ticks).ToString("o")}, Current UTC: {DateTime.UtcNow.ToString("o")}, diffSec={diffSec}", DevLogLevel.Info); | |
| 939 | 997 | if (diffSec > MaxAllowedTimeJumpSeconds) |
| 940 | 998 | { |
| 941 | DevLog($"Time jump detected: {diffSec} seconds | |
| 942 | ClearBytes(aesKey); | |
| 943 | ||
| 944 | ||
| 999 | DevLog($"Time jump detected: {diffSec} seconds > Max ({MaxAllowedTimeJumpSeconds}). [Defense: Reject Load]", DevLogLevel.Warning); | |
| 1000 | ClearBytes(aesKey); ClearBytes(hmacKey); ClearBytes(expectedHmac); | |
| 945 | 1001 | return null; |
| 946 | 1002 | } |
| 947 | 1003 | } |
| 1004 | ||
| 948 | 1005 | byte[] plain; |
| 949 | using (Aes aes = Aes.Create()) | |
| 950 | { | |
| 951 | aes.KeySize = 256; | |
| 952 | aes.Mode = CipherMode.CBC; | |
| 953 | aes.Padding = PaddingMode.PKCS7; | |
| 954 | aes.Key = aesKey; | |
| 955 | aes.IV = iv; | |
| 956 | using (var dec = aes.CreateDecryptor(aes.Key, aes.IV)) | |
| 957 | plain = dec.TransformFinalBlock(cipher, 0, cipher.Length); | |
| 958 | } | |
| 959 | string json = Encoding.UTF8.GetString(plain); | |
| 960 | ClearBytes(aesKey); | |
| 961 | ClearBytes(hmacKey); | |
| 962 | ClearBytes(expected); | |
| 963 | ClearBytes(plain); | |
| 964 | ClearBytes(iv); | |
| 965 | ClearBytes(cipher); | |
| 966 | ClearBytes(salt); | |
| 967 | ClearBytes(rotation); | |
| 968 | perfLoad.Stop(); | |
| 969 | loadCount++; | |
| 970 | totalLoadMs += perfLoad.ElapsedMilliseconds; | |
| 971 | DevLog($"Load complete: {filePath} ({total.Length} bytes). Load time: {perfLoad.ElapsedMilliseconds} ms (avg {totalLoadMs / (double)loadCount:F1} ms over {loadCount} loads)", DevLogLevel.Info); | |
| 972 | return json; | |
| 973 | } | |
| 974 | } | |
| 975 | catch (Exception ex) | |
| 976 | { | |
| 977 | DevLog("Load exception: " + ex.ToString(), DevLogLevel.Error); | |
| 978 | string bak = filePath + ".bak"; | |
| 979 | if (File.Exists(bak)) | |
| 980 | { | |
| 981 | DevLog("Attempting to load from backup.", DevLogLevel.Info); | |
| 982 | 1006 | try |
| 983 | 1007 | { |
| 984 | ||
| 985 | ||
| 986 | ||
| 1008 | using (Aes aes = Aes.Create()) | |
| 987 | 1009 | { |
| 988 | ||
| 989 | ||
| 990 | ||
| 991 | ||
| 992 | ||
| 993 | ||
| 994 | ||
| 995 | ||
| 996 | ||
| 997 | ||
| 998 | ||
| 999 | ||
| 1000 | ||
| 1001 | ||
| 1002 | ||
| 1003 | ||
| 1004 | ||
| 1005 | ||
| 1006 | ||
| 1007 | ||
| 1008 | ||
| 1009 | ||
| 1010 | ||
| 1011 | ||
| 1012 | ||
| 1013 | ||
| 1014 | ||
| 1015 | ||
| 1016 | ||
| 1017 | ||
| 1018 | ||
| 1019 | ||
| 1020 | ||
| 1021 | ||
| 1022 | ||
| 1023 | ||
| 1024 | ||
| 1025 | ||
| 1026 | ||
| 1027 | ||
| 1028 | ||
| 1029 | ||
| 1030 | ||
| 1031 | ||
| 1032 | ||
| 1033 | ||
| 1034 | ||
| 1035 | ||
| 1036 | ||
| 1037 | ||
| 1038 | ||
| 1039 | ||
| 1040 | ||
| 1041 | ||
| 1042 | ||
| 1043 | ||
| 1010 | aes.KeySize = 256; | |
| 1011 | aes.Mode = CipherMode.CBC; | |
| 1012 | aes.Padding = PaddingMode.PKCS7; | |
| 1013 | aes.Key = aesKey; | |
| 1014 | aes.IV = iv; | |
| 1015 | using (var dec = aes.CreateDecryptor(aes.Key, aes.IV)) | |
| 1016 | plain = dec.TransformFinalBlock(cipher, 0, cipher.Length); | |
| 1044 | 1017 | } |
| 1045 | 1018 | } |
| 1046 | catch (Exception ex | |
| 1019 | catch (CryptographicException ex) | |
| 1047 | 1020 | { |
| 1048 | DevLog(" | |
| 1021 | DevLog($"AES Decryption failed in {path}. [Defense: Reject Load]", DevLogLevel.Warning, ex); | |
| 1022 | ClearBytes(aesKey); ClearBytes(hmacKey); ClearBytes(expectedHmac); | |
| 1049 | 1023 | return null; |
| 1050 | 1024 | } |
| 1025 | ||
| 1026 | string json = Encoding.UTF8.GetString(plain); | |
| 1027 | ||
| 1028 | ClearBytes(aesKey); ClearBytes(hmacKey); ClearBytes(expectedHmac); ClearBytes(plain); | |
| 1029 | ClearBytes(iv); ClearBytes(cipher); ClearBytes(salt); ClearBytes(rotation); | |
| 1030 | ||
| 1031 | return json; | |
| 1051 | 1032 | } |
| 1052 | return null; | |
| 1053 | 1033 | } |
| 1034 | catch (EndOfStreamException ex) { DevLog($"File structure truncated in {path}. [Defense: Reject File]", DevLogLevel.Error, ex); return null; } | |
| 1035 | catch (Exception ex) { DevLog($"Load processing failed (General Error) for {path}. [Defense: Reject File]", DevLogLevel.Critical, ex); return null; } | |
| 1054 | 1036 | } |
| 1055 | 1037 | |
| 1056 | p | |
| 1038 | public SecureMetrics GetDiagnosticMetrics() | |
| 1057 | 1039 | { |
| 1058 | ||
| 1059 | ||
| 1060 | ||
| 1061 | ||
| 1062 | ||
| 1063 | ||
| 1064 | ||
| 1065 | ||
| 1066 | ||
| 1067 | ||
| 1068 | ||
| 1069 | ||
| 1070 | ||
| 1071 | ||
| 1072 | ||
| 1073 | ||
| 1040 | string reason = ""; | |
| 1041 | bool isTampered = IsTamperedOrDebug(out reason); | |
| 1042 | ||
| 1043 | return new SecureMetrics | |
| 1074 | 1044 | { |
| 1075 | ||
| 1076 | st | |
| 1077 | s | |
| 1078 | ||
| 1079 | ret | |
| 1080 | } | |
| 1045 | TotalSaveTimeMs = totalSaveMs, | |
| 1046 | TotalLoadTimeMs = totalLoadMs, | |
| 1047 | SaveCount = saveCount, | |
| 1048 | LoadCount = loadCount, | |
| 1049 | SessionNonceStatus = nonceLoadedSecurely ? "SECURELY_LOADED" : "FALLBACK_USED", | |
| 1050 | IsTamperingForced = ForceTamperingForTest, | |
| 1051 | IsEnvironmentTampered = isTampered | |
| 1052 | }; | |
| 1081 | 1053 | } |
| 1082 | 1054 | |
| 1083 | 1055 | private bool IsTamperedOrDebug(out string reason) |
| 1084 | 1056 | { |
| 1085 | 1057 | reason = ""; |
| 1058 | ||
| 1059 | if (ForceTamperingForTest) { reason = "Forced via Inspector/Dev Tools"; return true; } | |
| 1086 | 1060 | if (!EnableHardening) return false; |
| 1061 | ||
| 1087 | 1062 | try |
| 1088 | 1063 | { |
| 1089 | 1064 | if (EnableAntiDebugChecks) |
| 1090 | 1065 | { |
| 1091 | if (System.Diagnostics.Debugger.IsAttached) | |
| 1092 | ||
| 1093 | ||
| 1094 | ||
| 1095 | ||
| 1096 | ||
| 1097 | ||
| 1098 | ||
| 1099 | ||
| 1100 | ||
| 1101 | ||
| 1102 | ||
| 1103 | ||
| 1104 | ||
| 1105 | ||
| 1106 | ||
| 1107 | ||
| 1108 | ||
| 1066 | if (System.Diagnostics.Debugger.IsAttached) { reason = "Debugger Attached"; return true; } | |
| 1067 | string proc = System.Diagnostics.Process.GetCurrentProcess().ProcessName.ToLower(); | |
| 1068 | if (proc.Contains("debug") || proc.Contains("devenv") || proc.Contains("mono") || proc.Contains("dnspy")) { reason = $"ProcessName suspicious: {proc}"; return true; } | |
| 1109 | 1069 | } |
| 1110 | 1070 | } |
| 1111 | catch | |
| 1071 | catch { } | |
| 1072 | ||
| 1112 | 1073 | try |
| 1113 | 1074 | { |
| 1114 | 1075 | if (EnableRootDetection) |
| 1115 | 1076 | { |
| 1116 | 1077 | string[] suspectPaths = new string[] { "/system/bin/su", "/system/xbin/su", "/sbin/su" }; |
| 1117 | foreach (var p in suspectPaths) if (File.Exists(p)) | |
| 1118 | ||
| 1119 | ||
| 1120 | ||
| 1121 | ||
| 1078 | foreach (var p in suspectPaths) if (File.Exists(p)) { reason = $"Root path found: {p}"; return true; } | |
| 1122 | 1079 | } |
| 1123 | 1080 | } |
| 1124 | catch | |
| 1081 | catch { } | |
| 1082 | ||
| 1125 | 1083 | return false; |
| 1126 | 1084 | } |
| 1127 | 1085 | |
| ... | ... | |
| 1150 | 1108 | { |
| 1151 | 1109 | Assembly asm = typeof(SecureManager).Assembly; |
| 1152 | 1110 | string loc = asm.Location; |
| 1153 | if (string.IsNullOrEmpty(loc)) | |
| 1111 | if (string.IsNullOrEmpty(loc)) return ""; | |
| 1154 | 1112 | byte[] bytes = File.ReadAllBytes(loc); |
| 1155 | 1113 | using (var sha = SHA256.Create()) |
| 1156 | 1114 | { |
| ... | ... | |
| 1160 | 1118 | return hex; |
| 1161 | 1119 | } |
| 1162 | 1120 | } |
| 1163 | catch { | |
| 1121 | catch { return ""; } | |
| 1164 | 1122 | } |
| 1165 | 1123 | |
| 1166 | private void DevLog(string message, DevLogLevel level = DevLogLevel.Info) | |
| 1124 | private void DevLog(string message, DevLogLevel level = DevLogLevel.Info, Exception ex = null, [CallerMemberName] string methodName = "") | |
| 1167 | 1125 | { |
| 1168 | if (!EnableDeveloperLogging | |
| 1169 | ||
| 1170 | string prefix = $"[SM:{level}] "; | |
| 1126 | if (!EnableDeveloperLogging || level < DeveloperLogLevel) return; | |
| 1127 | ||
| 1128 | string prefix = $"[SM:{level}][{methodName}] "; | |
| 1171 | 1129 | string line = prefix + message; |
| 1130 | ||
| 1131 | if (ex != null) | |
| 1132 | { | |
| 1133 | line += $" | EXCEPTION_TYPE: {ex.GetType().Name} | EXCEPTION_MSG: {ex.Message}"; | |
| 1134 | if (level >= DevLogLevel.Error) line += $"\n--- STACK TRACE ---\n{ex.StackTrace}"; | |
| 1135 | } | |
| 1136 | ||
| 1172 | 1137 | try |
| 1173 | 1138 | { |
| 1174 | if (level == DevLogLevel.Error | |
| 1175 | else if (level == DevLogLevel.Warning) Debug.LogWarning(line); | |
| 1176 | else Debug.Log(line); | |
| 1139 | if (level == DevLogLevel.Critical) UnityEngine.Debug.LogError("[CRITICAL] " + line); | |
| 1140 | else if (level == DevLogLevel.Error) UnityEngine.Debug.LogError(line); | |
| 1141 | else if (level == DevLogLevel.Warning) UnityEngine.Debug.LogWarning(line); | |
| 1142 | else UnityEngine.Debug.Log(line); | |
| 1177 | 1143 | } |
| 1178 | 1144 | catch { } |
| 1145 | ||
| 1179 | 1146 | try |
| 1180 | 1147 | { |
| 1181 | 1148 | File.AppendAllText(devLogFilePath, DateTime.UtcNow.ToString("o") + " " + line + Environment.NewLine); |
| ... | ... | |
| 1183 | 1150 | catch { } |
| 1184 | 1151 | } |
| 1185 | 1152 | |
| 1153 | private static byte[] GenerateRandomBytes(int len) | |
| 1154 | { | |
| 1155 | byte[] b = new byte[len]; | |
| 1156 | using (var rng = RandomNumberGenerator.Create()) rng.GetBytes(b); | |
| 1157 | return b; | |
| 1158 | } | |
| 1159 | ||
| 1160 | private static void ClearBytes(byte[] b) | |
| 1161 | { | |
| 1162 | if (b == null) return; | |
| 1163 | Array.Clear(b, 0, b.Length); | |
| 1164 | } | |
| 1165 | ||
| 1166 | private string ResolveFileName(string baseName) | |
| 1167 | { | |
| 1168 | if (!EnableHardening || !EnableFileNameObfuscation) return baseName + ".dat"; | |
| 1169 | byte[] nameBytes = Encoding.UTF8.GetBytes(baseName + Application.identifier); | |
| 1170 | using (var sha = SHA256.Create()) | |
| 1171 | { | |
| 1172 | byte[] hash = sha.ComputeHash(nameBytes); | |
| 1173 | string b64 = Convert.ToBase64String(hash); | |
| 1174 | string safe = b64.Replace('+', '-').Replace('/', '_').Replace('=', 'x'); | |
| 1175 | ClearBytes(hash); | |
| 1176 | return safe.Substring(0, Math.Min(28, safe.Length)) + ".dat"; | |
| 1177 | } | |
| 1178 | } | |
| 1179 | ||
| 1186 | 1180 | private byte[] TryProtectedProtect(byte[] data) |
| 1187 | 1181 | { |
| 1188 | 1182 | try |
| ... | ... |