{"repo_name": "TSforge", "file_name": "/TSforge/LibTSforge/SPP/SPPUtils.cs", "inference_info": {"prefix_code": "namespace LibTSforge.SPP\n{\n using Microsoft.Win32;\n using System;\n using System.IO;\n using System.Linq;\n using System.ServiceProcess;\n using Crypto;\n using PhysicalStore;\n using TokenStore;\n\n public static class SPPUtils\n {\n public static void KillSPP(PSVersion version)\n {\n ServiceController sc;\n\n string svcName = version == PSVersion.Vista ? \"slsvc\" : \"sppsvc\";\n\n try\n {\n sc = new ServiceController(svcName);\n\n if (sc.Status == ServiceControllerStatus.Stopped)\n return;\n }\n catch (InvalidOperationException ex)\n {\n throw new InvalidOperationException(string.Format(\"Unable to access {0}: \", svcName) + ex.Message);\n }\n\n Logger.WriteLine(string.Format(\"Stopping {0}...\", svcName));\n\n bool stopped = false;\n\n for (int i = 0; stopped == false && i < 1080; i++)\n {\n try\n {\n if (sc.Status != ServiceControllerStatus.StopPending)\n sc.Stop();\n\n sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromMilliseconds(500));\n }\n catch (System.ServiceProcess.TimeoutException)\n {\n continue;\n }\n catch (InvalidOperationException ex)\n {\n Logger.WriteLine(\"Warning: Stopping sppsvc failed, retrying. Details: \" + ex.Message);\n System.Threading.Thread.Sleep(500);\n continue;\n }\n\n stopped = true;\n }\n\n if (!stopped)\n throw new System.TimeoutException(string.Format(\"Failed to stop {0}\", svcName));\n\n Logger.WriteLine(string.Format(\"{0} stopped successfully.\", svcName));\n\n if (version == PSVersion.Vista && SPSys.IsSpSysRunning())\n {\n Logger.WriteLine(\"Unloading spsys...\");\n\n int status = SPSys.ControlSpSys(false);\n\n if (status < 0)\n {\n throw new IOException(\"Failed to unload spsys\");\n }\n\n Logger.WriteLine(\"spsys unloaded successfully.\");\n }\n }\n\n public static void RestartSPP(PSVersion version)\n {\n if (version == PSVersion.Vista)\n {\n ServiceController sc;\n\n try\n {\n sc = new ServiceController(\"slsvc\");\n\n if (sc.Status == ServiceControllerStatus.Running)\n return;\n }\n catch (InvalidOperationException ex)\n {\n throw new InvalidOperationException(\"Unable to access slsvc: \" + ex.Message);\n }\n\n Logger.WriteLine(\"Starting slsvc...\");\n\n bool started = false;\n\n for (int i = 0; started == false && i < 360; i++)\n {\n try\n {\n if (sc.Status != ServiceControllerStatus.StartPending)\n sc.Start();\n\n sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMilliseconds(500));\n }\n catch (System.ServiceProcess.TimeoutException)\n {\n continue;\n }\n catch (InvalidOperationException ex)\n {\n Logger.WriteLine(\"Warning: Starting slsvc failed, retrying. Details: \" + ex.Message);\n System.Threading.Thread.Sleep(500);\n continue;\n }\n\n started = true;\n }\n\n if (!started)\n throw new System.TimeoutException(\"Failed to start slsvc\");\n\n Logger.WriteLine(\"slsvc started successfully.\");\n }\n\n SLApi.RefreshLicenseStatus();\n }\n\n ", "suffix_code": "\n\n public static string GetPSPath(PSVersion version)\n {\n switch (version)\n {\n case PSVersion.Vista:\n case PSVersion.Win7:\n return Directory.GetFiles(\n Environment.GetFolderPath(Environment.SpecialFolder.System),\n \"7B296FB0-376B-497e-B012-9C450E1B7327-*.C7483456-A289-439d-8115-601632D005A0\")\n .FirstOrDefault() ?? \"\";\n default:\n string psDir = Environment.ExpandEnvironmentVariables(\n (string)Registry.GetValue(\n @\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform\",\n \"TokenStore\",\n \"\"\n )\n );\n string psPath = Path.Combine(psDir, \"data.dat\");\n\n if (string.IsNullOrEmpty(psDir) || !File.Exists(psPath))\n {\n string[] psDirs =\n {\n @\"spp\\store\",\n @\"spp\\store\\2.0\",\n @\"spp\\store_test\",\n @\"spp\\store_test\\2.0\"\n };\n\n foreach (string dir in psDirs)\n {\n psPath = Path.Combine(\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.System),\n dir\n ),\n \"data.dat\"\n );\n\n if (File.Exists(psPath)) return psPath;\n }\n } \n else\n {\n return psPath;\n }\n\n throw new FileNotFoundException(\"Failed to locate physical store.\");\n }\n }\n\n public static string GetTokensPath(PSVersion version)\n {\n switch (version)\n {\n case PSVersion.Vista:\n return Path.Combine(\n Environment.ExpandEnvironmentVariables(\"%WINDIR%\"),\n @\"ServiceProfiles\\NetworkService\\AppData\\Roaming\\Microsoft\\SoftwareLicensing\\tokens.dat\"\n );\n case PSVersion.Win7:\n return Path.Combine(\n Environment.ExpandEnvironmentVariables(\"%WINDIR%\"),\n @\"ServiceProfiles\\NetworkService\\AppData\\Roaming\\Microsoft\\SoftwareProtectionPlatform\\tokens.dat\"\n );\n default:\n string tokDir = Environment.ExpandEnvironmentVariables(\n (string)Registry.GetValue(\n @\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform\",\n \"TokenStore\",\n \"\"\n )\n );\n string tokPath = Path.Combine(tokDir, \"tokens.dat\");\n\n if (string.IsNullOrEmpty(tokDir) || !File.Exists(tokPath))\n {\n string[] tokDirs =\n {\n @\"spp\\store\",\n @\"spp\\store\\2.0\",\n @\"spp\\store_test\",\n @\"spp\\store_test\\2.0\"\n };\n\n foreach (string dir in tokDirs)\n {\n tokPath = Path.Combine(\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.System),\n dir\n ),\n \"tokens.dat\"\n );\n\n if (File.Exists(tokPath)) return tokPath;\n }\n }\n else\n {\n return tokPath;\n }\n\n throw new FileNotFoundException(\"Failed to locate token store.\");\n }\n }\n\n public static IPhysicalStore GetStore(PSVersion version, bool production)\n {\n string psPath = GetPSPath(version);\n\n switch (version)\n {\n case PSVersion.Vista:\n return new PhysicalStoreVista(psPath, production);\n case PSVersion.Win7:\n return new PhysicalStoreWin7(psPath, production);\n default:\n return new PhysicalStoreModern(psPath, production, version);\n }\n }\n\n public static ITokenStore GetTokenStore(PSVersion version)\n {\n string tokPath = GetTokensPath(version);\n\n return new TokenStoreModern(tokPath);\n }\n\n public static void DumpStore(PSVersion version, bool production, string filePath, string encrFilePath)\n {\n bool manageSpp = false;\n\n if (encrFilePath == null)\n {\n encrFilePath = GetPSPath(version);\n manageSpp = true;\n KillSPP(version);\n }\n\n if (string.IsNullOrEmpty(encrFilePath) || !File.Exists(encrFilePath))\n {\n throw new FileNotFoundException(\"Store does not exist at expected path '\" + encrFilePath + \"'.\");\n }\n\n try\n {\n using (FileStream fs = File.Open(encrFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))\n {\n byte[] encrData = fs.ReadAllBytes();\n File.WriteAllBytes(filePath, PhysStoreCrypto.DecryptPhysicalStore(encrData, production, version));\n }\n Logger.WriteLine(\"Store dumped successfully to '\" + filePath + \"'.\");\n }\n finally\n {\n if (manageSpp)\n {\n RestartSPP(version);\n }\n }\n }\n\n public static void LoadStore(PSVersion version, bool production, string filePath)\n {\n if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))\n {\n throw new FileNotFoundException(\"Store file '\" + filePath + \"' does not exist.\");\n }\n\n KillSPP(version);\n\n using (IPhysicalStore store = GetStore(version, production))\n {\n store.WriteRaw(File.ReadAllBytes(filePath));\n }\n\n RestartSPP(version);\n\n Logger.WriteLine(\"Loaded store file successfully.\");\n }\n }\n}\n", "middle_code": "public static bool DetectCurrentKey()\n {\n SLApi.RefreshLicenseStatus();\n using (RegistryKey wpaKey = Registry.LocalMachine.OpenSubKey(@\"SYSTEM\\WPA\"))\n {\n foreach (string subKey in wpaKey.GetSubKeyNames())\n {\n if (subKey.StartsWith(\"8DEC0AF1\"))\n {\n return subKey.Contains(\"P\");\n }\n }\n }\n throw new FileNotFoundException(\"Failed to autodetect key type, specify physical store key with /prod or /test arguments.\");\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/TSforge/LibTSforge/Modifiers/GenPKeyInstall.cs", "namespace LibTSforge.Modifiers\n{\n using System;\n using System.IO;\n using Microsoft.Win32;\n using PhysicalStore;\n using SPP;\n using TokenStore;\n\n public static class GenPKeyInstall\n {\n private static void WritePkey2005RegistryValues(PSVersion version, ProductKey pkey)\n {\n Logger.WriteLine(\"Writing registry data for Windows product key...\");\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"ProductId\", pkey.GetPid2());\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"DigitalProductId\", pkey.GetPid3());\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"DigitalProductId4\", pkey.GetPid4());\n\n if (Registry.GetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Registration\", \"ProductId\", null) != null)\n {\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Registration\", \"ProductId\", pkey.GetPid2());\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Registration\", \"DigitalProductId\", pkey.GetPid3());\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Registration\", \"DigitalProductId4\", pkey.GetPid4());\n }\n\n if (pkey.Channel == \"Volume:CSVLK\" && version != PSVersion.Win7)\n {\n Registry.SetValue(@\"HKEY_USERS\\S-1-5-20\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform\", \"KmsHostConfig\", 1);\n }\n }\n\n public static void InstallGenPKey(PSVersion version, bool production, Guid actId)\n {\n if (version == PSVersion.Vista) throw new NotSupportedException(\"This feature is not supported on Windows Vista/Server 2008.\");\n if (actId == Guid.Empty) throw new ArgumentException(\"Activation ID must be specified for generated product key install.\");\n\n PKeyConfig pkc = new PKeyConfig();\n \n try\n {\n pkc.LoadConfig(actId);\n }\n catch (ArgumentException)\n {\n pkc.LoadAllConfigs(SLApi.GetAppId(actId));\n }\n\n ProductConfig config;\n pkc.Products.TryGetValue(actId, out config);\n\n if (config == null) throw new ArgumentException(\"Activation ID \" + actId + \" not found in PKeyConfig.\");\n\n ProductKey pkey = config.GetRandomKey();\n\n Guid instPkeyId = SLApi.GetInstalledPkeyID(actId);\n if (instPkeyId != Guid.Empty) SLApi.UninstallProductKey(instPkeyId);\n\n if (pkey.Algorithm == PKeyAlgorithm.PKEY2009)\n {\n uint status = SLApi.InstallProductKey(pkey);\n Logger.WriteLine(string.Format(\"Installing generated product key {0} status {1:X}\", pkey, status));\n\n if ((int)status < 0)\n {\n throw new ApplicationException(\"Failed to install generated product key.\");\n }\n\n Logger.WriteLine(\"Successfully deposited generated product key.\");\n return;\n }\n\n Logger.WriteLine(\"Key range is PKEY2005, creating fake key data...\");\n\n if (pkey.Channel == \"Volume:GVLK\" && version == PSVersion.Win7) throw new NotSupportedException(\"Fake GVLK generation is not supported on Windows 7.\");\n\n VariableBag pkb = new VariableBag(version);\n pkb.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingProductKey\",\n ValueAsStr = pkey.ToString()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingMPC\",\n ValueAsStr = pkey.GetMPC()\n },\n new CRCBlockModern {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingPid2\",\n ValueAsStr = pkey.GetPid2()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingPid3\",\n Value = pkey.GetPid3()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingPid4\",\n Value = pkey.GetPid4()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyChannelId\",\n ValueAsStr = pkey.Channel\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingEditionId\",\n ValueAsStr = pkey.Edition\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = (version == PSVersion.Win7) ? \"SppPkeyShortAuthenticator\" : \"SppPkeyPhoneActivationData\",\n Value = pkey.GetPhoneData(version)\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingMiscData\",\n Value = new byte[] { }\n }\n });\n\n Guid appId = SLApi.GetAppId(actId);\n string pkeyId = pkey.GetPkeyId().ToString();\n bool isAddon = SLApi.IsAddon(actId);\n string currEdition = SLApi.GetMetaStr(actId, \"Family\");\n\n if (appId == SLApi.WINDOWS_APP_ID && !isAddon)\n {\n SLApi.UninstallAllProductKeys(appId);\n }\n\n SPPUtils.KillSPP(version);\n\n using (IPhysicalStore ps = SPPUtils.GetStore(version, production))\n {\n using (ITokenStore tks = SPPUtils.GetTokenStore(version))\n {\n Logger.WriteLine(\"Writing to physical store and token store...\");\n\n string suffix = (version == PSVersion.Win8 || version == PSVersion.WinBlue || version == PSVersion.WinModern) ? \"_--\" : \"\";\n string metSuffix = suffix + \"_met\";\n\n if (appId == SLApi.WINDOWS_APP_ID && !isAddon)\n {\n string edTokName = \"msft:spp/token/windows/productkeyid/\" + currEdition;\n\n TokenMeta edToken = tks.GetMetaEntry(edTokName);\n edToken.Data[\"windowsComponentEditionPkeyId\"] = pkeyId;\n edToken.Data[\"windowsComponentEditionSkuId\"] = actId.ToString();\n tks.SetEntry(edTokName, \"xml\", edToken.Serialize());\n\n WritePkey2005RegistryValues(version, pkey);\n }\n\n string uriMapName = \"msft:spp/token/PKeyIdUriMapper\" + metSuffix;\n TokenMeta uriMap = tks.GetMetaEntry(uriMapName);\n uriMap.Data[pkeyId] = pkey.GetAlgoUri();\n tks.SetEntry(uriMapName, \"xml\", uriMap.Serialize());\n\n string skuMetaName = actId + metSuffix;\n TokenMeta skuMeta = tks.GetMetaEntry(skuMetaName);\n\n foreach (string k in skuMeta.Data.Keys)\n {\n if (k.StartsWith(\"pkeyId_\"))\n {\n skuMeta.Data.Remove(k);\n break;\n }\n }\n\n skuMeta.Data[\"pkeyId\"] = pkeyId;\n skuMeta.Data[\"pkeyIdList\"] = pkeyId;\n tks.SetEntry(skuMetaName, \"xml\", skuMeta.Serialize());\n\n string psKey = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n ps.DeleteBlock(psKey, pkeyId);\n ps.AddBlock(new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = (version == PSVersion.WinModern) ? (uint)0x402 : 0x2,\n KeyAsStr = psKey,\n ValueAsStr = pkeyId,\n Data = pkb.Serialize()\n });\n\n string cachePath = SPPUtils.GetTokensPath(version).Replace(\"tokens.dat\", @\"cache\\cache.dat\");\n if (File.Exists(cachePath)) File.Delete(cachePath);\n }\n }\n\n SLApi.RefreshTrustedTime(actId);\n Logger.WriteLine(\"Successfully deposited fake product key.\");\n }\n }\n}\n"], ["/TSforge/TSforgeCLI/Program.cs", "namespace TSforgeCLI\n{\n using System;\n using LibTSforge;\n using LibTSforge.Activators;\n using LibTSforge.Modifiers;\n using LibTSforge.SPP;\n\n public class Program\n {\n private class Options\n {\n public bool Dump;\n public string DumpFilePath = \"dump.dat\";\n public string EncrFilePath;\n public bool Load;\n public string LoadFilePath = \"load.dat\";\n public bool KMS4k;\n public bool AVMA4k;\n public bool ZCID;\n public bool TimerReset;\n public bool RearmReset;\n public bool DeleteUniqueId;\n public bool InstallGenPKey;\n public bool KMSHostCharge;\n public bool TamperedFlagsDelete;\n public bool KeyChangeLockDelete;\n public bool SetIIDParams;\n public bool? Production;\n public PSVersion? Version;\n public Guid ActivationId = Guid.Empty;\n public bool ShowHelp;\n public PKeyAlgorithm? Algorithm;\n public int Group;\n public int Serial;\n public ulong Security;\n }\n\n public static void Main(string[] args)\n {\n Logger.WriteLine(\"TSforge (c) MASSGRAVE 2025\");\n\n Utils.Wow64EnableWow64FsRedirection(false);\n\n try\n {\n if (args.Length == 0)\n {\n DisplayUsage();\n return;\n }\n\n Options options = ParseArguments(args);\n\n if (options.ShowHelp)\n {\n DisplayUsage();\n return;\n }\n\n PSVersion version = options.Version ?? Utils.DetectVersion();\n bool production = options.Production ?? SPPUtils.DetectCurrentKey();\n\n if (options.Dump)\n {\n SPPUtils.DumpStore(version, production, options.DumpFilePath, options.EncrFilePath);\n }\n else if (options.Load)\n {\n SPPUtils.LoadStore(version, production, options.LoadFilePath);\n }\n else if (options.KMS4k)\n {\n KMS4k.Activate(version, production, options.ActivationId);\n }\n else if (options.AVMA4k)\n {\n AVMA4k.Activate(version, production, options.ActivationId);\n }\n else if (options.ZCID)\n {\n ZeroCID.Activate(version, production, options.ActivationId);\n }\n else if (options.TimerReset)\n {\n GracePeriodReset.Reset(version, production);\n }\n else if (options.DeleteUniqueId)\n {\n UniqueIdDelete.DeleteUniqueId(version, production, options.ActivationId);\n }\n else if (options.RearmReset)\n {\n RearmReset.Reset(version, production);\n }\n else if (options.InstallGenPKey)\n {\n GenPKeyInstall.InstallGenPKey(version, production, options.ActivationId);\n }\n else if (options.KMSHostCharge)\n {\n KMSHostCharge.Charge(version, production, options.ActivationId);\n }\n else if (options.TamperedFlagsDelete)\n {\n TamperedFlagsDelete.DeleteTamperFlags(version, production);\n }\n else if (options.KeyChangeLockDelete)\n {\n KeyChangeLockDelete.Delete(version, production);\n } \n else if (options.SetIIDParams)\n {\n SetIIDParams.SetParams(version, production, options.ActivationId, options.Algorithm.Value, options.Group, options.Serial, options.Security);\n }\n else\n {\n DisplayUsage();\n }\n }\n catch (Exception e)\n {\n#if DEBUG\n throw;\n#else\n Logger.WriteLine(\"Fatal error: \" + e.ToString());\n Environment.Exit(1);\n#endif\n }\n }\n\n private static Options ParseArguments(string[] args)\n {\n Options options = new Options();\n for (int i = 0; i < args.Length; i++)\n {\n string arg = args[i].Trim().ToLowerInvariant();\n switch (arg)\n {\n case \"/dump\":\n options.Dump = true;\n if (i + 1 < args.Length && !args[i + 1].StartsWith(\"/\"))\n {\n options.DumpFilePath = args[++i];\n }\n if (i + 1 < args.Length && !args[i + 1].StartsWith(\"/\"))\n {\n options.EncrFilePath = args[++i];\n }\n break;\n case \"/load\":\n options.Load = true;\n if (i + 1 < args.Length && !args[i + 1].StartsWith(\"/\"))\n {\n options.LoadFilePath = args[++i];\n }\n break;\n case \"/kms4k\":\n options.KMS4k = true;\n break;\n case \"/avma4k\":\n options.AVMA4k = true;\n break;\n case \"/zcid\":\n options.ZCID = true;\n break;\n case \"/ver\":\n options.Version = i + 1 < args.Length ? ParseVersion(args[++i]) : throw new ArgumentException(\"/ver requires a version argument.\");\n break;\n case \"/rtmr\":\n options.TimerReset = true;\n break;\n case \"/?\":\n options.ShowHelp = true;\n break;\n case \"/duid\":\n options.DeleteUniqueId = true;\n break;\n case \"/rrmc\":\n options.RearmReset = true;\n break;\n case \"/igpk\":\n options.InstallGenPKey = true;\n break;\n case \"/kmsc\":\n options.KMSHostCharge = true;\n break;\n case \"/test\":\n options.Production = false;\n break;\n case \"/prod\":\n options.Production = true;\n break;\n case \"/ctpr\":\n options.TamperedFlagsDelete = true;\n break;\n case \"/revl\":\n options.KeyChangeLockDelete = true;\n break;\n case \"/siid\":\n options.SetIIDParams = true;\n\n if (args.Length - i - 1 < 4) throw new ArgumentException(\"Not enough arguments specified.\");\n\n string algoType = args[++i];\n\n if (algoType == \"5\")\n {\n options.Algorithm = PKeyAlgorithm.PKEY2005;\n }\n else if (algoType == \"9\")\n {\n options.Algorithm = PKeyAlgorithm.PKEY2009;\n } \n else \n { \n throw new ArgumentException(\"Invalid key algorithm specified.\");\n }\n\n try\n {\n options.Group = int.Parse(args[++i]);\n options.Serial = int.Parse(args[++i]);\n options.Security = ulong.Parse(args[++i]);\n } \n catch\n {\n throw new ArgumentException(\"Failed to parse key parameters.\");\n }\n\n break;\n default:\n try\n {\n options.ActivationId = new Guid(arg);\n }\n catch (FormatException)\n {\n Logger.WriteLine(\"Argument doesn't exist or the specified activation ID is invalid.\");\n options.ShowHelp = true;\n }\n break;\n }\n }\n\n return options;\n }\n\n private static void DisplayUsage()\n {\n string exeName = typeof(Program).Namespace;\n Logger.WriteLine(\"Usage: \" + exeName + \" [/dump ()] [/load ] [/kms4k] [/avma4k] [/zcid] [/rtmr] [/duid] [/igpk] [/kmsc] [/ctpr] [/revl] [/siid <5/9> ] [/prod] [/test] [] [/ver ]\");\n Logger.WriteLine(\"Options:\");\n Logger.WriteLine(\"\\t/dump () Dump and decrypt the physical store to the specified path.\");\n Logger.WriteLine(\"\\t/load Load and re-encrypt the physical store from the specified path.\");\n Logger.WriteLine(\"\\t/kms4k Activate using KMS4k. Only supports KMS-activatable editions.\");\n Logger.WriteLine(\"\\t/avma4k Activate using AVMA4k. Only supports Windows Server 2012 R2+.\");\n Logger.WriteLine(\"\\t/zcid Activate using ZeroCID. Only supports phone-activatable editions.\");\n Logger.WriteLine(\"\\t/rtmr Reset grace/evaluation period timers.\");\n Logger.WriteLine(\"\\t/rrmc Reset the rearm count.\");\n Logger.WriteLine(\"\\t/duid Delete product key Unique ID used in online key validation.\");\n Logger.WriteLine(\"\\t/igpk Install auto-generated/fake product key according to the specified Activation ID\");\n Logger.WriteLine(\"\\t/kmsc Reset the charged count on the local KMS server to 25. Requires an activated KMS host.\");\n Logger.WriteLine(\"\\t/ctpr Remove the tamper flags that get set in the physical store when sppsvc detects an attempt to tamper with it.\");\n Logger.WriteLine(\"\\t/revl Remove the key change lock in evaluation edition store.\");\n Logger.WriteLine(\"\\t/siid <5/9> Set Installation ID parameters independently of installed key. 5/9 argument specifies PKEY200[5/9] key algorithm.\");\n Logger.WriteLine(\"\\t/prod Use SPP production key.\");\n Logger.WriteLine(\"\\t/test Use SPP test key.\");\n Logger.WriteLine(\"\\t/ver Override the detected version. Available versions: vista, 7, 8, blue, modern.\");\n Logger.WriteLine(\"\\t A specific activation ID. Useful if you want to activate specific addons like ESU.\");\n Logger.WriteLine(\"\\t/? Display this help message.\");\n }\n\n private static PSVersion ParseVersion(string ver)\n {\n switch (ver.Trim().ToLowerInvariant())\n {\n case \"vista\": return PSVersion.Vista;\n case \"7\": return PSVersion.Win7;\n case \"8\": return PSVersion.Win8;\n case \"blue\": return PSVersion.WinBlue;\n case \"modern\": return PSVersion.WinModern;\n default: throw new ArgumentException(\"Invalid version specified.\");\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/KMSHostCharge.cs", "namespace LibTSforge.Modifiers\n{\n using System;\n using System.IO;\n using PhysicalStore;\n using SPP;\n\n public static class KMSHostCharge\n {\n public static void Charge(PSVersion version, bool production, Guid actId)\n {\n if (actId == Guid.Empty)\n {\n actId = SLApi.GetDefaultActivationID(SLApi.WINDOWS_APP_ID, true);\n\n if (actId == Guid.Empty)\n {\n throw new NotSupportedException(\"No applicable activation IDs found.\");\n }\n }\n\n if (SLApi.GetPKeyChannel(SLApi.GetInstalledPkeyID(actId)) != \"Volume:CSVLK\")\n {\n throw new NotSupportedException(\"Non-Volume:CSVLK product key installed.\");\n }\n\n Guid appId = SLApi.GetAppId(actId);\n int totalClients = 50;\n int currClients = 25;\n byte[] hwidBlock = Constants.UniversalHWIDBlock;\n string key = string.Format(\"SPPSVC\\\\{0}\", appId);\n long ldapTimestamp = DateTime.Now.ToFileTime();\n\n byte[] cmidGuids = { };\n byte[] reqCounts = { };\n byte[] kmsChargeData = { };\n\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n\n if (version == PSVersion.Vista)\n {\n writer.Write(new byte[44]);\n writer.Seek(0, SeekOrigin.Begin);\n\n writer.Write(totalClients);\n writer.Write(43200);\n writer.Write(32);\n\n writer.Seek(20, SeekOrigin.Begin);\n writer.Write((byte)currClients);\n\n writer.Seek(32, SeekOrigin.Begin);\n writer.Write((byte)currClients);\n\n writer.Seek(0, SeekOrigin.End);\n\n for (int i = 0; i < currClients; i++)\n {\n writer.Write(Guid.NewGuid().ToByteArray());\n writer.Write(ldapTimestamp - (10 * (i + 1)));\n }\n\n kmsChargeData = writer.GetBytes();\n } \n else\n {\n for (int i = 0; i < currClients; i++)\n {\n writer.Write(ldapTimestamp - (10 * (i + 1)));\n writer.Write(Guid.NewGuid().ToByteArray());\n }\n\n cmidGuids = writer.GetBytes();\n\n writer = new BinaryWriter(new MemoryStream());\n\n writer.Write(new byte[40]);\n\n writer.Seek(4, SeekOrigin.Begin);\n writer.Write((byte)currClients);\n\n writer.Seek(24, SeekOrigin.Begin);\n writer.Write((byte)currClients);\n\n reqCounts = writer.GetBytes();\n }\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n if (version != PSVersion.Vista)\n {\n VariableBag kmsCountData = new VariableBag(version);\n kmsCountData.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppBindingLicenseData\",\n Value = hwidBlock\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.UINT,\n Key = new byte[] { },\n ValueAsInt = (uint)totalClients\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.UINT,\n Key = new byte[] { },\n ValueAsInt = 1051200000\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.UINT,\n Key = new byte[] { },\n ValueAsInt = (uint)currClients\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n Key = new byte[] { },\n Value = cmidGuids\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n Key = new byte[] { },\n Value = reqCounts\n }\n });\n\n kmsChargeData = kmsCountData.Serialize();\n }\n\n string countVal = version == PSVersion.Vista ? \"C8F6FFF1-79CE-404C-B150-F97991273DF1\" : string.Format(\"msft:spp/kms/host/2.0/store/counters/{0}\", appId);\n\n store.DeleteBlock(key, countVal);\n store.AddBlock(new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = (version == PSVersion.WinModern) ? (uint)0x400 : 0,\n KeyAsStr = key,\n ValueAsStr = countVal,\n Data = kmsChargeData\n });\n\n Logger.WriteLine(string.Format(\"Set charge count to {0} successfully.\", currClients));\n }\n\n SPPUtils.RestartSPP(version);\n }\n }\n}\n"], ["/TSforge/LibTSforge/Activators/KMS4K.cs", "namespace LibTSforge.Activators\n{\n using System;\n using System.IO;\n using PhysicalStore;\n using SPP;\n\n public class KMS4k\n {\n public static void Activate(PSVersion version, bool production, Guid actId)\n {\n Guid appId;\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, true);\n\n if (actId == Guid.Empty)\n {\n throw new NotSupportedException(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n if (SLApi.GetPKeyChannel(SLApi.GetInstalledPkeyID(actId)) != \"Volume:GVLK\")\n {\n throw new NotSupportedException(\"Non-Volume:GVLK product key installed.\");\n }\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n\n ulong unknown = 0;\n ulong time1;\n ulong time2 = (ulong)DateTime.UtcNow.ToFileTime();\n ulong expiry = Constants.TimerMax;\n\n if (version == PSVersion.Vista || version == PSVersion.Win7)\n {\n unknown = 0x800000000;\n time1 = 0;\n }\n else\n {\n long creationTime = BitConverter.ToInt64(store.GetBlock(\"__##USERSEP##\\\\$$_RESERVED_$$\\\\NAMESPACE__\", \"__##USERSEP-RESERVED##__$$GLOBAL-CREATION-TIME$$\").Data, 0);\n long tickCount = BitConverter.ToInt64(store.GetBlock(\"__##USERSEP##\\\\$$_RESERVED_$$\\\\NAMESPACE__\", \"__##USERSEP-RESERVED##__$$GLOBAL-TICKCOUNT-UPTIME$$\").Data, 0);\n long deltaTime = BitConverter.ToInt64(store.GetBlock(key, \"__##USERSEP-RESERVED##__$$UP-TIME-DELTA$$\").Data, 0);\n\n time1 = (ulong)(creationTime + tickCount + deltaTime);\n time2 /= 10000;\n expiry /= 10000;\n }\n\n if (version == PSVersion.Vista)\n {\n VistaTimer vistaTimer = new VistaTimer\n {\n Time = time2,\n Expiry = Constants.TimerMax\n };\n\n string vistaTimerName = string.Format(\"msft:sl/timer/VLExpiration/VOLUME/{0}/{1}\", appId, actId);\n\n store.DeleteBlock(key, vistaTimerName);\n store.DeleteBlock(key, actId.ToString());\n\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(Constants.KMSv4Response.Length);\n writer.Write(Constants.KMSv4Response);\n writer.Write(Constants.UniversalHWIDBlock);\n byte[] kmsData = writer.GetBytes();\n\n store.AddBlocks(new[]\n {\n new PSBlock\n {\n Type = BlockType.TIMER,\n Flags = 0,\n KeyAsStr = key,\n ValueAsStr = vistaTimerName,\n Data = vistaTimer.CastToArray()\n },\n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = 0,\n KeyAsStr = key,\n ValueAsStr = actId.ToString(),\n Data = kmsData\n }\n });\n }\n else\n {\n byte[] hwidBlock = Constants.UniversalHWIDBlock;\n byte[] kmsResp;\n\n switch (version)\n {\n case PSVersion.Win7:\n kmsResp = Constants.KMSv4Response;\n break;\n case PSVersion.Win8:\n kmsResp = Constants.KMSv5Response;\n break;\n case PSVersion.WinBlue:\n case PSVersion.WinModern:\n kmsResp = Constants.KMSv6Response;\n break;\n default:\n throw new NotSupportedException(\"Unsupported PSVersion.\");\n }\n\n VariableBag kmsBinding = new VariableBag(version);\n\n kmsBinding.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n Key = new byte[] { },\n Value = kmsResp\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"msft:rm/algorithm/hwid/4.0\"\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppBindingLicenseData\",\n Value = hwidBlock\n }\n });\n\n if (version == PSVersion.WinModern)\n {\n kmsBinding.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"massgrave.dev\"\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"6969\"\n }\n });\n }\n\n byte[] kmsBindingData = kmsBinding.Serialize();\n\n Timer kmsTimer = new Timer\n {\n Unknown = unknown,\n Time1 = time1,\n Time2 = time2,\n Expiry = expiry\n };\n\n string storeVal = string.Format(\"msft:spp/kms/bind/2.0/store/{0}/{1}\", appId, actId);\n string timerVal = string.Format(\"msft:spp/kms/bind/2.0/timer/{0}/{1}\", appId, actId);\n\n store.DeleteBlock(key, storeVal);\n store.DeleteBlock(key, timerVal);\n\n store.AddBlocks(new[]\n {\n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = (version == PSVersion.WinModern) ? (uint)0x400 : 0,\n KeyAsStr = key,\n ValueAsStr = storeVal,\n Data = kmsBindingData\n },\n new PSBlock\n {\n Type = BlockType.TIMER,\n Flags = (version == PSVersion.Win7) ? (uint)0 : 0x4,\n KeyAsStr = key,\n ValueAsStr = timerVal,\n Data = kmsTimer.CastToArray()\n }\n });\n }\n }\n\n SPPUtils.RestartSPP(version);\n SLApi.FireStateChangedEvent(appId);\n Logger.WriteLine(\"Activated using KMS4k successfully.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/SPP/ProductKey.cs", "namespace LibTSforge.SPP\n{\n using System;\n using System.IO;\n using System.Linq;\n using Crypto;\n using PhysicalStore;\n\n public class ProductKey\n {\n private static readonly string ALPHABET = \"BCDFGHJKMPQRTVWXY2346789\";\n\n private readonly ulong klow;\n private readonly ulong khigh;\n\n public int Group;\n public int Serial;\n public ulong Security;\n public bool Upgrade;\n public PKeyAlgorithm Algorithm;\n public readonly string EulaType;\n public readonly string PartNumber;\n public readonly string Edition;\n public readonly string Channel;\n public readonly Guid ActivationId;\n\n private string mpc;\n private string pid2;\n\n public byte[] KeyBytes\n {\n get { return BitConverter.GetBytes(klow).Concat(BitConverter.GetBytes(khigh)).ToArray(); }\n }\n\n public ProductKey()\n {\n\n }\n\n public ProductKey(int serial, ulong security, bool upgrade, PKeyAlgorithm algorithm, ProductConfig config, KeyRange range)\n {\n Group = config.GroupId;\n Serial = serial;\n Security = security;\n Upgrade = upgrade;\n Algorithm = algorithm;\n EulaType = range.EulaType;\n PartNumber = range.PartNumber.Split(':', ';')[0];\n Edition = config.Edition;\n Channel = config.Channel;\n ActivationId = config.ActivationId;\n\n klow = ((security & 0x3fff) << 50 | ((ulong)serial & 0x3fffffff) << 20 | ((ulong)Group & 0xfffff));\n khigh = ((upgrade ? (ulong)1 : 0) << 49 | ((security >> 14) & 0x7fffffffff));\n\n uint checksum = Utils.CRC32(KeyBytes) & 0x3ff;\n\n khigh |= ((ulong)checksum << 39);\n }\n\n public string GetAlgoUri()\n {\n return \"msft:rm/algorithm/pkey/\" + (Algorithm == PKeyAlgorithm.PKEY2005 ? \"2005\" : (Algorithm == PKeyAlgorithm.PKEY2009 ? \"2009\" : \"Unknown\"));\n }\n\n public Guid GetPkeyId()\n {\n VariableBag pkb = new VariableBag(PSVersion.WinModern);\n pkb.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingProductKey\",\n ValueAsStr = ToString()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingMiscData\",\n Value = new byte[] { }\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingAlgorithm\",\n ValueAsStr = GetAlgoUri()\n }\n });\n\n return new Guid(CryptoUtils.SHA256Hash(pkb.Serialize()).Take(16).ToArray());\n }\n\n public string GetMPC()\n {\n if (mpc != null)\n {\n return mpc;\n }\n\n int build = Environment.OSVersion.Version.Build;\n\n mpc = build >= 10240 ? \"03612\" :\n build >= 9600 ? \"06401\" :\n build >= 9200 ? \"05426\" :\n \"55041\";\n\n // setup.cfg doesn't exist in Windows 8+\n string setupcfg = string.Format(@\"{0}\\oobe\\{1}\", Environment.SystemDirectory, \"setup.cfg\");\n\n if (!File.Exists(setupcfg) || Edition.Contains(\";\"))\n {\n return mpc;\n }\n\n string mpcKey = string.Format(\"{0}.{1}=\", Utils.GetArchitecture(), Edition);\n string localMPC = File.ReadAllLines(setupcfg).FirstOrDefault(line => line.Contains(mpcKey));\n if (localMPC != null)\n {\n mpc = localMPC.Split('=')[1].Trim();\n }\n\n return mpc;\n }\n\n public string GetPid2()\n {\n if (pid2 != null)\n {\n return pid2;\n }\n\n pid2 = \"\";\n\n if (Algorithm == PKeyAlgorithm.PKEY2005)\n {\n string mpc = GetMPC();\n string serialHigh;\n int serialLow;\n int lastPart;\n\n if (EulaType == \"OEM\")\n {\n serialHigh = \"OEM\";\n serialLow = ((Group / 2) % 100) * 10000 + (Serial / 100000);\n lastPart = Serial % 100000;\n }\n else\n {\n serialHigh = (Serial / 1000000).ToString(\"D3\");\n serialLow = Serial % 1000000;\n lastPart = ((Group / 2) % 100) * 1000 + new Random().Next(1000);\n }\n\n int checksum = 0;\n\n foreach (char c in serialLow.ToString())\n {\n checksum += int.Parse(c.ToString());\n }\n checksum = 7 - (checksum % 7);\n\n pid2 = string.Format(\"{0}-{1}-{2:D6}{3}-{4:D5}\", mpc, serialHigh, serialLow, checksum, lastPart);\n }\n\n return pid2;\n }\n\n public byte[] GetPid3()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(0xA4);\n writer.Write(0x3);\n writer.WriteFixedString(GetPid2(), 24);\n writer.Write(Group);\n writer.WriteFixedString(PartNumber, 16);\n writer.WritePadding(0x6C);\n byte[] data = writer.GetBytes();\n byte[] crc = BitConverter.GetBytes(~Utils.CRC32(data.Reverse().ToArray())).Reverse().ToArray();\n writer.Write(crc);\n\n return writer.GetBytes();\n }\n\n public byte[] GetPid4()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(0x4F8);\n writer.Write(0x4);\n writer.WriteFixedString16(GetExtendedPid(), 0x80);\n writer.WriteFixedString16(ActivationId.ToString(), 0x80);\n writer.WritePadding(0x10);\n writer.WriteFixedString16(Edition, 0x208);\n writer.Write(Upgrade ? (ulong)1 : 0);\n writer.WritePadding(0x50);\n writer.WriteFixedString16(PartNumber, 0x80);\n writer.WriteFixedString16(Channel, 0x80);\n writer.WriteFixedString16(EulaType, 0x80);\n\n return writer.GetBytes();\n }\n\n public string GetExtendedPid()\n {\n string mpc = GetMPC();\n int serialHigh = Serial / 1000000;\n int serialLow = Serial % 1000000;\n int licenseType;\n uint lcid = Utils.GetSystemDefaultLCID();\n int build = Environment.OSVersion.Version.Build;\n int dayOfYear = DateTime.Now.DayOfYear;\n int year = DateTime.Now.Year;\n\n switch (EulaType)\n {\n case \"OEM\":\n licenseType = 2;\n break;\n\n case \"Volume\":\n licenseType = 3;\n break;\n\n default:\n licenseType = 0;\n break;\n }\n\n return string.Format(\n \"{0}-{1:D5}-{2:D3}-{3:D6}-{4:D2}-{5:D4}-{6:D4}.0000-{7:D3}{8:D4}\",\n mpc,\n Group,\n serialHigh,\n serialLow,\n licenseType,\n lcid,\n build,\n dayOfYear,\n year\n );\n }\n\n public byte[] GetPhoneData(PSVersion version)\n {\n if (version == PSVersion.Win7)\n {\n ulong shortauth = ((ulong)Group << 41) | (Security << 31) | ((ulong)Serial << 1) | (Upgrade ? (ulong)1 : 0);\n return BitConverter.GetBytes(shortauth);\n }\n\n int serialHigh = Serial / 1000000;\n int serialLow = Serial % 1000000;\n\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n string algoId = Algorithm == PKeyAlgorithm.PKEY2005 ? \"B8731595-A2F6-430B-A799-FBFFB81A8D73\" : \"660672EF-7809-4CFD-8D54-41B7FB738988\";\n\n writer.Write(new Guid(algoId).ToByteArray());\n writer.Write(Group);\n writer.Write(serialHigh);\n writer.Write(serialLow);\n writer.Write(Upgrade ? 1 : 0);\n writer.Write(Security);\n\n return writer.GetBytes();\n }\n\n public override string ToString()\n {\n string keyStr = \"\";\n Random rnd = new Random(Group * 1000000000 + Serial);\n\n if (Algorithm == PKeyAlgorithm.PKEY2005)\n {\n keyStr = \"H4X3DH4X3DH4X3DH4X3D\";\n\n for (int i = 0; i < 5; i++)\n {\n keyStr += ALPHABET[rnd.Next(24)];\n }\n }\n else if (Algorithm == PKeyAlgorithm.PKEY2009)\n {\n int last = 0;\n byte[] bKey = KeyBytes;\n\n for (int i = 24; i >= 0; i--)\n {\n int current = 0;\n\n for (int j = 14; j >= 0; j--)\n {\n current *= 0x100;\n current += bKey[j];\n bKey[j] = (byte)(current / 24);\n current %= 24;\n last = current;\n }\n\n keyStr = ALPHABET[current] + keyStr;\n }\n\n keyStr = keyStr.Substring(1, last) + \"N\" + keyStr.Substring(last + 1, keyStr.Length - last - 1);\n }\n\n for (int i = 5; i < keyStr.Length; i += 6)\n {\n keyStr = keyStr.Insert(i, \"-\");\n }\n\n return keyStr;\n }\n }\n}\n"], ["/TSforge/LibTSforge/Activators/ZeroCID.cs", "namespace LibTSforge.Activators\n{\n using System;\n using System.IO;\n using System.Linq;\n using Crypto;\n using PhysicalStore;\n using SPP;\n\n public static class ZeroCID\n {\n private static void Deposit(Guid actId, string instId)\n {\n uint status = SLApi.DepositConfirmationID(actId, instId, Constants.ZeroCID);\n Logger.WriteLine(string.Format(\"Depositing fake CID status {0:X}\", status));\n\n if (status != 0)\n {\n throw new InvalidOperationException(\"Failed to deposit fake CID.\");\n }\n }\n\n public static void Activate(PSVersion version, bool production, Guid actId)\n {\n Guid appId;\n\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, false);\n\n if (actId == Guid.Empty)\n {\n throw new NotSupportedException(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n if (!SLApi.IsPhoneActivatable(actId))\n {\n throw new NotSupportedException(\"Phone license is unavailable for this product.\");\n }\n\n string instId = SLApi.GetInstallationID(actId);\n Guid pkeyId = SLApi.GetInstalledPkeyID(actId);\n\n if (version == PSVersion.Vista || version == PSVersion.Win7)\n {\n Deposit(actId, instId);\n }\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n byte[] hwidBlock = Constants.UniversalHWIDBlock;\n\n Logger.WriteLine(\"Activation ID: \" + actId);\n Logger.WriteLine(\"Installation ID: \" + instId);\n Logger.WriteLine(\"Product Key ID: \" + pkeyId);\n\n byte[] iidHash;\n\n if (version == PSVersion.Vista)\n {\n iidHash = CryptoUtils.SHA256Hash(Utils.EncodeString(instId)).Take(0x10).ToArray();\n }\n else if (version == PSVersion.Win7)\n {\n iidHash = CryptoUtils.SHA256Hash(Utils.EncodeString(instId));\n }\n else\n {\n iidHash = CryptoUtils.SHA256Hash(Utils.EncodeString(instId + '\\0' + Constants.ZeroCID));\n }\n\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n PSBlock keyBlock = store.GetBlock(key, pkeyId.ToString());\n\n if (keyBlock == null)\n {\n throw new InvalidDataException(\"Failed to get product key data for activation ID \" + actId + \".\");\n }\n\n VariableBag pkb = new VariableBag(keyBlock.Data, version);\n\n byte[] pkeyData;\n\n if (version == PSVersion.Vista)\n {\n pkeyData = pkb.GetBlock(\"PKeyBasicInfo\").Value;\n string uniqueId = Utils.DecodeString(pkeyData.Skip(0x120).Take(0x80).ToArray());\n string extPid = Utils.DecodeString(pkeyData.Skip(0x1A0).Take(0x80).ToArray());\n\n uint group;\n uint.TryParse(extPid.Split('-')[1], out group);\n\n if (group == 0)\n {\n throw new FormatException(\"Extended PID has invalid format.\");\n }\n\n ulong shortauth;\n\n try\n {\n shortauth = BitConverter.ToUInt64(Convert.FromBase64String(uniqueId.Split('&')[1]), 0);\n } \n catch\n {\n throw new FormatException(\"Key Unique ID has invalid format.\");\n }\n\n shortauth |= (ulong)group << 41;\n pkeyData = BitConverter.GetBytes(shortauth);\n }\n else if (version == PSVersion.Win7)\n {\n pkeyData = pkb.GetBlock(\"SppPkeyShortAuthenticator\").Value;\n }\n else\n {\n pkeyData = pkb.GetBlock(\"SppPkeyPhoneActivationData\").Value;\n }\n\n pkb.DeleteBlock(\"SppPkeyVirtual\");\n store.SetBlock(key, pkeyId.ToString(), pkb.Serialize());\n\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(iidHash.Length);\n writer.Write(iidHash);\n writer.Write(hwidBlock.Length);\n writer.Write(hwidBlock);\n byte[] tsHwidData = writer.GetBytes();\n\n writer = new BinaryWriter(new MemoryStream());\n writer.Write(iidHash.Length);\n writer.Write(iidHash);\n writer.Write(pkeyData.Length);\n writer.Write(pkeyData);\n byte[] tsPkeyInfoData = writer.GetBytes();\n\n string phoneVersion = version == PSVersion.Vista ? \"6.0\" : \"7.0\";\n Guid indexSlid = version == PSVersion.Vista ? actId : pkeyId;\n string hwidBlockName = string.Format(\"msft:Windows/{0}/Phone/Cached/HwidBlock/{1}\", phoneVersion, indexSlid);\n string pkeyInfoName = string.Format(\"msft:Windows/{0}/Phone/Cached/PKeyInfo/{1}\", phoneVersion, indexSlid);\n\n store.DeleteBlock(key, hwidBlockName);\n store.DeleteBlock(key, pkeyInfoName);\n\n store.AddBlocks(new[] {\n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = 0,\n KeyAsStr = key,\n ValueAsStr = hwidBlockName,\n Data = tsHwidData\n }, \n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = 0,\n KeyAsStr = key,\n ValueAsStr = pkeyInfoName,\n Data = tsPkeyInfoData\n }\n });\n }\n\n if (version != PSVersion.Vista && version != PSVersion.Win7)\n {\n Deposit(actId, instId);\n }\n\n SPPUtils.RestartSPP(version);\n SLApi.FireStateChangedEvent(appId);\n Logger.WriteLine(\"Activated using ZeroCID successfully.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/TokenStore/TokenStoreModern.cs", "namespace LibTSforge.TokenStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using System.Linq;\n using Crypto;\n\n public class TokenStoreModern : ITokenStore\n {\n private static readonly uint VERSION = 3;\n private static readonly int ENTRY_SIZE = 0x9E;\n private static readonly int BLOCK_SIZE = 0x4020;\n private static readonly int ENTRIES_PER_BLOCK = BLOCK_SIZE / ENTRY_SIZE;\n private static readonly int BLOCK_PAD_SIZE = 0x66;\n\n private static readonly byte[] CONTS_HEADER = Enumerable.Repeat((byte)0x55, 0x20).ToArray();\n private static readonly byte[] CONTS_FOOTER = Enumerable.Repeat((byte)0xAA, 0x20).ToArray();\n\n private List Entries = new List();\n private readonly FileStream TokensFile;\n\n public void Deserialize()\n {\n if (TokensFile.Length < BLOCK_SIZE) return;\n\n TokensFile.Seek(0x24, SeekOrigin.Begin);\n uint nextBlock;\n\n BinaryReader reader = new BinaryReader(TokensFile);\n do\n {\n reader.ReadUInt32();\n nextBlock = reader.ReadUInt32();\n\n for (int i = 0; i < ENTRIES_PER_BLOCK; i++)\n {\n uint curOffset = reader.ReadUInt32();\n bool populated = reader.ReadUInt32() == 1;\n uint contentOffset = reader.ReadUInt32();\n uint contentLength = reader.ReadUInt32();\n uint allocLength = reader.ReadUInt32();\n byte[] contentData = { };\n\n if (populated)\n {\n reader.BaseStream.Seek(contentOffset + 0x20, SeekOrigin.Begin);\n uint dataLength = reader.ReadUInt32();\n\n if (dataLength != contentLength)\n {\n throw new FormatException(\"Data length in tokens content is inconsistent with entry.\");\n }\n\n reader.ReadBytes(0x20);\n contentData = reader.ReadBytes((int)contentLength);\n }\n\n reader.BaseStream.Seek(curOffset + 0x14, SeekOrigin.Begin);\n\n Entries.Add(new TokenEntry\n {\n Name = reader.ReadNullTerminatedString(0x82),\n Extension = reader.ReadNullTerminatedString(0x8),\n Data = contentData,\n Populated = populated\n });\n }\n\n reader.BaseStream.Seek(nextBlock, SeekOrigin.Begin);\n } while (nextBlock != 0);\n }\n\n public void Serialize()\n {\n MemoryStream tokens = new MemoryStream();\n\n using (BinaryWriter writer = new BinaryWriter(tokens))\n {\n writer.Write(VERSION);\n writer.Write(CONTS_HEADER);\n\n int curBlockOffset = (int)writer.BaseStream.Position;\n int curEntryOffset = curBlockOffset + 0x8;\n int curContsOffset = curBlockOffset + BLOCK_SIZE;\n\n for (int eIndex = 0; eIndex < ((Entries.Count / ENTRIES_PER_BLOCK) + 1) * ENTRIES_PER_BLOCK; eIndex++)\n {\n TokenEntry entry;\n\n if (eIndex < Entries.Count)\n {\n entry = Entries[eIndex];\n }\n else\n {\n entry = new TokenEntry\n {\n Name = \"\",\n Extension = \"\",\n Populated = false,\n Data = new byte[] { }\n };\n }\n\n writer.BaseStream.Seek(curBlockOffset, SeekOrigin.Begin);\n writer.Write(curBlockOffset);\n writer.Write(0);\n\n writer.BaseStream.Seek(curEntryOffset, SeekOrigin.Begin);\n writer.Write(curEntryOffset);\n writer.Write(entry.Populated ? 1 : 0);\n writer.Write(entry.Populated ? curContsOffset : 0);\n writer.Write(entry.Populated ? entry.Data.Length : -1);\n writer.Write(entry.Populated ? entry.Data.Length : -1);\n writer.WriteFixedString16(entry.Name, 0x82);\n writer.WriteFixedString16(entry.Extension, 0x8);\n curEntryOffset = (int)writer.BaseStream.Position;\n\n if (entry.Populated)\n {\n writer.BaseStream.Seek(curContsOffset, SeekOrigin.Begin);\n writer.Write(CONTS_HEADER);\n writer.Write(entry.Data.Length);\n writer.Write(CryptoUtils.SHA256Hash(entry.Data));\n writer.Write(entry.Data);\n writer.Write(CONTS_FOOTER);\n curContsOffset = (int)writer.BaseStream.Position;\n }\n\n if ((eIndex + 1) % ENTRIES_PER_BLOCK == 0 && eIndex != 0)\n {\n if (eIndex < Entries.Count)\n {\n writer.BaseStream.Seek(curBlockOffset + 0x4, SeekOrigin.Begin);\n writer.Write(curContsOffset);\n }\n\n writer.BaseStream.Seek(curEntryOffset, SeekOrigin.Begin);\n writer.WritePadding(BLOCK_PAD_SIZE);\n\n writer.BaseStream.Seek(curBlockOffset, SeekOrigin.Begin);\n byte[] blockData = new byte[BLOCK_SIZE - 0x20];\n\n tokens.Read(blockData, 0, BLOCK_SIZE - 0x20);\n byte[] blockHash = CryptoUtils.SHA256Hash(blockData);\n\n writer.BaseStream.Seek(curBlockOffset + BLOCK_SIZE - 0x20, SeekOrigin.Begin);\n writer.Write(blockHash);\n\n curBlockOffset = curContsOffset;\n curEntryOffset = curBlockOffset + 0x8;\n curContsOffset = curBlockOffset + BLOCK_SIZE;\n }\n }\n\n tokens.SetLength(curBlockOffset);\n }\n\n byte[] tokensData = tokens.ToArray();\n byte[] tokensHash = CryptoUtils.SHA256Hash(tokensData.Take(0x4).Concat(tokensData.Skip(0x24)).ToArray());\n\n tokens = new MemoryStream(tokensData);\n\n BinaryWriter tokWriter = new BinaryWriter(TokensFile);\n using (BinaryReader reader = new BinaryReader(tokens))\n {\n TokensFile.Seek(0, SeekOrigin.Begin);\n TokensFile.SetLength(tokens.Length);\n tokWriter.Write(reader.ReadBytes(0x4));\n reader.ReadBytes(0x20);\n tokWriter.Write(tokensHash);\n tokWriter.Write(reader.ReadBytes((int)reader.BaseStream.Length - 0x4));\n }\n }\n\n public void AddEntry(TokenEntry entry)\n {\n Entries.Add(entry);\n }\n\n public void AddEntries(TokenEntry[] entries)\n {\n Entries.AddRange(entries);\n }\n\n public void DeleteEntry(string name, string ext)\n {\n foreach (TokenEntry entry in Entries)\n {\n if (entry.Name == name && entry.Extension == ext)\n {\n Entries.Remove(entry);\n return;\n }\n }\n }\n\n public void DeleteUnpopEntry(string name, string ext)\n {\n List delEntries = new List();\n foreach (TokenEntry entry in Entries)\n {\n if (entry.Name == name && entry.Extension == ext && !entry.Populated)\n {\n delEntries.Add(entry);\n }\n }\n\n Entries = Entries.Except(delEntries).ToList();\n }\n\n public TokenEntry GetEntry(string name, string ext)\n {\n foreach (TokenEntry entry in Entries)\n {\n if (entry.Name == name && entry.Extension == ext)\n {\n if (!entry.Populated) continue;\n return entry;\n }\n }\n\n return null;\n }\n\n public TokenMeta GetMetaEntry(string name)\n {\n DeleteUnpopEntry(name, \"xml\");\n TokenEntry entry = GetEntry(name, \"xml\");\n TokenMeta meta;\n\n if (entry == null)\n {\n meta = new TokenMeta\n {\n Name = name\n };\n }\n else\n {\n meta = new TokenMeta(entry.Data);\n }\n\n return meta;\n }\n\n public void SetEntry(string name, string ext, byte[] data)\n {\n for (int i = 0; i < Entries.Count; i++)\n {\n TokenEntry entry = Entries[i];\n\n if (entry.Name == name && entry.Extension == ext && entry.Populated)\n {\n entry.Data = data;\n Entries[i] = entry;\n return;\n }\n }\n\n Entries.Add(new TokenEntry\n {\n Populated = true,\n Name = name,\n Extension = ext,\n Data = data\n });\n }\n\n public TokenStoreModern(string tokensPath)\n {\n TokensFile = File.Open(tokensPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n Deserialize();\n }\n\n public void Dispose()\n {\n Serialize();\n TokensFile.Close();\n }\n }\n}\n"], ["/TSforge/LibTSforge/SPP/PKeyConfig.cs", "namespace LibTSforge.SPP\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using System.Linq;\n using System.Text;\n using System.Xml;\n\n public enum PKeyAlgorithm\n {\n PKEY2005,\n PKEY2009\n }\n\n public class KeyRange\n {\n public int Start;\n public int End;\n public string EulaType;\n public string PartNumber;\n public bool Valid;\n\n public bool Contains(int n)\n {\n return Start <= n && End <= n;\n }\n }\n\n public class ProductConfig\n {\n public int GroupId;\n public string Edition;\n public string Description;\n public string Channel;\n public bool Randomized;\n public PKeyAlgorithm Algorithm;\n public List Ranges;\n public Guid ActivationId;\n\n private List GetPkeyRanges()\n {\n if (Ranges.Count == 0)\n {\n throw new ArgumentException(\"No key ranges.\");\n }\n\n if (Algorithm == PKeyAlgorithm.PKEY2005)\n {\n return Ranges;\n }\n\n List FilteredRanges = Ranges.Where(r => !r.EulaType.Contains(\"WAU\")).ToList();\n\n if (FilteredRanges.Count == 0)\n {\n throw new NotSupportedException(\"Specified Activation ID is usable only for Windows Anytime Upgrade. Please use a non-WAU Activation ID instead.\");\n }\n\n return FilteredRanges;\n }\n\n public ProductKey GetRandomKey()\n {\n List KeyRanges = GetPkeyRanges();\n Random rnd = new Random();\n\n KeyRange range = KeyRanges[rnd.Next(KeyRanges.Count)];\n int serial = rnd.Next(range.Start, range.End);\n\n return new ProductKey(serial, 0, false, Algorithm, this, range);\n }\n }\n\n public class PKeyConfig\n {\n public readonly Dictionary Products = new Dictionary();\n private readonly List loadedPkeyConfigs = new List();\n\n public void LoadConfig(Guid actId)\n {\n string pkcData;\n Guid pkcFileId = SLApi.GetPkeyConfigFileId(actId);\n\n if (loadedPkeyConfigs.Contains(pkcFileId)) return;\n\n string licConts = SLApi.GetLicenseContents(pkcFileId);\n\n using (TextReader tr = new StringReader(licConts))\n {\n XmlDocument lic = new XmlDocument();\n lic.Load(tr);\n\n XmlNamespaceManager nsmgr = new XmlNamespaceManager(lic.NameTable);\n nsmgr.AddNamespace(\"rg\", \"urn:mpeg:mpeg21:2003:01-REL-R-NS\");\n nsmgr.AddNamespace(\"r\", \"urn:mpeg:mpeg21:2003:01-REL-R-NS\");\n nsmgr.AddNamespace(\"tm\", \"http://www.microsoft.com/DRM/XrML2/TM/v2\");\n\n XmlNode root = lic.DocumentElement;\n XmlNode pkcDataNode = root.SelectSingleNode(\"/rg:licenseGroup/r:license/r:otherInfo/tm:infoTables/tm:infoList/tm:infoBin[@name=\\\"pkeyConfigData\\\"]\", nsmgr);\n pkcData = Encoding.UTF8.GetString(Convert.FromBase64String(pkcDataNode.InnerText));\n }\n\n using (TextReader tr = new StringReader(pkcData))\n {\n XmlDocument lic = new XmlDocument();\n lic.Load(tr);\n\n XmlNamespaceManager nsmgr = new XmlNamespaceManager(lic.NameTable);\n nsmgr.AddNamespace(\"p\", \"http://www.microsoft.com/DRM/PKEY/Configuration/2.0\");\n XmlNodeList configNodes = lic.SelectNodes(\"//p:ProductKeyConfiguration/p:Configurations/p:Configuration\", nsmgr);\n XmlNodeList rangeNodes = lic.SelectNodes(\"//p:ProductKeyConfiguration/p:KeyRanges/p:KeyRange\", nsmgr);\n XmlNodeList pubKeyNodes = lic.SelectNodes(\"//p:ProductKeyConfiguration/p:PublicKeys/p:PublicKey\", nsmgr);\n\n Dictionary algorithms = new Dictionary();\n Dictionary> ranges = new Dictionary>();\n\n Dictionary algoConv = new Dictionary\n {\n { \"msft:rm/algorithm/pkey/2005\", PKeyAlgorithm.PKEY2005 },\n { \"msft:rm/algorithm/pkey/2009\", PKeyAlgorithm.PKEY2009 }\n };\n\n foreach (XmlNode pubKeyNode in pubKeyNodes)\n {\n int group = int.Parse(pubKeyNode.SelectSingleNode(\"./p:GroupId\", nsmgr).InnerText);\n algorithms[group] = algoConv[pubKeyNode.SelectSingleNode(\"./p:AlgorithmId\", nsmgr).InnerText];\n }\n\n foreach (XmlNode rangeNode in rangeNodes)\n {\n string refActIdStr = rangeNode.SelectSingleNode(\"./p:RefActConfigId\", nsmgr).InnerText;\n\n if (!ranges.ContainsKey(refActIdStr))\n {\n ranges[refActIdStr] = new List();\n }\n\n KeyRange keyRange = new KeyRange\n {\n Start = int.Parse(rangeNode.SelectSingleNode(\"./p:Start\", nsmgr).InnerText),\n End = int.Parse(rangeNode.SelectSingleNode(\"./p:End\", nsmgr).InnerText),\n EulaType = rangeNode.SelectSingleNode(\"./p:EulaType\", nsmgr).InnerText,\n PartNumber = rangeNode.SelectSingleNode(\"./p:PartNumber\", nsmgr).InnerText,\n Valid = rangeNode.SelectSingleNode(\"./p:IsValid\", nsmgr).InnerText.ToLower() == \"true\"\n };\n\n ranges[refActIdStr].Add(keyRange);\n }\n\n foreach (XmlNode configNode in configNodes)\n {\n string refActIdStr = configNode.SelectSingleNode(\"./p:ActConfigId\", nsmgr).InnerText;\n Guid refActId = new Guid(refActIdStr);\n int group = int.Parse(configNode.SelectSingleNode(\"./p:RefGroupId\", nsmgr).InnerText);\n List keyRanges = ranges[refActIdStr];\n\n if (keyRanges.Count > 0 && !Products.ContainsKey(refActId))\n {\n ProductConfig productConfig = new ProductConfig\n {\n GroupId = group,\n Edition = configNode.SelectSingleNode(\"./p:EditionId\", nsmgr).InnerText,\n Description = configNode.SelectSingleNode(\"./p:ProductDescription\", nsmgr).InnerText,\n Channel = configNode.SelectSingleNode(\"./p:ProductKeyType\", nsmgr).InnerText,\n Randomized = configNode.SelectSingleNode(\"./p:ProductKeyType\", nsmgr).InnerText.ToLower() == \"true\",\n Algorithm = algorithms[group],\n Ranges = keyRanges,\n ActivationId = refActId\n };\n\n Products[refActId] = productConfig;\n }\n }\n }\n\n loadedPkeyConfigs.Add(pkcFileId);\n }\n\n public ProductConfig MatchParams(int group, int serial)\n {\n foreach (ProductConfig config in Products.Values)\n {\n if (config.GroupId == group)\n {\n foreach (KeyRange range in config.Ranges)\n {\n if (range.Contains(serial))\n {\n return config;\n }\n }\n }\n }\n\n throw new FileNotFoundException(\"Failed to find product matching supplied product key parameters.\");\n }\n\n public void LoadAllConfigs(Guid appId)\n {\n foreach (Guid actId in SLApi.GetActivationIds(appId))\n {\n try\n {\n LoadConfig(actId);\n } \n catch (ArgumentException)\n {\n\n }\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/Activators/AVMA4K.cs", "namespace LibTSforge.Activators\n{\n using System;\n using PhysicalStore;\n using SPP;\n\n public static class AVMA4k\n {\n public static void Activate(PSVersion version, bool production, Guid actId)\n {\n if (version != PSVersion.WinModern && version != PSVersion.WinBlue)\n {\n throw new NotSupportedException(\"AVMA licenses are not available for this product.\");\n }\n\n Guid appId;\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, false);\n\n if (actId == Guid.Empty)\n {\n throw new NotSupportedException(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n if (SLApi.GetPKeyChannel(SLApi.GetInstalledPkeyID(actId)) != \"VT:IA\")\n {\n throw new NotSupportedException(\"Non-VT:IA product key installed.\");\n }\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n\n long creationTime = BitConverter.ToInt64(store.GetBlock(\"__##USERSEP##\\\\$$_RESERVED_$$\\\\NAMESPACE__\", \"__##USERSEP-RESERVED##__$$GLOBAL-CREATION-TIME$$\").Data, 0);\n long tickCount = BitConverter.ToInt64(store.GetBlock(\"__##USERSEP##\\\\$$_RESERVED_$$\\\\NAMESPACE__\", \"__##USERSEP-RESERVED##__$$GLOBAL-TICKCOUNT-UPTIME$$\").Data, 0);\n long deltaTime = BitConverter.ToInt64(store.GetBlock(key, \"__##USERSEP-RESERVED##__$$UP-TIME-DELTA$$\").Data, 0);\n\n const ulong unknown = 0;\n ulong time1 = (ulong)(creationTime + tickCount + deltaTime);\n ulong crcBindTime = (ulong)DateTime.UtcNow.ToFileTime();\n ulong timerTime = crcBindTime / 10000;\n ulong expiry = Constants.TimerMax / 10000;\n\n VariableBag avmaBinding = new VariableBag(version);\n\n avmaBinding.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n Key = new byte[] { },\n Value = BitConverter.GetBytes(crcBindTime),\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"AVMA4K\",\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"00491-50000-00001-AA666\",\n }\n });\n\n byte[] avmaBindingData = avmaBinding.Serialize();\n\n Timer avmaTimer = new Timer\n {\n Unknown = unknown,\n Time1 = time1,\n Time2 = timerTime,\n Expiry = expiry\n };\n\n string storeVal = string.Format(\"msft:spp/ia/bind/1.0/store/{0}/{1}\", appId, actId);\n string timerVal = string.Format(\"msft:spp/ia/bind/1.0/timer/{0}/{1}\", appId, actId);\n\n store.DeleteBlock(key, storeVal);\n store.DeleteBlock(key, timerVal);\n\n store.AddBlocks(new[]\n {\n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = 0x400,\n KeyAsStr = key,\n ValueAsStr = storeVal,\n Data = avmaBindingData,\n },\n new PSBlock\n {\n Type = BlockType.TIMER,\n Flags = 0x4,\n KeyAsStr = key,\n ValueAsStr = timerVal,\n Data = avmaTimer.CastToArray()\n }\n });\n }\n\n SLApi.RefreshLicenseStatus();\n SLApi.FireStateChangedEvent(appId);\n Logger.WriteLine(\"Activated using AVMA4k successfully.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/PhysicalStoreModern.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using Crypto;\n\n public class ModernBlock\n {\n public BlockType Type;\n public uint Flags;\n public uint Unknown;\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n public byte[] Data;\n public string DataAsStr\n {\n get\n {\n return Utils.DecodeString(Data);\n }\n set\n {\n Data = Utils.EncodeString(value);\n }\n }\n public uint DataAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Data, 0);\n }\n set\n {\n Data = BitConverter.GetBytes(value);\n }\n }\n\n public void Encode(BinaryWriter writer)\n {\n writer.Write((uint)Type);\n writer.Write(Flags);\n writer.Write((uint)Value.Length);\n writer.Write((uint)Data.Length);\n writer.Write(Unknown);\n writer.Write(Value);\n writer.Write(Data);\n }\n\n public static ModernBlock Decode(BinaryReader reader)\n {\n uint type = reader.ReadUInt32();\n uint flags = reader.ReadUInt32();\n\n uint valueLen = reader.ReadUInt32();\n uint dataLen = reader.ReadUInt32();\n uint unk3 = reader.ReadUInt32();\n\n byte[] value = reader.ReadBytes((int)valueLen);\n byte[] data = reader.ReadBytes((int)dataLen);\n\n return new ModernBlock\n {\n Type = (BlockType)type,\n Flags = flags,\n Unknown = unk3,\n Value = value,\n Data = data,\n };\n }\n }\n\n public sealed class PhysicalStoreModern : IPhysicalStore\n {\n private byte[] PreHeaderBytes = { };\n private readonly Dictionary> Data = new Dictionary>();\n private readonly FileStream TSFile;\n private readonly PSVersion Version;\n private readonly bool Production;\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(PreHeaderBytes);\n writer.Write(Data.Keys.Count);\n\n foreach (string key in Data.Keys)\n {\n List blocks = Data[key];\n byte[] keyNameEnc = Utils.EncodeString(key);\n\n writer.Write(keyNameEnc.Length);\n writer.Write(keyNameEnc);\n writer.Write(blocks.Count);\n writer.Align(4);\n\n foreach (ModernBlock block in blocks)\n {\n block.Encode(writer);\n writer.Align(4);\n }\n }\n\n return writer.GetBytes();\n }\n\n public void Deserialize(byte[] data)\n {\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n PreHeaderBytes = reader.ReadBytes(8);\n\n while (reader.BaseStream.Position < data.Length - 0x4)\n {\n uint numKeys = reader.ReadUInt32();\n\n for (int i = 0; i < numKeys; i++)\n {\n uint lenKeyName = reader.ReadUInt32();\n string keyName = Utils.DecodeString(reader.ReadBytes((int)lenKeyName)); uint numValues = reader.ReadUInt32();\n\n reader.Align(4);\n\n Data[keyName] = new List();\n\n for (int j = 0; j < numValues; j++)\n {\n Data[keyName].Add(ModernBlock.Decode(reader));\n reader.Align(4);\n }\n }\n }\n }\n\n public void AddBlock(PSBlock block)\n {\n if (!Data.ContainsKey(block.KeyAsStr))\n {\n Data[block.KeyAsStr] = new List();\n }\n\n Data[block.KeyAsStr].Add(new ModernBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Unknown = block.Unknown,\n Value = block.Value,\n Data = block.Data\n });\n }\n\n public void AddBlocks(IEnumerable blocks)\n {\n foreach (PSBlock block in blocks)\n {\n AddBlock(block);\n }\n }\n\n public PSBlock GetBlock(string key, string value)\n {\n List blocks = Data[key];\n\n foreach (ModernBlock block in blocks)\n {\n if (block.ValueAsStr == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = Utils.EncodeString(key),\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public PSBlock GetBlock(string key, uint value)\n {\n List blocks = Data[key];\n\n foreach (ModernBlock block in blocks)\n {\n if (block.ValueAsInt == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = Utils.EncodeString(key),\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public void SetBlock(string key, string value, byte[] data)\n {\n List blocks = Data[key];\n\n for (int i = 0; i < blocks.Count; i++)\n {\n ModernBlock block = blocks[i];\n\n if (block.ValueAsStr == value)\n {\n block.Data = data;\n blocks[i] = block;\n break;\n }\n }\n\n Data[key] = blocks;\n }\n\n public void SetBlock(string key, uint value, byte[] data)\n {\n List blocks = Data[key];\n\n for (int i = 0; i < blocks.Count; i++)\n {\n ModernBlock block = blocks[i];\n\n if (block.ValueAsInt == value)\n {\n block.Data = data;\n blocks[i] = block;\n break;\n }\n }\n\n Data[key] = blocks;\n }\n\n public void SetBlock(string key, string value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, string value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void SetBlock(string key, uint value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, uint value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void DeleteBlock(string key, string value)\n {\n if (!Data.ContainsKey(key))\n {\n return;\n }\n\n List blocks = Data[key];\n\n foreach (ModernBlock block in blocks)\n {\n if (block.ValueAsStr == value)\n {\n blocks.Remove(block);\n break;\n }\n }\n\n Data[key] = blocks;\n }\n\n public void DeleteBlock(string key, uint value)\n {\n if (!Data.ContainsKey(key))\n {\n return;\n }\n\n List blocks = Data[key];\n\n foreach (ModernBlock block in blocks)\n {\n if (block.ValueAsInt == value)\n {\n blocks.Remove(block);\n break;\n }\n }\n\n Data[key] = blocks;\n }\n\n public PhysicalStoreModern(string tsPath, bool production, PSVersion version)\n {\n TSFile = File.Open(tsPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n Deserialize(PhysStoreCrypto.DecryptPhysicalStore(TSFile.ReadAllBytes(), production, version));\n TSFile.Seek(0, SeekOrigin.Begin);\n Version = version;\n Production = production;\n }\n\n public void Dispose()\n {\n if (TSFile.CanWrite)\n {\n byte[] data = PhysStoreCrypto.EncryptPhysicalStore(Serialize(), Production, Version);\n TSFile.SetLength(data.LongLength);\n TSFile.Seek(0, SeekOrigin.Begin);\n TSFile.WriteAllBytes(data);\n TSFile.Close();\n }\n }\n\n public byte[] ReadRaw()\n {\n byte[] data = PhysStoreCrypto.DecryptPhysicalStore(TSFile.ReadAllBytes(), Production, Version);\n TSFile.Seek(0, SeekOrigin.Begin);\n return data;\n }\n\n public void WriteRaw(byte[] data)\n {\n byte[] encrData = PhysStoreCrypto.EncryptPhysicalStore(data, Production, Version);\n TSFile.SetLength(encrData.LongLength);\n TSFile.Seek(0, SeekOrigin.Begin);\n TSFile.WriteAllBytes(encrData);\n TSFile.Close();\n }\n\n public IEnumerable FindBlocks(string valueSearch)\n {\n List results = new List();\n\n foreach (string key in Data.Keys)\n {\n List values = Data[key];\n\n foreach (ModernBlock block in values)\n {\n if (block.ValueAsStr.Contains(valueSearch))\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n KeyAsStr = key,\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n }\n\n return results;\n }\n\n public IEnumerable FindBlocks(uint valueSearch)\n {\n List results = new List();\n\n foreach (string key in Data.Keys)\n {\n List values = Data[key];\n\n foreach (ModernBlock block in values)\n {\n if (block.ValueAsInt == valueSearch)\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n KeyAsStr = key,\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n }\n\n return results;\n }\n }\n}\n"], ["/TSforge/LibTSforge/SPP/SLAPI.cs", "namespace LibTSforge.SPP\n{\n using System;\n using System.Collections.Generic;\n using System.Linq;\n using System.Runtime.InteropServices;\n using System.Text;\n\n public static class SLApi\n {\n private enum SLIDTYPE\n {\n SL_ID_APPLICATION,\n SL_ID_PRODUCT_SKU,\n SL_ID_LICENSE_FILE,\n SL_ID_LICENSE,\n SL_ID_PKEY,\n SL_ID_ALL_LICENSES,\n SL_ID_ALL_LICENSE_FILES,\n SL_ID_STORE_TOKEN,\n SL_ID_LAST\n }\n\n private enum SLDATATYPE\n {\n SL_DATA_NONE,\n SL_DATA_SZ,\n SL_DATA_DWORD,\n SL_DATA_BINARY,\n SL_DATA_MULTI_SZ,\n SL_DATA_SUM\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct SL_LICENSING_STATUS\n {\n public Guid SkuId;\n public uint eStatus;\n public uint dwGraceTime;\n public uint dwTotalGraceDays;\n public uint hrReason;\n public ulong qwValidityExpiration;\n }\n\n public static readonly Guid WINDOWS_APP_ID = new Guid(\"55c92734-d682-4d71-983e-d6ec3f16059f\");\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode, PreserveSig = false)]\n private static extern void SLOpen(out IntPtr hSLC);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode, PreserveSig = false)]\n private static extern void SLClose(IntPtr hSLC);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetWindowsInformationDWORD(string ValueName, ref int Value);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLInstallProofOfPurchase(IntPtr hSLC, string pwszPKeyAlgorithm, string pwszPKeyString, uint cbPKeySpecificData, byte[] pbPKeySpecificData, ref Guid PKeyId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLUninstallProofOfPurchase(IntPtr hSLC, ref Guid PKeyId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetPKeyInformation(IntPtr hSLC, ref Guid pPKeyId, string pwszValueName, out SLDATATYPE peDataType, out uint pcbValue, out IntPtr ppbValue);\n\n [DllImport(\"slcext.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLActivateProduct(IntPtr hSLC, ref Guid pProductSkuId, byte[] cbAppSpecificData, byte[] pvAppSpecificData, byte[] pActivationInfo, string pwszProxyServer, ushort wProxyPort);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGenerateOfflineInstallationId(IntPtr hSLC, ref Guid pProductSkuId, ref string ppwszInstallationId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLDepositOfflineConfirmationId(IntPtr hSLC, ref Guid pProductSkuId, string pwszInstallationId, string pwszConfirmationId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetSLIDList(IntPtr hSLC, SLIDTYPE eQueryIdType, ref Guid pQueryId, SLIDTYPE eReturnIdType, out uint pnReturnIds, out IntPtr ppReturnIds);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode, PreserveSig = false)]\n private static extern void SLGetLicensingStatusInformation(IntPtr hSLC, ref Guid pAppID, IntPtr pProductSkuId, string pwszRightName, out uint pnStatusCount, out IntPtr ppLicensingStatus);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetInstalledProductKeyIds(IntPtr hSLC, ref Guid pProductSkuId, out uint pnProductKeyIds, out IntPtr ppProductKeyIds);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLConsumeWindowsRight(uint unknown);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetProductSkuInformation(IntPtr hSLC, ref Guid pProductSkuId, string pwszValueName, out SLDATATYPE peDataType, out uint pcbValue, out IntPtr ppbValue);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetLicense(IntPtr hSLC, ref Guid pLicenseFileId, out uint pcbLicenseFile, out IntPtr ppbLicenseFile);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLSetCurrentProductKey(IntPtr hSLC, ref Guid pProductSkuId, ref Guid pProductKeyId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLFireEvent(IntPtr hSLC, string pwszEventId, ref Guid pApplicationId);\n\n private class SLContext : IDisposable\n {\n public readonly IntPtr Handle;\n\n public SLContext()\n {\n SLOpen(out Handle);\n }\n\n public void Dispose()\n {\n SLClose(Handle);\n GC.SuppressFinalize(this);\n }\n\n ~SLContext()\n {\n Dispose();\n }\n }\n\n public static Guid GetDefaultActivationID(Guid appId, bool includeActivated)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr pLicStat;\n\n SLGetLicensingStatusInformation(sl.Handle, ref appId, IntPtr.Zero, null, out count, out pLicStat);\n\n unsafe\n {\n SL_LICENSING_STATUS* licensingStatuses = (SL_LICENSING_STATUS*)pLicStat;\n for (int i = 0; i < count; i++)\n {\n SL_LICENSING_STATUS slStatus = licensingStatuses[i];\n\n Guid actId = slStatus.SkuId;\n if (GetInstalledPkeyID(actId) == Guid.Empty) continue;\n if (IsAddon(actId)) continue;\n if (!includeActivated && (slStatus.eStatus == 1)) continue;\n\n return actId;\n }\n }\n\n return Guid.Empty;\n }\n }\n\n public static string GetInstallationID(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n string installationId = null;\n return SLGenerateOfflineInstallationId(sl.Handle, ref actId, ref installationId) == 0 ? installationId : null;\n }\n }\n\n public static Guid GetInstalledPkeyID(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr pProductKeyIds;\n\n uint status = SLGetSLIDList(sl.Handle, SLIDTYPE.SL_ID_PRODUCT_SKU, ref actId, SLIDTYPE.SL_ID_PKEY, out count, out pProductKeyIds);\n\n if (status != 0 || count == 0)\n {\n return Guid.Empty;\n }\n\n unsafe { return *(Guid*)pProductKeyIds; }\n }\n }\n\n public static uint DepositConfirmationID(Guid actId, string installationId, string confirmationId)\n {\n using (SLContext sl = new SLContext())\n {\n return SLDepositOfflineConfirmationId(sl.Handle, ref actId, installationId, confirmationId);\n }\n }\n\n public static void RefreshLicenseStatus()\n {\n SLConsumeWindowsRight(0);\n }\n\n public static void RefreshTrustedTime(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n SLDATATYPE type;\n uint count;\n IntPtr ppbValue;\n\n SLGetProductSkuInformation(sl.Handle, ref actId, \"TrustedTime\", out type, out count, out ppbValue);\n }\n }\n\n public static void FireStateChangedEvent(Guid appId)\n {\n using (SLContext sl = new SLContext())\n {\n SLFireEvent(sl.Handle, \"msft:rm/event/licensingstatechanged\", ref appId);\n }\n }\n\n public static Guid GetAppId(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr pAppIds;\n\n uint status = SLGetSLIDList(sl.Handle, SLIDTYPE.SL_ID_PRODUCT_SKU, ref actId, SLIDTYPE.SL_ID_APPLICATION, out count, out pAppIds);\n\n if (status != 0 || count == 0)\n {\n return Guid.Empty;\n }\n\n unsafe { return *(Guid*)pAppIds; }\n }\n }\n\n public static bool IsAddon(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n SLDATATYPE type;\n IntPtr ppbValue;\n\n uint status = SLGetProductSkuInformation(sl.Handle, ref actId, \"DependsOn\", out type, out count, out ppbValue);\n return (int)status >= 0 && status != 0xC004F012;\n }\n }\n\n public static Guid GetLicenseFileId(Guid licId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr ppReturnLics;\n\n uint status = SLGetSLIDList(sl.Handle, SLIDTYPE.SL_ID_LICENSE, ref licId, SLIDTYPE.SL_ID_LICENSE_FILE, out count, out ppReturnLics);\n\n if (status != 0 || count == 0)\n {\n return Guid.Empty;\n }\n\n unsafe { return *(Guid*)ppReturnLics; }\n }\n }\n\n public static Guid GetPkeyConfigFileId(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n SLDATATYPE type;\n uint len;\n IntPtr ppReturnLics;\n\n uint status = SLGetProductSkuInformation(sl.Handle, ref actId, \"pkeyConfigLicenseId\", out type, out len, out ppReturnLics);\n\n if (status != 0 || len == 0)\n {\n return Guid.Empty;\n }\n\n Guid pkcId = new Guid(Marshal.PtrToStringAuto(ppReturnLics));\n return GetLicenseFileId(pkcId);\n }\n }\n\n public static string GetLicenseContents(Guid fileId)\n {\n if (fileId == Guid.Empty) throw new ArgumentException(\"License contents could not be retrieved.\");\n\n using (SLContext sl = new SLContext())\n {\n uint dataLen;\n IntPtr dataPtr;\n\n if (SLGetLicense(sl.Handle, ref fileId, out dataLen, out dataPtr) != 0)\n {\n return null;\n }\n\n byte[] data = new byte[dataLen];\n Marshal.Copy(dataPtr, data, 0, (int)dataLen);\n\n data = data.Skip(Array.IndexOf(data, (byte)'<')).ToArray();\n return Encoding.UTF8.GetString(data);\n }\n }\n\n public static bool IsPhoneActivatable(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n SLDATATYPE type;\n IntPtr ppbValue;\n\n uint status = SLGetProductSkuInformation(sl.Handle, ref actId, \"msft:sl/EUL/PHONE/PUBLIC\", out type, out count, out ppbValue);\n return status != 0xC004F012;\n }\n }\n\n public static string GetPKeyChannel(Guid pkeyId)\n {\n using (SLContext sl = new SLContext())\n {\n SLDATATYPE type;\n uint len;\n IntPtr ppbValue;\n\n uint status = SLGetPKeyInformation(sl.Handle, ref pkeyId, \"Channel\", out type, out len, out ppbValue);\n\n if (status != 0 || len == 0)\n {\n return null;\n }\n\n return Marshal.PtrToStringAuto(ppbValue);\n }\n }\n\n public static string GetMetaStr(Guid actId, string value)\n {\n using (SLContext sl = new SLContext())\n {\n uint len;\n SLDATATYPE type;\n IntPtr ppbValue;\n\n uint status = SLGetProductSkuInformation(sl.Handle, ref actId, value, out type, out len, out ppbValue);\n\n if (status != 0 || len == 0 || type != SLDATATYPE.SL_DATA_SZ)\n {\n return null;\n }\n\n return Marshal.PtrToStringAuto(ppbValue);\n }\n }\n\n public static List GetActivationIds(Guid appId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr pLicStat;\n\n SLGetLicensingStatusInformation(sl.Handle, ref appId, IntPtr.Zero, null, out count, out pLicStat);\n\n List result = new List();\n\n unsafe\n {\n SL_LICENSING_STATUS* licensingStatuses = (SL_LICENSING_STATUS*)pLicStat;\n for (int i = 0; i < count; i++)\n {\n result.Add(licensingStatuses[i].SkuId);\n }\n }\n\n return result;\n }\n }\n\n public static uint SetCurrentProductKey(Guid actId, Guid pkeyId)\n {\n using (SLContext sl = new SLContext())\n {\n return SLSetCurrentProductKey(sl.Handle, ref actId, ref pkeyId);\n }\n }\n\n public static uint InstallProductKey(ProductKey pkey)\n {\n using (SLContext sl = new SLContext())\n {\n Guid pkeyId = Guid.Empty;\n return SLInstallProofOfPurchase(sl.Handle, pkey.GetAlgoUri(), pkey.ToString(), 0, null, ref pkeyId);\n }\n }\n\n public static void UninstallProductKey(Guid pkeyId)\n {\n using (SLContext sl = new SLContext())\n {\n SLUninstallProofOfPurchase(sl.Handle, ref pkeyId);\n }\n }\n\n public static void UninstallAllProductKeys(Guid appId)\n {\n foreach (Guid actId in GetActivationIds(appId))\n {\n Guid pkeyId = GetInstalledPkeyID(actId);\n if (pkeyId == Guid.Empty) continue;\n if (IsAddon(actId)) continue;\n UninstallProductKey(pkeyId);\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/Crypto/PhysStoreCrypto.cs", "namespace LibTSforge.Crypto\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using System.Linq;\n using System.Text;\n\n public static class PhysStoreCrypto\n {\n public static byte[] DecryptPhysicalStore(byte[] data, bool production, PSVersion version)\n {\n byte[] rsaKey = production ? Keys.PRODUCTION : Keys.TEST;\n BinaryReader br = new BinaryReader(new MemoryStream(data));\n br.BaseStream.Seek(0x10, SeekOrigin.Begin);\n byte[] aesKeySig = br.ReadBytes(0x80);\n byte[] encAesKey = br.ReadBytes(0x80);\n\n if (!CryptoUtils.RSAVerifySignature(rsaKey, encAesKey, aesKeySig))\n {\n throw new Exception(\"Failed to decrypt physical store.\");\n }\n\n byte[] aesKey = CryptoUtils.RSADecrypt(rsaKey, encAesKey);\n byte[] decData = CryptoUtils.AESDecrypt(br.ReadBytes((int)br.BaseStream.Length - 0x110), aesKey);\n byte[] hmacKey = decData.Take(0x10).ToArray(); // SHA-1 salt on Vista\n byte[] hmacSig = decData.Skip(0x10).Take(0x14).ToArray(); // SHA-1 hash on Vista\n byte[] psData = decData.Skip(0x28).ToArray();\n\n if (version != PSVersion.Vista)\n {\n if (!CryptoUtils.HMACVerify(hmacKey, psData, hmacSig))\n {\n throw new InvalidDataException(\"Failed to verify HMAC. Physical store is corrupt.\");\n }\n }\n else\n {\n if (!CryptoUtils.SaltSHAVerify(hmacKey, psData, hmacSig))\n {\n throw new InvalidDataException(\"Failed to verify checksum. Physical store is corrupt.\");\n }\n }\n\n return psData;\n }\n\n public static byte[] EncryptPhysicalStore(byte[] data, bool production, PSVersion version)\n {\n Dictionary versionTable = new Dictionary\n {\n {PSVersion.Vista, 2},\n {PSVersion.Win7, 5},\n {PSVersion.Win8, 1},\n {PSVersion.WinBlue, 2},\n {PSVersion.WinModern, 3}\n };\n\n byte[] rsaKey = production ? Keys.PRODUCTION : Keys.TEST;\n\n byte[] aesKey = Encoding.UTF8.GetBytes(\"massgrave.dev :3\");\n byte[] hmacKey = CryptoUtils.GenerateRandomKey(0x10);\n\n byte[] encAesKey = CryptoUtils.RSAEncrypt(rsaKey, aesKey);\n byte[] aesKeySig = CryptoUtils.RSASign(rsaKey, encAesKey);\n byte[] hmacSig = version != PSVersion.Vista ? CryptoUtils.HMACSign(hmacKey, data) : CryptoUtils.SaltSHASum(hmacKey, data);\n\n byte[] decData = { };\n decData = decData.Concat(hmacKey).Concat(hmacSig).Concat(BitConverter.GetBytes(0)).Concat(data).ToArray();\n byte[] encData = CryptoUtils.AESEncrypt(decData, aesKey);\n\n BinaryWriter bw = new BinaryWriter(new MemoryStream());\n bw.Write(versionTable[version]);\n bw.Write(Encoding.UTF8.GetBytes(\"UNTRUSTSTORE\"));\n bw.Write(aesKeySig);\n bw.Write(encAesKey);\n bw.Write(encData);\n\n return bw.GetBytes();\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/PhysicalStoreWin7.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using Crypto;\n\n public class Win7Block\n {\n public BlockType Type;\n public uint Flags;\n public byte[] Key;\n public string KeyAsStr\n {\n get\n {\n return Utils.DecodeString(Key);\n }\n set\n {\n Key = Utils.EncodeString(value);\n }\n }\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n public byte[] Data;\n public string DataAsStr\n {\n get\n {\n return Utils.DecodeString(Data);\n }\n set\n {\n Data = Utils.EncodeString(value);\n }\n }\n public uint DataAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Data, 0);\n }\n set\n {\n Data = BitConverter.GetBytes(value);\n }\n }\n\n internal void Encode(BinaryWriter writer)\n {\n writer.Write((uint)Type);\n writer.Write(Flags);\n writer.Write(Key.Length);\n writer.Write(Value.Length);\n writer.Write(Data.Length);\n writer.Write(Key);\n writer.Write(Value);\n writer.Write(Data);\n }\n\n internal static Win7Block Decode(BinaryReader reader)\n {\n uint type = reader.ReadUInt32();\n uint flags = reader.ReadUInt32();\n\n int keyLen = reader.ReadInt32();\n int valueLen = reader.ReadInt32();\n int dataLen = reader.ReadInt32();\n\n byte[] key = reader.ReadBytes(keyLen);\n byte[] value = reader.ReadBytes(valueLen);\n byte[] data = reader.ReadBytes(dataLen);\n return new Win7Block\n {\n Type = (BlockType)type,\n Flags = flags,\n Key = key,\n Value = value,\n Data = data,\n };\n }\n }\n\n public sealed class PhysicalStoreWin7 : IPhysicalStore\n {\n private byte[] PreHeaderBytes = { };\n private readonly List Blocks = new List();\n private readonly FileStream TSPrimary;\n private readonly FileStream TSSecondary;\n private readonly bool Production;\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(PreHeaderBytes);\n\n foreach (Win7Block block in Blocks)\n {\n block.Encode(writer);\n writer.Align(4);\n }\n\n return writer.GetBytes();\n }\n\n public void Deserialize(byte[] data)\n {\n int len = data.Length;\n\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n PreHeaderBytes = reader.ReadBytes(8);\n\n while (reader.BaseStream.Position < len - 0x14)\n {\n Blocks.Add(Win7Block.Decode(reader));\n reader.Align(4);\n }\n }\n\n public void AddBlock(PSBlock block)\n {\n Blocks.Add(new Win7Block\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n });\n }\n\n public void AddBlocks(IEnumerable blocks)\n {\n foreach (PSBlock block in blocks)\n {\n AddBlock(block);\n }\n }\n\n public PSBlock GetBlock(string key, string value)\n {\n foreach (Win7Block block in Blocks)\n {\n if (block.KeyAsStr == key && block.ValueAsStr == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public PSBlock GetBlock(string key, uint value)\n {\n foreach (Win7Block block in Blocks)\n {\n if (block.KeyAsStr == key && block.ValueAsInt == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public void SetBlock(string key, string value, byte[] data)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n Win7Block block = Blocks[i];\n\n if (block.KeyAsStr == key && block.ValueAsStr == value)\n {\n block.Data = data;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void SetBlock(string key, uint value, byte[] data)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n Win7Block block = Blocks[i];\n\n if (block.KeyAsStr == key && block.ValueAsInt == value)\n {\n block.Data = data;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void SetBlock(string key, string value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, string value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void SetBlock(string key, uint value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, uint value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void DeleteBlock(string key, string value)\n {\n foreach (Win7Block block in Blocks)\n {\n if (block.KeyAsStr == key && block.ValueAsStr == value)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public void DeleteBlock(string key, uint value)\n {\n foreach (Win7Block block in Blocks)\n {\n if (block.KeyAsStr == key && block.ValueAsInt == value)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public PhysicalStoreWin7(string primaryPath, bool production)\n {\n TSPrimary = File.Open(primaryPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n TSSecondary = File.Open(primaryPath.Replace(\"-0.\", \"-1.\"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n Production = production;\n\n Deserialize(PhysStoreCrypto.DecryptPhysicalStore(TSPrimary.ReadAllBytes(), production, PSVersion.Win7));\n TSPrimary.Seek(0, SeekOrigin.Begin);\n }\n\n public void Dispose()\n {\n if (TSPrimary.CanWrite && TSSecondary.CanWrite)\n {\n byte[] data = PhysStoreCrypto.EncryptPhysicalStore(Serialize(), Production, PSVersion.Win7);\n\n TSPrimary.SetLength(data.LongLength);\n TSSecondary.SetLength(data.LongLength);\n\n TSPrimary.Seek(0, SeekOrigin.Begin);\n TSSecondary.Seek(0, SeekOrigin.Begin);\n\n TSPrimary.WriteAllBytes(data);\n TSSecondary.WriteAllBytes(data);\n\n TSPrimary.Close();\n TSSecondary.Close();\n }\n }\n\n public byte[] ReadRaw()\n {\n byte[] data = PhysStoreCrypto.DecryptPhysicalStore(TSPrimary.ReadAllBytes(), Production, PSVersion.Win7);\n TSPrimary.Seek(0, SeekOrigin.Begin);\n return data;\n }\n\n public void WriteRaw(byte[] data)\n {\n byte[] encrData = PhysStoreCrypto.EncryptPhysicalStore(data, Production, PSVersion.Win7);\n\n TSPrimary.SetLength(encrData.LongLength);\n TSSecondary.SetLength(encrData.LongLength);\n\n TSPrimary.Seek(0, SeekOrigin.Begin);\n TSSecondary.Seek(0, SeekOrigin.Begin);\n\n TSPrimary.WriteAllBytes(encrData);\n TSSecondary.WriteAllBytes(encrData);\n\n TSPrimary.Close();\n TSSecondary.Close();\n }\n\n public IEnumerable FindBlocks(string valueSearch)\n {\n List results = new List();\n\n foreach (Win7Block block in Blocks)\n {\n if (block.ValueAsStr.Contains(valueSearch))\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n\n return results;\n }\n\n public IEnumerable FindBlocks(uint valueSearch)\n {\n List results = new List();\n\n foreach (Win7Block block in Blocks)\n {\n if (block.ValueAsInt == valueSearch)\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n\n return results;\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/PhysicalStoreVista.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using Crypto;\n\n public class VistaBlock\n {\n public BlockType Type;\n public uint Flags;\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n public byte[] Data;\n public string DataAsStr\n {\n get\n {\n return Utils.DecodeString(Data);\n }\n set\n {\n Data = Utils.EncodeString(value);\n }\n }\n public uint DataAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Data, 0);\n }\n set\n {\n Data = BitConverter.GetBytes(value);\n }\n }\n\n internal void Encode(BinaryWriter writer)\n {\n writer.Write((uint)Type);\n writer.Write(Flags);\n writer.Write(Value.Length);\n writer.Write(Data.Length);\n writer.Write(Value);\n writer.Write(Data);\n }\n\n internal static VistaBlock Decode(BinaryReader reader)\n {\n uint type = reader.ReadUInt32();\n uint flags = reader.ReadUInt32();\n\n int valueLen = reader.ReadInt32();\n int dataLen = reader.ReadInt32();\n\n byte[] value = reader.ReadBytes(valueLen);\n byte[] data = reader.ReadBytes(dataLen);\n return new VistaBlock\n {\n Type = (BlockType)type,\n Flags = flags,\n Value = value,\n Data = data,\n };\n }\n }\n\n public sealed class PhysicalStoreVista : IPhysicalStore\n {\n private byte[] PreHeaderBytes = { };\n private readonly List Blocks = new List();\n private readonly FileStream TSPrimary;\n private readonly FileStream TSSecondary;\n private readonly bool Production;\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(PreHeaderBytes);\n\n foreach (VistaBlock block in Blocks)\n {\n block.Encode(writer);\n writer.Align(4);\n }\n\n return writer.GetBytes();\n }\n\n public void Deserialize(byte[] data)\n {\n int len = data.Length;\n\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n PreHeaderBytes = reader.ReadBytes(8);\n\n while (reader.BaseStream.Position < len - 0x14)\n {\n Blocks.Add(VistaBlock.Decode(reader));\n reader.Align(4);\n }\n }\n\n public void AddBlock(PSBlock block)\n {\n Blocks.Add(new VistaBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Value = block.Value,\n Data = block.Data\n });\n }\n\n public void AddBlocks(IEnumerable blocks)\n {\n foreach (PSBlock block in blocks)\n {\n AddBlock(block);\n }\n }\n\n public PSBlock GetBlock(string key, string value)\n {\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsStr == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = new byte[0],\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public PSBlock GetBlock(string key, uint value)\n {\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsInt == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = new byte[0],\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public void SetBlock(string key, string value, byte[] data)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n VistaBlock block = Blocks[i];\n\n if (block.ValueAsStr == value)\n {\n block.Data = data;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void SetBlock(string key, uint value, byte[] data)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n VistaBlock block = Blocks[i];\n\n if (block.ValueAsInt == value)\n {\n block.Data = data;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void SetBlock(string key, string value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, string value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void SetBlock(string key, uint value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, uint value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void DeleteBlock(string key, string value)\n {\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsStr == value)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public void DeleteBlock(string key, uint value)\n {\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsInt == value)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public PhysicalStoreVista(string primaryPath, bool production)\n {\n TSPrimary = File.Open(primaryPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n TSSecondary = File.Open(primaryPath.Replace(\"-0.\", \"-1.\"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n Production = production;\n\n Deserialize(PhysStoreCrypto.DecryptPhysicalStore(TSPrimary.ReadAllBytes(), production, PSVersion.Vista));\n TSPrimary.Seek(0, SeekOrigin.Begin);\n }\n\n public void Dispose()\n {\n if (TSPrimary.CanWrite && TSSecondary.CanWrite)\n {\n byte[] data = PhysStoreCrypto.EncryptPhysicalStore(Serialize(), Production, PSVersion.Vista);\n\n TSPrimary.SetLength(data.LongLength);\n TSSecondary.SetLength(data.LongLength);\n\n TSPrimary.Seek(0, SeekOrigin.Begin);\n TSSecondary.Seek(0, SeekOrigin.Begin);\n\n TSPrimary.WriteAllBytes(data);\n TSSecondary.WriteAllBytes(data);\n\n TSPrimary.Close();\n TSSecondary.Close();\n }\n }\n\n public byte[] ReadRaw()\n {\n byte[] data = PhysStoreCrypto.DecryptPhysicalStore(TSPrimary.ReadAllBytes(), Production, PSVersion.Vista);\n TSPrimary.Seek(0, SeekOrigin.Begin);\n return data;\n }\n\n public void WriteRaw(byte[] data)\n {\n byte[] encrData = PhysStoreCrypto.EncryptPhysicalStore(data, Production, PSVersion.Vista);\n\n TSPrimary.SetLength(encrData.LongLength);\n TSSecondary.SetLength(encrData.LongLength);\n\n TSPrimary.Seek(0, SeekOrigin.Begin);\n TSSecondary.Seek(0, SeekOrigin.Begin);\n\n TSPrimary.WriteAllBytes(encrData);\n TSSecondary.WriteAllBytes(encrData);\n\n TSPrimary.Close();\n TSSecondary.Close();\n }\n\n public IEnumerable FindBlocks(string valueSearch)\n {\n List results = new List();\n\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsStr.Contains(valueSearch))\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = new byte[0],\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n\n return results;\n }\n\n public IEnumerable FindBlocks(uint valueSearch)\n {\n List results = new List();\n\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsInt == valueSearch)\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = new byte[0],\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n\n return results;\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/SetIIDParams.cs", "namespace LibTSforge.Modifiers\n{\n using PhysicalStore;\n using SPP;\n using System.IO;\n using System;\n\n public static class SetIIDParams\n {\n public static void SetParams(PSVersion version, bool production, Guid actId, PKeyAlgorithm algorithm, int group, int serial, ulong security)\n {\n if (version == PSVersion.Vista) throw new NotSupportedException(\"This feature is not supported on Windows Vista/Server 2008.\");\n\n Guid appId;\n\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, true);\n\n if (actId == Guid.Empty)\n {\n throw new Exception(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n Guid pkeyId = SLApi.GetInstalledPkeyID(actId);\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n PSBlock keyBlock = store.GetBlock(key, pkeyId.ToString());\n\n if (keyBlock == null)\n {\n throw new InvalidDataException(\"Failed to get product key data for activation ID \" + actId + \".\");\n }\n\n VariableBag pkb = new VariableBag(keyBlock.Data, version);\n\n ProductKey pkey = new ProductKey\n {\n Group = group,\n Serial = serial,\n Security = security,\n Algorithm = algorithm,\n Upgrade = false\n };\n\n string blockName = version == PSVersion.Win7 ? \"SppPkeyShortAuthenticator\" : \"SppPkeyPhoneActivationData\";\n pkb.SetBlock(blockName, pkey.GetPhoneData(version));\n store.SetBlock(key, pkeyId.ToString(), pkb.Serialize());\n }\n\n Logger.WriteLine(\"Successfully set IID parameters.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/RearmReset.cs", "namespace LibTSforge.Modifiers\n{\n using System.Collections.Generic;\n using System.Linq;\n using PhysicalStore;\n using SPP;\n\n public static class RearmReset\n {\n public static void Reset(PSVersion version, bool production)\n {\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n List blocks;\n\n if (version == PSVersion.Vista)\n {\n blocks = store.FindBlocks(\"740D70D8-6448-4b2f-9063-4A7A463600C5\").ToList();\n }\n else if (version == PSVersion.Win7)\n {\n blocks = store.FindBlocks(0xA0000).ToList();\n }\n else\n {\n blocks = store.FindBlocks(\"__##USERSEP-RESERVED##__$$REARM-COUNT$$\").ToList();\n }\n\n foreach (PSBlock block in blocks)\n {\n if (version == PSVersion.Vista)\n {\n store.DeleteBlock(block.KeyAsStr, block.ValueAsStr);\n }\n else if (version == PSVersion.Win7)\n {\n store.SetBlock(block.KeyAsStr, block.ValueAsInt, new byte[8]);\n }\n else\n {\n store.SetBlock(block.KeyAsStr, block.ValueAsStr, new byte[8]);\n }\n }\n\n Logger.WriteLine(\"Successfully reset all rearm counters.\");\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/UniqueIdDelete.cs", "namespace LibTSforge.Modifiers\n{\n using System;\n using PhysicalStore;\n using SPP;\n\n public static class UniqueIdDelete\n {\n public static void DeleteUniqueId(PSVersion version, bool production, Guid actId)\n {\n if (version == PSVersion.Vista) throw new NotSupportedException(\"This feature is not supported on Windows Vista/Server 2008.\");\n\n Guid appId;\n\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, true);\n\n if (actId == Guid.Empty)\n {\n throw new Exception(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n Guid pkeyId = SLApi.GetInstalledPkeyID(actId);\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n PSBlock keyBlock = store.GetBlock(key, pkeyId.ToString());\n\n if (keyBlock == null)\n {\n throw new Exception(\"No product key found.\");\n }\n\n VariableBag pkb = new VariableBag(keyBlock.Data, version);\n\n pkb.DeleteBlock(\"SppPkeyUniqueIdToken\");\n\n store.SetBlock(key, pkeyId.ToString(), pkb.Serialize());\n }\n\n Logger.WriteLine(\"Successfully removed Unique ID for product key ID \" + pkeyId);\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/KeyChangeLockDelete.cs", "namespace LibTSforge.Modifiers\n{\n using System.Collections.Generic;\n using System.Linq;\n using PhysicalStore;\n using SPP;\n using System;\n\n public static class KeyChangeLockDelete\n {\n public static void Delete(PSVersion version, bool production)\n {\n if (version == PSVersion.Vista) throw new NotSupportedException(\"This feature is not supported on Windows Vista/Server 2008.\");\n\n SPPUtils.KillSPP(version);\n Logger.WriteLine(\"Writing TrustedStore data...\");\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n List values = new List\n {\n \"msft:spp/timebased/AB\",\n \"msft:spp/timebased/CD\"\n };\n List blocks = new List();\n foreach (string value in values)\n {\n blocks.AddRange(store.FindBlocks(value).ToList());\n }\n foreach (PSBlock block in blocks)\n {\n store.DeleteBlock(block.KeyAsStr, block.ValueAsStr);\n }\n }\n Logger.WriteLine(\"Successfully removed the key change lock.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/TamperedFlagsDelete.cs", "namespace LibTSforge.Modifiers\n{\n using System.Linq;\n using PhysicalStore;\n using SPP;\n\n public static class TamperedFlagsDelete\n {\n public static void DeleteTamperFlags(PSVersion version, bool production)\n {\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n if (version == PSVersion.Vista)\n {\n DeleteFlag(store, \"6BE8425B-E3CF-4e86-A6AF-5863E3DCB606\");\n }\n else if (version == PSVersion.Win7)\n {\n SetFlag(store, 0xA0001);\n }\n else\n {\n DeleteFlag(store, \"__##USERSEP-RESERVED##__$$RECREATED-FLAG$$\");\n DeleteFlag(store, \"__##USERSEP-RESERVED##__$$RECOVERED-FLAG$$\");\n }\n\n Logger.WriteLine(\"Successfully cleared the tamper state.\");\n }\n\n SPPUtils.RestartSPP(version);\n }\n\n private static void DeleteFlag(IPhysicalStore store, string flag)\n {\n store.FindBlocks(flag).ToList().ForEach(block => store.DeleteBlock(block.KeyAsStr, block.ValueAsStr));\n }\n\n private static void SetFlag(IPhysicalStore store, uint flag)\n {\n store.FindBlocks(flag).ToList().ForEach(block => store.SetBlock(block.KeyAsStr, block.ValueAsInt, new byte[8]));\n }\n }\n}\n"], ["/TSforge/LibTSforge/Common.cs", "namespace LibTSforge\n{\n using System;\n using System.IO;\n using System.Linq;\n using System.Runtime.InteropServices;\n using System.Text;\n\n public enum PSVersion\n {\n Vista,\n Win7,\n Win8,\n WinBlue,\n WinModern\n }\n\n public static class Constants\n {\n public static readonly byte[] UniversalHWIDBlock =\n {\n 0x26, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x01, 0x0c, 0x01, 0x00\n };\n\n public static readonly byte[] KMSv4Response =\n {\n 0x00, 0x00, 0x04, 0x00, 0x62, 0x00, 0x00, 0x00, 0x30, 0x00, 0x35, 0x00, 0x34, 0x00, 0x32, 0x00,\n 0x36, 0x00, 0x2D, 0x00, 0x30, 0x00, 0x30, 0x00, 0x32, 0x00, 0x30, 0x00, 0x36, 0x00, 0x2D, 0x00,\n 0x31, 0x00, 0x36, 0x00, 0x31, 0x00, 0x2D, 0x00, 0x36, 0x00, 0x35, 0x00, 0x35, 0x00, 0x35, 0x00,\n 0x30, 0x00, 0x36, 0x00, 0x2D, 0x00, 0x30, 0x00, 0x33, 0x00, 0x2D, 0x00, 0x31, 0x00, 0x30, 0x00,\n 0x33, 0x00, 0x33, 0x00, 0x2D, 0x00, 0x39, 0x00, 0x32, 0x00, 0x30, 0x00, 0x30, 0x00, 0x2E, 0x00,\n 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x2D, 0x00, 0x30, 0x00, 0x36, 0x00, 0x35, 0x00,\n 0x32, 0x00, 0x30, 0x00, 0x31, 0x00, 0x33, 0x00, 0x00, 0x00, 0xDE, 0x19, 0x02, 0xCF, 0x1F, 0x35,\n 0x97, 0x4E, 0x8A, 0x8F, 0xB8, 0x07, 0xB1, 0x92, 0xB5, 0xB5, 0x97, 0x42, 0xEC, 0x3A, 0x76, 0x84,\n 0xD5, 0x01, 0x32, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00, 0x60, 0x27, 0x00, 0x00, 0xC4, 0x1E,\n 0xAA, 0x8B, 0xDD, 0x0C, 0xAB, 0x55, 0x6A, 0xCE, 0xAF, 0xAC, 0x7F, 0x5F, 0xBD, 0xE9\n };\n\n public static readonly byte[] KMSv5Response =\n {\n 0x00, 0x00, 0x05, 0x00, 0xBE, 0x96, 0xF9, 0x04, 0x54, 0x17, 0x3F, 0xAF, 0xE3, 0x08, 0x50, 0xEB,\n 0x22, 0xBA, 0x53, 0xBF, 0xF2, 0x6A, 0x7B, 0xC9, 0x05, 0x1D, 0xB5, 0x19, 0xDF, 0x98, 0xE2, 0x71,\n 0x4D, 0x00, 0x61, 0xE9, 0x9D, 0x03, 0xFB, 0x31, 0xF9, 0x1F, 0x2E, 0x60, 0x59, 0xC7, 0x73, 0xC8,\n 0xE8, 0xB6, 0xE1, 0x2B, 0x39, 0xC6, 0x35, 0x0E, 0x68, 0x7A, 0xAA, 0x4F, 0x28, 0x23, 0x12, 0x18,\n 0xE3, 0xAA, 0x84, 0x81, 0x6E, 0x82, 0xF0, 0x3F, 0xD9, 0x69, 0xA9, 0xDF, 0xBA, 0x5F, 0xCA, 0x32,\n 0x54, 0xB2, 0x52, 0x3B, 0x3E, 0xD1, 0x5C, 0x65, 0xBC, 0x3E, 0x59, 0x0D, 0x15, 0x9F, 0x37, 0xEC,\n 0x30, 0x9C, 0xCC, 0x1B, 0x39, 0x0D, 0x21, 0x32, 0x29, 0xA2, 0xDD, 0xC7, 0xC1, 0x69, 0xF2, 0x72,\n 0x3F, 0x00, 0x98, 0x1E, 0xF8, 0x9A, 0x79, 0x44, 0x5D, 0x25, 0x80, 0x7B, 0xF5, 0xE1, 0x7C, 0x68,\n 0x25, 0xAA, 0x0D, 0x67, 0x98, 0xE5, 0x59, 0x9B, 0x04, 0xC1, 0x23, 0x33, 0x48, 0xFB, 0x28, 0xD0,\n 0x76, 0xDF, 0x01, 0x56, 0xE7, 0xEC, 0xBF, 0x1A, 0xA2, 0x22, 0x28, 0xCA, 0xB1, 0xB4, 0x4C, 0x30,\n 0x14, 0x6F, 0xD2, 0x2E, 0x01, 0x2A, 0x04, 0xE3, 0xBD, 0xA7, 0x41, 0x2F, 0xC9, 0xEF, 0x53, 0xC0,\n 0x70, 0x48, 0xF1, 0xB2, 0xB6, 0xEA, 0xE7, 0x0F, 0x7A, 0x15, 0xD1, 0xA6, 0xFE, 0x23, 0xC8, 0xF3,\n 0xE1, 0x02, 0x9E, 0xA0, 0x4E, 0xBD, 0xF5, 0xEA, 0x53, 0x74, 0x8E, 0x74, 0xA1, 0xA1, 0xBD, 0xBE,\n 0x66, 0xC4, 0x73, 0x8F, 0x24, 0xA7, 0x2A, 0x2F, 0xE3, 0xD9, 0xF4, 0x28, 0xD9, 0xF8, 0xA3, 0x93,\n 0x03, 0x9E, 0x29, 0xAB\n };\n\n public static readonly byte[] KMSv6Response =\n {\n 0x00, 0x00, 0x06, 0x00, 0x54, 0xD3, 0x40, 0x08, 0xF3, 0xCD, 0x03, 0xEF, 0xC8, 0x15, 0x87, 0x9E,\n 0xCA, 0x2E, 0x85, 0xFB, 0xE6, 0xF6, 0x73, 0x66, 0xFB, 0xDA, 0xBB, 0x7B, 0xB1, 0xBC, 0xD6, 0xF9,\n 0x5C, 0x41, 0xA0, 0xFE, 0xE1, 0x74, 0xC4, 0xBB, 0x91, 0xE5, 0xDE, 0x6D, 0x3A, 0x11, 0xD5, 0xFC,\n 0x68, 0xC0, 0x7B, 0x82, 0xB2, 0x24, 0xD1, 0x85, 0xBA, 0x45, 0xBF, 0xF1, 0x26, 0xFA, 0xA5, 0xC6,\n 0x61, 0x70, 0x69, 0x69, 0x6E, 0x0F, 0x0B, 0x60, 0xB7, 0x3D, 0xE8, 0xF1, 0x47, 0x0B, 0x65, 0xFD,\n 0xA7, 0x30, 0x1E, 0xF6, 0xA4, 0xD0, 0x79, 0xC4, 0x58, 0x8D, 0x81, 0xFD, 0xA7, 0xE7, 0x53, 0xF1,\n 0x67, 0x78, 0xF0, 0x0F, 0x60, 0x8F, 0xC8, 0x16, 0x35, 0x22, 0x94, 0x48, 0xCB, 0x0F, 0x8E, 0xB2,\n 0x1D, 0xF7, 0x3E, 0x28, 0x42, 0x55, 0x6B, 0x07, 0xE3, 0xE8, 0x51, 0xD5, 0xFA, 0x22, 0x0C, 0x86,\n 0x65, 0x0D, 0x3F, 0xDD, 0x8D, 0x9B, 0x1B, 0xC9, 0xD3, 0xB8, 0x3A, 0xEC, 0xF1, 0x11, 0x19, 0x25,\n 0xF7, 0x84, 0x4A, 0x4C, 0x0A, 0xB5, 0x31, 0x94, 0x37, 0x76, 0xCE, 0xE7, 0xAB, 0xA9, 0x69, 0xDF,\n 0xA4, 0xC9, 0x22, 0x6C, 0x23, 0xFF, 0x6B, 0xFC, 0xDA, 0x78, 0xD8, 0xC4, 0x8F, 0x74, 0xBB, 0x26,\n 0x05, 0x00, 0x98, 0x9B, 0xE5, 0xE2, 0xAD, 0x0D, 0x57, 0x95, 0x80, 0x66, 0x8E, 0x43, 0x74, 0x87,\n 0x93, 0x1F, 0xF4, 0xB2, 0x2C, 0x20, 0x5F, 0xD8, 0x9C, 0x4C, 0x56, 0xB3, 0x57, 0x44, 0x62, 0x68,\n 0x8D, 0xAA, 0x40, 0x11, 0x9D, 0x84, 0x62, 0x0E, 0x43, 0x8A, 0x1D, 0xF0, 0x1C, 0x49, 0xD8, 0x56,\n 0xEF, 0x4C, 0xD3, 0x64, 0xBA, 0x0D, 0xEF, 0x87, 0xB5, 0x2C, 0x88, 0xF3, 0x18, 0xFF, 0x3A, 0x8C,\n 0xF5, 0xA6, 0x78, 0x5C, 0x62, 0xE3, 0x9E, 0x4C, 0xB6, 0x31, 0x2D, 0x06, 0x80, 0x92, 0xBC, 0x2E,\n 0x92, 0xA6, 0x56, 0x96\n };\n\n // 2^31 - 8 minutes\n public static readonly ulong TimerMax = (ulong)TimeSpan.FromMinutes(2147483640).Ticks;\n\n public static readonly string ZeroCID = new string('0', 48);\n }\n\n public static class BinaryReaderExt\n {\n public static void Align(this BinaryReader reader, int to)\n {\n int pos = (int)reader.BaseStream.Position;\n reader.BaseStream.Seek(-pos & (to - 1), SeekOrigin.Current);\n }\n\n public static string ReadNullTerminatedString(this BinaryReader reader, int maxLen)\n {\n return Encoding.Unicode.GetString(reader.ReadBytes(maxLen)).Split(new char[] { '\\0' }, 2)[0];\n }\n }\n\n public static class BinaryWriterExt\n {\n public static void Align(this BinaryWriter writer, int to)\n {\n int pos = (int)writer.BaseStream.Position;\n writer.WritePadding(-pos & (to - 1));\n }\n\n public static void WritePadding(this BinaryWriter writer, int len)\n {\n writer.Write(Enumerable.Repeat((byte)0, len).ToArray());\n }\n\n public static void WriteFixedString(this BinaryWriter writer, string str, int bLen)\n {\n writer.Write(Encoding.ASCII.GetBytes(str));\n writer.WritePadding(bLen - str.Length);\n }\n\n public static void WriteFixedString16(this BinaryWriter writer, string str, int bLen)\n {\n byte[] bstr = Utils.EncodeString(str);\n writer.Write(bstr);\n writer.WritePadding(bLen - bstr.Length);\n }\n\n public static byte[] GetBytes(this BinaryWriter writer)\n {\n return ((MemoryStream)writer.BaseStream).ToArray();\n }\n }\n\n public static class ByteArrayExt\n {\n public static byte[] CastToArray(this T data) where T : struct\n {\n int size = Marshal.SizeOf(typeof(T));\n byte[] result = new byte[size];\n GCHandle handle = GCHandle.Alloc(result, GCHandleType.Pinned);\n try\n {\n Marshal.StructureToPtr(data, handle.AddrOfPinnedObject(), false);\n }\n finally\n {\n handle.Free();\n }\n return result;\n }\n }\n\n public static class FileStreamExt\n {\n public static byte[] ReadAllBytes(this FileStream fs)\n {\n BinaryReader br = new BinaryReader(fs);\n return br.ReadBytes((int)fs.Length);\n }\n\n public static void WriteAllBytes(this FileStream fs, byte[] data)\n {\n fs.Seek(0, SeekOrigin.Begin);\n fs.SetLength(data.Length);\n fs.Write(data, 0, data.Length);\n }\n }\n\n public static class Utils\n {\n [DllImport(\"kernel32.dll\")]\n public static extern uint GetSystemDefaultLCID();\n\n [DllImport(\"kernel32.dll\")]\n public static extern bool Wow64EnableWow64FsRedirection(bool Wow64FsEnableRedirection);\n\n public static string DecodeString(byte[] data)\n {\n return Encoding.Unicode.GetString(data).Trim('\\0');\n }\n\n public static byte[] EncodeString(string str)\n {\n return Encoding.Unicode.GetBytes(str + '\\0');\n }\n\n public static uint CRC32(byte[] data)\n {\n const uint polynomial = 0x04C11DB7;\n uint crc = 0xffffffff;\n\n foreach (byte b in data)\n {\n crc ^= (uint)b << 24;\n for (int bit = 0; bit < 8; bit++)\n {\n if ((crc & 0x80000000) != 0)\n {\n crc = (crc << 1) ^ polynomial;\n }\n else\n {\n crc <<= 1;\n }\n }\n }\n return ~crc;\n }\n\n public static string GetArchitecture()\n {\n string arch = Environment.GetEnvironmentVariable(\"PROCESSOR_ARCHITECTURE\", EnvironmentVariableTarget.Machine).ToUpperInvariant();\n return arch == \"AMD64\" ? \"X64\" : arch;\n }\n\n public static PSVersion DetectVersion()\n {\n int build = Environment.OSVersion.Version.Build;\n\n if (build >= 9600) return PSVersion.WinModern;\n if (build >= 6000 && build <= 6003) return PSVersion.Vista;\n if (build >= 7600 && build <= 7602) return PSVersion.Win7;\n if (build == 9200) return PSVersion.Win8;\n\n throw new NotSupportedException(\"Unable to auto-detect version info\");\n }\n }\n\n public static class Logger\n {\n public static bool HideOutput = false;\n\n public static void WriteLine(string line)\n {\n if (!HideOutput) Console.WriteLine(line);\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/VariableBag.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n\n public enum CRCBlockType : uint\n {\n UINT = 1 << 0,\n STRING = 1 << 1,\n BINARY = 1 << 2\n }\n\n public abstract class CRCBlock\n {\n public CRCBlockType DataType;\n public byte[] Key;\n public string KeyAsStr\n {\n get\n {\n return Utils.DecodeString(Key);\n }\n set\n {\n Key = Utils.EncodeString(value);\n }\n }\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n\n public abstract void Encode(BinaryWriter writer);\n public abstract void Decode(BinaryReader reader);\n public abstract uint CRC();\n }\n\n public class CRCBlockVista : CRCBlock\n {\n public override void Encode(BinaryWriter writer)\n {\n uint crc = CRC();\n writer.Write((uint)DataType);\n writer.Write(0);\n writer.Write(Key.Length);\n writer.Write(Value.Length);\n writer.Write(crc);\n\n writer.Write(Key);\n\n writer.Write(Value);\n }\n\n public override void Decode(BinaryReader reader)\n {\n uint type = reader.ReadUInt32();\n reader.ReadUInt32();\n uint lenName = reader.ReadUInt32();\n uint lenVal = reader.ReadUInt32();\n uint crc = reader.ReadUInt32();\n\n byte[] key = reader.ReadBytes((int)lenName);\n byte[] value = reader.ReadBytes((int)lenVal);\n\n DataType = (CRCBlockType)type;\n Key = key;\n Value = value;\n\n if (CRC() != crc)\n {\n throw new InvalidDataException(\"Invalid CRC in variable bag.\");\n }\n }\n\n public override uint CRC()\n {\n return Utils.CRC32(Value);\n }\n }\n\n public class CRCBlockModern : CRCBlock\n {\n public override void Encode(BinaryWriter writer)\n {\n uint crc = CRC();\n writer.Write(crc);\n writer.Write((uint)DataType);\n writer.Write(Key.Length);\n writer.Write(Value.Length);\n\n writer.Write(Key);\n writer.Align(8);\n\n writer.Write(Value);\n writer.Align(8);\n }\n\n public override void Decode(BinaryReader reader)\n {\n uint crc = reader.ReadUInt32();\n uint type = reader.ReadUInt32();\n uint lenName = reader.ReadUInt32();\n uint lenVal = reader.ReadUInt32();\n\n byte[] key = reader.ReadBytes((int)lenName);\n reader.Align(8);\n\n byte[] value = reader.ReadBytes((int)lenVal);\n reader.Align(8);\n\n DataType = (CRCBlockType)type;\n Key = key;\n Value = value;\n\n if (CRC() != crc)\n {\n throw new InvalidDataException(\"Invalid CRC in variable bag.\");\n }\n }\n\n public override uint CRC()\n {\n BinaryWriter wtemp = new BinaryWriter(new MemoryStream());\n wtemp.Write(0);\n wtemp.Write((uint)DataType);\n wtemp.Write(Key.Length);\n wtemp.Write(Value.Length);\n wtemp.Write(Key);\n wtemp.Write(Value);\n return Utils.CRC32(wtemp.GetBytes());\n }\n }\n\n public class VariableBag\n {\n public List Blocks = new List();\n private readonly PSVersion Version;\n\n private void Deserialize(byte[] data)\n {\n int len = data.Length;\n\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n\n while (reader.BaseStream.Position < len - 0x10)\n {\n CRCBlock block;\n\n if (Version == PSVersion.Vista)\n {\n block = new CRCBlockVista();\n }\n else\n {\n block = new CRCBlockModern();\n }\n\n block.Decode(reader);\n Blocks.Add(block);\n }\n }\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n\n foreach (CRCBlock block in Blocks)\n {\n if (Version == PSVersion.Vista)\n {\n ((CRCBlockVista)block).Encode(writer);\n } else\n {\n ((CRCBlockModern)block).Encode(writer);\n }\n }\n\n return writer.GetBytes();\n }\n\n public CRCBlock GetBlock(string key)\n {\n foreach (CRCBlock block in Blocks)\n {\n if (block.KeyAsStr == key)\n {\n return block;\n }\n }\n\n return null;\n }\n\n public void SetBlock(string key, byte[] value)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n CRCBlock block = Blocks[i];\n\n if (block.KeyAsStr == key)\n {\n block.Value = value;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void DeleteBlock(string key)\n {\n foreach (CRCBlock block in Blocks)\n {\n if (block.KeyAsStr == key)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public VariableBag(byte[] data, PSVersion version)\n {\n Version = version;\n Deserialize(data);\n }\n\n public VariableBag(PSVersion version)\n {\n Version = version;\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/GracePeriodReset.cs", "namespace LibTSforge.Modifiers\n{\n using System.Collections.Generic;\n using System.Linq;\n using PhysicalStore;\n using SPP;\n\n public static class GracePeriodReset\n {\n public static void Reset(PSVersion version, bool production)\n {\n SPPUtils.KillSPP(version);\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string value = \"msft:sl/timer\";\n List blocks = store.FindBlocks(value).ToList();\n\n foreach (PSBlock block in blocks)\n {\n store.DeleteBlock(block.KeyAsStr, block.ValueAsStr);\n }\n }\n\n SPPUtils.RestartSPP(version);\n Logger.WriteLine(\"Successfully reset all grace and evaluation period timers.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/Crypto/CryptoUtils.cs", "namespace LibTSforge.Crypto\n{\n using System;\n using System.Linq;\n using System.Security.Cryptography;\n\n public static class CryptoUtils\n {\n public static byte[] GenerateRandomKey(int len)\n {\n byte[] rand = new byte[len];\n Random r = new Random();\n r.NextBytes(rand);\n\n return rand;\n }\n\n public static byte[] AESEncrypt(byte[] data, byte[] key)\n {\n using (Aes aes = Aes.Create())\n {\n aes.Key = key;\n aes.Mode = CipherMode.CBC;\n aes.Padding = PaddingMode.PKCS7;\n\n ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, Enumerable.Repeat((byte)0, 16).ToArray());\n byte[] encryptedData = encryptor.TransformFinalBlock(data, 0, data.Length);\n return encryptedData;\n }\n }\n\n public static byte[] AESDecrypt(byte[] data, byte[] key)\n {\n using (Aes aes = Aes.Create())\n {\n aes.Key = key;\n aes.Mode = CipherMode.CBC;\n aes.Padding = PaddingMode.PKCS7;\n\n ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, Enumerable.Repeat((byte)0, 16).ToArray());\n byte[] decryptedData = decryptor.TransformFinalBlock(data, 0, data.Length);\n return decryptedData;\n }\n }\n\n public static byte[] RSADecrypt(byte[] rsaKey, byte[] data)\n {\n\n using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())\n {\n rsa.ImportCspBlob(rsaKey);\n return rsa.Decrypt(data, false);\n }\n }\n\n public static byte[] RSAEncrypt(byte[] rsaKey, byte[] data)\n {\n using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())\n {\n rsa.ImportCspBlob(rsaKey);\n return rsa.Encrypt(data, false);\n }\n }\n\n public static byte[] RSASign(byte[] rsaKey, byte[] data)\n {\n using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())\n {\n rsa.ImportCspBlob(rsaKey);\n RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(rsa);\n formatter.SetHashAlgorithm(\"SHA1\");\n\n byte[] hash;\n using (SHA1 sha1 = SHA1.Create())\n {\n hash = sha1.ComputeHash(data);\n }\n\n return formatter.CreateSignature(hash);\n }\n }\n\n public static bool RSAVerifySignature(byte[] rsaKey, byte[] data, byte[] signature)\n {\n using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())\n {\n rsa.ImportCspBlob(rsaKey);\n RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(rsa);\n deformatter.SetHashAlgorithm(\"SHA1\");\n\n byte[] hash;\n using (SHA1 sha1 = SHA1.Create())\n {\n hash = sha1.ComputeHash(data);\n }\n\n return deformatter.VerifySignature(hash, signature);\n }\n }\n\n public static byte[] HMACSign(byte[] key, byte[] data)\n {\n HMACSHA1 hmac = new HMACSHA1(key);\n return hmac.ComputeHash(data);\n }\n\n public static bool HMACVerify(byte[] key, byte[] data, byte[] signature)\n {\n return Enumerable.SequenceEqual(signature, HMACSign(key, data));\n }\n\n public static byte[] SaltSHASum(byte[] salt, byte[] data)\n {\n SHA1 sha1 = SHA1.Create();\n byte[] sha_data = salt.Concat(data).ToArray();\n return sha1.ComputeHash(sha_data);\n }\n\n public static bool SaltSHAVerify(byte[] salt, byte[] data, byte[] checksum)\n {\n return Enumerable.SequenceEqual(checksum, SaltSHASum(salt, data));\n }\n\n public static byte[] SHA256Hash(byte[] data)\n {\n using (SHA256 sha256 = SHA256.Create())\n {\n return sha256.ComputeHash(data);\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/SPP/SPSys.cs", "namespace LibTSforge.SPP\n{\n using Microsoft.Win32.SafeHandles;\n using System;\n using System.Runtime.InteropServices;\n\n public class SPSys\n {\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n private static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);\n private static SafeFileHandle CreateFileSafe(string device)\n {\n return new SafeFileHandle(CreateFile(device, 0xC0000000, 0, IntPtr.Zero, 3, 0, IntPtr.Zero), true);\n }\n\n [return: MarshalAs(UnmanagedType.Bool)]\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n private static extern bool DeviceIoControl([In] SafeFileHandle hDevice, [In] uint dwIoControlCode, [In] IntPtr lpInBuffer, [In] int nInBufferSize, [Out] IntPtr lpOutBuffer, [In] int nOutBufferSize, out int lpBytesReturned, [In] IntPtr lpOverlapped);\n\n public static bool IsSpSysRunning()\n {\n SafeFileHandle file = CreateFileSafe(@\"\\\\.\\SpDevice\");\n IntPtr buffer = Marshal.AllocHGlobal(1);\n int bytesReturned;\n DeviceIoControl(file, 0x80006008, IntPtr.Zero, 0, buffer, 1, out bytesReturned, IntPtr.Zero);\n bool running = Marshal.ReadByte(buffer) != 0;\n Marshal.FreeHGlobal(buffer);\n file.Close();\n return running;\n }\n\n public static int ControlSpSys(bool start)\n {\n SafeFileHandle file = CreateFileSafe(@\"\\\\.\\SpDevice\");\n IntPtr buffer = Marshal.AllocHGlobal(4);\n int bytesReturned;\n DeviceIoControl(file, start ? 0x8000a000 : 0x8000a004, IntPtr.Zero, 0, buffer, 4, out bytesReturned, IntPtr.Zero);\n int result = Marshal.ReadInt32(buffer);\n Marshal.FreeHGlobal(buffer);\n file.Close();\n return result;\n }\n }\n}\n"], ["/TSforge/LibTSforge/TokenStore/Common.cs", "namespace LibTSforge.TokenStore\n{\n using System.Collections.Generic;\n using System.IO;\n\n public class TokenEntry\n {\n public string Name;\n public string Extension;\n public byte[] Data;\n public bool Populated;\n }\n\n public class TokenMeta\n {\n public string Name;\n public readonly Dictionary Data = new Dictionary();\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(1);\n byte[] nameBytes = Utils.EncodeString(Name);\n writer.Write(nameBytes.Length);\n writer.Write(nameBytes);\n\n foreach (KeyValuePair kv in Data)\n {\n byte[] keyBytes = Utils.EncodeString(kv.Key);\n byte[] valueBytes = Utils.EncodeString(kv.Value);\n writer.Write(keyBytes.Length);\n writer.Write(valueBytes.Length);\n writer.Write(keyBytes);\n writer.Write(valueBytes);\n }\n\n return writer.GetBytes();\n }\n\n private void Deserialize(byte[] data)\n {\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n reader.ReadInt32();\n int nameLen = reader.ReadInt32();\n Name = reader.ReadNullTerminatedString(nameLen);\n\n while (reader.BaseStream.Position < data.Length - 0x8)\n {\n int keyLen = reader.ReadInt32();\n int valueLen = reader.ReadInt32();\n string key = reader.ReadNullTerminatedString(keyLen);\n string value = reader.ReadNullTerminatedString(valueLen);\n Data[key] = value;\n }\n }\n\n public TokenMeta(byte[] data)\n {\n Deserialize(data);\n }\n\n public TokenMeta()\n {\n\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/IPhysicalStore.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n\n public class PSBlock\n {\n public BlockType Type;\n public uint Flags;\n public uint Unknown = 0;\n public byte[] Key;\n public string KeyAsStr\n {\n get\n {\n return Utils.DecodeString(Key);\n }\n set\n {\n Key = Utils.EncodeString(value);\n }\n }\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n public byte[] Data;\n public string DataAsStr\n {\n get\n {\n return Utils.DecodeString(Data);\n }\n set\n {\n Data = Utils.EncodeString(value);\n }\n }\n public uint DataAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Data, 0);\n }\n set\n {\n Data = BitConverter.GetBytes(value);\n }\n }\n }\n\n public interface IPhysicalStore : IDisposable\n {\n PSBlock GetBlock(string key, string value);\n PSBlock GetBlock(string key, uint value);\n void AddBlock(PSBlock block);\n void AddBlocks(IEnumerable blocks);\n void SetBlock(string key, string value, byte[] data);\n void SetBlock(string key, string value, string data);\n void SetBlock(string key, string value, uint data);\n void SetBlock(string key, uint value, byte[] data);\n void SetBlock(string key, uint value, string data);\n void SetBlock(string key, uint value, uint data);\n void DeleteBlock(string key, string value);\n void DeleteBlock(string key, uint value);\n byte[] Serialize();\n void Deserialize(byte[] data);\n byte[] ReadRaw();\n void WriteRaw(byte[] data);\n IEnumerable FindBlocks(string valueSearch);\n IEnumerable FindBlocks(uint valueSearch);\n }\n}\n"], ["/TSforge/LibTSforge/Crypto/Keys.cs", "namespace LibTSforge.Crypto\n{\n public static class Keys\n {\n public static readonly byte[] PRODUCTION = {\n 0x07, 0x02, 0x00, 0x00, 0x00, 0xA4, 0x00, 0x00, 0x52, 0x53, 0x41, 0x32, 0x00, 0x04, 0x00, 0x00,\n 0x01, 0x00, 0x01, 0x00, 0x29, 0x87, 0xBA, 0x3F, 0x52, 0x90, 0x57, 0xD8, 0x12, 0x26, 0x6B, 0x38,\n 0xB2, 0x3B, 0xF9, 0x67, 0x08, 0x4F, 0xDD, 0x8B, 0xF5, 0xE3, 0x11, 0xB8, 0x61, 0x3A, 0x33, 0x42,\n 0x51, 0x65, 0x05, 0x86, 0x1E, 0x00, 0x41, 0xDE, 0xC5, 0xDD, 0x44, 0x60, 0x56, 0x3D, 0x14, 0x39,\n 0xB7, 0x43, 0x65, 0xE9, 0xF7, 0x2B, 0xA5, 0xF0, 0xA3, 0x65, 0x68, 0xE9, 0xE4, 0x8B, 0x5C, 0x03,\n 0x2D, 0x36, 0xFE, 0x28, 0x4C, 0xD1, 0x3C, 0x3D, 0xC1, 0x90, 0x75, 0xF9, 0x6E, 0x02, 0xE0, 0x58,\n 0x97, 0x6A, 0xCA, 0x80, 0x02, 0x42, 0x3F, 0x6C, 0x15, 0x85, 0x4D, 0x83, 0x23, 0x6A, 0x95, 0x9E,\n 0x38, 0x52, 0x59, 0x38, 0x6A, 0x99, 0xF0, 0xB5, 0xCD, 0x53, 0x7E, 0x08, 0x7C, 0xB5, 0x51, 0xD3,\n 0x8F, 0xA3, 0x0D, 0xA0, 0xFA, 0x8D, 0x87, 0x3C, 0xFC, 0x59, 0x21, 0xD8, 0x2E, 0xD9, 0x97, 0x8B,\n 0x40, 0x60, 0xB1, 0xD7, 0x2B, 0x0A, 0x6E, 0x60, 0xB5, 0x50, 0xCC, 0x3C, 0xB1, 0x57, 0xE4, 0xB7,\n 0xDC, 0x5A, 0x4D, 0xE1, 0x5C, 0xE0, 0x94, 0x4C, 0x5E, 0x28, 0xFF, 0xFA, 0x80, 0x6A, 0x13, 0x53,\n 0x52, 0xDB, 0xF3, 0x04, 0x92, 0x43, 0x38, 0xB9, 0x1B, 0xD9, 0x85, 0x54, 0x7B, 0x14, 0xC7, 0x89,\n 0x16, 0x8A, 0x4B, 0x82, 0xA1, 0x08, 0x02, 0x99, 0x23, 0x48, 0xDD, 0x75, 0x9C, 0xC8, 0xC1, 0xCE,\n 0xB0, 0xD7, 0x1B, 0xD8, 0xFB, 0x2D, 0xA7, 0x2E, 0x47, 0xA7, 0x18, 0x4B, 0xF6, 0x29, 0x69, 0x44,\n 0x30, 0x33, 0xBA, 0xA7, 0x1F, 0xCE, 0x96, 0x9E, 0x40, 0xE1, 0x43, 0xF0, 0xE0, 0x0D, 0x0A, 0x32,\n 0xB4, 0xEE, 0xA1, 0xC3, 0x5E, 0x9B, 0xC7, 0x7F, 0xF5, 0x9D, 0xD8, 0xF2, 0x0F, 0xD9, 0x8F, 0xAD,\n 0x75, 0x0A, 0x00, 0xD5, 0x25, 0x43, 0xF7, 0xAE, 0x51, 0x7F, 0xB7, 0xDE, 0xB7, 0xAD, 0xFB, 0xCE,\n 0x83, 0xE1, 0x81, 0xFF, 0xDD, 0xA2, 0x77, 0xFE, 0xEB, 0x27, 0x1F, 0x10, 0xFA, 0x82, 0x37, 0xF4,\n 0x7E, 0xCC, 0xE2, 0xA1, 0x58, 0xC8, 0xAF, 0x1D, 0x1A, 0x81, 0x31, 0x6E, 0xF4, 0x8B, 0x63, 0x34,\n 0xF3, 0x05, 0x0F, 0xE1, 0xCC, 0x15, 0xDC, 0xA4, 0x28, 0x7A, 0x9E, 0xEB, 0x62, 0xD8, 0xD8, 0x8C,\n 0x85, 0xD7, 0x07, 0x87, 0x90, 0x2F, 0xF7, 0x1C, 0x56, 0x85, 0x2F, 0xEF, 0x32, 0x37, 0x07, 0xAB,\n 0xB0, 0xE6, 0xB5, 0x02, 0x19, 0x35, 0xAF, 0xDB, 0xD4, 0xA2, 0x9C, 0x36, 0x80, 0xC6, 0xDC, 0x82,\n 0x08, 0xE0, 0xC0, 0x5F, 0x3C, 0x59, 0xAA, 0x4E, 0x26, 0x03, 0x29, 0xB3, 0x62, 0x58, 0x41, 0x59,\n 0x3A, 0x37, 0x43, 0x35, 0xE3, 0x9F, 0x34, 0xE2, 0xA1, 0x04, 0x97, 0x12, 0x9D, 0x8C, 0xAD, 0xF7,\n 0xFB, 0x8C, 0xA1, 0xA2, 0xE9, 0xE4, 0xEF, 0xD9, 0xC5, 0xE5, 0xDF, 0x0E, 0xBF, 0x4A, 0xE0, 0x7A,\n 0x1E, 0x10, 0x50, 0x58, 0x63, 0x51, 0xE1, 0xD4, 0xFE, 0x57, 0xB0, 0x9E, 0xD7, 0xDA, 0x8C, 0xED,\n 0x7D, 0x82, 0xAC, 0x2F, 0x25, 0x58, 0x0A, 0x58, 0xE6, 0xA4, 0xF4, 0x57, 0x4B, 0xA4, 0x1B, 0x65,\n 0xB9, 0x4A, 0x87, 0x46, 0xEB, 0x8C, 0x0F, 0x9A, 0x48, 0x90, 0xF9, 0x9F, 0x76, 0x69, 0x03, 0x72,\n 0x77, 0xEC, 0xC1, 0x42, 0x4C, 0x87, 0xDB, 0x0B, 0x3C, 0xD4, 0x74, 0xEF, 0xE5, 0x34, 0xE0, 0x32,\n 0x45, 0xB0, 0xF8, 0xAB, 0xD5, 0x26, 0x21, 0xD7, 0xD2, 0x98, 0x54, 0x8F, 0x64, 0x88, 0x20, 0x2B,\n 0x14, 0xE3, 0x82, 0xD5, 0x2A, 0x4B, 0x8F, 0x4E, 0x35, 0x20, 0x82, 0x7E, 0x1B, 0xFE, 0xFA, 0x2C,\n 0x79, 0x6C, 0x6E, 0x66, 0x94, 0xBB, 0x0A, 0xEB, 0xBA, 0xD9, 0x70, 0x61, 0xE9, 0x47, 0xB5, 0x82,\n 0xFC, 0x18, 0x3C, 0x66, 0x3A, 0x09, 0x2E, 0x1F, 0x61, 0x74, 0xCA, 0xCB, 0xF6, 0x7A, 0x52, 0x37,\n 0x1D, 0xAC, 0x8D, 0x63, 0x69, 0x84, 0x8E, 0xC7, 0x70, 0x59, 0xDD, 0x2D, 0x91, 0x1E, 0xF7, 0xB1,\n 0x56, 0xED, 0x7A, 0x06, 0x9D, 0x5B, 0x33, 0x15, 0xDD, 0x31, 0xD0, 0xE6, 0x16, 0x07, 0x9B, 0xA5,\n 0x94, 0x06, 0x7D, 0xC1, 0xE9, 0xD6, 0xC8, 0xAF, 0xB4, 0x1E, 0x2D, 0x88, 0x06, 0xA7, 0x63, 0xB8,\n 0xCF, 0xC8, 0xA2, 0x6E, 0x84, 0xB3, 0x8D, 0xE5, 0x47, 0xE6, 0x13, 0x63, 0x8E, 0xD1, 0x7F, 0xD4,\n 0x81, 0x44, 0x38, 0xBF\n };\n\n public static readonly byte[] TEST = {\n 0x07, 0x02, 0x00, 0x00, 0x00, 0xA4, 0x00, 0x00, 0x52, 0x53, 0x41, 0x32, 0x00, 0x04, 0x00, 0x00,\n 0x01, 0x00, 0x01, 0x00, 0x0F, 0xBE, 0x77, 0xB8, 0xDD, 0x54, 0x36, 0xDD, 0x67, 0xD4, 0x17, 0x66,\n 0xC4, 0x13, 0xD1, 0x3F, 0x1E, 0x16, 0x0C, 0x16, 0x35, 0xAB, 0x6D, 0x3D, 0x34, 0x51, 0xED, 0x3F,\n 0x57, 0x14, 0xB6, 0xB7, 0x08, 0xE9, 0xD9, 0x7A, 0x80, 0xB3, 0x5F, 0x9B, 0x3A, 0xFD, 0x9E, 0x37,\n 0x3A, 0x53, 0x72, 0x67, 0x92, 0x60, 0xC3, 0xEF, 0xB5, 0x8E, 0x1E, 0xCF, 0x9D, 0x9C, 0xD3, 0x90,\n 0xE5, 0xDD, 0xF4, 0xDB, 0xF3, 0xD6, 0x65, 0xB3, 0xC1, 0xBD, 0x69, 0xE1, 0x76, 0x95, 0xD9, 0x37,\n 0xB8, 0x5E, 0xCA, 0x3D, 0x98, 0xFC, 0x50, 0x5C, 0x98, 0xAE, 0xE3, 0x7C, 0x4C, 0x27, 0xC3, 0xD0,\n 0xCE, 0x78, 0x06, 0x51, 0x68, 0x23, 0xE6, 0x70, 0xF8, 0x7C, 0xAE, 0x36, 0xBE, 0x41, 0x57, 0xE2,\n 0xC3, 0x2D, 0xAF, 0x21, 0xB1, 0xB3, 0x15, 0x81, 0x19, 0x26, 0x6B, 0x10, 0xB3, 0xE9, 0xD1, 0x45,\n 0x21, 0x77, 0x9C, 0xF6, 0xE1, 0xDD, 0xB6, 0x78, 0x9D, 0x1D, 0x32, 0x61, 0xBC, 0x2B, 0xDB, 0x86,\n 0xFB, 0x07, 0x24, 0x10, 0x19, 0x4F, 0x09, 0x6D, 0x03, 0x90, 0xD4, 0x5E, 0x30, 0x85, 0xC5, 0x58,\n 0x7E, 0x5D, 0xAE, 0x9F, 0x64, 0x93, 0x04, 0x82, 0x09, 0x0E, 0x1C, 0x66, 0xA8, 0x95, 0x91, 0x51,\n 0xB2, 0xED, 0x9A, 0x75, 0x04, 0x87, 0x50, 0xAC, 0xCC, 0x20, 0x06, 0x45, 0xB9, 0x7B, 0x42, 0x53,\n 0x9A, 0xD1, 0x29, 0xFC, 0xEF, 0xB9, 0x47, 0x16, 0x75, 0x69, 0x05, 0x87, 0x2B, 0xCB, 0x54, 0x9C,\n 0x21, 0x2D, 0x50, 0x8E, 0x12, 0xDE, 0xD3, 0x6B, 0xEC, 0x92, 0xA1, 0xB1, 0xE9, 0x4B, 0xBF, 0x6B,\n 0x9A, 0x38, 0xC7, 0x13, 0xFA, 0x78, 0xA1, 0x3C, 0x1E, 0xBB, 0x38, 0x31, 0xBB, 0x0C, 0x9F, 0x70,\n 0x1A, 0x31, 0x00, 0xD7, 0x5A, 0xA5, 0x84, 0x24, 0x89, 0x80, 0xF5, 0x88, 0xC2, 0x31, 0x18, 0xDC,\n 0x53, 0x05, 0x5D, 0xFA, 0x81, 0xDC, 0xE1, 0xCE, 0xA4, 0xAA, 0xBA, 0x07, 0xDA, 0x28, 0x4F, 0x64,\n 0x0E, 0x84, 0x9B, 0x06, 0xDE, 0xC8, 0x78, 0x66, 0x2F, 0x17, 0x25, 0xA8, 0x9C, 0x99, 0xFC, 0xBC,\n 0x7D, 0x01, 0x42, 0xD7, 0x35, 0xBF, 0x19, 0xF6, 0x3F, 0x20, 0xD9, 0x98, 0x9B, 0x5D, 0xDD, 0x39,\n 0xBE, 0x81, 0x00, 0x0B, 0xDE, 0x6F, 0x14, 0xCA, 0x7E, 0xF8, 0xC0, 0x26, 0xA8, 0x1D, 0xD1, 0x16,\n 0x88, 0x64, 0x87, 0x36, 0x45, 0x37, 0x50, 0xDA, 0x6C, 0xEB, 0x85, 0xB5, 0x43, 0x29, 0x88, 0x6F,\n 0x2F, 0xFE, 0x8D, 0x12, 0x8B, 0x72, 0xB7, 0x5A, 0xCB, 0x66, 0xC2, 0x2E, 0x1D, 0x7D, 0x42, 0xA6,\n 0xF4, 0xFE, 0x26, 0x5D, 0x54, 0x9E, 0x77, 0x1D, 0x97, 0xC2, 0xF3, 0xFD, 0x60, 0xB3, 0x22, 0x88,\n 0xCA, 0x27, 0x99, 0xDF, 0xC8, 0xB1, 0xD7, 0xC6, 0x54, 0xA6, 0x50, 0xB9, 0x54, 0xF5, 0xDE, 0xFE,\n 0xE1, 0x81, 0xA2, 0xBE, 0x81, 0x9F, 0x48, 0xFF, 0x2F, 0xB8, 0xA4, 0xB3, 0x17, 0xD8, 0xC1, 0xB9,\n 0x5D, 0x21, 0x3D, 0xA2, 0xED, 0x1C, 0x96, 0x66, 0xEE, 0x1F, 0x47, 0xCF, 0x62, 0xFA, 0xD6, 0xC1,\n 0x87, 0x5B, 0xC4, 0xE5, 0xD9, 0x08, 0x38, 0x22, 0xFA, 0x21, 0xBD, 0xF2, 0x88, 0xDA, 0xE2, 0x24,\n 0x25, 0x1F, 0xF1, 0x0B, 0x2D, 0xAE, 0x04, 0xBE, 0xA6, 0x7F, 0x75, 0x8C, 0xD9, 0x97, 0xE1, 0xCA,\n 0x35, 0xB9, 0xFC, 0x6F, 0x01, 0x68, 0x11, 0xD3, 0x68, 0x32, 0xD0, 0xC1, 0x69, 0xA3, 0xCF, 0x9B,\n 0x10, 0xE4, 0x69, 0xA7, 0xCF, 0xE1, 0xFE, 0x2A, 0x07, 0x9E, 0xC1, 0x37, 0x84, 0x68, 0xE5, 0xC5,\n 0xAB, 0x25, 0xEC, 0x7D, 0x7D, 0x74, 0x6A, 0xD1, 0xD5, 0x4D, 0xD7, 0xE1, 0x7D, 0xDE, 0x30, 0x4B,\n 0xE6, 0x5D, 0xCD, 0x91, 0x59, 0xF6, 0x80, 0xFD, 0xC6, 0x3C, 0xDD, 0x94, 0x7F, 0x15, 0x9D, 0xEF,\n 0x2F, 0x00, 0x62, 0xD7, 0xDA, 0xB9, 0xB3, 0xD9, 0x8D, 0xE8, 0xD7, 0x3C, 0x96, 0x45, 0x5D, 0x1E,\n 0x50, 0xFB, 0xAA, 0x43, 0xD3, 0x47, 0x77, 0x81, 0xE9, 0x67, 0xE4, 0xFE, 0xDF, 0x42, 0x79, 0xCB,\n 0xA7, 0xAD, 0x5D, 0x48, 0xF5, 0xB7, 0x74, 0x96, 0x12, 0x23, 0x06, 0x70, 0x42, 0x68, 0x7A, 0x44,\n 0xFC, 0xA0, 0x31, 0x7F, 0x68, 0xCA, 0xA2, 0x14, 0x5D, 0xA3, 0xCF, 0x42, 0x23, 0xAB, 0x47, 0xF6,\n 0xB2, 0xFC, 0x6D, 0xF1\n };\n }\n}\n"], ["/TSforge/LibTSforge/TokenStore/ITokenStore.cs", "namespace LibTSforge.TokenStore\n{\n using System;\n\n public interface ITokenStore : IDisposable\n {\n void Deserialize();\n void Serialize();\n void AddEntry(TokenEntry entry);\n void AddEntries(TokenEntry[] entries);\n void DeleteEntry(string name, string ext);\n void DeleteUnpopEntry(string name, string ext);\n TokenEntry GetEntry(string name, string ext);\n TokenMeta GetMetaEntry(string name);\n void SetEntry(string name, string ext, byte[] data);\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/Common.cs", "namespace LibTSforge.PhysicalStore\n{\n using System.Runtime.InteropServices;\n\n public enum BlockType : uint\n {\n NONE,\n NAMED,\n ATTRIBUTE,\n TIMER\n }\n\n [StructLayout(LayoutKind.Sequential, Pack = 1)]\n public struct Timer\n {\n public ulong Unknown;\n public ulong Time1;\n public ulong Time2;\n public ulong Expiry;\n }\n\n [StructLayout(LayoutKind.Sequential, Pack = 1)]\n public struct VistaTimer\n {\n public ulong Time;\n public ulong Expiry;\n }\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 19:06:23", "created_task_model": "DeepSeek-R1", "function_skeleton": "public static bool DetectCurrentKey () {}", "code_description": "This code segment functions to: Determine the presence of specific registry entries related to software licensing and validate their configuration state based on predefined identifier patterns."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\n public static bool DetectCurrentKey()\n {\n object value = Registry.GetValue(\n @\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform\",\n \"KeyManagementServiceCurrentKey\",\n \"\"\n );\n\n return (value is string key && !string.IsNullOrEmpty(key));\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 19-06-38"}, "editdistance_info": {"edit_distance": 18.75, "calculate_time": "2025-08-20 19:06:38", "true_code_clean": "public static bool DetectCurrentKey()\n {\n SLApi.RefreshLicenseStatus();\n using (RegistryKey wpaKey = Registry.LocalMachine.OpenSubKey(@\"SYSTEM\\WPA\"))\n {\n foreach (string subKey in wpaKey.GetSubKeyNames())\n {\n if (subKey.StartsWith(\"8DEC0AF1\"))\n {\n return subKey.Contains(\"P\");\n }\n }\n }\n throw new FileNotFoundException(\"Failed to autodetect key type, specify physical store key with /prod or /test arguments.\");\n }", "predict_code_clean": "public static bool DetectCurrentKey()\n {\n object value = Registry.GetValue(\n @\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform\",\n \"KeyManagementServiceCurrentKey\",\n \"\"\n );\n return (value is string key && !string.IsNullOrEmpty(key));\n }"}} {"repo_name": "TSforge", "file_name": "/TSforge/LibTSforge/SPP/SPPUtils.cs", "inference_info": {"prefix_code": "namespace LibTSforge.SPP\n{\n using Microsoft.Win32;\n using System;\n using System.IO;\n using System.Linq;\n using System.ServiceProcess;\n using Crypto;\n using PhysicalStore;\n using TokenStore;\n\n public static class SPPUtils\n {\n public static void KillSPP(PSVersion version)\n {\n ServiceController sc;\n\n string svcName = version == PSVersion.Vista ? \"slsvc\" : \"sppsvc\";\n\n try\n {\n sc = new ServiceController(svcName);\n\n if (sc.Status == ServiceControllerStatus.Stopped)\n return;\n }\n catch (InvalidOperationException ex)\n {\n throw new InvalidOperationException(string.Format(\"Unable to access {0}: \", svcName) + ex.Message);\n }\n\n Logger.WriteLine(string.Format(\"Stopping {0}...\", svcName));\n\n bool stopped = false;\n\n for (int i = 0; stopped == false && i < 1080; i++)\n {\n try\n {\n if (sc.Status != ServiceControllerStatus.StopPending)\n sc.Stop();\n\n sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromMilliseconds(500));\n }\n catch (System.ServiceProcess.TimeoutException)\n {\n continue;\n }\n catch (InvalidOperationException ex)\n {\n Logger.WriteLine(\"Warning: Stopping sppsvc failed, retrying. Details: \" + ex.Message);\n System.Threading.Thread.Sleep(500);\n continue;\n }\n\n stopped = true;\n }\n\n if (!stopped)\n throw new System.TimeoutException(string.Format(\"Failed to stop {0}\", svcName));\n\n Logger.WriteLine(string.Format(\"{0} stopped successfully.\", svcName));\n\n if (version == PSVersion.Vista && SPSys.IsSpSysRunning())\n {\n Logger.WriteLine(\"Unloading spsys...\");\n\n int status = SPSys.ControlSpSys(false);\n\n if (status < 0)\n {\n throw new IOException(\"Failed to unload spsys\");\n }\n\n Logger.WriteLine(\"spsys unloaded successfully.\");\n }\n }\n\n public static void RestartSPP(PSVersion version)\n {\n if (version == PSVersion.Vista)\n {\n ServiceController sc;\n\n try\n {\n sc = new ServiceController(\"slsvc\");\n\n if (sc.Status == ServiceControllerStatus.Running)\n return;\n }\n catch (InvalidOperationException ex)\n {\n throw new InvalidOperationException(\"Unable to access slsvc: \" + ex.Message);\n }\n\n Logger.WriteLine(\"Starting slsvc...\");\n\n bool started = false;\n\n for (int i = 0; started == false && i < 360; i++)\n {\n try\n {\n if (sc.Status != ServiceControllerStatus.StartPending)\n sc.Start();\n\n sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMilliseconds(500));\n }\n catch (System.ServiceProcess.TimeoutException)\n {\n continue;\n }\n catch (InvalidOperationException ex)\n {\n Logger.WriteLine(\"Warning: Starting slsvc failed, retrying. Details: \" + ex.Message);\n System.Threading.Thread.Sleep(500);\n continue;\n }\n\n started = true;\n }\n\n if (!started)\n throw new System.TimeoutException(\"Failed to start slsvc\");\n\n Logger.WriteLine(\"slsvc started successfully.\");\n }\n\n SLApi.RefreshLicenseStatus();\n }\n\n public static bool DetectCurrentKey()\n {\n SLApi.RefreshLicenseStatus();\n\n using (RegistryKey wpaKey = Registry.LocalMachine.OpenSubKey(@\"SYSTEM\\WPA\"))\n {\n foreach (string subKey in wpaKey.GetSubKeyNames())\n {\n if (subKey.StartsWith(\"8DEC0AF1\"))\n {\n return subKey.Contains(\"P\");\n }\n }\n }\n\n throw new FileNotFoundException(\"Failed to autodetect key type, specify physical store key with /prod or /test arguments.\");\n }\n\n public static string GetPSPath(PSVersion version)\n {\n switch (version)\n {\n case PSVersion.Vista:\n case PSVersion.Win7:\n return Directory.GetFiles(\n Environment.GetFolderPath(Environment.SpecialFolder.System),\n \"7B296FB0-376B-497e-B012-9C450E1B7327-*.C7483456-A289-439d-8115-601632D005A0\")\n .FirstOrDefault() ?? \"\";\n default:\n string psDir = Environment.ExpandEnvironmentVariables(\n (string)Registry.GetValue(\n @\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform\",\n \"TokenStore\",\n \"\"\n )\n );\n string psPath = Path.Combine(psDir, \"data.dat\");\n\n if (string.IsNullOrEmpty(psDir) || !File.Exists(psPath))\n {\n string[] psDirs =\n {\n @\"spp\\store\",\n @\"spp\\store\\2.0\",\n @\"spp\\store_test\",\n @\"spp\\store_test\\2.0\"\n };\n\n foreach (string dir in psDirs)\n {\n psPath = Path.Combine(\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.System),\n dir\n ),\n \"data.dat\"\n );\n\n if (File.Exists(psPath)) return psPath;\n }\n } \n else\n {\n return psPath;\n }\n\n throw new FileNotFoundException(\"Failed to locate physical store.\");\n }\n }\n\n public static string GetTokensPath(PSVersion version)\n {\n switch (version)\n {\n case PSVersion.Vista:\n return Path.Combine(\n Environment.ExpandEnvironmentVariables(\"%WINDIR%\"),\n @\"ServiceProfiles\\NetworkService\\AppData\\Roaming\\Microsoft\\SoftwareLicensing\\tokens.dat\"\n );\n case PSVersion.Win7:\n return Path.Combine(\n Environment.ExpandEnvironmentVariables(\"%WINDIR%\"),\n @\"ServiceProfiles\\NetworkService\\AppData\\Roaming\\Microsoft\\SoftwareProtectionPlatform\\tokens.dat\"\n );\n default:\n string tokDir = Environment.ExpandEnvironmentVariables(\n (string)Registry.GetValue(\n @\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform\",\n \"TokenStore\",\n \"\"\n )\n );\n string tokPath = Path.Combine(tokDir, \"tokens.dat\");\n\n if (string.IsNullOrEmpty(tokDir) || !File.Exists(tokPath))\n {\n string[] tokDirs =\n {\n @\"spp\\store\",\n @\"spp\\store\\2.0\",\n @\"spp\\store_test\",\n @\"spp\\store_test\\2.0\"\n };\n\n foreach (string dir in tokDirs)\n {\n tokPath = Path.Combine(\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.System),\n dir\n ),\n \"tokens.dat\"\n );\n\n if (File.Exists(tokPath)) return tokPath;\n }\n }\n else\n {\n return tokPath;\n }\n\n throw new FileNotFoundException(\"Failed to locate token store.\");\n }\n }\n\n public static IPhysicalStore GetStore(PSVersion version, bool production)\n {\n string psPath = GetPSPath(version);\n\n switch (version)\n {\n case PSVersion.Vista:\n return new PhysicalStoreVista(psPath, production);\n case PSVersion.Win7:\n return new PhysicalStoreWin7(psPath, production);\n default:\n return new PhysicalStoreModern(psPath, production, version);\n }\n }\n\n public static ITokenStore GetTokenStore(PSVersion version)\n {\n string tokPath = GetTokensPath(version);\n\n return new TokenStoreModern(tokPath);\n }\n\n public static void DumpStore(PSVersion version, bool production, string filePath, string encrFilePath)\n {\n bool manageSpp = false;\n\n if (encrFilePath == null)\n {\n encrFilePath = GetPSPath(version);\n manageSpp = true;\n KillSPP(version);\n }\n\n if (string.IsNullOrEmpty(encrFilePath) || !File.Exists(encrFilePath))\n {\n throw new FileNotFoundException(\"Store does not exist at expected path '\" + encrFilePath + \"'.\");\n }\n\n try\n {\n using (FileStream fs = File.Open(encrFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))\n {\n byte[] encrData = fs.ReadAllBytes();\n File.WriteAllBytes(filePath, PhysStoreCrypto.DecryptPhysicalStore(encrData, production, version));\n }\n Logger.WriteLine(\"Store dumped successfully to '\" + filePath + \"'.\");\n }\n finally\n {\n if (manageSpp)\n {\n RestartSPP(version);\n }\n }\n }\n\n ", "suffix_code": "\n }\n}\n", "middle_code": "public static void LoadStore(PSVersion version, bool production, string filePath)\n {\n if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))\n {\n throw new FileNotFoundException(\"Store file '\" + filePath + \"' does not exist.\");\n }\n KillSPP(version);\n using (IPhysicalStore store = GetStore(version, production))\n {\n store.WriteRaw(File.ReadAllBytes(filePath));\n }\n RestartSPP(version);\n Logger.WriteLine(\"Loaded store file successfully.\");\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/TSforge/LibTSforge/Modifiers/GenPKeyInstall.cs", "namespace LibTSforge.Modifiers\n{\n using System;\n using System.IO;\n using Microsoft.Win32;\n using PhysicalStore;\n using SPP;\n using TokenStore;\n\n public static class GenPKeyInstall\n {\n private static void WritePkey2005RegistryValues(PSVersion version, ProductKey pkey)\n {\n Logger.WriteLine(\"Writing registry data for Windows product key...\");\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"ProductId\", pkey.GetPid2());\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"DigitalProductId\", pkey.GetPid3());\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"DigitalProductId4\", pkey.GetPid4());\n\n if (Registry.GetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Registration\", \"ProductId\", null) != null)\n {\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Registration\", \"ProductId\", pkey.GetPid2());\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Registration\", \"DigitalProductId\", pkey.GetPid3());\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Registration\", \"DigitalProductId4\", pkey.GetPid4());\n }\n\n if (pkey.Channel == \"Volume:CSVLK\" && version != PSVersion.Win7)\n {\n Registry.SetValue(@\"HKEY_USERS\\S-1-5-20\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform\", \"KmsHostConfig\", 1);\n }\n }\n\n public static void InstallGenPKey(PSVersion version, bool production, Guid actId)\n {\n if (version == PSVersion.Vista) throw new NotSupportedException(\"This feature is not supported on Windows Vista/Server 2008.\");\n if (actId == Guid.Empty) throw new ArgumentException(\"Activation ID must be specified for generated product key install.\");\n\n PKeyConfig pkc = new PKeyConfig();\n \n try\n {\n pkc.LoadConfig(actId);\n }\n catch (ArgumentException)\n {\n pkc.LoadAllConfigs(SLApi.GetAppId(actId));\n }\n\n ProductConfig config;\n pkc.Products.TryGetValue(actId, out config);\n\n if (config == null) throw new ArgumentException(\"Activation ID \" + actId + \" not found in PKeyConfig.\");\n\n ProductKey pkey = config.GetRandomKey();\n\n Guid instPkeyId = SLApi.GetInstalledPkeyID(actId);\n if (instPkeyId != Guid.Empty) SLApi.UninstallProductKey(instPkeyId);\n\n if (pkey.Algorithm == PKeyAlgorithm.PKEY2009)\n {\n uint status = SLApi.InstallProductKey(pkey);\n Logger.WriteLine(string.Format(\"Installing generated product key {0} status {1:X}\", pkey, status));\n\n if ((int)status < 0)\n {\n throw new ApplicationException(\"Failed to install generated product key.\");\n }\n\n Logger.WriteLine(\"Successfully deposited generated product key.\");\n return;\n }\n\n Logger.WriteLine(\"Key range is PKEY2005, creating fake key data...\");\n\n if (pkey.Channel == \"Volume:GVLK\" && version == PSVersion.Win7) throw new NotSupportedException(\"Fake GVLK generation is not supported on Windows 7.\");\n\n VariableBag pkb = new VariableBag(version);\n pkb.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingProductKey\",\n ValueAsStr = pkey.ToString()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingMPC\",\n ValueAsStr = pkey.GetMPC()\n },\n new CRCBlockModern {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingPid2\",\n ValueAsStr = pkey.GetPid2()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingPid3\",\n Value = pkey.GetPid3()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingPid4\",\n Value = pkey.GetPid4()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyChannelId\",\n ValueAsStr = pkey.Channel\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingEditionId\",\n ValueAsStr = pkey.Edition\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = (version == PSVersion.Win7) ? \"SppPkeyShortAuthenticator\" : \"SppPkeyPhoneActivationData\",\n Value = pkey.GetPhoneData(version)\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingMiscData\",\n Value = new byte[] { }\n }\n });\n\n Guid appId = SLApi.GetAppId(actId);\n string pkeyId = pkey.GetPkeyId().ToString();\n bool isAddon = SLApi.IsAddon(actId);\n string currEdition = SLApi.GetMetaStr(actId, \"Family\");\n\n if (appId == SLApi.WINDOWS_APP_ID && !isAddon)\n {\n SLApi.UninstallAllProductKeys(appId);\n }\n\n SPPUtils.KillSPP(version);\n\n using (IPhysicalStore ps = SPPUtils.GetStore(version, production))\n {\n using (ITokenStore tks = SPPUtils.GetTokenStore(version))\n {\n Logger.WriteLine(\"Writing to physical store and token store...\");\n\n string suffix = (version == PSVersion.Win8 || version == PSVersion.WinBlue || version == PSVersion.WinModern) ? \"_--\" : \"\";\n string metSuffix = suffix + \"_met\";\n\n if (appId == SLApi.WINDOWS_APP_ID && !isAddon)\n {\n string edTokName = \"msft:spp/token/windows/productkeyid/\" + currEdition;\n\n TokenMeta edToken = tks.GetMetaEntry(edTokName);\n edToken.Data[\"windowsComponentEditionPkeyId\"] = pkeyId;\n edToken.Data[\"windowsComponentEditionSkuId\"] = actId.ToString();\n tks.SetEntry(edTokName, \"xml\", edToken.Serialize());\n\n WritePkey2005RegistryValues(version, pkey);\n }\n\n string uriMapName = \"msft:spp/token/PKeyIdUriMapper\" + metSuffix;\n TokenMeta uriMap = tks.GetMetaEntry(uriMapName);\n uriMap.Data[pkeyId] = pkey.GetAlgoUri();\n tks.SetEntry(uriMapName, \"xml\", uriMap.Serialize());\n\n string skuMetaName = actId + metSuffix;\n TokenMeta skuMeta = tks.GetMetaEntry(skuMetaName);\n\n foreach (string k in skuMeta.Data.Keys)\n {\n if (k.StartsWith(\"pkeyId_\"))\n {\n skuMeta.Data.Remove(k);\n break;\n }\n }\n\n skuMeta.Data[\"pkeyId\"] = pkeyId;\n skuMeta.Data[\"pkeyIdList\"] = pkeyId;\n tks.SetEntry(skuMetaName, \"xml\", skuMeta.Serialize());\n\n string psKey = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n ps.DeleteBlock(psKey, pkeyId);\n ps.AddBlock(new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = (version == PSVersion.WinModern) ? (uint)0x402 : 0x2,\n KeyAsStr = psKey,\n ValueAsStr = pkeyId,\n Data = pkb.Serialize()\n });\n\n string cachePath = SPPUtils.GetTokensPath(version).Replace(\"tokens.dat\", @\"cache\\cache.dat\");\n if (File.Exists(cachePath)) File.Delete(cachePath);\n }\n }\n\n SLApi.RefreshTrustedTime(actId);\n Logger.WriteLine(\"Successfully deposited fake product key.\");\n }\n }\n}\n"], ["/TSforge/TSforgeCLI/Program.cs", "namespace TSforgeCLI\n{\n using System;\n using LibTSforge;\n using LibTSforge.Activators;\n using LibTSforge.Modifiers;\n using LibTSforge.SPP;\n\n public class Program\n {\n private class Options\n {\n public bool Dump;\n public string DumpFilePath = \"dump.dat\";\n public string EncrFilePath;\n public bool Load;\n public string LoadFilePath = \"load.dat\";\n public bool KMS4k;\n public bool AVMA4k;\n public bool ZCID;\n public bool TimerReset;\n public bool RearmReset;\n public bool DeleteUniqueId;\n public bool InstallGenPKey;\n public bool KMSHostCharge;\n public bool TamperedFlagsDelete;\n public bool KeyChangeLockDelete;\n public bool SetIIDParams;\n public bool? Production;\n public PSVersion? Version;\n public Guid ActivationId = Guid.Empty;\n public bool ShowHelp;\n public PKeyAlgorithm? Algorithm;\n public int Group;\n public int Serial;\n public ulong Security;\n }\n\n public static void Main(string[] args)\n {\n Logger.WriteLine(\"TSforge (c) MASSGRAVE 2025\");\n\n Utils.Wow64EnableWow64FsRedirection(false);\n\n try\n {\n if (args.Length == 0)\n {\n DisplayUsage();\n return;\n }\n\n Options options = ParseArguments(args);\n\n if (options.ShowHelp)\n {\n DisplayUsage();\n return;\n }\n\n PSVersion version = options.Version ?? Utils.DetectVersion();\n bool production = options.Production ?? SPPUtils.DetectCurrentKey();\n\n if (options.Dump)\n {\n SPPUtils.DumpStore(version, production, options.DumpFilePath, options.EncrFilePath);\n }\n else if (options.Load)\n {\n SPPUtils.LoadStore(version, production, options.LoadFilePath);\n }\n else if (options.KMS4k)\n {\n KMS4k.Activate(version, production, options.ActivationId);\n }\n else if (options.AVMA4k)\n {\n AVMA4k.Activate(version, production, options.ActivationId);\n }\n else if (options.ZCID)\n {\n ZeroCID.Activate(version, production, options.ActivationId);\n }\n else if (options.TimerReset)\n {\n GracePeriodReset.Reset(version, production);\n }\n else if (options.DeleteUniqueId)\n {\n UniqueIdDelete.DeleteUniqueId(version, production, options.ActivationId);\n }\n else if (options.RearmReset)\n {\n RearmReset.Reset(version, production);\n }\n else if (options.InstallGenPKey)\n {\n GenPKeyInstall.InstallGenPKey(version, production, options.ActivationId);\n }\n else if (options.KMSHostCharge)\n {\n KMSHostCharge.Charge(version, production, options.ActivationId);\n }\n else if (options.TamperedFlagsDelete)\n {\n TamperedFlagsDelete.DeleteTamperFlags(version, production);\n }\n else if (options.KeyChangeLockDelete)\n {\n KeyChangeLockDelete.Delete(version, production);\n } \n else if (options.SetIIDParams)\n {\n SetIIDParams.SetParams(version, production, options.ActivationId, options.Algorithm.Value, options.Group, options.Serial, options.Security);\n }\n else\n {\n DisplayUsage();\n }\n }\n catch (Exception e)\n {\n#if DEBUG\n throw;\n#else\n Logger.WriteLine(\"Fatal error: \" + e.ToString());\n Environment.Exit(1);\n#endif\n }\n }\n\n private static Options ParseArguments(string[] args)\n {\n Options options = new Options();\n for (int i = 0; i < args.Length; i++)\n {\n string arg = args[i].Trim().ToLowerInvariant();\n switch (arg)\n {\n case \"/dump\":\n options.Dump = true;\n if (i + 1 < args.Length && !args[i + 1].StartsWith(\"/\"))\n {\n options.DumpFilePath = args[++i];\n }\n if (i + 1 < args.Length && !args[i + 1].StartsWith(\"/\"))\n {\n options.EncrFilePath = args[++i];\n }\n break;\n case \"/load\":\n options.Load = true;\n if (i + 1 < args.Length && !args[i + 1].StartsWith(\"/\"))\n {\n options.LoadFilePath = args[++i];\n }\n break;\n case \"/kms4k\":\n options.KMS4k = true;\n break;\n case \"/avma4k\":\n options.AVMA4k = true;\n break;\n case \"/zcid\":\n options.ZCID = true;\n break;\n case \"/ver\":\n options.Version = i + 1 < args.Length ? ParseVersion(args[++i]) : throw new ArgumentException(\"/ver requires a version argument.\");\n break;\n case \"/rtmr\":\n options.TimerReset = true;\n break;\n case \"/?\":\n options.ShowHelp = true;\n break;\n case \"/duid\":\n options.DeleteUniqueId = true;\n break;\n case \"/rrmc\":\n options.RearmReset = true;\n break;\n case \"/igpk\":\n options.InstallGenPKey = true;\n break;\n case \"/kmsc\":\n options.KMSHostCharge = true;\n break;\n case \"/test\":\n options.Production = false;\n break;\n case \"/prod\":\n options.Production = true;\n break;\n case \"/ctpr\":\n options.TamperedFlagsDelete = true;\n break;\n case \"/revl\":\n options.KeyChangeLockDelete = true;\n break;\n case \"/siid\":\n options.SetIIDParams = true;\n\n if (args.Length - i - 1 < 4) throw new ArgumentException(\"Not enough arguments specified.\");\n\n string algoType = args[++i];\n\n if (algoType == \"5\")\n {\n options.Algorithm = PKeyAlgorithm.PKEY2005;\n }\n else if (algoType == \"9\")\n {\n options.Algorithm = PKeyAlgorithm.PKEY2009;\n } \n else \n { \n throw new ArgumentException(\"Invalid key algorithm specified.\");\n }\n\n try\n {\n options.Group = int.Parse(args[++i]);\n options.Serial = int.Parse(args[++i]);\n options.Security = ulong.Parse(args[++i]);\n } \n catch\n {\n throw new ArgumentException(\"Failed to parse key parameters.\");\n }\n\n break;\n default:\n try\n {\n options.ActivationId = new Guid(arg);\n }\n catch (FormatException)\n {\n Logger.WriteLine(\"Argument doesn't exist or the specified activation ID is invalid.\");\n options.ShowHelp = true;\n }\n break;\n }\n }\n\n return options;\n }\n\n private static void DisplayUsage()\n {\n string exeName = typeof(Program).Namespace;\n Logger.WriteLine(\"Usage: \" + exeName + \" [/dump ()] [/load ] [/kms4k] [/avma4k] [/zcid] [/rtmr] [/duid] [/igpk] [/kmsc] [/ctpr] [/revl] [/siid <5/9> ] [/prod] [/test] [] [/ver ]\");\n Logger.WriteLine(\"Options:\");\n Logger.WriteLine(\"\\t/dump () Dump and decrypt the physical store to the specified path.\");\n Logger.WriteLine(\"\\t/load Load and re-encrypt the physical store from the specified path.\");\n Logger.WriteLine(\"\\t/kms4k Activate using KMS4k. Only supports KMS-activatable editions.\");\n Logger.WriteLine(\"\\t/avma4k Activate using AVMA4k. Only supports Windows Server 2012 R2+.\");\n Logger.WriteLine(\"\\t/zcid Activate using ZeroCID. Only supports phone-activatable editions.\");\n Logger.WriteLine(\"\\t/rtmr Reset grace/evaluation period timers.\");\n Logger.WriteLine(\"\\t/rrmc Reset the rearm count.\");\n Logger.WriteLine(\"\\t/duid Delete product key Unique ID used in online key validation.\");\n Logger.WriteLine(\"\\t/igpk Install auto-generated/fake product key according to the specified Activation ID\");\n Logger.WriteLine(\"\\t/kmsc Reset the charged count on the local KMS server to 25. Requires an activated KMS host.\");\n Logger.WriteLine(\"\\t/ctpr Remove the tamper flags that get set in the physical store when sppsvc detects an attempt to tamper with it.\");\n Logger.WriteLine(\"\\t/revl Remove the key change lock in evaluation edition store.\");\n Logger.WriteLine(\"\\t/siid <5/9> Set Installation ID parameters independently of installed key. 5/9 argument specifies PKEY200[5/9] key algorithm.\");\n Logger.WriteLine(\"\\t/prod Use SPP production key.\");\n Logger.WriteLine(\"\\t/test Use SPP test key.\");\n Logger.WriteLine(\"\\t/ver Override the detected version. Available versions: vista, 7, 8, blue, modern.\");\n Logger.WriteLine(\"\\t A specific activation ID. Useful if you want to activate specific addons like ESU.\");\n Logger.WriteLine(\"\\t/? Display this help message.\");\n }\n\n private static PSVersion ParseVersion(string ver)\n {\n switch (ver.Trim().ToLowerInvariant())\n {\n case \"vista\": return PSVersion.Vista;\n case \"7\": return PSVersion.Win7;\n case \"8\": return PSVersion.Win8;\n case \"blue\": return PSVersion.WinBlue;\n case \"modern\": return PSVersion.WinModern;\n default: throw new ArgumentException(\"Invalid version specified.\");\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/KMSHostCharge.cs", "namespace LibTSforge.Modifiers\n{\n using System;\n using System.IO;\n using PhysicalStore;\n using SPP;\n\n public static class KMSHostCharge\n {\n public static void Charge(PSVersion version, bool production, Guid actId)\n {\n if (actId == Guid.Empty)\n {\n actId = SLApi.GetDefaultActivationID(SLApi.WINDOWS_APP_ID, true);\n\n if (actId == Guid.Empty)\n {\n throw new NotSupportedException(\"No applicable activation IDs found.\");\n }\n }\n\n if (SLApi.GetPKeyChannel(SLApi.GetInstalledPkeyID(actId)) != \"Volume:CSVLK\")\n {\n throw new NotSupportedException(\"Non-Volume:CSVLK product key installed.\");\n }\n\n Guid appId = SLApi.GetAppId(actId);\n int totalClients = 50;\n int currClients = 25;\n byte[] hwidBlock = Constants.UniversalHWIDBlock;\n string key = string.Format(\"SPPSVC\\\\{0}\", appId);\n long ldapTimestamp = DateTime.Now.ToFileTime();\n\n byte[] cmidGuids = { };\n byte[] reqCounts = { };\n byte[] kmsChargeData = { };\n\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n\n if (version == PSVersion.Vista)\n {\n writer.Write(new byte[44]);\n writer.Seek(0, SeekOrigin.Begin);\n\n writer.Write(totalClients);\n writer.Write(43200);\n writer.Write(32);\n\n writer.Seek(20, SeekOrigin.Begin);\n writer.Write((byte)currClients);\n\n writer.Seek(32, SeekOrigin.Begin);\n writer.Write((byte)currClients);\n\n writer.Seek(0, SeekOrigin.End);\n\n for (int i = 0; i < currClients; i++)\n {\n writer.Write(Guid.NewGuid().ToByteArray());\n writer.Write(ldapTimestamp - (10 * (i + 1)));\n }\n\n kmsChargeData = writer.GetBytes();\n } \n else\n {\n for (int i = 0; i < currClients; i++)\n {\n writer.Write(ldapTimestamp - (10 * (i + 1)));\n writer.Write(Guid.NewGuid().ToByteArray());\n }\n\n cmidGuids = writer.GetBytes();\n\n writer = new BinaryWriter(new MemoryStream());\n\n writer.Write(new byte[40]);\n\n writer.Seek(4, SeekOrigin.Begin);\n writer.Write((byte)currClients);\n\n writer.Seek(24, SeekOrigin.Begin);\n writer.Write((byte)currClients);\n\n reqCounts = writer.GetBytes();\n }\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n if (version != PSVersion.Vista)\n {\n VariableBag kmsCountData = new VariableBag(version);\n kmsCountData.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppBindingLicenseData\",\n Value = hwidBlock\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.UINT,\n Key = new byte[] { },\n ValueAsInt = (uint)totalClients\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.UINT,\n Key = new byte[] { },\n ValueAsInt = 1051200000\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.UINT,\n Key = new byte[] { },\n ValueAsInt = (uint)currClients\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n Key = new byte[] { },\n Value = cmidGuids\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n Key = new byte[] { },\n Value = reqCounts\n }\n });\n\n kmsChargeData = kmsCountData.Serialize();\n }\n\n string countVal = version == PSVersion.Vista ? \"C8F6FFF1-79CE-404C-B150-F97991273DF1\" : string.Format(\"msft:spp/kms/host/2.0/store/counters/{0}\", appId);\n\n store.DeleteBlock(key, countVal);\n store.AddBlock(new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = (version == PSVersion.WinModern) ? (uint)0x400 : 0,\n KeyAsStr = key,\n ValueAsStr = countVal,\n Data = kmsChargeData\n });\n\n Logger.WriteLine(string.Format(\"Set charge count to {0} successfully.\", currClients));\n }\n\n SPPUtils.RestartSPP(version);\n }\n }\n}\n"], ["/TSforge/LibTSforge/Activators/KMS4K.cs", "namespace LibTSforge.Activators\n{\n using System;\n using System.IO;\n using PhysicalStore;\n using SPP;\n\n public class KMS4k\n {\n public static void Activate(PSVersion version, bool production, Guid actId)\n {\n Guid appId;\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, true);\n\n if (actId == Guid.Empty)\n {\n throw new NotSupportedException(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n if (SLApi.GetPKeyChannel(SLApi.GetInstalledPkeyID(actId)) != \"Volume:GVLK\")\n {\n throw new NotSupportedException(\"Non-Volume:GVLK product key installed.\");\n }\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n\n ulong unknown = 0;\n ulong time1;\n ulong time2 = (ulong)DateTime.UtcNow.ToFileTime();\n ulong expiry = Constants.TimerMax;\n\n if (version == PSVersion.Vista || version == PSVersion.Win7)\n {\n unknown = 0x800000000;\n time1 = 0;\n }\n else\n {\n long creationTime = BitConverter.ToInt64(store.GetBlock(\"__##USERSEP##\\\\$$_RESERVED_$$\\\\NAMESPACE__\", \"__##USERSEP-RESERVED##__$$GLOBAL-CREATION-TIME$$\").Data, 0);\n long tickCount = BitConverter.ToInt64(store.GetBlock(\"__##USERSEP##\\\\$$_RESERVED_$$\\\\NAMESPACE__\", \"__##USERSEP-RESERVED##__$$GLOBAL-TICKCOUNT-UPTIME$$\").Data, 0);\n long deltaTime = BitConverter.ToInt64(store.GetBlock(key, \"__##USERSEP-RESERVED##__$$UP-TIME-DELTA$$\").Data, 0);\n\n time1 = (ulong)(creationTime + tickCount + deltaTime);\n time2 /= 10000;\n expiry /= 10000;\n }\n\n if (version == PSVersion.Vista)\n {\n VistaTimer vistaTimer = new VistaTimer\n {\n Time = time2,\n Expiry = Constants.TimerMax\n };\n\n string vistaTimerName = string.Format(\"msft:sl/timer/VLExpiration/VOLUME/{0}/{1}\", appId, actId);\n\n store.DeleteBlock(key, vistaTimerName);\n store.DeleteBlock(key, actId.ToString());\n\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(Constants.KMSv4Response.Length);\n writer.Write(Constants.KMSv4Response);\n writer.Write(Constants.UniversalHWIDBlock);\n byte[] kmsData = writer.GetBytes();\n\n store.AddBlocks(new[]\n {\n new PSBlock\n {\n Type = BlockType.TIMER,\n Flags = 0,\n KeyAsStr = key,\n ValueAsStr = vistaTimerName,\n Data = vistaTimer.CastToArray()\n },\n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = 0,\n KeyAsStr = key,\n ValueAsStr = actId.ToString(),\n Data = kmsData\n }\n });\n }\n else\n {\n byte[] hwidBlock = Constants.UniversalHWIDBlock;\n byte[] kmsResp;\n\n switch (version)\n {\n case PSVersion.Win7:\n kmsResp = Constants.KMSv4Response;\n break;\n case PSVersion.Win8:\n kmsResp = Constants.KMSv5Response;\n break;\n case PSVersion.WinBlue:\n case PSVersion.WinModern:\n kmsResp = Constants.KMSv6Response;\n break;\n default:\n throw new NotSupportedException(\"Unsupported PSVersion.\");\n }\n\n VariableBag kmsBinding = new VariableBag(version);\n\n kmsBinding.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n Key = new byte[] { },\n Value = kmsResp\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"msft:rm/algorithm/hwid/4.0\"\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppBindingLicenseData\",\n Value = hwidBlock\n }\n });\n\n if (version == PSVersion.WinModern)\n {\n kmsBinding.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"massgrave.dev\"\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"6969\"\n }\n });\n }\n\n byte[] kmsBindingData = kmsBinding.Serialize();\n\n Timer kmsTimer = new Timer\n {\n Unknown = unknown,\n Time1 = time1,\n Time2 = time2,\n Expiry = expiry\n };\n\n string storeVal = string.Format(\"msft:spp/kms/bind/2.0/store/{0}/{1}\", appId, actId);\n string timerVal = string.Format(\"msft:spp/kms/bind/2.0/timer/{0}/{1}\", appId, actId);\n\n store.DeleteBlock(key, storeVal);\n store.DeleteBlock(key, timerVal);\n\n store.AddBlocks(new[]\n {\n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = (version == PSVersion.WinModern) ? (uint)0x400 : 0,\n KeyAsStr = key,\n ValueAsStr = storeVal,\n Data = kmsBindingData\n },\n new PSBlock\n {\n Type = BlockType.TIMER,\n Flags = (version == PSVersion.Win7) ? (uint)0 : 0x4,\n KeyAsStr = key,\n ValueAsStr = timerVal,\n Data = kmsTimer.CastToArray()\n }\n });\n }\n }\n\n SPPUtils.RestartSPP(version);\n SLApi.FireStateChangedEvent(appId);\n Logger.WriteLine(\"Activated using KMS4k successfully.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/SPP/ProductKey.cs", "namespace LibTSforge.SPP\n{\n using System;\n using System.IO;\n using System.Linq;\n using Crypto;\n using PhysicalStore;\n\n public class ProductKey\n {\n private static readonly string ALPHABET = \"BCDFGHJKMPQRTVWXY2346789\";\n\n private readonly ulong klow;\n private readonly ulong khigh;\n\n public int Group;\n public int Serial;\n public ulong Security;\n public bool Upgrade;\n public PKeyAlgorithm Algorithm;\n public readonly string EulaType;\n public readonly string PartNumber;\n public readonly string Edition;\n public readonly string Channel;\n public readonly Guid ActivationId;\n\n private string mpc;\n private string pid2;\n\n public byte[] KeyBytes\n {\n get { return BitConverter.GetBytes(klow).Concat(BitConverter.GetBytes(khigh)).ToArray(); }\n }\n\n public ProductKey()\n {\n\n }\n\n public ProductKey(int serial, ulong security, bool upgrade, PKeyAlgorithm algorithm, ProductConfig config, KeyRange range)\n {\n Group = config.GroupId;\n Serial = serial;\n Security = security;\n Upgrade = upgrade;\n Algorithm = algorithm;\n EulaType = range.EulaType;\n PartNumber = range.PartNumber.Split(':', ';')[0];\n Edition = config.Edition;\n Channel = config.Channel;\n ActivationId = config.ActivationId;\n\n klow = ((security & 0x3fff) << 50 | ((ulong)serial & 0x3fffffff) << 20 | ((ulong)Group & 0xfffff));\n khigh = ((upgrade ? (ulong)1 : 0) << 49 | ((security >> 14) & 0x7fffffffff));\n\n uint checksum = Utils.CRC32(KeyBytes) & 0x3ff;\n\n khigh |= ((ulong)checksum << 39);\n }\n\n public string GetAlgoUri()\n {\n return \"msft:rm/algorithm/pkey/\" + (Algorithm == PKeyAlgorithm.PKEY2005 ? \"2005\" : (Algorithm == PKeyAlgorithm.PKEY2009 ? \"2009\" : \"Unknown\"));\n }\n\n public Guid GetPkeyId()\n {\n VariableBag pkb = new VariableBag(PSVersion.WinModern);\n pkb.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingProductKey\",\n ValueAsStr = ToString()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingMiscData\",\n Value = new byte[] { }\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingAlgorithm\",\n ValueAsStr = GetAlgoUri()\n }\n });\n\n return new Guid(CryptoUtils.SHA256Hash(pkb.Serialize()).Take(16).ToArray());\n }\n\n public string GetMPC()\n {\n if (mpc != null)\n {\n return mpc;\n }\n\n int build = Environment.OSVersion.Version.Build;\n\n mpc = build >= 10240 ? \"03612\" :\n build >= 9600 ? \"06401\" :\n build >= 9200 ? \"05426\" :\n \"55041\";\n\n // setup.cfg doesn't exist in Windows 8+\n string setupcfg = string.Format(@\"{0}\\oobe\\{1}\", Environment.SystemDirectory, \"setup.cfg\");\n\n if (!File.Exists(setupcfg) || Edition.Contains(\";\"))\n {\n return mpc;\n }\n\n string mpcKey = string.Format(\"{0}.{1}=\", Utils.GetArchitecture(), Edition);\n string localMPC = File.ReadAllLines(setupcfg).FirstOrDefault(line => line.Contains(mpcKey));\n if (localMPC != null)\n {\n mpc = localMPC.Split('=')[1].Trim();\n }\n\n return mpc;\n }\n\n public string GetPid2()\n {\n if (pid2 != null)\n {\n return pid2;\n }\n\n pid2 = \"\";\n\n if (Algorithm == PKeyAlgorithm.PKEY2005)\n {\n string mpc = GetMPC();\n string serialHigh;\n int serialLow;\n int lastPart;\n\n if (EulaType == \"OEM\")\n {\n serialHigh = \"OEM\";\n serialLow = ((Group / 2) % 100) * 10000 + (Serial / 100000);\n lastPart = Serial % 100000;\n }\n else\n {\n serialHigh = (Serial / 1000000).ToString(\"D3\");\n serialLow = Serial % 1000000;\n lastPart = ((Group / 2) % 100) * 1000 + new Random().Next(1000);\n }\n\n int checksum = 0;\n\n foreach (char c in serialLow.ToString())\n {\n checksum += int.Parse(c.ToString());\n }\n checksum = 7 - (checksum % 7);\n\n pid2 = string.Format(\"{0}-{1}-{2:D6}{3}-{4:D5}\", mpc, serialHigh, serialLow, checksum, lastPart);\n }\n\n return pid2;\n }\n\n public byte[] GetPid3()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(0xA4);\n writer.Write(0x3);\n writer.WriteFixedString(GetPid2(), 24);\n writer.Write(Group);\n writer.WriteFixedString(PartNumber, 16);\n writer.WritePadding(0x6C);\n byte[] data = writer.GetBytes();\n byte[] crc = BitConverter.GetBytes(~Utils.CRC32(data.Reverse().ToArray())).Reverse().ToArray();\n writer.Write(crc);\n\n return writer.GetBytes();\n }\n\n public byte[] GetPid4()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(0x4F8);\n writer.Write(0x4);\n writer.WriteFixedString16(GetExtendedPid(), 0x80);\n writer.WriteFixedString16(ActivationId.ToString(), 0x80);\n writer.WritePadding(0x10);\n writer.WriteFixedString16(Edition, 0x208);\n writer.Write(Upgrade ? (ulong)1 : 0);\n writer.WritePadding(0x50);\n writer.WriteFixedString16(PartNumber, 0x80);\n writer.WriteFixedString16(Channel, 0x80);\n writer.WriteFixedString16(EulaType, 0x80);\n\n return writer.GetBytes();\n }\n\n public string GetExtendedPid()\n {\n string mpc = GetMPC();\n int serialHigh = Serial / 1000000;\n int serialLow = Serial % 1000000;\n int licenseType;\n uint lcid = Utils.GetSystemDefaultLCID();\n int build = Environment.OSVersion.Version.Build;\n int dayOfYear = DateTime.Now.DayOfYear;\n int year = DateTime.Now.Year;\n\n switch (EulaType)\n {\n case \"OEM\":\n licenseType = 2;\n break;\n\n case \"Volume\":\n licenseType = 3;\n break;\n\n default:\n licenseType = 0;\n break;\n }\n\n return string.Format(\n \"{0}-{1:D5}-{2:D3}-{3:D6}-{4:D2}-{5:D4}-{6:D4}.0000-{7:D3}{8:D4}\",\n mpc,\n Group,\n serialHigh,\n serialLow,\n licenseType,\n lcid,\n build,\n dayOfYear,\n year\n );\n }\n\n public byte[] GetPhoneData(PSVersion version)\n {\n if (version == PSVersion.Win7)\n {\n ulong shortauth = ((ulong)Group << 41) | (Security << 31) | ((ulong)Serial << 1) | (Upgrade ? (ulong)1 : 0);\n return BitConverter.GetBytes(shortauth);\n }\n\n int serialHigh = Serial / 1000000;\n int serialLow = Serial % 1000000;\n\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n string algoId = Algorithm == PKeyAlgorithm.PKEY2005 ? \"B8731595-A2F6-430B-A799-FBFFB81A8D73\" : \"660672EF-7809-4CFD-8D54-41B7FB738988\";\n\n writer.Write(new Guid(algoId).ToByteArray());\n writer.Write(Group);\n writer.Write(serialHigh);\n writer.Write(serialLow);\n writer.Write(Upgrade ? 1 : 0);\n writer.Write(Security);\n\n return writer.GetBytes();\n }\n\n public override string ToString()\n {\n string keyStr = \"\";\n Random rnd = new Random(Group * 1000000000 + Serial);\n\n if (Algorithm == PKeyAlgorithm.PKEY2005)\n {\n keyStr = \"H4X3DH4X3DH4X3DH4X3D\";\n\n for (int i = 0; i < 5; i++)\n {\n keyStr += ALPHABET[rnd.Next(24)];\n }\n }\n else if (Algorithm == PKeyAlgorithm.PKEY2009)\n {\n int last = 0;\n byte[] bKey = KeyBytes;\n\n for (int i = 24; i >= 0; i--)\n {\n int current = 0;\n\n for (int j = 14; j >= 0; j--)\n {\n current *= 0x100;\n current += bKey[j];\n bKey[j] = (byte)(current / 24);\n current %= 24;\n last = current;\n }\n\n keyStr = ALPHABET[current] + keyStr;\n }\n\n keyStr = keyStr.Substring(1, last) + \"N\" + keyStr.Substring(last + 1, keyStr.Length - last - 1);\n }\n\n for (int i = 5; i < keyStr.Length; i += 6)\n {\n keyStr = keyStr.Insert(i, \"-\");\n }\n\n return keyStr;\n }\n }\n}\n"], ["/TSforge/LibTSforge/Activators/ZeroCID.cs", "namespace LibTSforge.Activators\n{\n using System;\n using System.IO;\n using System.Linq;\n using Crypto;\n using PhysicalStore;\n using SPP;\n\n public static class ZeroCID\n {\n private static void Deposit(Guid actId, string instId)\n {\n uint status = SLApi.DepositConfirmationID(actId, instId, Constants.ZeroCID);\n Logger.WriteLine(string.Format(\"Depositing fake CID status {0:X}\", status));\n\n if (status != 0)\n {\n throw new InvalidOperationException(\"Failed to deposit fake CID.\");\n }\n }\n\n public static void Activate(PSVersion version, bool production, Guid actId)\n {\n Guid appId;\n\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, false);\n\n if (actId == Guid.Empty)\n {\n throw new NotSupportedException(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n if (!SLApi.IsPhoneActivatable(actId))\n {\n throw new NotSupportedException(\"Phone license is unavailable for this product.\");\n }\n\n string instId = SLApi.GetInstallationID(actId);\n Guid pkeyId = SLApi.GetInstalledPkeyID(actId);\n\n if (version == PSVersion.Vista || version == PSVersion.Win7)\n {\n Deposit(actId, instId);\n }\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n byte[] hwidBlock = Constants.UniversalHWIDBlock;\n\n Logger.WriteLine(\"Activation ID: \" + actId);\n Logger.WriteLine(\"Installation ID: \" + instId);\n Logger.WriteLine(\"Product Key ID: \" + pkeyId);\n\n byte[] iidHash;\n\n if (version == PSVersion.Vista)\n {\n iidHash = CryptoUtils.SHA256Hash(Utils.EncodeString(instId)).Take(0x10).ToArray();\n }\n else if (version == PSVersion.Win7)\n {\n iidHash = CryptoUtils.SHA256Hash(Utils.EncodeString(instId));\n }\n else\n {\n iidHash = CryptoUtils.SHA256Hash(Utils.EncodeString(instId + '\\0' + Constants.ZeroCID));\n }\n\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n PSBlock keyBlock = store.GetBlock(key, pkeyId.ToString());\n\n if (keyBlock == null)\n {\n throw new InvalidDataException(\"Failed to get product key data for activation ID \" + actId + \".\");\n }\n\n VariableBag pkb = new VariableBag(keyBlock.Data, version);\n\n byte[] pkeyData;\n\n if (version == PSVersion.Vista)\n {\n pkeyData = pkb.GetBlock(\"PKeyBasicInfo\").Value;\n string uniqueId = Utils.DecodeString(pkeyData.Skip(0x120).Take(0x80).ToArray());\n string extPid = Utils.DecodeString(pkeyData.Skip(0x1A0).Take(0x80).ToArray());\n\n uint group;\n uint.TryParse(extPid.Split('-')[1], out group);\n\n if (group == 0)\n {\n throw new FormatException(\"Extended PID has invalid format.\");\n }\n\n ulong shortauth;\n\n try\n {\n shortauth = BitConverter.ToUInt64(Convert.FromBase64String(uniqueId.Split('&')[1]), 0);\n } \n catch\n {\n throw new FormatException(\"Key Unique ID has invalid format.\");\n }\n\n shortauth |= (ulong)group << 41;\n pkeyData = BitConverter.GetBytes(shortauth);\n }\n else if (version == PSVersion.Win7)\n {\n pkeyData = pkb.GetBlock(\"SppPkeyShortAuthenticator\").Value;\n }\n else\n {\n pkeyData = pkb.GetBlock(\"SppPkeyPhoneActivationData\").Value;\n }\n\n pkb.DeleteBlock(\"SppPkeyVirtual\");\n store.SetBlock(key, pkeyId.ToString(), pkb.Serialize());\n\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(iidHash.Length);\n writer.Write(iidHash);\n writer.Write(hwidBlock.Length);\n writer.Write(hwidBlock);\n byte[] tsHwidData = writer.GetBytes();\n\n writer = new BinaryWriter(new MemoryStream());\n writer.Write(iidHash.Length);\n writer.Write(iidHash);\n writer.Write(pkeyData.Length);\n writer.Write(pkeyData);\n byte[] tsPkeyInfoData = writer.GetBytes();\n\n string phoneVersion = version == PSVersion.Vista ? \"6.0\" : \"7.0\";\n Guid indexSlid = version == PSVersion.Vista ? actId : pkeyId;\n string hwidBlockName = string.Format(\"msft:Windows/{0}/Phone/Cached/HwidBlock/{1}\", phoneVersion, indexSlid);\n string pkeyInfoName = string.Format(\"msft:Windows/{0}/Phone/Cached/PKeyInfo/{1}\", phoneVersion, indexSlid);\n\n store.DeleteBlock(key, hwidBlockName);\n store.DeleteBlock(key, pkeyInfoName);\n\n store.AddBlocks(new[] {\n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = 0,\n KeyAsStr = key,\n ValueAsStr = hwidBlockName,\n Data = tsHwidData\n }, \n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = 0,\n KeyAsStr = key,\n ValueAsStr = pkeyInfoName,\n Data = tsPkeyInfoData\n }\n });\n }\n\n if (version != PSVersion.Vista && version != PSVersion.Win7)\n {\n Deposit(actId, instId);\n }\n\n SPPUtils.RestartSPP(version);\n SLApi.FireStateChangedEvent(appId);\n Logger.WriteLine(\"Activated using ZeroCID successfully.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/TokenStore/TokenStoreModern.cs", "namespace LibTSforge.TokenStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using System.Linq;\n using Crypto;\n\n public class TokenStoreModern : ITokenStore\n {\n private static readonly uint VERSION = 3;\n private static readonly int ENTRY_SIZE = 0x9E;\n private static readonly int BLOCK_SIZE = 0x4020;\n private static readonly int ENTRIES_PER_BLOCK = BLOCK_SIZE / ENTRY_SIZE;\n private static readonly int BLOCK_PAD_SIZE = 0x66;\n\n private static readonly byte[] CONTS_HEADER = Enumerable.Repeat((byte)0x55, 0x20).ToArray();\n private static readonly byte[] CONTS_FOOTER = Enumerable.Repeat((byte)0xAA, 0x20).ToArray();\n\n private List Entries = new List();\n private readonly FileStream TokensFile;\n\n public void Deserialize()\n {\n if (TokensFile.Length < BLOCK_SIZE) return;\n\n TokensFile.Seek(0x24, SeekOrigin.Begin);\n uint nextBlock;\n\n BinaryReader reader = new BinaryReader(TokensFile);\n do\n {\n reader.ReadUInt32();\n nextBlock = reader.ReadUInt32();\n\n for (int i = 0; i < ENTRIES_PER_BLOCK; i++)\n {\n uint curOffset = reader.ReadUInt32();\n bool populated = reader.ReadUInt32() == 1;\n uint contentOffset = reader.ReadUInt32();\n uint contentLength = reader.ReadUInt32();\n uint allocLength = reader.ReadUInt32();\n byte[] contentData = { };\n\n if (populated)\n {\n reader.BaseStream.Seek(contentOffset + 0x20, SeekOrigin.Begin);\n uint dataLength = reader.ReadUInt32();\n\n if (dataLength != contentLength)\n {\n throw new FormatException(\"Data length in tokens content is inconsistent with entry.\");\n }\n\n reader.ReadBytes(0x20);\n contentData = reader.ReadBytes((int)contentLength);\n }\n\n reader.BaseStream.Seek(curOffset + 0x14, SeekOrigin.Begin);\n\n Entries.Add(new TokenEntry\n {\n Name = reader.ReadNullTerminatedString(0x82),\n Extension = reader.ReadNullTerminatedString(0x8),\n Data = contentData,\n Populated = populated\n });\n }\n\n reader.BaseStream.Seek(nextBlock, SeekOrigin.Begin);\n } while (nextBlock != 0);\n }\n\n public void Serialize()\n {\n MemoryStream tokens = new MemoryStream();\n\n using (BinaryWriter writer = new BinaryWriter(tokens))\n {\n writer.Write(VERSION);\n writer.Write(CONTS_HEADER);\n\n int curBlockOffset = (int)writer.BaseStream.Position;\n int curEntryOffset = curBlockOffset + 0x8;\n int curContsOffset = curBlockOffset + BLOCK_SIZE;\n\n for (int eIndex = 0; eIndex < ((Entries.Count / ENTRIES_PER_BLOCK) + 1) * ENTRIES_PER_BLOCK; eIndex++)\n {\n TokenEntry entry;\n\n if (eIndex < Entries.Count)\n {\n entry = Entries[eIndex];\n }\n else\n {\n entry = new TokenEntry\n {\n Name = \"\",\n Extension = \"\",\n Populated = false,\n Data = new byte[] { }\n };\n }\n\n writer.BaseStream.Seek(curBlockOffset, SeekOrigin.Begin);\n writer.Write(curBlockOffset);\n writer.Write(0);\n\n writer.BaseStream.Seek(curEntryOffset, SeekOrigin.Begin);\n writer.Write(curEntryOffset);\n writer.Write(entry.Populated ? 1 : 0);\n writer.Write(entry.Populated ? curContsOffset : 0);\n writer.Write(entry.Populated ? entry.Data.Length : -1);\n writer.Write(entry.Populated ? entry.Data.Length : -1);\n writer.WriteFixedString16(entry.Name, 0x82);\n writer.WriteFixedString16(entry.Extension, 0x8);\n curEntryOffset = (int)writer.BaseStream.Position;\n\n if (entry.Populated)\n {\n writer.BaseStream.Seek(curContsOffset, SeekOrigin.Begin);\n writer.Write(CONTS_HEADER);\n writer.Write(entry.Data.Length);\n writer.Write(CryptoUtils.SHA256Hash(entry.Data));\n writer.Write(entry.Data);\n writer.Write(CONTS_FOOTER);\n curContsOffset = (int)writer.BaseStream.Position;\n }\n\n if ((eIndex + 1) % ENTRIES_PER_BLOCK == 0 && eIndex != 0)\n {\n if (eIndex < Entries.Count)\n {\n writer.BaseStream.Seek(curBlockOffset + 0x4, SeekOrigin.Begin);\n writer.Write(curContsOffset);\n }\n\n writer.BaseStream.Seek(curEntryOffset, SeekOrigin.Begin);\n writer.WritePadding(BLOCK_PAD_SIZE);\n\n writer.BaseStream.Seek(curBlockOffset, SeekOrigin.Begin);\n byte[] blockData = new byte[BLOCK_SIZE - 0x20];\n\n tokens.Read(blockData, 0, BLOCK_SIZE - 0x20);\n byte[] blockHash = CryptoUtils.SHA256Hash(blockData);\n\n writer.BaseStream.Seek(curBlockOffset + BLOCK_SIZE - 0x20, SeekOrigin.Begin);\n writer.Write(blockHash);\n\n curBlockOffset = curContsOffset;\n curEntryOffset = curBlockOffset + 0x8;\n curContsOffset = curBlockOffset + BLOCK_SIZE;\n }\n }\n\n tokens.SetLength(curBlockOffset);\n }\n\n byte[] tokensData = tokens.ToArray();\n byte[] tokensHash = CryptoUtils.SHA256Hash(tokensData.Take(0x4).Concat(tokensData.Skip(0x24)).ToArray());\n\n tokens = new MemoryStream(tokensData);\n\n BinaryWriter tokWriter = new BinaryWriter(TokensFile);\n using (BinaryReader reader = new BinaryReader(tokens))\n {\n TokensFile.Seek(0, SeekOrigin.Begin);\n TokensFile.SetLength(tokens.Length);\n tokWriter.Write(reader.ReadBytes(0x4));\n reader.ReadBytes(0x20);\n tokWriter.Write(tokensHash);\n tokWriter.Write(reader.ReadBytes((int)reader.BaseStream.Length - 0x4));\n }\n }\n\n public void AddEntry(TokenEntry entry)\n {\n Entries.Add(entry);\n }\n\n public void AddEntries(TokenEntry[] entries)\n {\n Entries.AddRange(entries);\n }\n\n public void DeleteEntry(string name, string ext)\n {\n foreach (TokenEntry entry in Entries)\n {\n if (entry.Name == name && entry.Extension == ext)\n {\n Entries.Remove(entry);\n return;\n }\n }\n }\n\n public void DeleteUnpopEntry(string name, string ext)\n {\n List delEntries = new List();\n foreach (TokenEntry entry in Entries)\n {\n if (entry.Name == name && entry.Extension == ext && !entry.Populated)\n {\n delEntries.Add(entry);\n }\n }\n\n Entries = Entries.Except(delEntries).ToList();\n }\n\n public TokenEntry GetEntry(string name, string ext)\n {\n foreach (TokenEntry entry in Entries)\n {\n if (entry.Name == name && entry.Extension == ext)\n {\n if (!entry.Populated) continue;\n return entry;\n }\n }\n\n return null;\n }\n\n public TokenMeta GetMetaEntry(string name)\n {\n DeleteUnpopEntry(name, \"xml\");\n TokenEntry entry = GetEntry(name, \"xml\");\n TokenMeta meta;\n\n if (entry == null)\n {\n meta = new TokenMeta\n {\n Name = name\n };\n }\n else\n {\n meta = new TokenMeta(entry.Data);\n }\n\n return meta;\n }\n\n public void SetEntry(string name, string ext, byte[] data)\n {\n for (int i = 0; i < Entries.Count; i++)\n {\n TokenEntry entry = Entries[i];\n\n if (entry.Name == name && entry.Extension == ext && entry.Populated)\n {\n entry.Data = data;\n Entries[i] = entry;\n return;\n }\n }\n\n Entries.Add(new TokenEntry\n {\n Populated = true,\n Name = name,\n Extension = ext,\n Data = data\n });\n }\n\n public TokenStoreModern(string tokensPath)\n {\n TokensFile = File.Open(tokensPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n Deserialize();\n }\n\n public void Dispose()\n {\n Serialize();\n TokensFile.Close();\n }\n }\n}\n"], ["/TSforge/LibTSforge/SPP/PKeyConfig.cs", "namespace LibTSforge.SPP\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using System.Linq;\n using System.Text;\n using System.Xml;\n\n public enum PKeyAlgorithm\n {\n PKEY2005,\n PKEY2009\n }\n\n public class KeyRange\n {\n public int Start;\n public int End;\n public string EulaType;\n public string PartNumber;\n public bool Valid;\n\n public bool Contains(int n)\n {\n return Start <= n && End <= n;\n }\n }\n\n public class ProductConfig\n {\n public int GroupId;\n public string Edition;\n public string Description;\n public string Channel;\n public bool Randomized;\n public PKeyAlgorithm Algorithm;\n public List Ranges;\n public Guid ActivationId;\n\n private List GetPkeyRanges()\n {\n if (Ranges.Count == 0)\n {\n throw new ArgumentException(\"No key ranges.\");\n }\n\n if (Algorithm == PKeyAlgorithm.PKEY2005)\n {\n return Ranges;\n }\n\n List FilteredRanges = Ranges.Where(r => !r.EulaType.Contains(\"WAU\")).ToList();\n\n if (FilteredRanges.Count == 0)\n {\n throw new NotSupportedException(\"Specified Activation ID is usable only for Windows Anytime Upgrade. Please use a non-WAU Activation ID instead.\");\n }\n\n return FilteredRanges;\n }\n\n public ProductKey GetRandomKey()\n {\n List KeyRanges = GetPkeyRanges();\n Random rnd = new Random();\n\n KeyRange range = KeyRanges[rnd.Next(KeyRanges.Count)];\n int serial = rnd.Next(range.Start, range.End);\n\n return new ProductKey(serial, 0, false, Algorithm, this, range);\n }\n }\n\n public class PKeyConfig\n {\n public readonly Dictionary Products = new Dictionary();\n private readonly List loadedPkeyConfigs = new List();\n\n public void LoadConfig(Guid actId)\n {\n string pkcData;\n Guid pkcFileId = SLApi.GetPkeyConfigFileId(actId);\n\n if (loadedPkeyConfigs.Contains(pkcFileId)) return;\n\n string licConts = SLApi.GetLicenseContents(pkcFileId);\n\n using (TextReader tr = new StringReader(licConts))\n {\n XmlDocument lic = new XmlDocument();\n lic.Load(tr);\n\n XmlNamespaceManager nsmgr = new XmlNamespaceManager(lic.NameTable);\n nsmgr.AddNamespace(\"rg\", \"urn:mpeg:mpeg21:2003:01-REL-R-NS\");\n nsmgr.AddNamespace(\"r\", \"urn:mpeg:mpeg21:2003:01-REL-R-NS\");\n nsmgr.AddNamespace(\"tm\", \"http://www.microsoft.com/DRM/XrML2/TM/v2\");\n\n XmlNode root = lic.DocumentElement;\n XmlNode pkcDataNode = root.SelectSingleNode(\"/rg:licenseGroup/r:license/r:otherInfo/tm:infoTables/tm:infoList/tm:infoBin[@name=\\\"pkeyConfigData\\\"]\", nsmgr);\n pkcData = Encoding.UTF8.GetString(Convert.FromBase64String(pkcDataNode.InnerText));\n }\n\n using (TextReader tr = new StringReader(pkcData))\n {\n XmlDocument lic = new XmlDocument();\n lic.Load(tr);\n\n XmlNamespaceManager nsmgr = new XmlNamespaceManager(lic.NameTable);\n nsmgr.AddNamespace(\"p\", \"http://www.microsoft.com/DRM/PKEY/Configuration/2.0\");\n XmlNodeList configNodes = lic.SelectNodes(\"//p:ProductKeyConfiguration/p:Configurations/p:Configuration\", nsmgr);\n XmlNodeList rangeNodes = lic.SelectNodes(\"//p:ProductKeyConfiguration/p:KeyRanges/p:KeyRange\", nsmgr);\n XmlNodeList pubKeyNodes = lic.SelectNodes(\"//p:ProductKeyConfiguration/p:PublicKeys/p:PublicKey\", nsmgr);\n\n Dictionary algorithms = new Dictionary();\n Dictionary> ranges = new Dictionary>();\n\n Dictionary algoConv = new Dictionary\n {\n { \"msft:rm/algorithm/pkey/2005\", PKeyAlgorithm.PKEY2005 },\n { \"msft:rm/algorithm/pkey/2009\", PKeyAlgorithm.PKEY2009 }\n };\n\n foreach (XmlNode pubKeyNode in pubKeyNodes)\n {\n int group = int.Parse(pubKeyNode.SelectSingleNode(\"./p:GroupId\", nsmgr).InnerText);\n algorithms[group] = algoConv[pubKeyNode.SelectSingleNode(\"./p:AlgorithmId\", nsmgr).InnerText];\n }\n\n foreach (XmlNode rangeNode in rangeNodes)\n {\n string refActIdStr = rangeNode.SelectSingleNode(\"./p:RefActConfigId\", nsmgr).InnerText;\n\n if (!ranges.ContainsKey(refActIdStr))\n {\n ranges[refActIdStr] = new List();\n }\n\n KeyRange keyRange = new KeyRange\n {\n Start = int.Parse(rangeNode.SelectSingleNode(\"./p:Start\", nsmgr).InnerText),\n End = int.Parse(rangeNode.SelectSingleNode(\"./p:End\", nsmgr).InnerText),\n EulaType = rangeNode.SelectSingleNode(\"./p:EulaType\", nsmgr).InnerText,\n PartNumber = rangeNode.SelectSingleNode(\"./p:PartNumber\", nsmgr).InnerText,\n Valid = rangeNode.SelectSingleNode(\"./p:IsValid\", nsmgr).InnerText.ToLower() == \"true\"\n };\n\n ranges[refActIdStr].Add(keyRange);\n }\n\n foreach (XmlNode configNode in configNodes)\n {\n string refActIdStr = configNode.SelectSingleNode(\"./p:ActConfigId\", nsmgr).InnerText;\n Guid refActId = new Guid(refActIdStr);\n int group = int.Parse(configNode.SelectSingleNode(\"./p:RefGroupId\", nsmgr).InnerText);\n List keyRanges = ranges[refActIdStr];\n\n if (keyRanges.Count > 0 && !Products.ContainsKey(refActId))\n {\n ProductConfig productConfig = new ProductConfig\n {\n GroupId = group,\n Edition = configNode.SelectSingleNode(\"./p:EditionId\", nsmgr).InnerText,\n Description = configNode.SelectSingleNode(\"./p:ProductDescription\", nsmgr).InnerText,\n Channel = configNode.SelectSingleNode(\"./p:ProductKeyType\", nsmgr).InnerText,\n Randomized = configNode.SelectSingleNode(\"./p:ProductKeyType\", nsmgr).InnerText.ToLower() == \"true\",\n Algorithm = algorithms[group],\n Ranges = keyRanges,\n ActivationId = refActId\n };\n\n Products[refActId] = productConfig;\n }\n }\n }\n\n loadedPkeyConfigs.Add(pkcFileId);\n }\n\n public ProductConfig MatchParams(int group, int serial)\n {\n foreach (ProductConfig config in Products.Values)\n {\n if (config.GroupId == group)\n {\n foreach (KeyRange range in config.Ranges)\n {\n if (range.Contains(serial))\n {\n return config;\n }\n }\n }\n }\n\n throw new FileNotFoundException(\"Failed to find product matching supplied product key parameters.\");\n }\n\n public void LoadAllConfigs(Guid appId)\n {\n foreach (Guid actId in SLApi.GetActivationIds(appId))\n {\n try\n {\n LoadConfig(actId);\n } \n catch (ArgumentException)\n {\n\n }\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/Activators/AVMA4K.cs", "namespace LibTSforge.Activators\n{\n using System;\n using PhysicalStore;\n using SPP;\n\n public static class AVMA4k\n {\n public static void Activate(PSVersion version, bool production, Guid actId)\n {\n if (version != PSVersion.WinModern && version != PSVersion.WinBlue)\n {\n throw new NotSupportedException(\"AVMA licenses are not available for this product.\");\n }\n\n Guid appId;\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, false);\n\n if (actId == Guid.Empty)\n {\n throw new NotSupportedException(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n if (SLApi.GetPKeyChannel(SLApi.GetInstalledPkeyID(actId)) != \"VT:IA\")\n {\n throw new NotSupportedException(\"Non-VT:IA product key installed.\");\n }\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n\n long creationTime = BitConverter.ToInt64(store.GetBlock(\"__##USERSEP##\\\\$$_RESERVED_$$\\\\NAMESPACE__\", \"__##USERSEP-RESERVED##__$$GLOBAL-CREATION-TIME$$\").Data, 0);\n long tickCount = BitConverter.ToInt64(store.GetBlock(\"__##USERSEP##\\\\$$_RESERVED_$$\\\\NAMESPACE__\", \"__##USERSEP-RESERVED##__$$GLOBAL-TICKCOUNT-UPTIME$$\").Data, 0);\n long deltaTime = BitConverter.ToInt64(store.GetBlock(key, \"__##USERSEP-RESERVED##__$$UP-TIME-DELTA$$\").Data, 0);\n\n const ulong unknown = 0;\n ulong time1 = (ulong)(creationTime + tickCount + deltaTime);\n ulong crcBindTime = (ulong)DateTime.UtcNow.ToFileTime();\n ulong timerTime = crcBindTime / 10000;\n ulong expiry = Constants.TimerMax / 10000;\n\n VariableBag avmaBinding = new VariableBag(version);\n\n avmaBinding.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n Key = new byte[] { },\n Value = BitConverter.GetBytes(crcBindTime),\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"AVMA4K\",\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"00491-50000-00001-AA666\",\n }\n });\n\n byte[] avmaBindingData = avmaBinding.Serialize();\n\n Timer avmaTimer = new Timer\n {\n Unknown = unknown,\n Time1 = time1,\n Time2 = timerTime,\n Expiry = expiry\n };\n\n string storeVal = string.Format(\"msft:spp/ia/bind/1.0/store/{0}/{1}\", appId, actId);\n string timerVal = string.Format(\"msft:spp/ia/bind/1.0/timer/{0}/{1}\", appId, actId);\n\n store.DeleteBlock(key, storeVal);\n store.DeleteBlock(key, timerVal);\n\n store.AddBlocks(new[]\n {\n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = 0x400,\n KeyAsStr = key,\n ValueAsStr = storeVal,\n Data = avmaBindingData,\n },\n new PSBlock\n {\n Type = BlockType.TIMER,\n Flags = 0x4,\n KeyAsStr = key,\n ValueAsStr = timerVal,\n Data = avmaTimer.CastToArray()\n }\n });\n }\n\n SLApi.RefreshLicenseStatus();\n SLApi.FireStateChangedEvent(appId);\n Logger.WriteLine(\"Activated using AVMA4k successfully.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/PhysicalStoreModern.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using Crypto;\n\n public class ModernBlock\n {\n public BlockType Type;\n public uint Flags;\n public uint Unknown;\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n public byte[] Data;\n public string DataAsStr\n {\n get\n {\n return Utils.DecodeString(Data);\n }\n set\n {\n Data = Utils.EncodeString(value);\n }\n }\n public uint DataAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Data, 0);\n }\n set\n {\n Data = BitConverter.GetBytes(value);\n }\n }\n\n public void Encode(BinaryWriter writer)\n {\n writer.Write((uint)Type);\n writer.Write(Flags);\n writer.Write((uint)Value.Length);\n writer.Write((uint)Data.Length);\n writer.Write(Unknown);\n writer.Write(Value);\n writer.Write(Data);\n }\n\n public static ModernBlock Decode(BinaryReader reader)\n {\n uint type = reader.ReadUInt32();\n uint flags = reader.ReadUInt32();\n\n uint valueLen = reader.ReadUInt32();\n uint dataLen = reader.ReadUInt32();\n uint unk3 = reader.ReadUInt32();\n\n byte[] value = reader.ReadBytes((int)valueLen);\n byte[] data = reader.ReadBytes((int)dataLen);\n\n return new ModernBlock\n {\n Type = (BlockType)type,\n Flags = flags,\n Unknown = unk3,\n Value = value,\n Data = data,\n };\n }\n }\n\n public sealed class PhysicalStoreModern : IPhysicalStore\n {\n private byte[] PreHeaderBytes = { };\n private readonly Dictionary> Data = new Dictionary>();\n private readonly FileStream TSFile;\n private readonly PSVersion Version;\n private readonly bool Production;\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(PreHeaderBytes);\n writer.Write(Data.Keys.Count);\n\n foreach (string key in Data.Keys)\n {\n List blocks = Data[key];\n byte[] keyNameEnc = Utils.EncodeString(key);\n\n writer.Write(keyNameEnc.Length);\n writer.Write(keyNameEnc);\n writer.Write(blocks.Count);\n writer.Align(4);\n\n foreach (ModernBlock block in blocks)\n {\n block.Encode(writer);\n writer.Align(4);\n }\n }\n\n return writer.GetBytes();\n }\n\n public void Deserialize(byte[] data)\n {\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n PreHeaderBytes = reader.ReadBytes(8);\n\n while (reader.BaseStream.Position < data.Length - 0x4)\n {\n uint numKeys = reader.ReadUInt32();\n\n for (int i = 0; i < numKeys; i++)\n {\n uint lenKeyName = reader.ReadUInt32();\n string keyName = Utils.DecodeString(reader.ReadBytes((int)lenKeyName)); uint numValues = reader.ReadUInt32();\n\n reader.Align(4);\n\n Data[keyName] = new List();\n\n for (int j = 0; j < numValues; j++)\n {\n Data[keyName].Add(ModernBlock.Decode(reader));\n reader.Align(4);\n }\n }\n }\n }\n\n public void AddBlock(PSBlock block)\n {\n if (!Data.ContainsKey(block.KeyAsStr))\n {\n Data[block.KeyAsStr] = new List();\n }\n\n Data[block.KeyAsStr].Add(new ModernBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Unknown = block.Unknown,\n Value = block.Value,\n Data = block.Data\n });\n }\n\n public void AddBlocks(IEnumerable blocks)\n {\n foreach (PSBlock block in blocks)\n {\n AddBlock(block);\n }\n }\n\n public PSBlock GetBlock(string key, string value)\n {\n List blocks = Data[key];\n\n foreach (ModernBlock block in blocks)\n {\n if (block.ValueAsStr == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = Utils.EncodeString(key),\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public PSBlock GetBlock(string key, uint value)\n {\n List blocks = Data[key];\n\n foreach (ModernBlock block in blocks)\n {\n if (block.ValueAsInt == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = Utils.EncodeString(key),\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public void SetBlock(string key, string value, byte[] data)\n {\n List blocks = Data[key];\n\n for (int i = 0; i < blocks.Count; i++)\n {\n ModernBlock block = blocks[i];\n\n if (block.ValueAsStr == value)\n {\n block.Data = data;\n blocks[i] = block;\n break;\n }\n }\n\n Data[key] = blocks;\n }\n\n public void SetBlock(string key, uint value, byte[] data)\n {\n List blocks = Data[key];\n\n for (int i = 0; i < blocks.Count; i++)\n {\n ModernBlock block = blocks[i];\n\n if (block.ValueAsInt == value)\n {\n block.Data = data;\n blocks[i] = block;\n break;\n }\n }\n\n Data[key] = blocks;\n }\n\n public void SetBlock(string key, string value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, string value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void SetBlock(string key, uint value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, uint value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void DeleteBlock(string key, string value)\n {\n if (!Data.ContainsKey(key))\n {\n return;\n }\n\n List blocks = Data[key];\n\n foreach (ModernBlock block in blocks)\n {\n if (block.ValueAsStr == value)\n {\n blocks.Remove(block);\n break;\n }\n }\n\n Data[key] = blocks;\n }\n\n public void DeleteBlock(string key, uint value)\n {\n if (!Data.ContainsKey(key))\n {\n return;\n }\n\n List blocks = Data[key];\n\n foreach (ModernBlock block in blocks)\n {\n if (block.ValueAsInt == value)\n {\n blocks.Remove(block);\n break;\n }\n }\n\n Data[key] = blocks;\n }\n\n public PhysicalStoreModern(string tsPath, bool production, PSVersion version)\n {\n TSFile = File.Open(tsPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n Deserialize(PhysStoreCrypto.DecryptPhysicalStore(TSFile.ReadAllBytes(), production, version));\n TSFile.Seek(0, SeekOrigin.Begin);\n Version = version;\n Production = production;\n }\n\n public void Dispose()\n {\n if (TSFile.CanWrite)\n {\n byte[] data = PhysStoreCrypto.EncryptPhysicalStore(Serialize(), Production, Version);\n TSFile.SetLength(data.LongLength);\n TSFile.Seek(0, SeekOrigin.Begin);\n TSFile.WriteAllBytes(data);\n TSFile.Close();\n }\n }\n\n public byte[] ReadRaw()\n {\n byte[] data = PhysStoreCrypto.DecryptPhysicalStore(TSFile.ReadAllBytes(), Production, Version);\n TSFile.Seek(0, SeekOrigin.Begin);\n return data;\n }\n\n public void WriteRaw(byte[] data)\n {\n byte[] encrData = PhysStoreCrypto.EncryptPhysicalStore(data, Production, Version);\n TSFile.SetLength(encrData.LongLength);\n TSFile.Seek(0, SeekOrigin.Begin);\n TSFile.WriteAllBytes(encrData);\n TSFile.Close();\n }\n\n public IEnumerable FindBlocks(string valueSearch)\n {\n List results = new List();\n\n foreach (string key in Data.Keys)\n {\n List values = Data[key];\n\n foreach (ModernBlock block in values)\n {\n if (block.ValueAsStr.Contains(valueSearch))\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n KeyAsStr = key,\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n }\n\n return results;\n }\n\n public IEnumerable FindBlocks(uint valueSearch)\n {\n List results = new List();\n\n foreach (string key in Data.Keys)\n {\n List values = Data[key];\n\n foreach (ModernBlock block in values)\n {\n if (block.ValueAsInt == valueSearch)\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n KeyAsStr = key,\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n }\n\n return results;\n }\n }\n}\n"], ["/TSforge/LibTSforge/SPP/SLAPI.cs", "namespace LibTSforge.SPP\n{\n using System;\n using System.Collections.Generic;\n using System.Linq;\n using System.Runtime.InteropServices;\n using System.Text;\n\n public static class SLApi\n {\n private enum SLIDTYPE\n {\n SL_ID_APPLICATION,\n SL_ID_PRODUCT_SKU,\n SL_ID_LICENSE_FILE,\n SL_ID_LICENSE,\n SL_ID_PKEY,\n SL_ID_ALL_LICENSES,\n SL_ID_ALL_LICENSE_FILES,\n SL_ID_STORE_TOKEN,\n SL_ID_LAST\n }\n\n private enum SLDATATYPE\n {\n SL_DATA_NONE,\n SL_DATA_SZ,\n SL_DATA_DWORD,\n SL_DATA_BINARY,\n SL_DATA_MULTI_SZ,\n SL_DATA_SUM\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct SL_LICENSING_STATUS\n {\n public Guid SkuId;\n public uint eStatus;\n public uint dwGraceTime;\n public uint dwTotalGraceDays;\n public uint hrReason;\n public ulong qwValidityExpiration;\n }\n\n public static readonly Guid WINDOWS_APP_ID = new Guid(\"55c92734-d682-4d71-983e-d6ec3f16059f\");\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode, PreserveSig = false)]\n private static extern void SLOpen(out IntPtr hSLC);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode, PreserveSig = false)]\n private static extern void SLClose(IntPtr hSLC);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetWindowsInformationDWORD(string ValueName, ref int Value);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLInstallProofOfPurchase(IntPtr hSLC, string pwszPKeyAlgorithm, string pwszPKeyString, uint cbPKeySpecificData, byte[] pbPKeySpecificData, ref Guid PKeyId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLUninstallProofOfPurchase(IntPtr hSLC, ref Guid PKeyId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetPKeyInformation(IntPtr hSLC, ref Guid pPKeyId, string pwszValueName, out SLDATATYPE peDataType, out uint pcbValue, out IntPtr ppbValue);\n\n [DllImport(\"slcext.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLActivateProduct(IntPtr hSLC, ref Guid pProductSkuId, byte[] cbAppSpecificData, byte[] pvAppSpecificData, byte[] pActivationInfo, string pwszProxyServer, ushort wProxyPort);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGenerateOfflineInstallationId(IntPtr hSLC, ref Guid pProductSkuId, ref string ppwszInstallationId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLDepositOfflineConfirmationId(IntPtr hSLC, ref Guid pProductSkuId, string pwszInstallationId, string pwszConfirmationId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetSLIDList(IntPtr hSLC, SLIDTYPE eQueryIdType, ref Guid pQueryId, SLIDTYPE eReturnIdType, out uint pnReturnIds, out IntPtr ppReturnIds);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode, PreserveSig = false)]\n private static extern void SLGetLicensingStatusInformation(IntPtr hSLC, ref Guid pAppID, IntPtr pProductSkuId, string pwszRightName, out uint pnStatusCount, out IntPtr ppLicensingStatus);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetInstalledProductKeyIds(IntPtr hSLC, ref Guid pProductSkuId, out uint pnProductKeyIds, out IntPtr ppProductKeyIds);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLConsumeWindowsRight(uint unknown);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetProductSkuInformation(IntPtr hSLC, ref Guid pProductSkuId, string pwszValueName, out SLDATATYPE peDataType, out uint pcbValue, out IntPtr ppbValue);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetLicense(IntPtr hSLC, ref Guid pLicenseFileId, out uint pcbLicenseFile, out IntPtr ppbLicenseFile);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLSetCurrentProductKey(IntPtr hSLC, ref Guid pProductSkuId, ref Guid pProductKeyId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLFireEvent(IntPtr hSLC, string pwszEventId, ref Guid pApplicationId);\n\n private class SLContext : IDisposable\n {\n public readonly IntPtr Handle;\n\n public SLContext()\n {\n SLOpen(out Handle);\n }\n\n public void Dispose()\n {\n SLClose(Handle);\n GC.SuppressFinalize(this);\n }\n\n ~SLContext()\n {\n Dispose();\n }\n }\n\n public static Guid GetDefaultActivationID(Guid appId, bool includeActivated)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr pLicStat;\n\n SLGetLicensingStatusInformation(sl.Handle, ref appId, IntPtr.Zero, null, out count, out pLicStat);\n\n unsafe\n {\n SL_LICENSING_STATUS* licensingStatuses = (SL_LICENSING_STATUS*)pLicStat;\n for (int i = 0; i < count; i++)\n {\n SL_LICENSING_STATUS slStatus = licensingStatuses[i];\n\n Guid actId = slStatus.SkuId;\n if (GetInstalledPkeyID(actId) == Guid.Empty) continue;\n if (IsAddon(actId)) continue;\n if (!includeActivated && (slStatus.eStatus == 1)) continue;\n\n return actId;\n }\n }\n\n return Guid.Empty;\n }\n }\n\n public static string GetInstallationID(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n string installationId = null;\n return SLGenerateOfflineInstallationId(sl.Handle, ref actId, ref installationId) == 0 ? installationId : null;\n }\n }\n\n public static Guid GetInstalledPkeyID(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr pProductKeyIds;\n\n uint status = SLGetSLIDList(sl.Handle, SLIDTYPE.SL_ID_PRODUCT_SKU, ref actId, SLIDTYPE.SL_ID_PKEY, out count, out pProductKeyIds);\n\n if (status != 0 || count == 0)\n {\n return Guid.Empty;\n }\n\n unsafe { return *(Guid*)pProductKeyIds; }\n }\n }\n\n public static uint DepositConfirmationID(Guid actId, string installationId, string confirmationId)\n {\n using (SLContext sl = new SLContext())\n {\n return SLDepositOfflineConfirmationId(sl.Handle, ref actId, installationId, confirmationId);\n }\n }\n\n public static void RefreshLicenseStatus()\n {\n SLConsumeWindowsRight(0);\n }\n\n public static void RefreshTrustedTime(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n SLDATATYPE type;\n uint count;\n IntPtr ppbValue;\n\n SLGetProductSkuInformation(sl.Handle, ref actId, \"TrustedTime\", out type, out count, out ppbValue);\n }\n }\n\n public static void FireStateChangedEvent(Guid appId)\n {\n using (SLContext sl = new SLContext())\n {\n SLFireEvent(sl.Handle, \"msft:rm/event/licensingstatechanged\", ref appId);\n }\n }\n\n public static Guid GetAppId(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr pAppIds;\n\n uint status = SLGetSLIDList(sl.Handle, SLIDTYPE.SL_ID_PRODUCT_SKU, ref actId, SLIDTYPE.SL_ID_APPLICATION, out count, out pAppIds);\n\n if (status != 0 || count == 0)\n {\n return Guid.Empty;\n }\n\n unsafe { return *(Guid*)pAppIds; }\n }\n }\n\n public static bool IsAddon(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n SLDATATYPE type;\n IntPtr ppbValue;\n\n uint status = SLGetProductSkuInformation(sl.Handle, ref actId, \"DependsOn\", out type, out count, out ppbValue);\n return (int)status >= 0 && status != 0xC004F012;\n }\n }\n\n public static Guid GetLicenseFileId(Guid licId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr ppReturnLics;\n\n uint status = SLGetSLIDList(sl.Handle, SLIDTYPE.SL_ID_LICENSE, ref licId, SLIDTYPE.SL_ID_LICENSE_FILE, out count, out ppReturnLics);\n\n if (status != 0 || count == 0)\n {\n return Guid.Empty;\n }\n\n unsafe { return *(Guid*)ppReturnLics; }\n }\n }\n\n public static Guid GetPkeyConfigFileId(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n SLDATATYPE type;\n uint len;\n IntPtr ppReturnLics;\n\n uint status = SLGetProductSkuInformation(sl.Handle, ref actId, \"pkeyConfigLicenseId\", out type, out len, out ppReturnLics);\n\n if (status != 0 || len == 0)\n {\n return Guid.Empty;\n }\n\n Guid pkcId = new Guid(Marshal.PtrToStringAuto(ppReturnLics));\n return GetLicenseFileId(pkcId);\n }\n }\n\n public static string GetLicenseContents(Guid fileId)\n {\n if (fileId == Guid.Empty) throw new ArgumentException(\"License contents could not be retrieved.\");\n\n using (SLContext sl = new SLContext())\n {\n uint dataLen;\n IntPtr dataPtr;\n\n if (SLGetLicense(sl.Handle, ref fileId, out dataLen, out dataPtr) != 0)\n {\n return null;\n }\n\n byte[] data = new byte[dataLen];\n Marshal.Copy(dataPtr, data, 0, (int)dataLen);\n\n data = data.Skip(Array.IndexOf(data, (byte)'<')).ToArray();\n return Encoding.UTF8.GetString(data);\n }\n }\n\n public static bool IsPhoneActivatable(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n SLDATATYPE type;\n IntPtr ppbValue;\n\n uint status = SLGetProductSkuInformation(sl.Handle, ref actId, \"msft:sl/EUL/PHONE/PUBLIC\", out type, out count, out ppbValue);\n return status != 0xC004F012;\n }\n }\n\n public static string GetPKeyChannel(Guid pkeyId)\n {\n using (SLContext sl = new SLContext())\n {\n SLDATATYPE type;\n uint len;\n IntPtr ppbValue;\n\n uint status = SLGetPKeyInformation(sl.Handle, ref pkeyId, \"Channel\", out type, out len, out ppbValue);\n\n if (status != 0 || len == 0)\n {\n return null;\n }\n\n return Marshal.PtrToStringAuto(ppbValue);\n }\n }\n\n public static string GetMetaStr(Guid actId, string value)\n {\n using (SLContext sl = new SLContext())\n {\n uint len;\n SLDATATYPE type;\n IntPtr ppbValue;\n\n uint status = SLGetProductSkuInformation(sl.Handle, ref actId, value, out type, out len, out ppbValue);\n\n if (status != 0 || len == 0 || type != SLDATATYPE.SL_DATA_SZ)\n {\n return null;\n }\n\n return Marshal.PtrToStringAuto(ppbValue);\n }\n }\n\n public static List GetActivationIds(Guid appId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr pLicStat;\n\n SLGetLicensingStatusInformation(sl.Handle, ref appId, IntPtr.Zero, null, out count, out pLicStat);\n\n List result = new List();\n\n unsafe\n {\n SL_LICENSING_STATUS* licensingStatuses = (SL_LICENSING_STATUS*)pLicStat;\n for (int i = 0; i < count; i++)\n {\n result.Add(licensingStatuses[i].SkuId);\n }\n }\n\n return result;\n }\n }\n\n public static uint SetCurrentProductKey(Guid actId, Guid pkeyId)\n {\n using (SLContext sl = new SLContext())\n {\n return SLSetCurrentProductKey(sl.Handle, ref actId, ref pkeyId);\n }\n }\n\n public static uint InstallProductKey(ProductKey pkey)\n {\n using (SLContext sl = new SLContext())\n {\n Guid pkeyId = Guid.Empty;\n return SLInstallProofOfPurchase(sl.Handle, pkey.GetAlgoUri(), pkey.ToString(), 0, null, ref pkeyId);\n }\n }\n\n public static void UninstallProductKey(Guid pkeyId)\n {\n using (SLContext sl = new SLContext())\n {\n SLUninstallProofOfPurchase(sl.Handle, ref pkeyId);\n }\n }\n\n public static void UninstallAllProductKeys(Guid appId)\n {\n foreach (Guid actId in GetActivationIds(appId))\n {\n Guid pkeyId = GetInstalledPkeyID(actId);\n if (pkeyId == Guid.Empty) continue;\n if (IsAddon(actId)) continue;\n UninstallProductKey(pkeyId);\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/Crypto/PhysStoreCrypto.cs", "namespace LibTSforge.Crypto\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using System.Linq;\n using System.Text;\n\n public static class PhysStoreCrypto\n {\n public static byte[] DecryptPhysicalStore(byte[] data, bool production, PSVersion version)\n {\n byte[] rsaKey = production ? Keys.PRODUCTION : Keys.TEST;\n BinaryReader br = new BinaryReader(new MemoryStream(data));\n br.BaseStream.Seek(0x10, SeekOrigin.Begin);\n byte[] aesKeySig = br.ReadBytes(0x80);\n byte[] encAesKey = br.ReadBytes(0x80);\n\n if (!CryptoUtils.RSAVerifySignature(rsaKey, encAesKey, aesKeySig))\n {\n throw new Exception(\"Failed to decrypt physical store.\");\n }\n\n byte[] aesKey = CryptoUtils.RSADecrypt(rsaKey, encAesKey);\n byte[] decData = CryptoUtils.AESDecrypt(br.ReadBytes((int)br.BaseStream.Length - 0x110), aesKey);\n byte[] hmacKey = decData.Take(0x10).ToArray(); // SHA-1 salt on Vista\n byte[] hmacSig = decData.Skip(0x10).Take(0x14).ToArray(); // SHA-1 hash on Vista\n byte[] psData = decData.Skip(0x28).ToArray();\n\n if (version != PSVersion.Vista)\n {\n if (!CryptoUtils.HMACVerify(hmacKey, psData, hmacSig))\n {\n throw new InvalidDataException(\"Failed to verify HMAC. Physical store is corrupt.\");\n }\n }\n else\n {\n if (!CryptoUtils.SaltSHAVerify(hmacKey, psData, hmacSig))\n {\n throw new InvalidDataException(\"Failed to verify checksum. Physical store is corrupt.\");\n }\n }\n\n return psData;\n }\n\n public static byte[] EncryptPhysicalStore(byte[] data, bool production, PSVersion version)\n {\n Dictionary versionTable = new Dictionary\n {\n {PSVersion.Vista, 2},\n {PSVersion.Win7, 5},\n {PSVersion.Win8, 1},\n {PSVersion.WinBlue, 2},\n {PSVersion.WinModern, 3}\n };\n\n byte[] rsaKey = production ? Keys.PRODUCTION : Keys.TEST;\n\n byte[] aesKey = Encoding.UTF8.GetBytes(\"massgrave.dev :3\");\n byte[] hmacKey = CryptoUtils.GenerateRandomKey(0x10);\n\n byte[] encAesKey = CryptoUtils.RSAEncrypt(rsaKey, aesKey);\n byte[] aesKeySig = CryptoUtils.RSASign(rsaKey, encAesKey);\n byte[] hmacSig = version != PSVersion.Vista ? CryptoUtils.HMACSign(hmacKey, data) : CryptoUtils.SaltSHASum(hmacKey, data);\n\n byte[] decData = { };\n decData = decData.Concat(hmacKey).Concat(hmacSig).Concat(BitConverter.GetBytes(0)).Concat(data).ToArray();\n byte[] encData = CryptoUtils.AESEncrypt(decData, aesKey);\n\n BinaryWriter bw = new BinaryWriter(new MemoryStream());\n bw.Write(versionTable[version]);\n bw.Write(Encoding.UTF8.GetBytes(\"UNTRUSTSTORE\"));\n bw.Write(aesKeySig);\n bw.Write(encAesKey);\n bw.Write(encData);\n\n return bw.GetBytes();\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/PhysicalStoreWin7.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using Crypto;\n\n public class Win7Block\n {\n public BlockType Type;\n public uint Flags;\n public byte[] Key;\n public string KeyAsStr\n {\n get\n {\n return Utils.DecodeString(Key);\n }\n set\n {\n Key = Utils.EncodeString(value);\n }\n }\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n public byte[] Data;\n public string DataAsStr\n {\n get\n {\n return Utils.DecodeString(Data);\n }\n set\n {\n Data = Utils.EncodeString(value);\n }\n }\n public uint DataAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Data, 0);\n }\n set\n {\n Data = BitConverter.GetBytes(value);\n }\n }\n\n internal void Encode(BinaryWriter writer)\n {\n writer.Write((uint)Type);\n writer.Write(Flags);\n writer.Write(Key.Length);\n writer.Write(Value.Length);\n writer.Write(Data.Length);\n writer.Write(Key);\n writer.Write(Value);\n writer.Write(Data);\n }\n\n internal static Win7Block Decode(BinaryReader reader)\n {\n uint type = reader.ReadUInt32();\n uint flags = reader.ReadUInt32();\n\n int keyLen = reader.ReadInt32();\n int valueLen = reader.ReadInt32();\n int dataLen = reader.ReadInt32();\n\n byte[] key = reader.ReadBytes(keyLen);\n byte[] value = reader.ReadBytes(valueLen);\n byte[] data = reader.ReadBytes(dataLen);\n return new Win7Block\n {\n Type = (BlockType)type,\n Flags = flags,\n Key = key,\n Value = value,\n Data = data,\n };\n }\n }\n\n public sealed class PhysicalStoreWin7 : IPhysicalStore\n {\n private byte[] PreHeaderBytes = { };\n private readonly List Blocks = new List();\n private readonly FileStream TSPrimary;\n private readonly FileStream TSSecondary;\n private readonly bool Production;\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(PreHeaderBytes);\n\n foreach (Win7Block block in Blocks)\n {\n block.Encode(writer);\n writer.Align(4);\n }\n\n return writer.GetBytes();\n }\n\n public void Deserialize(byte[] data)\n {\n int len = data.Length;\n\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n PreHeaderBytes = reader.ReadBytes(8);\n\n while (reader.BaseStream.Position < len - 0x14)\n {\n Blocks.Add(Win7Block.Decode(reader));\n reader.Align(4);\n }\n }\n\n public void AddBlock(PSBlock block)\n {\n Blocks.Add(new Win7Block\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n });\n }\n\n public void AddBlocks(IEnumerable blocks)\n {\n foreach (PSBlock block in blocks)\n {\n AddBlock(block);\n }\n }\n\n public PSBlock GetBlock(string key, string value)\n {\n foreach (Win7Block block in Blocks)\n {\n if (block.KeyAsStr == key && block.ValueAsStr == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public PSBlock GetBlock(string key, uint value)\n {\n foreach (Win7Block block in Blocks)\n {\n if (block.KeyAsStr == key && block.ValueAsInt == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public void SetBlock(string key, string value, byte[] data)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n Win7Block block = Blocks[i];\n\n if (block.KeyAsStr == key && block.ValueAsStr == value)\n {\n block.Data = data;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void SetBlock(string key, uint value, byte[] data)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n Win7Block block = Blocks[i];\n\n if (block.KeyAsStr == key && block.ValueAsInt == value)\n {\n block.Data = data;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void SetBlock(string key, string value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, string value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void SetBlock(string key, uint value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, uint value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void DeleteBlock(string key, string value)\n {\n foreach (Win7Block block in Blocks)\n {\n if (block.KeyAsStr == key && block.ValueAsStr == value)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public void DeleteBlock(string key, uint value)\n {\n foreach (Win7Block block in Blocks)\n {\n if (block.KeyAsStr == key && block.ValueAsInt == value)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public PhysicalStoreWin7(string primaryPath, bool production)\n {\n TSPrimary = File.Open(primaryPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n TSSecondary = File.Open(primaryPath.Replace(\"-0.\", \"-1.\"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n Production = production;\n\n Deserialize(PhysStoreCrypto.DecryptPhysicalStore(TSPrimary.ReadAllBytes(), production, PSVersion.Win7));\n TSPrimary.Seek(0, SeekOrigin.Begin);\n }\n\n public void Dispose()\n {\n if (TSPrimary.CanWrite && TSSecondary.CanWrite)\n {\n byte[] data = PhysStoreCrypto.EncryptPhysicalStore(Serialize(), Production, PSVersion.Win7);\n\n TSPrimary.SetLength(data.LongLength);\n TSSecondary.SetLength(data.LongLength);\n\n TSPrimary.Seek(0, SeekOrigin.Begin);\n TSSecondary.Seek(0, SeekOrigin.Begin);\n\n TSPrimary.WriteAllBytes(data);\n TSSecondary.WriteAllBytes(data);\n\n TSPrimary.Close();\n TSSecondary.Close();\n }\n }\n\n public byte[] ReadRaw()\n {\n byte[] data = PhysStoreCrypto.DecryptPhysicalStore(TSPrimary.ReadAllBytes(), Production, PSVersion.Win7);\n TSPrimary.Seek(0, SeekOrigin.Begin);\n return data;\n }\n\n public void WriteRaw(byte[] data)\n {\n byte[] encrData = PhysStoreCrypto.EncryptPhysicalStore(data, Production, PSVersion.Win7);\n\n TSPrimary.SetLength(encrData.LongLength);\n TSSecondary.SetLength(encrData.LongLength);\n\n TSPrimary.Seek(0, SeekOrigin.Begin);\n TSSecondary.Seek(0, SeekOrigin.Begin);\n\n TSPrimary.WriteAllBytes(encrData);\n TSSecondary.WriteAllBytes(encrData);\n\n TSPrimary.Close();\n TSSecondary.Close();\n }\n\n public IEnumerable FindBlocks(string valueSearch)\n {\n List results = new List();\n\n foreach (Win7Block block in Blocks)\n {\n if (block.ValueAsStr.Contains(valueSearch))\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n\n return results;\n }\n\n public IEnumerable FindBlocks(uint valueSearch)\n {\n List results = new List();\n\n foreach (Win7Block block in Blocks)\n {\n if (block.ValueAsInt == valueSearch)\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n\n return results;\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/PhysicalStoreVista.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using Crypto;\n\n public class VistaBlock\n {\n public BlockType Type;\n public uint Flags;\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n public byte[] Data;\n public string DataAsStr\n {\n get\n {\n return Utils.DecodeString(Data);\n }\n set\n {\n Data = Utils.EncodeString(value);\n }\n }\n public uint DataAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Data, 0);\n }\n set\n {\n Data = BitConverter.GetBytes(value);\n }\n }\n\n internal void Encode(BinaryWriter writer)\n {\n writer.Write((uint)Type);\n writer.Write(Flags);\n writer.Write(Value.Length);\n writer.Write(Data.Length);\n writer.Write(Value);\n writer.Write(Data);\n }\n\n internal static VistaBlock Decode(BinaryReader reader)\n {\n uint type = reader.ReadUInt32();\n uint flags = reader.ReadUInt32();\n\n int valueLen = reader.ReadInt32();\n int dataLen = reader.ReadInt32();\n\n byte[] value = reader.ReadBytes(valueLen);\n byte[] data = reader.ReadBytes(dataLen);\n return new VistaBlock\n {\n Type = (BlockType)type,\n Flags = flags,\n Value = value,\n Data = data,\n };\n }\n }\n\n public sealed class PhysicalStoreVista : IPhysicalStore\n {\n private byte[] PreHeaderBytes = { };\n private readonly List Blocks = new List();\n private readonly FileStream TSPrimary;\n private readonly FileStream TSSecondary;\n private readonly bool Production;\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(PreHeaderBytes);\n\n foreach (VistaBlock block in Blocks)\n {\n block.Encode(writer);\n writer.Align(4);\n }\n\n return writer.GetBytes();\n }\n\n public void Deserialize(byte[] data)\n {\n int len = data.Length;\n\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n PreHeaderBytes = reader.ReadBytes(8);\n\n while (reader.BaseStream.Position < len - 0x14)\n {\n Blocks.Add(VistaBlock.Decode(reader));\n reader.Align(4);\n }\n }\n\n public void AddBlock(PSBlock block)\n {\n Blocks.Add(new VistaBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Value = block.Value,\n Data = block.Data\n });\n }\n\n public void AddBlocks(IEnumerable blocks)\n {\n foreach (PSBlock block in blocks)\n {\n AddBlock(block);\n }\n }\n\n public PSBlock GetBlock(string key, string value)\n {\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsStr == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = new byte[0],\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public PSBlock GetBlock(string key, uint value)\n {\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsInt == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = new byte[0],\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public void SetBlock(string key, string value, byte[] data)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n VistaBlock block = Blocks[i];\n\n if (block.ValueAsStr == value)\n {\n block.Data = data;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void SetBlock(string key, uint value, byte[] data)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n VistaBlock block = Blocks[i];\n\n if (block.ValueAsInt == value)\n {\n block.Data = data;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void SetBlock(string key, string value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, string value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void SetBlock(string key, uint value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, uint value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void DeleteBlock(string key, string value)\n {\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsStr == value)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public void DeleteBlock(string key, uint value)\n {\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsInt == value)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public PhysicalStoreVista(string primaryPath, bool production)\n {\n TSPrimary = File.Open(primaryPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n TSSecondary = File.Open(primaryPath.Replace(\"-0.\", \"-1.\"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n Production = production;\n\n Deserialize(PhysStoreCrypto.DecryptPhysicalStore(TSPrimary.ReadAllBytes(), production, PSVersion.Vista));\n TSPrimary.Seek(0, SeekOrigin.Begin);\n }\n\n public void Dispose()\n {\n if (TSPrimary.CanWrite && TSSecondary.CanWrite)\n {\n byte[] data = PhysStoreCrypto.EncryptPhysicalStore(Serialize(), Production, PSVersion.Vista);\n\n TSPrimary.SetLength(data.LongLength);\n TSSecondary.SetLength(data.LongLength);\n\n TSPrimary.Seek(0, SeekOrigin.Begin);\n TSSecondary.Seek(0, SeekOrigin.Begin);\n\n TSPrimary.WriteAllBytes(data);\n TSSecondary.WriteAllBytes(data);\n\n TSPrimary.Close();\n TSSecondary.Close();\n }\n }\n\n public byte[] ReadRaw()\n {\n byte[] data = PhysStoreCrypto.DecryptPhysicalStore(TSPrimary.ReadAllBytes(), Production, PSVersion.Vista);\n TSPrimary.Seek(0, SeekOrigin.Begin);\n return data;\n }\n\n public void WriteRaw(byte[] data)\n {\n byte[] encrData = PhysStoreCrypto.EncryptPhysicalStore(data, Production, PSVersion.Vista);\n\n TSPrimary.SetLength(encrData.LongLength);\n TSSecondary.SetLength(encrData.LongLength);\n\n TSPrimary.Seek(0, SeekOrigin.Begin);\n TSSecondary.Seek(0, SeekOrigin.Begin);\n\n TSPrimary.WriteAllBytes(encrData);\n TSSecondary.WriteAllBytes(encrData);\n\n TSPrimary.Close();\n TSSecondary.Close();\n }\n\n public IEnumerable FindBlocks(string valueSearch)\n {\n List results = new List();\n\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsStr.Contains(valueSearch))\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = new byte[0],\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n\n return results;\n }\n\n public IEnumerable FindBlocks(uint valueSearch)\n {\n List results = new List();\n\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsInt == valueSearch)\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = new byte[0],\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n\n return results;\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/SetIIDParams.cs", "namespace LibTSforge.Modifiers\n{\n using PhysicalStore;\n using SPP;\n using System.IO;\n using System;\n\n public static class SetIIDParams\n {\n public static void SetParams(PSVersion version, bool production, Guid actId, PKeyAlgorithm algorithm, int group, int serial, ulong security)\n {\n if (version == PSVersion.Vista) throw new NotSupportedException(\"This feature is not supported on Windows Vista/Server 2008.\");\n\n Guid appId;\n\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, true);\n\n if (actId == Guid.Empty)\n {\n throw new Exception(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n Guid pkeyId = SLApi.GetInstalledPkeyID(actId);\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n PSBlock keyBlock = store.GetBlock(key, pkeyId.ToString());\n\n if (keyBlock == null)\n {\n throw new InvalidDataException(\"Failed to get product key data for activation ID \" + actId + \".\");\n }\n\n VariableBag pkb = new VariableBag(keyBlock.Data, version);\n\n ProductKey pkey = new ProductKey\n {\n Group = group,\n Serial = serial,\n Security = security,\n Algorithm = algorithm,\n Upgrade = false\n };\n\n string blockName = version == PSVersion.Win7 ? \"SppPkeyShortAuthenticator\" : \"SppPkeyPhoneActivationData\";\n pkb.SetBlock(blockName, pkey.GetPhoneData(version));\n store.SetBlock(key, pkeyId.ToString(), pkb.Serialize());\n }\n\n Logger.WriteLine(\"Successfully set IID parameters.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/RearmReset.cs", "namespace LibTSforge.Modifiers\n{\n using System.Collections.Generic;\n using System.Linq;\n using PhysicalStore;\n using SPP;\n\n public static class RearmReset\n {\n public static void Reset(PSVersion version, bool production)\n {\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n List blocks;\n\n if (version == PSVersion.Vista)\n {\n blocks = store.FindBlocks(\"740D70D8-6448-4b2f-9063-4A7A463600C5\").ToList();\n }\n else if (version == PSVersion.Win7)\n {\n blocks = store.FindBlocks(0xA0000).ToList();\n }\n else\n {\n blocks = store.FindBlocks(\"__##USERSEP-RESERVED##__$$REARM-COUNT$$\").ToList();\n }\n\n foreach (PSBlock block in blocks)\n {\n if (version == PSVersion.Vista)\n {\n store.DeleteBlock(block.KeyAsStr, block.ValueAsStr);\n }\n else if (version == PSVersion.Win7)\n {\n store.SetBlock(block.KeyAsStr, block.ValueAsInt, new byte[8]);\n }\n else\n {\n store.SetBlock(block.KeyAsStr, block.ValueAsStr, new byte[8]);\n }\n }\n\n Logger.WriteLine(\"Successfully reset all rearm counters.\");\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/UniqueIdDelete.cs", "namespace LibTSforge.Modifiers\n{\n using System;\n using PhysicalStore;\n using SPP;\n\n public static class UniqueIdDelete\n {\n public static void DeleteUniqueId(PSVersion version, bool production, Guid actId)\n {\n if (version == PSVersion.Vista) throw new NotSupportedException(\"This feature is not supported on Windows Vista/Server 2008.\");\n\n Guid appId;\n\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, true);\n\n if (actId == Guid.Empty)\n {\n throw new Exception(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n Guid pkeyId = SLApi.GetInstalledPkeyID(actId);\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n PSBlock keyBlock = store.GetBlock(key, pkeyId.ToString());\n\n if (keyBlock == null)\n {\n throw new Exception(\"No product key found.\");\n }\n\n VariableBag pkb = new VariableBag(keyBlock.Data, version);\n\n pkb.DeleteBlock(\"SppPkeyUniqueIdToken\");\n\n store.SetBlock(key, pkeyId.ToString(), pkb.Serialize());\n }\n\n Logger.WriteLine(\"Successfully removed Unique ID for product key ID \" + pkeyId);\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/KeyChangeLockDelete.cs", "namespace LibTSforge.Modifiers\n{\n using System.Collections.Generic;\n using System.Linq;\n using PhysicalStore;\n using SPP;\n using System;\n\n public static class KeyChangeLockDelete\n {\n public static void Delete(PSVersion version, bool production)\n {\n if (version == PSVersion.Vista) throw new NotSupportedException(\"This feature is not supported on Windows Vista/Server 2008.\");\n\n SPPUtils.KillSPP(version);\n Logger.WriteLine(\"Writing TrustedStore data...\");\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n List values = new List\n {\n \"msft:spp/timebased/AB\",\n \"msft:spp/timebased/CD\"\n };\n List blocks = new List();\n foreach (string value in values)\n {\n blocks.AddRange(store.FindBlocks(value).ToList());\n }\n foreach (PSBlock block in blocks)\n {\n store.DeleteBlock(block.KeyAsStr, block.ValueAsStr);\n }\n }\n Logger.WriteLine(\"Successfully removed the key change lock.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/TamperedFlagsDelete.cs", "namespace LibTSforge.Modifiers\n{\n using System.Linq;\n using PhysicalStore;\n using SPP;\n\n public static class TamperedFlagsDelete\n {\n public static void DeleteTamperFlags(PSVersion version, bool production)\n {\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n if (version == PSVersion.Vista)\n {\n DeleteFlag(store, \"6BE8425B-E3CF-4e86-A6AF-5863E3DCB606\");\n }\n else if (version == PSVersion.Win7)\n {\n SetFlag(store, 0xA0001);\n }\n else\n {\n DeleteFlag(store, \"__##USERSEP-RESERVED##__$$RECREATED-FLAG$$\");\n DeleteFlag(store, \"__##USERSEP-RESERVED##__$$RECOVERED-FLAG$$\");\n }\n\n Logger.WriteLine(\"Successfully cleared the tamper state.\");\n }\n\n SPPUtils.RestartSPP(version);\n }\n\n private static void DeleteFlag(IPhysicalStore store, string flag)\n {\n store.FindBlocks(flag).ToList().ForEach(block => store.DeleteBlock(block.KeyAsStr, block.ValueAsStr));\n }\n\n private static void SetFlag(IPhysicalStore store, uint flag)\n {\n store.FindBlocks(flag).ToList().ForEach(block => store.SetBlock(block.KeyAsStr, block.ValueAsInt, new byte[8]));\n }\n }\n}\n"], ["/TSforge/LibTSforge/Common.cs", "namespace LibTSforge\n{\n using System;\n using System.IO;\n using System.Linq;\n using System.Runtime.InteropServices;\n using System.Text;\n\n public enum PSVersion\n {\n Vista,\n Win7,\n Win8,\n WinBlue,\n WinModern\n }\n\n public static class Constants\n {\n public static readonly byte[] UniversalHWIDBlock =\n {\n 0x26, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x01, 0x0c, 0x01, 0x00\n };\n\n public static readonly byte[] KMSv4Response =\n {\n 0x00, 0x00, 0x04, 0x00, 0x62, 0x00, 0x00, 0x00, 0x30, 0x00, 0x35, 0x00, 0x34, 0x00, 0x32, 0x00,\n 0x36, 0x00, 0x2D, 0x00, 0x30, 0x00, 0x30, 0x00, 0x32, 0x00, 0x30, 0x00, 0x36, 0x00, 0x2D, 0x00,\n 0x31, 0x00, 0x36, 0x00, 0x31, 0x00, 0x2D, 0x00, 0x36, 0x00, 0x35, 0x00, 0x35, 0x00, 0x35, 0x00,\n 0x30, 0x00, 0x36, 0x00, 0x2D, 0x00, 0x30, 0x00, 0x33, 0x00, 0x2D, 0x00, 0x31, 0x00, 0x30, 0x00,\n 0x33, 0x00, 0x33, 0x00, 0x2D, 0x00, 0x39, 0x00, 0x32, 0x00, 0x30, 0x00, 0x30, 0x00, 0x2E, 0x00,\n 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x2D, 0x00, 0x30, 0x00, 0x36, 0x00, 0x35, 0x00,\n 0x32, 0x00, 0x30, 0x00, 0x31, 0x00, 0x33, 0x00, 0x00, 0x00, 0xDE, 0x19, 0x02, 0xCF, 0x1F, 0x35,\n 0x97, 0x4E, 0x8A, 0x8F, 0xB8, 0x07, 0xB1, 0x92, 0xB5, 0xB5, 0x97, 0x42, 0xEC, 0x3A, 0x76, 0x84,\n 0xD5, 0x01, 0x32, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00, 0x60, 0x27, 0x00, 0x00, 0xC4, 0x1E,\n 0xAA, 0x8B, 0xDD, 0x0C, 0xAB, 0x55, 0x6A, 0xCE, 0xAF, 0xAC, 0x7F, 0x5F, 0xBD, 0xE9\n };\n\n public static readonly byte[] KMSv5Response =\n {\n 0x00, 0x00, 0x05, 0x00, 0xBE, 0x96, 0xF9, 0x04, 0x54, 0x17, 0x3F, 0xAF, 0xE3, 0x08, 0x50, 0xEB,\n 0x22, 0xBA, 0x53, 0xBF, 0xF2, 0x6A, 0x7B, 0xC9, 0x05, 0x1D, 0xB5, 0x19, 0xDF, 0x98, 0xE2, 0x71,\n 0x4D, 0x00, 0x61, 0xE9, 0x9D, 0x03, 0xFB, 0x31, 0xF9, 0x1F, 0x2E, 0x60, 0x59, 0xC7, 0x73, 0xC8,\n 0xE8, 0xB6, 0xE1, 0x2B, 0x39, 0xC6, 0x35, 0x0E, 0x68, 0x7A, 0xAA, 0x4F, 0x28, 0x23, 0x12, 0x18,\n 0xE3, 0xAA, 0x84, 0x81, 0x6E, 0x82, 0xF0, 0x3F, 0xD9, 0x69, 0xA9, 0xDF, 0xBA, 0x5F, 0xCA, 0x32,\n 0x54, 0xB2, 0x52, 0x3B, 0x3E, 0xD1, 0x5C, 0x65, 0xBC, 0x3E, 0x59, 0x0D, 0x15, 0x9F, 0x37, 0xEC,\n 0x30, 0x9C, 0xCC, 0x1B, 0x39, 0x0D, 0x21, 0x32, 0x29, 0xA2, 0xDD, 0xC7, 0xC1, 0x69, 0xF2, 0x72,\n 0x3F, 0x00, 0x98, 0x1E, 0xF8, 0x9A, 0x79, 0x44, 0x5D, 0x25, 0x80, 0x7B, 0xF5, 0xE1, 0x7C, 0x68,\n 0x25, 0xAA, 0x0D, 0x67, 0x98, 0xE5, 0x59, 0x9B, 0x04, 0xC1, 0x23, 0x33, 0x48, 0xFB, 0x28, 0xD0,\n 0x76, 0xDF, 0x01, 0x56, 0xE7, 0xEC, 0xBF, 0x1A, 0xA2, 0x22, 0x28, 0xCA, 0xB1, 0xB4, 0x4C, 0x30,\n 0x14, 0x6F, 0xD2, 0x2E, 0x01, 0x2A, 0x04, 0xE3, 0xBD, 0xA7, 0x41, 0x2F, 0xC9, 0xEF, 0x53, 0xC0,\n 0x70, 0x48, 0xF1, 0xB2, 0xB6, 0xEA, 0xE7, 0x0F, 0x7A, 0x15, 0xD1, 0xA6, 0xFE, 0x23, 0xC8, 0xF3,\n 0xE1, 0x02, 0x9E, 0xA0, 0x4E, 0xBD, 0xF5, 0xEA, 0x53, 0x74, 0x8E, 0x74, 0xA1, 0xA1, 0xBD, 0xBE,\n 0x66, 0xC4, 0x73, 0x8F, 0x24, 0xA7, 0x2A, 0x2F, 0xE3, 0xD9, 0xF4, 0x28, 0xD9, 0xF8, 0xA3, 0x93,\n 0x03, 0x9E, 0x29, 0xAB\n };\n\n public static readonly byte[] KMSv6Response =\n {\n 0x00, 0x00, 0x06, 0x00, 0x54, 0xD3, 0x40, 0x08, 0xF3, 0xCD, 0x03, 0xEF, 0xC8, 0x15, 0x87, 0x9E,\n 0xCA, 0x2E, 0x85, 0xFB, 0xE6, 0xF6, 0x73, 0x66, 0xFB, 0xDA, 0xBB, 0x7B, 0xB1, 0xBC, 0xD6, 0xF9,\n 0x5C, 0x41, 0xA0, 0xFE, 0xE1, 0x74, 0xC4, 0xBB, 0x91, 0xE5, 0xDE, 0x6D, 0x3A, 0x11, 0xD5, 0xFC,\n 0x68, 0xC0, 0x7B, 0x82, 0xB2, 0x24, 0xD1, 0x85, 0xBA, 0x45, 0xBF, 0xF1, 0x26, 0xFA, 0xA5, 0xC6,\n 0x61, 0x70, 0x69, 0x69, 0x6E, 0x0F, 0x0B, 0x60, 0xB7, 0x3D, 0xE8, 0xF1, 0x47, 0x0B, 0x65, 0xFD,\n 0xA7, 0x30, 0x1E, 0xF6, 0xA4, 0xD0, 0x79, 0xC4, 0x58, 0x8D, 0x81, 0xFD, 0xA7, 0xE7, 0x53, 0xF1,\n 0x67, 0x78, 0xF0, 0x0F, 0x60, 0x8F, 0xC8, 0x16, 0x35, 0x22, 0x94, 0x48, 0xCB, 0x0F, 0x8E, 0xB2,\n 0x1D, 0xF7, 0x3E, 0x28, 0x42, 0x55, 0x6B, 0x07, 0xE3, 0xE8, 0x51, 0xD5, 0xFA, 0x22, 0x0C, 0x86,\n 0x65, 0x0D, 0x3F, 0xDD, 0x8D, 0x9B, 0x1B, 0xC9, 0xD3, 0xB8, 0x3A, 0xEC, 0xF1, 0x11, 0x19, 0x25,\n 0xF7, 0x84, 0x4A, 0x4C, 0x0A, 0xB5, 0x31, 0x94, 0x37, 0x76, 0xCE, 0xE7, 0xAB, 0xA9, 0x69, 0xDF,\n 0xA4, 0xC9, 0x22, 0x6C, 0x23, 0xFF, 0x6B, 0xFC, 0xDA, 0x78, 0xD8, 0xC4, 0x8F, 0x74, 0xBB, 0x26,\n 0x05, 0x00, 0x98, 0x9B, 0xE5, 0xE2, 0xAD, 0x0D, 0x57, 0x95, 0x80, 0x66, 0x8E, 0x43, 0x74, 0x87,\n 0x93, 0x1F, 0xF4, 0xB2, 0x2C, 0x20, 0x5F, 0xD8, 0x9C, 0x4C, 0x56, 0xB3, 0x57, 0x44, 0x62, 0x68,\n 0x8D, 0xAA, 0x40, 0x11, 0x9D, 0x84, 0x62, 0x0E, 0x43, 0x8A, 0x1D, 0xF0, 0x1C, 0x49, 0xD8, 0x56,\n 0xEF, 0x4C, 0xD3, 0x64, 0xBA, 0x0D, 0xEF, 0x87, 0xB5, 0x2C, 0x88, 0xF3, 0x18, 0xFF, 0x3A, 0x8C,\n 0xF5, 0xA6, 0x78, 0x5C, 0x62, 0xE3, 0x9E, 0x4C, 0xB6, 0x31, 0x2D, 0x06, 0x80, 0x92, 0xBC, 0x2E,\n 0x92, 0xA6, 0x56, 0x96\n };\n\n // 2^31 - 8 minutes\n public static readonly ulong TimerMax = (ulong)TimeSpan.FromMinutes(2147483640).Ticks;\n\n public static readonly string ZeroCID = new string('0', 48);\n }\n\n public static class BinaryReaderExt\n {\n public static void Align(this BinaryReader reader, int to)\n {\n int pos = (int)reader.BaseStream.Position;\n reader.BaseStream.Seek(-pos & (to - 1), SeekOrigin.Current);\n }\n\n public static string ReadNullTerminatedString(this BinaryReader reader, int maxLen)\n {\n return Encoding.Unicode.GetString(reader.ReadBytes(maxLen)).Split(new char[] { '\\0' }, 2)[0];\n }\n }\n\n public static class BinaryWriterExt\n {\n public static void Align(this BinaryWriter writer, int to)\n {\n int pos = (int)writer.BaseStream.Position;\n writer.WritePadding(-pos & (to - 1));\n }\n\n public static void WritePadding(this BinaryWriter writer, int len)\n {\n writer.Write(Enumerable.Repeat((byte)0, len).ToArray());\n }\n\n public static void WriteFixedString(this BinaryWriter writer, string str, int bLen)\n {\n writer.Write(Encoding.ASCII.GetBytes(str));\n writer.WritePadding(bLen - str.Length);\n }\n\n public static void WriteFixedString16(this BinaryWriter writer, string str, int bLen)\n {\n byte[] bstr = Utils.EncodeString(str);\n writer.Write(bstr);\n writer.WritePadding(bLen - bstr.Length);\n }\n\n public static byte[] GetBytes(this BinaryWriter writer)\n {\n return ((MemoryStream)writer.BaseStream).ToArray();\n }\n }\n\n public static class ByteArrayExt\n {\n public static byte[] CastToArray(this T data) where T : struct\n {\n int size = Marshal.SizeOf(typeof(T));\n byte[] result = new byte[size];\n GCHandle handle = GCHandle.Alloc(result, GCHandleType.Pinned);\n try\n {\n Marshal.StructureToPtr(data, handle.AddrOfPinnedObject(), false);\n }\n finally\n {\n handle.Free();\n }\n return result;\n }\n }\n\n public static class FileStreamExt\n {\n public static byte[] ReadAllBytes(this FileStream fs)\n {\n BinaryReader br = new BinaryReader(fs);\n return br.ReadBytes((int)fs.Length);\n }\n\n public static void WriteAllBytes(this FileStream fs, byte[] data)\n {\n fs.Seek(0, SeekOrigin.Begin);\n fs.SetLength(data.Length);\n fs.Write(data, 0, data.Length);\n }\n }\n\n public static class Utils\n {\n [DllImport(\"kernel32.dll\")]\n public static extern uint GetSystemDefaultLCID();\n\n [DllImport(\"kernel32.dll\")]\n public static extern bool Wow64EnableWow64FsRedirection(bool Wow64FsEnableRedirection);\n\n public static string DecodeString(byte[] data)\n {\n return Encoding.Unicode.GetString(data).Trim('\\0');\n }\n\n public static byte[] EncodeString(string str)\n {\n return Encoding.Unicode.GetBytes(str + '\\0');\n }\n\n public static uint CRC32(byte[] data)\n {\n const uint polynomial = 0x04C11DB7;\n uint crc = 0xffffffff;\n\n foreach (byte b in data)\n {\n crc ^= (uint)b << 24;\n for (int bit = 0; bit < 8; bit++)\n {\n if ((crc & 0x80000000) != 0)\n {\n crc = (crc << 1) ^ polynomial;\n }\n else\n {\n crc <<= 1;\n }\n }\n }\n return ~crc;\n }\n\n public static string GetArchitecture()\n {\n string arch = Environment.GetEnvironmentVariable(\"PROCESSOR_ARCHITECTURE\", EnvironmentVariableTarget.Machine).ToUpperInvariant();\n return arch == \"AMD64\" ? \"X64\" : arch;\n }\n\n public static PSVersion DetectVersion()\n {\n int build = Environment.OSVersion.Version.Build;\n\n if (build >= 9600) return PSVersion.WinModern;\n if (build >= 6000 && build <= 6003) return PSVersion.Vista;\n if (build >= 7600 && build <= 7602) return PSVersion.Win7;\n if (build == 9200) return PSVersion.Win8;\n\n throw new NotSupportedException(\"Unable to auto-detect version info\");\n }\n }\n\n public static class Logger\n {\n public static bool HideOutput = false;\n\n public static void WriteLine(string line)\n {\n if (!HideOutput) Console.WriteLine(line);\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/VariableBag.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n\n public enum CRCBlockType : uint\n {\n UINT = 1 << 0,\n STRING = 1 << 1,\n BINARY = 1 << 2\n }\n\n public abstract class CRCBlock\n {\n public CRCBlockType DataType;\n public byte[] Key;\n public string KeyAsStr\n {\n get\n {\n return Utils.DecodeString(Key);\n }\n set\n {\n Key = Utils.EncodeString(value);\n }\n }\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n\n public abstract void Encode(BinaryWriter writer);\n public abstract void Decode(BinaryReader reader);\n public abstract uint CRC();\n }\n\n public class CRCBlockVista : CRCBlock\n {\n public override void Encode(BinaryWriter writer)\n {\n uint crc = CRC();\n writer.Write((uint)DataType);\n writer.Write(0);\n writer.Write(Key.Length);\n writer.Write(Value.Length);\n writer.Write(crc);\n\n writer.Write(Key);\n\n writer.Write(Value);\n }\n\n public override void Decode(BinaryReader reader)\n {\n uint type = reader.ReadUInt32();\n reader.ReadUInt32();\n uint lenName = reader.ReadUInt32();\n uint lenVal = reader.ReadUInt32();\n uint crc = reader.ReadUInt32();\n\n byte[] key = reader.ReadBytes((int)lenName);\n byte[] value = reader.ReadBytes((int)lenVal);\n\n DataType = (CRCBlockType)type;\n Key = key;\n Value = value;\n\n if (CRC() != crc)\n {\n throw new InvalidDataException(\"Invalid CRC in variable bag.\");\n }\n }\n\n public override uint CRC()\n {\n return Utils.CRC32(Value);\n }\n }\n\n public class CRCBlockModern : CRCBlock\n {\n public override void Encode(BinaryWriter writer)\n {\n uint crc = CRC();\n writer.Write(crc);\n writer.Write((uint)DataType);\n writer.Write(Key.Length);\n writer.Write(Value.Length);\n\n writer.Write(Key);\n writer.Align(8);\n\n writer.Write(Value);\n writer.Align(8);\n }\n\n public override void Decode(BinaryReader reader)\n {\n uint crc = reader.ReadUInt32();\n uint type = reader.ReadUInt32();\n uint lenName = reader.ReadUInt32();\n uint lenVal = reader.ReadUInt32();\n\n byte[] key = reader.ReadBytes((int)lenName);\n reader.Align(8);\n\n byte[] value = reader.ReadBytes((int)lenVal);\n reader.Align(8);\n\n DataType = (CRCBlockType)type;\n Key = key;\n Value = value;\n\n if (CRC() != crc)\n {\n throw new InvalidDataException(\"Invalid CRC in variable bag.\");\n }\n }\n\n public override uint CRC()\n {\n BinaryWriter wtemp = new BinaryWriter(new MemoryStream());\n wtemp.Write(0);\n wtemp.Write((uint)DataType);\n wtemp.Write(Key.Length);\n wtemp.Write(Value.Length);\n wtemp.Write(Key);\n wtemp.Write(Value);\n return Utils.CRC32(wtemp.GetBytes());\n }\n }\n\n public class VariableBag\n {\n public List Blocks = new List();\n private readonly PSVersion Version;\n\n private void Deserialize(byte[] data)\n {\n int len = data.Length;\n\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n\n while (reader.BaseStream.Position < len - 0x10)\n {\n CRCBlock block;\n\n if (Version == PSVersion.Vista)\n {\n block = new CRCBlockVista();\n }\n else\n {\n block = new CRCBlockModern();\n }\n\n block.Decode(reader);\n Blocks.Add(block);\n }\n }\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n\n foreach (CRCBlock block in Blocks)\n {\n if (Version == PSVersion.Vista)\n {\n ((CRCBlockVista)block).Encode(writer);\n } else\n {\n ((CRCBlockModern)block).Encode(writer);\n }\n }\n\n return writer.GetBytes();\n }\n\n public CRCBlock GetBlock(string key)\n {\n foreach (CRCBlock block in Blocks)\n {\n if (block.KeyAsStr == key)\n {\n return block;\n }\n }\n\n return null;\n }\n\n public void SetBlock(string key, byte[] value)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n CRCBlock block = Blocks[i];\n\n if (block.KeyAsStr == key)\n {\n block.Value = value;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void DeleteBlock(string key)\n {\n foreach (CRCBlock block in Blocks)\n {\n if (block.KeyAsStr == key)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public VariableBag(byte[] data, PSVersion version)\n {\n Version = version;\n Deserialize(data);\n }\n\n public VariableBag(PSVersion version)\n {\n Version = version;\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/GracePeriodReset.cs", "namespace LibTSforge.Modifiers\n{\n using System.Collections.Generic;\n using System.Linq;\n using PhysicalStore;\n using SPP;\n\n public static class GracePeriodReset\n {\n public static void Reset(PSVersion version, bool production)\n {\n SPPUtils.KillSPP(version);\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string value = \"msft:sl/timer\";\n List blocks = store.FindBlocks(value).ToList();\n\n foreach (PSBlock block in blocks)\n {\n store.DeleteBlock(block.KeyAsStr, block.ValueAsStr);\n }\n }\n\n SPPUtils.RestartSPP(version);\n Logger.WriteLine(\"Successfully reset all grace and evaluation period timers.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/Crypto/CryptoUtils.cs", "namespace LibTSforge.Crypto\n{\n using System;\n using System.Linq;\n using System.Security.Cryptography;\n\n public static class CryptoUtils\n {\n public static byte[] GenerateRandomKey(int len)\n {\n byte[] rand = new byte[len];\n Random r = new Random();\n r.NextBytes(rand);\n\n return rand;\n }\n\n public static byte[] AESEncrypt(byte[] data, byte[] key)\n {\n using (Aes aes = Aes.Create())\n {\n aes.Key = key;\n aes.Mode = CipherMode.CBC;\n aes.Padding = PaddingMode.PKCS7;\n\n ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, Enumerable.Repeat((byte)0, 16).ToArray());\n byte[] encryptedData = encryptor.TransformFinalBlock(data, 0, data.Length);\n return encryptedData;\n }\n }\n\n public static byte[] AESDecrypt(byte[] data, byte[] key)\n {\n using (Aes aes = Aes.Create())\n {\n aes.Key = key;\n aes.Mode = CipherMode.CBC;\n aes.Padding = PaddingMode.PKCS7;\n\n ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, Enumerable.Repeat((byte)0, 16).ToArray());\n byte[] decryptedData = decryptor.TransformFinalBlock(data, 0, data.Length);\n return decryptedData;\n }\n }\n\n public static byte[] RSADecrypt(byte[] rsaKey, byte[] data)\n {\n\n using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())\n {\n rsa.ImportCspBlob(rsaKey);\n return rsa.Decrypt(data, false);\n }\n }\n\n public static byte[] RSAEncrypt(byte[] rsaKey, byte[] data)\n {\n using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())\n {\n rsa.ImportCspBlob(rsaKey);\n return rsa.Encrypt(data, false);\n }\n }\n\n public static byte[] RSASign(byte[] rsaKey, byte[] data)\n {\n using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())\n {\n rsa.ImportCspBlob(rsaKey);\n RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(rsa);\n formatter.SetHashAlgorithm(\"SHA1\");\n\n byte[] hash;\n using (SHA1 sha1 = SHA1.Create())\n {\n hash = sha1.ComputeHash(data);\n }\n\n return formatter.CreateSignature(hash);\n }\n }\n\n public static bool RSAVerifySignature(byte[] rsaKey, byte[] data, byte[] signature)\n {\n using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())\n {\n rsa.ImportCspBlob(rsaKey);\n RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(rsa);\n deformatter.SetHashAlgorithm(\"SHA1\");\n\n byte[] hash;\n using (SHA1 sha1 = SHA1.Create())\n {\n hash = sha1.ComputeHash(data);\n }\n\n return deformatter.VerifySignature(hash, signature);\n }\n }\n\n public static byte[] HMACSign(byte[] key, byte[] data)\n {\n HMACSHA1 hmac = new HMACSHA1(key);\n return hmac.ComputeHash(data);\n }\n\n public static bool HMACVerify(byte[] key, byte[] data, byte[] signature)\n {\n return Enumerable.SequenceEqual(signature, HMACSign(key, data));\n }\n\n public static byte[] SaltSHASum(byte[] salt, byte[] data)\n {\n SHA1 sha1 = SHA1.Create();\n byte[] sha_data = salt.Concat(data).ToArray();\n return sha1.ComputeHash(sha_data);\n }\n\n public static bool SaltSHAVerify(byte[] salt, byte[] data, byte[] checksum)\n {\n return Enumerable.SequenceEqual(checksum, SaltSHASum(salt, data));\n }\n\n public static byte[] SHA256Hash(byte[] data)\n {\n using (SHA256 sha256 = SHA256.Create())\n {\n return sha256.ComputeHash(data);\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/SPP/SPSys.cs", "namespace LibTSforge.SPP\n{\n using Microsoft.Win32.SafeHandles;\n using System;\n using System.Runtime.InteropServices;\n\n public class SPSys\n {\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n private static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);\n private static SafeFileHandle CreateFileSafe(string device)\n {\n return new SafeFileHandle(CreateFile(device, 0xC0000000, 0, IntPtr.Zero, 3, 0, IntPtr.Zero), true);\n }\n\n [return: MarshalAs(UnmanagedType.Bool)]\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n private static extern bool DeviceIoControl([In] SafeFileHandle hDevice, [In] uint dwIoControlCode, [In] IntPtr lpInBuffer, [In] int nInBufferSize, [Out] IntPtr lpOutBuffer, [In] int nOutBufferSize, out int lpBytesReturned, [In] IntPtr lpOverlapped);\n\n public static bool IsSpSysRunning()\n {\n SafeFileHandle file = CreateFileSafe(@\"\\\\.\\SpDevice\");\n IntPtr buffer = Marshal.AllocHGlobal(1);\n int bytesReturned;\n DeviceIoControl(file, 0x80006008, IntPtr.Zero, 0, buffer, 1, out bytesReturned, IntPtr.Zero);\n bool running = Marshal.ReadByte(buffer) != 0;\n Marshal.FreeHGlobal(buffer);\n file.Close();\n return running;\n }\n\n public static int ControlSpSys(bool start)\n {\n SafeFileHandle file = CreateFileSafe(@\"\\\\.\\SpDevice\");\n IntPtr buffer = Marshal.AllocHGlobal(4);\n int bytesReturned;\n DeviceIoControl(file, start ? 0x8000a000 : 0x8000a004, IntPtr.Zero, 0, buffer, 4, out bytesReturned, IntPtr.Zero);\n int result = Marshal.ReadInt32(buffer);\n Marshal.FreeHGlobal(buffer);\n file.Close();\n return result;\n }\n }\n}\n"], ["/TSforge/LibTSforge/TokenStore/Common.cs", "namespace LibTSforge.TokenStore\n{\n using System.Collections.Generic;\n using System.IO;\n\n public class TokenEntry\n {\n public string Name;\n public string Extension;\n public byte[] Data;\n public bool Populated;\n }\n\n public class TokenMeta\n {\n public string Name;\n public readonly Dictionary Data = new Dictionary();\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(1);\n byte[] nameBytes = Utils.EncodeString(Name);\n writer.Write(nameBytes.Length);\n writer.Write(nameBytes);\n\n foreach (KeyValuePair kv in Data)\n {\n byte[] keyBytes = Utils.EncodeString(kv.Key);\n byte[] valueBytes = Utils.EncodeString(kv.Value);\n writer.Write(keyBytes.Length);\n writer.Write(valueBytes.Length);\n writer.Write(keyBytes);\n writer.Write(valueBytes);\n }\n\n return writer.GetBytes();\n }\n\n private void Deserialize(byte[] data)\n {\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n reader.ReadInt32();\n int nameLen = reader.ReadInt32();\n Name = reader.ReadNullTerminatedString(nameLen);\n\n while (reader.BaseStream.Position < data.Length - 0x8)\n {\n int keyLen = reader.ReadInt32();\n int valueLen = reader.ReadInt32();\n string key = reader.ReadNullTerminatedString(keyLen);\n string value = reader.ReadNullTerminatedString(valueLen);\n Data[key] = value;\n }\n }\n\n public TokenMeta(byte[] data)\n {\n Deserialize(data);\n }\n\n public TokenMeta()\n {\n\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/IPhysicalStore.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n\n public class PSBlock\n {\n public BlockType Type;\n public uint Flags;\n public uint Unknown = 0;\n public byte[] Key;\n public string KeyAsStr\n {\n get\n {\n return Utils.DecodeString(Key);\n }\n set\n {\n Key = Utils.EncodeString(value);\n }\n }\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n public byte[] Data;\n public string DataAsStr\n {\n get\n {\n return Utils.DecodeString(Data);\n }\n set\n {\n Data = Utils.EncodeString(value);\n }\n }\n public uint DataAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Data, 0);\n }\n set\n {\n Data = BitConverter.GetBytes(value);\n }\n }\n }\n\n public interface IPhysicalStore : IDisposable\n {\n PSBlock GetBlock(string key, string value);\n PSBlock GetBlock(string key, uint value);\n void AddBlock(PSBlock block);\n void AddBlocks(IEnumerable blocks);\n void SetBlock(string key, string value, byte[] data);\n void SetBlock(string key, string value, string data);\n void SetBlock(string key, string value, uint data);\n void SetBlock(string key, uint value, byte[] data);\n void SetBlock(string key, uint value, string data);\n void SetBlock(string key, uint value, uint data);\n void DeleteBlock(string key, string value);\n void DeleteBlock(string key, uint value);\n byte[] Serialize();\n void Deserialize(byte[] data);\n byte[] ReadRaw();\n void WriteRaw(byte[] data);\n IEnumerable FindBlocks(string valueSearch);\n IEnumerable FindBlocks(uint valueSearch);\n }\n}\n"], ["/TSforge/LibTSforge/Crypto/Keys.cs", "namespace LibTSforge.Crypto\n{\n public static class Keys\n {\n public static readonly byte[] PRODUCTION = {\n 0x07, 0x02, 0x00, 0x00, 0x00, 0xA4, 0x00, 0x00, 0x52, 0x53, 0x41, 0x32, 0x00, 0x04, 0x00, 0x00,\n 0x01, 0x00, 0x01, 0x00, 0x29, 0x87, 0xBA, 0x3F, 0x52, 0x90, 0x57, 0xD8, 0x12, 0x26, 0x6B, 0x38,\n 0xB2, 0x3B, 0xF9, 0x67, 0x08, 0x4F, 0xDD, 0x8B, 0xF5, 0xE3, 0x11, 0xB8, 0x61, 0x3A, 0x33, 0x42,\n 0x51, 0x65, 0x05, 0x86, 0x1E, 0x00, 0x41, 0xDE, 0xC5, 0xDD, 0x44, 0x60, 0x56, 0x3D, 0x14, 0x39,\n 0xB7, 0x43, 0x65, 0xE9, 0xF7, 0x2B, 0xA5, 0xF0, 0xA3, 0x65, 0x68, 0xE9, 0xE4, 0x8B, 0x5C, 0x03,\n 0x2D, 0x36, 0xFE, 0x28, 0x4C, 0xD1, 0x3C, 0x3D, 0xC1, 0x90, 0x75, 0xF9, 0x6E, 0x02, 0xE0, 0x58,\n 0x97, 0x6A, 0xCA, 0x80, 0x02, 0x42, 0x3F, 0x6C, 0x15, 0x85, 0x4D, 0x83, 0x23, 0x6A, 0x95, 0x9E,\n 0x38, 0x52, 0x59, 0x38, 0x6A, 0x99, 0xF0, 0xB5, 0xCD, 0x53, 0x7E, 0x08, 0x7C, 0xB5, 0x51, 0xD3,\n 0x8F, 0xA3, 0x0D, 0xA0, 0xFA, 0x8D, 0x87, 0x3C, 0xFC, 0x59, 0x21, 0xD8, 0x2E, 0xD9, 0x97, 0x8B,\n 0x40, 0x60, 0xB1, 0xD7, 0x2B, 0x0A, 0x6E, 0x60, 0xB5, 0x50, 0xCC, 0x3C, 0xB1, 0x57, 0xE4, 0xB7,\n 0xDC, 0x5A, 0x4D, 0xE1, 0x5C, 0xE0, 0x94, 0x4C, 0x5E, 0x28, 0xFF, 0xFA, 0x80, 0x6A, 0x13, 0x53,\n 0x52, 0xDB, 0xF3, 0x04, 0x92, 0x43, 0x38, 0xB9, 0x1B, 0xD9, 0x85, 0x54, 0x7B, 0x14, 0xC7, 0x89,\n 0x16, 0x8A, 0x4B, 0x82, 0xA1, 0x08, 0x02, 0x99, 0x23, 0x48, 0xDD, 0x75, 0x9C, 0xC8, 0xC1, 0xCE,\n 0xB0, 0xD7, 0x1B, 0xD8, 0xFB, 0x2D, 0xA7, 0x2E, 0x47, 0xA7, 0x18, 0x4B, 0xF6, 0x29, 0x69, 0x44,\n 0x30, 0x33, 0xBA, 0xA7, 0x1F, 0xCE, 0x96, 0x9E, 0x40, 0xE1, 0x43, 0xF0, 0xE0, 0x0D, 0x0A, 0x32,\n 0xB4, 0xEE, 0xA1, 0xC3, 0x5E, 0x9B, 0xC7, 0x7F, 0xF5, 0x9D, 0xD8, 0xF2, 0x0F, 0xD9, 0x8F, 0xAD,\n 0x75, 0x0A, 0x00, 0xD5, 0x25, 0x43, 0xF7, 0xAE, 0x51, 0x7F, 0xB7, 0xDE, 0xB7, 0xAD, 0xFB, 0xCE,\n 0x83, 0xE1, 0x81, 0xFF, 0xDD, 0xA2, 0x77, 0xFE, 0xEB, 0x27, 0x1F, 0x10, 0xFA, 0x82, 0x37, 0xF4,\n 0x7E, 0xCC, 0xE2, 0xA1, 0x58, 0xC8, 0xAF, 0x1D, 0x1A, 0x81, 0x31, 0x6E, 0xF4, 0x8B, 0x63, 0x34,\n 0xF3, 0x05, 0x0F, 0xE1, 0xCC, 0x15, 0xDC, 0xA4, 0x28, 0x7A, 0x9E, 0xEB, 0x62, 0xD8, 0xD8, 0x8C,\n 0x85, 0xD7, 0x07, 0x87, 0x90, 0x2F, 0xF7, 0x1C, 0x56, 0x85, 0x2F, 0xEF, 0x32, 0x37, 0x07, 0xAB,\n 0xB0, 0xE6, 0xB5, 0x02, 0x19, 0x35, 0xAF, 0xDB, 0xD4, 0xA2, 0x9C, 0x36, 0x80, 0xC6, 0xDC, 0x82,\n 0x08, 0xE0, 0xC0, 0x5F, 0x3C, 0x59, 0xAA, 0x4E, 0x26, 0x03, 0x29, 0xB3, 0x62, 0x58, 0x41, 0x59,\n 0x3A, 0x37, 0x43, 0x35, 0xE3, 0x9F, 0x34, 0xE2, 0xA1, 0x04, 0x97, 0x12, 0x9D, 0x8C, 0xAD, 0xF7,\n 0xFB, 0x8C, 0xA1, 0xA2, 0xE9, 0xE4, 0xEF, 0xD9, 0xC5, 0xE5, 0xDF, 0x0E, 0xBF, 0x4A, 0xE0, 0x7A,\n 0x1E, 0x10, 0x50, 0x58, 0x63, 0x51, 0xE1, 0xD4, 0xFE, 0x57, 0xB0, 0x9E, 0xD7, 0xDA, 0x8C, 0xED,\n 0x7D, 0x82, 0xAC, 0x2F, 0x25, 0x58, 0x0A, 0x58, 0xE6, 0xA4, 0xF4, 0x57, 0x4B, 0xA4, 0x1B, 0x65,\n 0xB9, 0x4A, 0x87, 0x46, 0xEB, 0x8C, 0x0F, 0x9A, 0x48, 0x90, 0xF9, 0x9F, 0x76, 0x69, 0x03, 0x72,\n 0x77, 0xEC, 0xC1, 0x42, 0x4C, 0x87, 0xDB, 0x0B, 0x3C, 0xD4, 0x74, 0xEF, 0xE5, 0x34, 0xE0, 0x32,\n 0x45, 0xB0, 0xF8, 0xAB, 0xD5, 0x26, 0x21, 0xD7, 0xD2, 0x98, 0x54, 0x8F, 0x64, 0x88, 0x20, 0x2B,\n 0x14, 0xE3, 0x82, 0xD5, 0x2A, 0x4B, 0x8F, 0x4E, 0x35, 0x20, 0x82, 0x7E, 0x1B, 0xFE, 0xFA, 0x2C,\n 0x79, 0x6C, 0x6E, 0x66, 0x94, 0xBB, 0x0A, 0xEB, 0xBA, 0xD9, 0x70, 0x61, 0xE9, 0x47, 0xB5, 0x82,\n 0xFC, 0x18, 0x3C, 0x66, 0x3A, 0x09, 0x2E, 0x1F, 0x61, 0x74, 0xCA, 0xCB, 0xF6, 0x7A, 0x52, 0x37,\n 0x1D, 0xAC, 0x8D, 0x63, 0x69, 0x84, 0x8E, 0xC7, 0x70, 0x59, 0xDD, 0x2D, 0x91, 0x1E, 0xF7, 0xB1,\n 0x56, 0xED, 0x7A, 0x06, 0x9D, 0x5B, 0x33, 0x15, 0xDD, 0x31, 0xD0, 0xE6, 0x16, 0x07, 0x9B, 0xA5,\n 0x94, 0x06, 0x7D, 0xC1, 0xE9, 0xD6, 0xC8, 0xAF, 0xB4, 0x1E, 0x2D, 0x88, 0x06, 0xA7, 0x63, 0xB8,\n 0xCF, 0xC8, 0xA2, 0x6E, 0x84, 0xB3, 0x8D, 0xE5, 0x47, 0xE6, 0x13, 0x63, 0x8E, 0xD1, 0x7F, 0xD4,\n 0x81, 0x44, 0x38, 0xBF\n };\n\n public static readonly byte[] TEST = {\n 0x07, 0x02, 0x00, 0x00, 0x00, 0xA4, 0x00, 0x00, 0x52, 0x53, 0x41, 0x32, 0x00, 0x04, 0x00, 0x00,\n 0x01, 0x00, 0x01, 0x00, 0x0F, 0xBE, 0x77, 0xB8, 0xDD, 0x54, 0x36, 0xDD, 0x67, 0xD4, 0x17, 0x66,\n 0xC4, 0x13, 0xD1, 0x3F, 0x1E, 0x16, 0x0C, 0x16, 0x35, 0xAB, 0x6D, 0x3D, 0x34, 0x51, 0xED, 0x3F,\n 0x57, 0x14, 0xB6, 0xB7, 0x08, 0xE9, 0xD9, 0x7A, 0x80, 0xB3, 0x5F, 0x9B, 0x3A, 0xFD, 0x9E, 0x37,\n 0x3A, 0x53, 0x72, 0x67, 0x92, 0x60, 0xC3, 0xEF, 0xB5, 0x8E, 0x1E, 0xCF, 0x9D, 0x9C, 0xD3, 0x90,\n 0xE5, 0xDD, 0xF4, 0xDB, 0xF3, 0xD6, 0x65, 0xB3, 0xC1, 0xBD, 0x69, 0xE1, 0x76, 0x95, 0xD9, 0x37,\n 0xB8, 0x5E, 0xCA, 0x3D, 0x98, 0xFC, 0x50, 0x5C, 0x98, 0xAE, 0xE3, 0x7C, 0x4C, 0x27, 0xC3, 0xD0,\n 0xCE, 0x78, 0x06, 0x51, 0x68, 0x23, 0xE6, 0x70, 0xF8, 0x7C, 0xAE, 0x36, 0xBE, 0x41, 0x57, 0xE2,\n 0xC3, 0x2D, 0xAF, 0x21, 0xB1, 0xB3, 0x15, 0x81, 0x19, 0x26, 0x6B, 0x10, 0xB3, 0xE9, 0xD1, 0x45,\n 0x21, 0x77, 0x9C, 0xF6, 0xE1, 0xDD, 0xB6, 0x78, 0x9D, 0x1D, 0x32, 0x61, 0xBC, 0x2B, 0xDB, 0x86,\n 0xFB, 0x07, 0x24, 0x10, 0x19, 0x4F, 0x09, 0x6D, 0x03, 0x90, 0xD4, 0x5E, 0x30, 0x85, 0xC5, 0x58,\n 0x7E, 0x5D, 0xAE, 0x9F, 0x64, 0x93, 0x04, 0x82, 0x09, 0x0E, 0x1C, 0x66, 0xA8, 0x95, 0x91, 0x51,\n 0xB2, 0xED, 0x9A, 0x75, 0x04, 0x87, 0x50, 0xAC, 0xCC, 0x20, 0x06, 0x45, 0xB9, 0x7B, 0x42, 0x53,\n 0x9A, 0xD1, 0x29, 0xFC, 0xEF, 0xB9, 0x47, 0x16, 0x75, 0x69, 0x05, 0x87, 0x2B, 0xCB, 0x54, 0x9C,\n 0x21, 0x2D, 0x50, 0x8E, 0x12, 0xDE, 0xD3, 0x6B, 0xEC, 0x92, 0xA1, 0xB1, 0xE9, 0x4B, 0xBF, 0x6B,\n 0x9A, 0x38, 0xC7, 0x13, 0xFA, 0x78, 0xA1, 0x3C, 0x1E, 0xBB, 0x38, 0x31, 0xBB, 0x0C, 0x9F, 0x70,\n 0x1A, 0x31, 0x00, 0xD7, 0x5A, 0xA5, 0x84, 0x24, 0x89, 0x80, 0xF5, 0x88, 0xC2, 0x31, 0x18, 0xDC,\n 0x53, 0x05, 0x5D, 0xFA, 0x81, 0xDC, 0xE1, 0xCE, 0xA4, 0xAA, 0xBA, 0x07, 0xDA, 0x28, 0x4F, 0x64,\n 0x0E, 0x84, 0x9B, 0x06, 0xDE, 0xC8, 0x78, 0x66, 0x2F, 0x17, 0x25, 0xA8, 0x9C, 0x99, 0xFC, 0xBC,\n 0x7D, 0x01, 0x42, 0xD7, 0x35, 0xBF, 0x19, 0xF6, 0x3F, 0x20, 0xD9, 0x98, 0x9B, 0x5D, 0xDD, 0x39,\n 0xBE, 0x81, 0x00, 0x0B, 0xDE, 0x6F, 0x14, 0xCA, 0x7E, 0xF8, 0xC0, 0x26, 0xA8, 0x1D, 0xD1, 0x16,\n 0x88, 0x64, 0x87, 0x36, 0x45, 0x37, 0x50, 0xDA, 0x6C, 0xEB, 0x85, 0xB5, 0x43, 0x29, 0x88, 0x6F,\n 0x2F, 0xFE, 0x8D, 0x12, 0x8B, 0x72, 0xB7, 0x5A, 0xCB, 0x66, 0xC2, 0x2E, 0x1D, 0x7D, 0x42, 0xA6,\n 0xF4, 0xFE, 0x26, 0x5D, 0x54, 0x9E, 0x77, 0x1D, 0x97, 0xC2, 0xF3, 0xFD, 0x60, 0xB3, 0x22, 0x88,\n 0xCA, 0x27, 0x99, 0xDF, 0xC8, 0xB1, 0xD7, 0xC6, 0x54, 0xA6, 0x50, 0xB9, 0x54, 0xF5, 0xDE, 0xFE,\n 0xE1, 0x81, 0xA2, 0xBE, 0x81, 0x9F, 0x48, 0xFF, 0x2F, 0xB8, 0xA4, 0xB3, 0x17, 0xD8, 0xC1, 0xB9,\n 0x5D, 0x21, 0x3D, 0xA2, 0xED, 0x1C, 0x96, 0x66, 0xEE, 0x1F, 0x47, 0xCF, 0x62, 0xFA, 0xD6, 0xC1,\n 0x87, 0x5B, 0xC4, 0xE5, 0xD9, 0x08, 0x38, 0x22, 0xFA, 0x21, 0xBD, 0xF2, 0x88, 0xDA, 0xE2, 0x24,\n 0x25, 0x1F, 0xF1, 0x0B, 0x2D, 0xAE, 0x04, 0xBE, 0xA6, 0x7F, 0x75, 0x8C, 0xD9, 0x97, 0xE1, 0xCA,\n 0x35, 0xB9, 0xFC, 0x6F, 0x01, 0x68, 0x11, 0xD3, 0x68, 0x32, 0xD0, 0xC1, 0x69, 0xA3, 0xCF, 0x9B,\n 0x10, 0xE4, 0x69, 0xA7, 0xCF, 0xE1, 0xFE, 0x2A, 0x07, 0x9E, 0xC1, 0x37, 0x84, 0x68, 0xE5, 0xC5,\n 0xAB, 0x25, 0xEC, 0x7D, 0x7D, 0x74, 0x6A, 0xD1, 0xD5, 0x4D, 0xD7, 0xE1, 0x7D, 0xDE, 0x30, 0x4B,\n 0xE6, 0x5D, 0xCD, 0x91, 0x59, 0xF6, 0x80, 0xFD, 0xC6, 0x3C, 0xDD, 0x94, 0x7F, 0x15, 0x9D, 0xEF,\n 0x2F, 0x00, 0x62, 0xD7, 0xDA, 0xB9, 0xB3, 0xD9, 0x8D, 0xE8, 0xD7, 0x3C, 0x96, 0x45, 0x5D, 0x1E,\n 0x50, 0xFB, 0xAA, 0x43, 0xD3, 0x47, 0x77, 0x81, 0xE9, 0x67, 0xE4, 0xFE, 0xDF, 0x42, 0x79, 0xCB,\n 0xA7, 0xAD, 0x5D, 0x48, 0xF5, 0xB7, 0x74, 0x96, 0x12, 0x23, 0x06, 0x70, 0x42, 0x68, 0x7A, 0x44,\n 0xFC, 0xA0, 0x31, 0x7F, 0x68, 0xCA, 0xA2, 0x14, 0x5D, 0xA3, 0xCF, 0x42, 0x23, 0xAB, 0x47, 0xF6,\n 0xB2, 0xFC, 0x6D, 0xF1\n };\n }\n}\n"], ["/TSforge/LibTSforge/TokenStore/ITokenStore.cs", "namespace LibTSforge.TokenStore\n{\n using System;\n\n public interface ITokenStore : IDisposable\n {\n void Deserialize();\n void Serialize();\n void AddEntry(TokenEntry entry);\n void AddEntries(TokenEntry[] entries);\n void DeleteEntry(string name, string ext);\n void DeleteUnpopEntry(string name, string ext);\n TokenEntry GetEntry(string name, string ext);\n TokenMeta GetMetaEntry(string name);\n void SetEntry(string name, string ext, byte[] data);\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/Common.cs", "namespace LibTSforge.PhysicalStore\n{\n using System.Runtime.InteropServices;\n\n public enum BlockType : uint\n {\n NONE,\n NAMED,\n ATTRIBUTE,\n TIMER\n }\n\n [StructLayout(LayoutKind.Sequential, Pack = 1)]\n public struct Timer\n {\n public ulong Unknown;\n public ulong Time1;\n public ulong Time2;\n public ulong Expiry;\n }\n\n [StructLayout(LayoutKind.Sequential, Pack = 1)]\n public struct VistaTimer\n {\n public ulong Time;\n public ulong Expiry;\n }\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 19:06:23", "created_task_model": "DeepSeek-R1", "function_skeleton": "public static void LoadStore (PSVersion version, bool production, string filePath) {}", "code_description": "This code segment functions to: Replace existing system storage data with contents from an external file while temporarily halting dependent services to ensure safe modification and restore operational state afterwards."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\n public static void LoadStore(PSVersion version, bool production, string filePath)\n {\n if (!File.Exists(filePath))\n {\n throw new FileNotFoundException(\"Decrypted store file not found at '\" + filePath + \"'\");\n }\n\n string encrFilePath = GetPSPath(version);\n bool manageSpp = true;\n \n KillSPP(version);\n\n try\n {\n byte[] decrData = File.ReadAllBytes(filePath);\n byte[] encrData = PhysStoreCrypto.EncryptPhysicalStore(decrData, production, version);\n\n if (string.IsNullOrEmpty(encrFilePath) || !File.Exists(encrFilePath))\n {\n throw new FileNotFoundException(\"Target store does not exist at expected path '\" + encrFilePath + \"'\");\n }\n\n File.WriteAllBytes(encrFilePath, encrData);\n Logger.WriteLine(\"Store loaded successfully from '\" + filePath + \"'\");\n }\n finally\n {\n if (manageSpp)\n {\n RestartSPP(version);\n }\n }\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 19-06-44"}, "editdistance_info": {"edit_distance": 25.4902, "calculate_time": "2025-08-20 19:06:44", "true_code_clean": "public static void LoadStore(PSVersion version, bool production, string filePath)\n {\n if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))\n {\n throw new FileNotFoundException(\"Store file '\" + filePath + \"' does not exist.\");\n }\n KillSPP(version);\n using (IPhysicalStore store = GetStore(version, production))\n {\n store.WriteRaw(File.ReadAllBytes(filePath));\n }\n RestartSPP(version);\n Logger.WriteLine(\"Loaded store file successfully.\");\n }", "predict_code_clean": "public static void LoadStore(PSVersion version, bool production, string filePath)\n {\n if (!File.Exists(filePath))\n {\n throw new FileNotFoundException(\"Decrypted store file not found at '\" + filePath + \"'\");\n }\n string encrFilePath = GetPSPath(version);\n bool manageSpp = true;\n KillSPP(version);\n try\n {\n byte[] decrData = File.ReadAllBytes(filePath);\n byte[] encrData = PhysStoreCrypto.EncryptPhysicalStore(decrData, production, version);\n if (string.IsNullOrEmpty(encrFilePath) || !File.Exists(encrFilePath))\n {\n throw new FileNotFoundException(\"Target store does not exist at expected path '\" + encrFilePath + \"'\");\n }\n File.WriteAllBytes(encrFilePath, encrData);\n Logger.WriteLine(\"Store loaded successfully from '\" + filePath + \"'\");\n }\n finally\n {\n if (manageSpp)\n {\n RestartSPP(version);\n }\n }\n }"}} {"repo_name": "TSforge", "file_name": "/TSforge/LibTSforge/Modifiers/GracePeriodReset.cs", "inference_info": {"prefix_code": "namespace LibTSforge.Modifiers\n{\n using System.Collections.Generic;\n using System.Linq;\n using PhysicalStore;\n using SPP;\n\n public static class GracePeriodReset\n {\n ", "suffix_code": "\n }\n}\n", "middle_code": "public static void Reset(PSVersion version, bool production)\n {\n SPPUtils.KillSPP(version);\n Logger.WriteLine(\"Writing TrustedStore data...\");\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string value = \"msft:sl/timer\";\n List blocks = store.FindBlocks(value).ToList();\n foreach (PSBlock block in blocks)\n {\n store.DeleteBlock(block.KeyAsStr, block.ValueAsStr);\n }\n }\n SPPUtils.RestartSPP(version);\n Logger.WriteLine(\"Successfully reset all grace and evaluation period timers.\");\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/TSforge/LibTSforge/Modifiers/RearmReset.cs", "namespace LibTSforge.Modifiers\n{\n using System.Collections.Generic;\n using System.Linq;\n using PhysicalStore;\n using SPP;\n\n public static class RearmReset\n {\n public static void Reset(PSVersion version, bool production)\n {\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n List blocks;\n\n if (version == PSVersion.Vista)\n {\n blocks = store.FindBlocks(\"740D70D8-6448-4b2f-9063-4A7A463600C5\").ToList();\n }\n else if (version == PSVersion.Win7)\n {\n blocks = store.FindBlocks(0xA0000).ToList();\n }\n else\n {\n blocks = store.FindBlocks(\"__##USERSEP-RESERVED##__$$REARM-COUNT$$\").ToList();\n }\n\n foreach (PSBlock block in blocks)\n {\n if (version == PSVersion.Vista)\n {\n store.DeleteBlock(block.KeyAsStr, block.ValueAsStr);\n }\n else if (version == PSVersion.Win7)\n {\n store.SetBlock(block.KeyAsStr, block.ValueAsInt, new byte[8]);\n }\n else\n {\n store.SetBlock(block.KeyAsStr, block.ValueAsStr, new byte[8]);\n }\n }\n\n Logger.WriteLine(\"Successfully reset all rearm counters.\");\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/KeyChangeLockDelete.cs", "namespace LibTSforge.Modifiers\n{\n using System.Collections.Generic;\n using System.Linq;\n using PhysicalStore;\n using SPP;\n using System;\n\n public static class KeyChangeLockDelete\n {\n public static void Delete(PSVersion version, bool production)\n {\n if (version == PSVersion.Vista) throw new NotSupportedException(\"This feature is not supported on Windows Vista/Server 2008.\");\n\n SPPUtils.KillSPP(version);\n Logger.WriteLine(\"Writing TrustedStore data...\");\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n List values = new List\n {\n \"msft:spp/timebased/AB\",\n \"msft:spp/timebased/CD\"\n };\n List blocks = new List();\n foreach (string value in values)\n {\n blocks.AddRange(store.FindBlocks(value).ToList());\n }\n foreach (PSBlock block in blocks)\n {\n store.DeleteBlock(block.KeyAsStr, block.ValueAsStr);\n }\n }\n Logger.WriteLine(\"Successfully removed the key change lock.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/TamperedFlagsDelete.cs", "namespace LibTSforge.Modifiers\n{\n using System.Linq;\n using PhysicalStore;\n using SPP;\n\n public static class TamperedFlagsDelete\n {\n public static void DeleteTamperFlags(PSVersion version, bool production)\n {\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n if (version == PSVersion.Vista)\n {\n DeleteFlag(store, \"6BE8425B-E3CF-4e86-A6AF-5863E3DCB606\");\n }\n else if (version == PSVersion.Win7)\n {\n SetFlag(store, 0xA0001);\n }\n else\n {\n DeleteFlag(store, \"__##USERSEP-RESERVED##__$$RECREATED-FLAG$$\");\n DeleteFlag(store, \"__##USERSEP-RESERVED##__$$RECOVERED-FLAG$$\");\n }\n\n Logger.WriteLine(\"Successfully cleared the tamper state.\");\n }\n\n SPPUtils.RestartSPP(version);\n }\n\n private static void DeleteFlag(IPhysicalStore store, string flag)\n {\n store.FindBlocks(flag).ToList().ForEach(block => store.DeleteBlock(block.KeyAsStr, block.ValueAsStr));\n }\n\n private static void SetFlag(IPhysicalStore store, uint flag)\n {\n store.FindBlocks(flag).ToList().ForEach(block => store.SetBlock(block.KeyAsStr, block.ValueAsInt, new byte[8]));\n }\n }\n}\n"], ["/TSforge/TSforgeCLI/Program.cs", "namespace TSforgeCLI\n{\n using System;\n using LibTSforge;\n using LibTSforge.Activators;\n using LibTSforge.Modifiers;\n using LibTSforge.SPP;\n\n public class Program\n {\n private class Options\n {\n public bool Dump;\n public string DumpFilePath = \"dump.dat\";\n public string EncrFilePath;\n public bool Load;\n public string LoadFilePath = \"load.dat\";\n public bool KMS4k;\n public bool AVMA4k;\n public bool ZCID;\n public bool TimerReset;\n public bool RearmReset;\n public bool DeleteUniqueId;\n public bool InstallGenPKey;\n public bool KMSHostCharge;\n public bool TamperedFlagsDelete;\n public bool KeyChangeLockDelete;\n public bool SetIIDParams;\n public bool? Production;\n public PSVersion? Version;\n public Guid ActivationId = Guid.Empty;\n public bool ShowHelp;\n public PKeyAlgorithm? Algorithm;\n public int Group;\n public int Serial;\n public ulong Security;\n }\n\n public static void Main(string[] args)\n {\n Logger.WriteLine(\"TSforge (c) MASSGRAVE 2025\");\n\n Utils.Wow64EnableWow64FsRedirection(false);\n\n try\n {\n if (args.Length == 0)\n {\n DisplayUsage();\n return;\n }\n\n Options options = ParseArguments(args);\n\n if (options.ShowHelp)\n {\n DisplayUsage();\n return;\n }\n\n PSVersion version = options.Version ?? Utils.DetectVersion();\n bool production = options.Production ?? SPPUtils.DetectCurrentKey();\n\n if (options.Dump)\n {\n SPPUtils.DumpStore(version, production, options.DumpFilePath, options.EncrFilePath);\n }\n else if (options.Load)\n {\n SPPUtils.LoadStore(version, production, options.LoadFilePath);\n }\n else if (options.KMS4k)\n {\n KMS4k.Activate(version, production, options.ActivationId);\n }\n else if (options.AVMA4k)\n {\n AVMA4k.Activate(version, production, options.ActivationId);\n }\n else if (options.ZCID)\n {\n ZeroCID.Activate(version, production, options.ActivationId);\n }\n else if (options.TimerReset)\n {\n GracePeriodReset.Reset(version, production);\n }\n else if (options.DeleteUniqueId)\n {\n UniqueIdDelete.DeleteUniqueId(version, production, options.ActivationId);\n }\n else if (options.RearmReset)\n {\n RearmReset.Reset(version, production);\n }\n else if (options.InstallGenPKey)\n {\n GenPKeyInstall.InstallGenPKey(version, production, options.ActivationId);\n }\n else if (options.KMSHostCharge)\n {\n KMSHostCharge.Charge(version, production, options.ActivationId);\n }\n else if (options.TamperedFlagsDelete)\n {\n TamperedFlagsDelete.DeleteTamperFlags(version, production);\n }\n else if (options.KeyChangeLockDelete)\n {\n KeyChangeLockDelete.Delete(version, production);\n } \n else if (options.SetIIDParams)\n {\n SetIIDParams.SetParams(version, production, options.ActivationId, options.Algorithm.Value, options.Group, options.Serial, options.Security);\n }\n else\n {\n DisplayUsage();\n }\n }\n catch (Exception e)\n {\n#if DEBUG\n throw;\n#else\n Logger.WriteLine(\"Fatal error: \" + e.ToString());\n Environment.Exit(1);\n#endif\n }\n }\n\n private static Options ParseArguments(string[] args)\n {\n Options options = new Options();\n for (int i = 0; i < args.Length; i++)\n {\n string arg = args[i].Trim().ToLowerInvariant();\n switch (arg)\n {\n case \"/dump\":\n options.Dump = true;\n if (i + 1 < args.Length && !args[i + 1].StartsWith(\"/\"))\n {\n options.DumpFilePath = args[++i];\n }\n if (i + 1 < args.Length && !args[i + 1].StartsWith(\"/\"))\n {\n options.EncrFilePath = args[++i];\n }\n break;\n case \"/load\":\n options.Load = true;\n if (i + 1 < args.Length && !args[i + 1].StartsWith(\"/\"))\n {\n options.LoadFilePath = args[++i];\n }\n break;\n case \"/kms4k\":\n options.KMS4k = true;\n break;\n case \"/avma4k\":\n options.AVMA4k = true;\n break;\n case \"/zcid\":\n options.ZCID = true;\n break;\n case \"/ver\":\n options.Version = i + 1 < args.Length ? ParseVersion(args[++i]) : throw new ArgumentException(\"/ver requires a version argument.\");\n break;\n case \"/rtmr\":\n options.TimerReset = true;\n break;\n case \"/?\":\n options.ShowHelp = true;\n break;\n case \"/duid\":\n options.DeleteUniqueId = true;\n break;\n case \"/rrmc\":\n options.RearmReset = true;\n break;\n case \"/igpk\":\n options.InstallGenPKey = true;\n break;\n case \"/kmsc\":\n options.KMSHostCharge = true;\n break;\n case \"/test\":\n options.Production = false;\n break;\n case \"/prod\":\n options.Production = true;\n break;\n case \"/ctpr\":\n options.TamperedFlagsDelete = true;\n break;\n case \"/revl\":\n options.KeyChangeLockDelete = true;\n break;\n case \"/siid\":\n options.SetIIDParams = true;\n\n if (args.Length - i - 1 < 4) throw new ArgumentException(\"Not enough arguments specified.\");\n\n string algoType = args[++i];\n\n if (algoType == \"5\")\n {\n options.Algorithm = PKeyAlgorithm.PKEY2005;\n }\n else if (algoType == \"9\")\n {\n options.Algorithm = PKeyAlgorithm.PKEY2009;\n } \n else \n { \n throw new ArgumentException(\"Invalid key algorithm specified.\");\n }\n\n try\n {\n options.Group = int.Parse(args[++i]);\n options.Serial = int.Parse(args[++i]);\n options.Security = ulong.Parse(args[++i]);\n } \n catch\n {\n throw new ArgumentException(\"Failed to parse key parameters.\");\n }\n\n break;\n default:\n try\n {\n options.ActivationId = new Guid(arg);\n }\n catch (FormatException)\n {\n Logger.WriteLine(\"Argument doesn't exist or the specified activation ID is invalid.\");\n options.ShowHelp = true;\n }\n break;\n }\n }\n\n return options;\n }\n\n private static void DisplayUsage()\n {\n string exeName = typeof(Program).Namespace;\n Logger.WriteLine(\"Usage: \" + exeName + \" [/dump ()] [/load ] [/kms4k] [/avma4k] [/zcid] [/rtmr] [/duid] [/igpk] [/kmsc] [/ctpr] [/revl] [/siid <5/9> ] [/prod] [/test] [] [/ver ]\");\n Logger.WriteLine(\"Options:\");\n Logger.WriteLine(\"\\t/dump () Dump and decrypt the physical store to the specified path.\");\n Logger.WriteLine(\"\\t/load Load and re-encrypt the physical store from the specified path.\");\n Logger.WriteLine(\"\\t/kms4k Activate using KMS4k. Only supports KMS-activatable editions.\");\n Logger.WriteLine(\"\\t/avma4k Activate using AVMA4k. Only supports Windows Server 2012 R2+.\");\n Logger.WriteLine(\"\\t/zcid Activate using ZeroCID. Only supports phone-activatable editions.\");\n Logger.WriteLine(\"\\t/rtmr Reset grace/evaluation period timers.\");\n Logger.WriteLine(\"\\t/rrmc Reset the rearm count.\");\n Logger.WriteLine(\"\\t/duid Delete product key Unique ID used in online key validation.\");\n Logger.WriteLine(\"\\t/igpk Install auto-generated/fake product key according to the specified Activation ID\");\n Logger.WriteLine(\"\\t/kmsc Reset the charged count on the local KMS server to 25. Requires an activated KMS host.\");\n Logger.WriteLine(\"\\t/ctpr Remove the tamper flags that get set in the physical store when sppsvc detects an attempt to tamper with it.\");\n Logger.WriteLine(\"\\t/revl Remove the key change lock in evaluation edition store.\");\n Logger.WriteLine(\"\\t/siid <5/9> Set Installation ID parameters independently of installed key. 5/9 argument specifies PKEY200[5/9] key algorithm.\");\n Logger.WriteLine(\"\\t/prod Use SPP production key.\");\n Logger.WriteLine(\"\\t/test Use SPP test key.\");\n Logger.WriteLine(\"\\t/ver Override the detected version. Available versions: vista, 7, 8, blue, modern.\");\n Logger.WriteLine(\"\\t A specific activation ID. Useful if you want to activate specific addons like ESU.\");\n Logger.WriteLine(\"\\t/? Display this help message.\");\n }\n\n private static PSVersion ParseVersion(string ver)\n {\n switch (ver.Trim().ToLowerInvariant())\n {\n case \"vista\": return PSVersion.Vista;\n case \"7\": return PSVersion.Win7;\n case \"8\": return PSVersion.Win8;\n case \"blue\": return PSVersion.WinBlue;\n case \"modern\": return PSVersion.WinModern;\n default: throw new ArgumentException(\"Invalid version specified.\");\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/Activators/KMS4K.cs", "namespace LibTSforge.Activators\n{\n using System;\n using System.IO;\n using PhysicalStore;\n using SPP;\n\n public class KMS4k\n {\n public static void Activate(PSVersion version, bool production, Guid actId)\n {\n Guid appId;\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, true);\n\n if (actId == Guid.Empty)\n {\n throw new NotSupportedException(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n if (SLApi.GetPKeyChannel(SLApi.GetInstalledPkeyID(actId)) != \"Volume:GVLK\")\n {\n throw new NotSupportedException(\"Non-Volume:GVLK product key installed.\");\n }\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n\n ulong unknown = 0;\n ulong time1;\n ulong time2 = (ulong)DateTime.UtcNow.ToFileTime();\n ulong expiry = Constants.TimerMax;\n\n if (version == PSVersion.Vista || version == PSVersion.Win7)\n {\n unknown = 0x800000000;\n time1 = 0;\n }\n else\n {\n long creationTime = BitConverter.ToInt64(store.GetBlock(\"__##USERSEP##\\\\$$_RESERVED_$$\\\\NAMESPACE__\", \"__##USERSEP-RESERVED##__$$GLOBAL-CREATION-TIME$$\").Data, 0);\n long tickCount = BitConverter.ToInt64(store.GetBlock(\"__##USERSEP##\\\\$$_RESERVED_$$\\\\NAMESPACE__\", \"__##USERSEP-RESERVED##__$$GLOBAL-TICKCOUNT-UPTIME$$\").Data, 0);\n long deltaTime = BitConverter.ToInt64(store.GetBlock(key, \"__##USERSEP-RESERVED##__$$UP-TIME-DELTA$$\").Data, 0);\n\n time1 = (ulong)(creationTime + tickCount + deltaTime);\n time2 /= 10000;\n expiry /= 10000;\n }\n\n if (version == PSVersion.Vista)\n {\n VistaTimer vistaTimer = new VistaTimer\n {\n Time = time2,\n Expiry = Constants.TimerMax\n };\n\n string vistaTimerName = string.Format(\"msft:sl/timer/VLExpiration/VOLUME/{0}/{1}\", appId, actId);\n\n store.DeleteBlock(key, vistaTimerName);\n store.DeleteBlock(key, actId.ToString());\n\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(Constants.KMSv4Response.Length);\n writer.Write(Constants.KMSv4Response);\n writer.Write(Constants.UniversalHWIDBlock);\n byte[] kmsData = writer.GetBytes();\n\n store.AddBlocks(new[]\n {\n new PSBlock\n {\n Type = BlockType.TIMER,\n Flags = 0,\n KeyAsStr = key,\n ValueAsStr = vistaTimerName,\n Data = vistaTimer.CastToArray()\n },\n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = 0,\n KeyAsStr = key,\n ValueAsStr = actId.ToString(),\n Data = kmsData\n }\n });\n }\n else\n {\n byte[] hwidBlock = Constants.UniversalHWIDBlock;\n byte[] kmsResp;\n\n switch (version)\n {\n case PSVersion.Win7:\n kmsResp = Constants.KMSv4Response;\n break;\n case PSVersion.Win8:\n kmsResp = Constants.KMSv5Response;\n break;\n case PSVersion.WinBlue:\n case PSVersion.WinModern:\n kmsResp = Constants.KMSv6Response;\n break;\n default:\n throw new NotSupportedException(\"Unsupported PSVersion.\");\n }\n\n VariableBag kmsBinding = new VariableBag(version);\n\n kmsBinding.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n Key = new byte[] { },\n Value = kmsResp\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"msft:rm/algorithm/hwid/4.0\"\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppBindingLicenseData\",\n Value = hwidBlock\n }\n });\n\n if (version == PSVersion.WinModern)\n {\n kmsBinding.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"massgrave.dev\"\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"6969\"\n }\n });\n }\n\n byte[] kmsBindingData = kmsBinding.Serialize();\n\n Timer kmsTimer = new Timer\n {\n Unknown = unknown,\n Time1 = time1,\n Time2 = time2,\n Expiry = expiry\n };\n\n string storeVal = string.Format(\"msft:spp/kms/bind/2.0/store/{0}/{1}\", appId, actId);\n string timerVal = string.Format(\"msft:spp/kms/bind/2.0/timer/{0}/{1}\", appId, actId);\n\n store.DeleteBlock(key, storeVal);\n store.DeleteBlock(key, timerVal);\n\n store.AddBlocks(new[]\n {\n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = (version == PSVersion.WinModern) ? (uint)0x400 : 0,\n KeyAsStr = key,\n ValueAsStr = storeVal,\n Data = kmsBindingData\n },\n new PSBlock\n {\n Type = BlockType.TIMER,\n Flags = (version == PSVersion.Win7) ? (uint)0 : 0x4,\n KeyAsStr = key,\n ValueAsStr = timerVal,\n Data = kmsTimer.CastToArray()\n }\n });\n }\n }\n\n SPPUtils.RestartSPP(version);\n SLApi.FireStateChangedEvent(appId);\n Logger.WriteLine(\"Activated using KMS4k successfully.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/Activators/ZeroCID.cs", "namespace LibTSforge.Activators\n{\n using System;\n using System.IO;\n using System.Linq;\n using Crypto;\n using PhysicalStore;\n using SPP;\n\n public static class ZeroCID\n {\n private static void Deposit(Guid actId, string instId)\n {\n uint status = SLApi.DepositConfirmationID(actId, instId, Constants.ZeroCID);\n Logger.WriteLine(string.Format(\"Depositing fake CID status {0:X}\", status));\n\n if (status != 0)\n {\n throw new InvalidOperationException(\"Failed to deposit fake CID.\");\n }\n }\n\n public static void Activate(PSVersion version, bool production, Guid actId)\n {\n Guid appId;\n\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, false);\n\n if (actId == Guid.Empty)\n {\n throw new NotSupportedException(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n if (!SLApi.IsPhoneActivatable(actId))\n {\n throw new NotSupportedException(\"Phone license is unavailable for this product.\");\n }\n\n string instId = SLApi.GetInstallationID(actId);\n Guid pkeyId = SLApi.GetInstalledPkeyID(actId);\n\n if (version == PSVersion.Vista || version == PSVersion.Win7)\n {\n Deposit(actId, instId);\n }\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n byte[] hwidBlock = Constants.UniversalHWIDBlock;\n\n Logger.WriteLine(\"Activation ID: \" + actId);\n Logger.WriteLine(\"Installation ID: \" + instId);\n Logger.WriteLine(\"Product Key ID: \" + pkeyId);\n\n byte[] iidHash;\n\n if (version == PSVersion.Vista)\n {\n iidHash = CryptoUtils.SHA256Hash(Utils.EncodeString(instId)).Take(0x10).ToArray();\n }\n else if (version == PSVersion.Win7)\n {\n iidHash = CryptoUtils.SHA256Hash(Utils.EncodeString(instId));\n }\n else\n {\n iidHash = CryptoUtils.SHA256Hash(Utils.EncodeString(instId + '\\0' + Constants.ZeroCID));\n }\n\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n PSBlock keyBlock = store.GetBlock(key, pkeyId.ToString());\n\n if (keyBlock == null)\n {\n throw new InvalidDataException(\"Failed to get product key data for activation ID \" + actId + \".\");\n }\n\n VariableBag pkb = new VariableBag(keyBlock.Data, version);\n\n byte[] pkeyData;\n\n if (version == PSVersion.Vista)\n {\n pkeyData = pkb.GetBlock(\"PKeyBasicInfo\").Value;\n string uniqueId = Utils.DecodeString(pkeyData.Skip(0x120).Take(0x80).ToArray());\n string extPid = Utils.DecodeString(pkeyData.Skip(0x1A0).Take(0x80).ToArray());\n\n uint group;\n uint.TryParse(extPid.Split('-')[1], out group);\n\n if (group == 0)\n {\n throw new FormatException(\"Extended PID has invalid format.\");\n }\n\n ulong shortauth;\n\n try\n {\n shortauth = BitConverter.ToUInt64(Convert.FromBase64String(uniqueId.Split('&')[1]), 0);\n } \n catch\n {\n throw new FormatException(\"Key Unique ID has invalid format.\");\n }\n\n shortauth |= (ulong)group << 41;\n pkeyData = BitConverter.GetBytes(shortauth);\n }\n else if (version == PSVersion.Win7)\n {\n pkeyData = pkb.GetBlock(\"SppPkeyShortAuthenticator\").Value;\n }\n else\n {\n pkeyData = pkb.GetBlock(\"SppPkeyPhoneActivationData\").Value;\n }\n\n pkb.DeleteBlock(\"SppPkeyVirtual\");\n store.SetBlock(key, pkeyId.ToString(), pkb.Serialize());\n\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(iidHash.Length);\n writer.Write(iidHash);\n writer.Write(hwidBlock.Length);\n writer.Write(hwidBlock);\n byte[] tsHwidData = writer.GetBytes();\n\n writer = new BinaryWriter(new MemoryStream());\n writer.Write(iidHash.Length);\n writer.Write(iidHash);\n writer.Write(pkeyData.Length);\n writer.Write(pkeyData);\n byte[] tsPkeyInfoData = writer.GetBytes();\n\n string phoneVersion = version == PSVersion.Vista ? \"6.0\" : \"7.0\";\n Guid indexSlid = version == PSVersion.Vista ? actId : pkeyId;\n string hwidBlockName = string.Format(\"msft:Windows/{0}/Phone/Cached/HwidBlock/{1}\", phoneVersion, indexSlid);\n string pkeyInfoName = string.Format(\"msft:Windows/{0}/Phone/Cached/PKeyInfo/{1}\", phoneVersion, indexSlid);\n\n store.DeleteBlock(key, hwidBlockName);\n store.DeleteBlock(key, pkeyInfoName);\n\n store.AddBlocks(new[] {\n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = 0,\n KeyAsStr = key,\n ValueAsStr = hwidBlockName,\n Data = tsHwidData\n }, \n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = 0,\n KeyAsStr = key,\n ValueAsStr = pkeyInfoName,\n Data = tsPkeyInfoData\n }\n });\n }\n\n if (version != PSVersion.Vista && version != PSVersion.Win7)\n {\n Deposit(actId, instId);\n }\n\n SPPUtils.RestartSPP(version);\n SLApi.FireStateChangedEvent(appId);\n Logger.WriteLine(\"Activated using ZeroCID successfully.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/GenPKeyInstall.cs", "namespace LibTSforge.Modifiers\n{\n using System;\n using System.IO;\n using Microsoft.Win32;\n using PhysicalStore;\n using SPP;\n using TokenStore;\n\n public static class GenPKeyInstall\n {\n private static void WritePkey2005RegistryValues(PSVersion version, ProductKey pkey)\n {\n Logger.WriteLine(\"Writing registry data for Windows product key...\");\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"ProductId\", pkey.GetPid2());\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"DigitalProductId\", pkey.GetPid3());\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"DigitalProductId4\", pkey.GetPid4());\n\n if (Registry.GetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Registration\", \"ProductId\", null) != null)\n {\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Registration\", \"ProductId\", pkey.GetPid2());\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Registration\", \"DigitalProductId\", pkey.GetPid3());\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Registration\", \"DigitalProductId4\", pkey.GetPid4());\n }\n\n if (pkey.Channel == \"Volume:CSVLK\" && version != PSVersion.Win7)\n {\n Registry.SetValue(@\"HKEY_USERS\\S-1-5-20\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform\", \"KmsHostConfig\", 1);\n }\n }\n\n public static void InstallGenPKey(PSVersion version, bool production, Guid actId)\n {\n if (version == PSVersion.Vista) throw new NotSupportedException(\"This feature is not supported on Windows Vista/Server 2008.\");\n if (actId == Guid.Empty) throw new ArgumentException(\"Activation ID must be specified for generated product key install.\");\n\n PKeyConfig pkc = new PKeyConfig();\n \n try\n {\n pkc.LoadConfig(actId);\n }\n catch (ArgumentException)\n {\n pkc.LoadAllConfigs(SLApi.GetAppId(actId));\n }\n\n ProductConfig config;\n pkc.Products.TryGetValue(actId, out config);\n\n if (config == null) throw new ArgumentException(\"Activation ID \" + actId + \" not found in PKeyConfig.\");\n\n ProductKey pkey = config.GetRandomKey();\n\n Guid instPkeyId = SLApi.GetInstalledPkeyID(actId);\n if (instPkeyId != Guid.Empty) SLApi.UninstallProductKey(instPkeyId);\n\n if (pkey.Algorithm == PKeyAlgorithm.PKEY2009)\n {\n uint status = SLApi.InstallProductKey(pkey);\n Logger.WriteLine(string.Format(\"Installing generated product key {0} status {1:X}\", pkey, status));\n\n if ((int)status < 0)\n {\n throw new ApplicationException(\"Failed to install generated product key.\");\n }\n\n Logger.WriteLine(\"Successfully deposited generated product key.\");\n return;\n }\n\n Logger.WriteLine(\"Key range is PKEY2005, creating fake key data...\");\n\n if (pkey.Channel == \"Volume:GVLK\" && version == PSVersion.Win7) throw new NotSupportedException(\"Fake GVLK generation is not supported on Windows 7.\");\n\n VariableBag pkb = new VariableBag(version);\n pkb.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingProductKey\",\n ValueAsStr = pkey.ToString()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingMPC\",\n ValueAsStr = pkey.GetMPC()\n },\n new CRCBlockModern {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingPid2\",\n ValueAsStr = pkey.GetPid2()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingPid3\",\n Value = pkey.GetPid3()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingPid4\",\n Value = pkey.GetPid4()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyChannelId\",\n ValueAsStr = pkey.Channel\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingEditionId\",\n ValueAsStr = pkey.Edition\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = (version == PSVersion.Win7) ? \"SppPkeyShortAuthenticator\" : \"SppPkeyPhoneActivationData\",\n Value = pkey.GetPhoneData(version)\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingMiscData\",\n Value = new byte[] { }\n }\n });\n\n Guid appId = SLApi.GetAppId(actId);\n string pkeyId = pkey.GetPkeyId().ToString();\n bool isAddon = SLApi.IsAddon(actId);\n string currEdition = SLApi.GetMetaStr(actId, \"Family\");\n\n if (appId == SLApi.WINDOWS_APP_ID && !isAddon)\n {\n SLApi.UninstallAllProductKeys(appId);\n }\n\n SPPUtils.KillSPP(version);\n\n using (IPhysicalStore ps = SPPUtils.GetStore(version, production))\n {\n using (ITokenStore tks = SPPUtils.GetTokenStore(version))\n {\n Logger.WriteLine(\"Writing to physical store and token store...\");\n\n string suffix = (version == PSVersion.Win8 || version == PSVersion.WinBlue || version == PSVersion.WinModern) ? \"_--\" : \"\";\n string metSuffix = suffix + \"_met\";\n\n if (appId == SLApi.WINDOWS_APP_ID && !isAddon)\n {\n string edTokName = \"msft:spp/token/windows/productkeyid/\" + currEdition;\n\n TokenMeta edToken = tks.GetMetaEntry(edTokName);\n edToken.Data[\"windowsComponentEditionPkeyId\"] = pkeyId;\n edToken.Data[\"windowsComponentEditionSkuId\"] = actId.ToString();\n tks.SetEntry(edTokName, \"xml\", edToken.Serialize());\n\n WritePkey2005RegistryValues(version, pkey);\n }\n\n string uriMapName = \"msft:spp/token/PKeyIdUriMapper\" + metSuffix;\n TokenMeta uriMap = tks.GetMetaEntry(uriMapName);\n uriMap.Data[pkeyId] = pkey.GetAlgoUri();\n tks.SetEntry(uriMapName, \"xml\", uriMap.Serialize());\n\n string skuMetaName = actId + metSuffix;\n TokenMeta skuMeta = tks.GetMetaEntry(skuMetaName);\n\n foreach (string k in skuMeta.Data.Keys)\n {\n if (k.StartsWith(\"pkeyId_\"))\n {\n skuMeta.Data.Remove(k);\n break;\n }\n }\n\n skuMeta.Data[\"pkeyId\"] = pkeyId;\n skuMeta.Data[\"pkeyIdList\"] = pkeyId;\n tks.SetEntry(skuMetaName, \"xml\", skuMeta.Serialize());\n\n string psKey = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n ps.DeleteBlock(psKey, pkeyId);\n ps.AddBlock(new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = (version == PSVersion.WinModern) ? (uint)0x402 : 0x2,\n KeyAsStr = psKey,\n ValueAsStr = pkeyId,\n Data = pkb.Serialize()\n });\n\n string cachePath = SPPUtils.GetTokensPath(version).Replace(\"tokens.dat\", @\"cache\\cache.dat\");\n if (File.Exists(cachePath)) File.Delete(cachePath);\n }\n }\n\n SLApi.RefreshTrustedTime(actId);\n Logger.WriteLine(\"Successfully deposited fake product key.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/SetIIDParams.cs", "namespace LibTSforge.Modifiers\n{\n using PhysicalStore;\n using SPP;\n using System.IO;\n using System;\n\n public static class SetIIDParams\n {\n public static void SetParams(PSVersion version, bool production, Guid actId, PKeyAlgorithm algorithm, int group, int serial, ulong security)\n {\n if (version == PSVersion.Vista) throw new NotSupportedException(\"This feature is not supported on Windows Vista/Server 2008.\");\n\n Guid appId;\n\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, true);\n\n if (actId == Guid.Empty)\n {\n throw new Exception(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n Guid pkeyId = SLApi.GetInstalledPkeyID(actId);\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n PSBlock keyBlock = store.GetBlock(key, pkeyId.ToString());\n\n if (keyBlock == null)\n {\n throw new InvalidDataException(\"Failed to get product key data for activation ID \" + actId + \".\");\n }\n\n VariableBag pkb = new VariableBag(keyBlock.Data, version);\n\n ProductKey pkey = new ProductKey\n {\n Group = group,\n Serial = serial,\n Security = security,\n Algorithm = algorithm,\n Upgrade = false\n };\n\n string blockName = version == PSVersion.Win7 ? \"SppPkeyShortAuthenticator\" : \"SppPkeyPhoneActivationData\";\n pkb.SetBlock(blockName, pkey.GetPhoneData(version));\n store.SetBlock(key, pkeyId.ToString(), pkb.Serialize());\n }\n\n Logger.WriteLine(\"Successfully set IID parameters.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/Activators/AVMA4K.cs", "namespace LibTSforge.Activators\n{\n using System;\n using PhysicalStore;\n using SPP;\n\n public static class AVMA4k\n {\n public static void Activate(PSVersion version, bool production, Guid actId)\n {\n if (version != PSVersion.WinModern && version != PSVersion.WinBlue)\n {\n throw new NotSupportedException(\"AVMA licenses are not available for this product.\");\n }\n\n Guid appId;\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, false);\n\n if (actId == Guid.Empty)\n {\n throw new NotSupportedException(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n if (SLApi.GetPKeyChannel(SLApi.GetInstalledPkeyID(actId)) != \"VT:IA\")\n {\n throw new NotSupportedException(\"Non-VT:IA product key installed.\");\n }\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n\n long creationTime = BitConverter.ToInt64(store.GetBlock(\"__##USERSEP##\\\\$$_RESERVED_$$\\\\NAMESPACE__\", \"__##USERSEP-RESERVED##__$$GLOBAL-CREATION-TIME$$\").Data, 0);\n long tickCount = BitConverter.ToInt64(store.GetBlock(\"__##USERSEP##\\\\$$_RESERVED_$$\\\\NAMESPACE__\", \"__##USERSEP-RESERVED##__$$GLOBAL-TICKCOUNT-UPTIME$$\").Data, 0);\n long deltaTime = BitConverter.ToInt64(store.GetBlock(key, \"__##USERSEP-RESERVED##__$$UP-TIME-DELTA$$\").Data, 0);\n\n const ulong unknown = 0;\n ulong time1 = (ulong)(creationTime + tickCount + deltaTime);\n ulong crcBindTime = (ulong)DateTime.UtcNow.ToFileTime();\n ulong timerTime = crcBindTime / 10000;\n ulong expiry = Constants.TimerMax / 10000;\n\n VariableBag avmaBinding = new VariableBag(version);\n\n avmaBinding.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n Key = new byte[] { },\n Value = BitConverter.GetBytes(crcBindTime),\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"AVMA4K\",\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"00491-50000-00001-AA666\",\n }\n });\n\n byte[] avmaBindingData = avmaBinding.Serialize();\n\n Timer avmaTimer = new Timer\n {\n Unknown = unknown,\n Time1 = time1,\n Time2 = timerTime,\n Expiry = expiry\n };\n\n string storeVal = string.Format(\"msft:spp/ia/bind/1.0/store/{0}/{1}\", appId, actId);\n string timerVal = string.Format(\"msft:spp/ia/bind/1.0/timer/{0}/{1}\", appId, actId);\n\n store.DeleteBlock(key, storeVal);\n store.DeleteBlock(key, timerVal);\n\n store.AddBlocks(new[]\n {\n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = 0x400,\n KeyAsStr = key,\n ValueAsStr = storeVal,\n Data = avmaBindingData,\n },\n new PSBlock\n {\n Type = BlockType.TIMER,\n Flags = 0x4,\n KeyAsStr = key,\n ValueAsStr = timerVal,\n Data = avmaTimer.CastToArray()\n }\n });\n }\n\n SLApi.RefreshLicenseStatus();\n SLApi.FireStateChangedEvent(appId);\n Logger.WriteLine(\"Activated using AVMA4k successfully.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/KMSHostCharge.cs", "namespace LibTSforge.Modifiers\n{\n using System;\n using System.IO;\n using PhysicalStore;\n using SPP;\n\n public static class KMSHostCharge\n {\n public static void Charge(PSVersion version, bool production, Guid actId)\n {\n if (actId == Guid.Empty)\n {\n actId = SLApi.GetDefaultActivationID(SLApi.WINDOWS_APP_ID, true);\n\n if (actId == Guid.Empty)\n {\n throw new NotSupportedException(\"No applicable activation IDs found.\");\n }\n }\n\n if (SLApi.GetPKeyChannel(SLApi.GetInstalledPkeyID(actId)) != \"Volume:CSVLK\")\n {\n throw new NotSupportedException(\"Non-Volume:CSVLK product key installed.\");\n }\n\n Guid appId = SLApi.GetAppId(actId);\n int totalClients = 50;\n int currClients = 25;\n byte[] hwidBlock = Constants.UniversalHWIDBlock;\n string key = string.Format(\"SPPSVC\\\\{0}\", appId);\n long ldapTimestamp = DateTime.Now.ToFileTime();\n\n byte[] cmidGuids = { };\n byte[] reqCounts = { };\n byte[] kmsChargeData = { };\n\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n\n if (version == PSVersion.Vista)\n {\n writer.Write(new byte[44]);\n writer.Seek(0, SeekOrigin.Begin);\n\n writer.Write(totalClients);\n writer.Write(43200);\n writer.Write(32);\n\n writer.Seek(20, SeekOrigin.Begin);\n writer.Write((byte)currClients);\n\n writer.Seek(32, SeekOrigin.Begin);\n writer.Write((byte)currClients);\n\n writer.Seek(0, SeekOrigin.End);\n\n for (int i = 0; i < currClients; i++)\n {\n writer.Write(Guid.NewGuid().ToByteArray());\n writer.Write(ldapTimestamp - (10 * (i + 1)));\n }\n\n kmsChargeData = writer.GetBytes();\n } \n else\n {\n for (int i = 0; i < currClients; i++)\n {\n writer.Write(ldapTimestamp - (10 * (i + 1)));\n writer.Write(Guid.NewGuid().ToByteArray());\n }\n\n cmidGuids = writer.GetBytes();\n\n writer = new BinaryWriter(new MemoryStream());\n\n writer.Write(new byte[40]);\n\n writer.Seek(4, SeekOrigin.Begin);\n writer.Write((byte)currClients);\n\n writer.Seek(24, SeekOrigin.Begin);\n writer.Write((byte)currClients);\n\n reqCounts = writer.GetBytes();\n }\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n if (version != PSVersion.Vista)\n {\n VariableBag kmsCountData = new VariableBag(version);\n kmsCountData.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppBindingLicenseData\",\n Value = hwidBlock\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.UINT,\n Key = new byte[] { },\n ValueAsInt = (uint)totalClients\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.UINT,\n Key = new byte[] { },\n ValueAsInt = 1051200000\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.UINT,\n Key = new byte[] { },\n ValueAsInt = (uint)currClients\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n Key = new byte[] { },\n Value = cmidGuids\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n Key = new byte[] { },\n Value = reqCounts\n }\n });\n\n kmsChargeData = kmsCountData.Serialize();\n }\n\n string countVal = version == PSVersion.Vista ? \"C8F6FFF1-79CE-404C-B150-F97991273DF1\" : string.Format(\"msft:spp/kms/host/2.0/store/counters/{0}\", appId);\n\n store.DeleteBlock(key, countVal);\n store.AddBlock(new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = (version == PSVersion.WinModern) ? (uint)0x400 : 0,\n KeyAsStr = key,\n ValueAsStr = countVal,\n Data = kmsChargeData\n });\n\n Logger.WriteLine(string.Format(\"Set charge count to {0} successfully.\", currClients));\n }\n\n SPPUtils.RestartSPP(version);\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/UniqueIdDelete.cs", "namespace LibTSforge.Modifiers\n{\n using System;\n using PhysicalStore;\n using SPP;\n\n public static class UniqueIdDelete\n {\n public static void DeleteUniqueId(PSVersion version, bool production, Guid actId)\n {\n if (version == PSVersion.Vista) throw new NotSupportedException(\"This feature is not supported on Windows Vista/Server 2008.\");\n\n Guid appId;\n\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, true);\n\n if (actId == Guid.Empty)\n {\n throw new Exception(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n Guid pkeyId = SLApi.GetInstalledPkeyID(actId);\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n PSBlock keyBlock = store.GetBlock(key, pkeyId.ToString());\n\n if (keyBlock == null)\n {\n throw new Exception(\"No product key found.\");\n }\n\n VariableBag pkb = new VariableBag(keyBlock.Data, version);\n\n pkb.DeleteBlock(\"SppPkeyUniqueIdToken\");\n\n store.SetBlock(key, pkeyId.ToString(), pkb.Serialize());\n }\n\n Logger.WriteLine(\"Successfully removed Unique ID for product key ID \" + pkeyId);\n }\n }\n}\n"], ["/TSforge/LibTSforge/SPP/SPPUtils.cs", "namespace LibTSforge.SPP\n{\n using Microsoft.Win32;\n using System;\n using System.IO;\n using System.Linq;\n using System.ServiceProcess;\n using Crypto;\n using PhysicalStore;\n using TokenStore;\n\n public static class SPPUtils\n {\n public static void KillSPP(PSVersion version)\n {\n ServiceController sc;\n\n string svcName = version == PSVersion.Vista ? \"slsvc\" : \"sppsvc\";\n\n try\n {\n sc = new ServiceController(svcName);\n\n if (sc.Status == ServiceControllerStatus.Stopped)\n return;\n }\n catch (InvalidOperationException ex)\n {\n throw new InvalidOperationException(string.Format(\"Unable to access {0}: \", svcName) + ex.Message);\n }\n\n Logger.WriteLine(string.Format(\"Stopping {0}...\", svcName));\n\n bool stopped = false;\n\n for (int i = 0; stopped == false && i < 1080; i++)\n {\n try\n {\n if (sc.Status != ServiceControllerStatus.StopPending)\n sc.Stop();\n\n sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromMilliseconds(500));\n }\n catch (System.ServiceProcess.TimeoutException)\n {\n continue;\n }\n catch (InvalidOperationException ex)\n {\n Logger.WriteLine(\"Warning: Stopping sppsvc failed, retrying. Details: \" + ex.Message);\n System.Threading.Thread.Sleep(500);\n continue;\n }\n\n stopped = true;\n }\n\n if (!stopped)\n throw new System.TimeoutException(string.Format(\"Failed to stop {0}\", svcName));\n\n Logger.WriteLine(string.Format(\"{0} stopped successfully.\", svcName));\n\n if (version == PSVersion.Vista && SPSys.IsSpSysRunning())\n {\n Logger.WriteLine(\"Unloading spsys...\");\n\n int status = SPSys.ControlSpSys(false);\n\n if (status < 0)\n {\n throw new IOException(\"Failed to unload spsys\");\n }\n\n Logger.WriteLine(\"spsys unloaded successfully.\");\n }\n }\n\n public static void RestartSPP(PSVersion version)\n {\n if (version == PSVersion.Vista)\n {\n ServiceController sc;\n\n try\n {\n sc = new ServiceController(\"slsvc\");\n\n if (sc.Status == ServiceControllerStatus.Running)\n return;\n }\n catch (InvalidOperationException ex)\n {\n throw new InvalidOperationException(\"Unable to access slsvc: \" + ex.Message);\n }\n\n Logger.WriteLine(\"Starting slsvc...\");\n\n bool started = false;\n\n for (int i = 0; started == false && i < 360; i++)\n {\n try\n {\n if (sc.Status != ServiceControllerStatus.StartPending)\n sc.Start();\n\n sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMilliseconds(500));\n }\n catch (System.ServiceProcess.TimeoutException)\n {\n continue;\n }\n catch (InvalidOperationException ex)\n {\n Logger.WriteLine(\"Warning: Starting slsvc failed, retrying. Details: \" + ex.Message);\n System.Threading.Thread.Sleep(500);\n continue;\n }\n\n started = true;\n }\n\n if (!started)\n throw new System.TimeoutException(\"Failed to start slsvc\");\n\n Logger.WriteLine(\"slsvc started successfully.\");\n }\n\n SLApi.RefreshLicenseStatus();\n }\n\n public static bool DetectCurrentKey()\n {\n SLApi.RefreshLicenseStatus();\n\n using (RegistryKey wpaKey = Registry.LocalMachine.OpenSubKey(@\"SYSTEM\\WPA\"))\n {\n foreach (string subKey in wpaKey.GetSubKeyNames())\n {\n if (subKey.StartsWith(\"8DEC0AF1\"))\n {\n return subKey.Contains(\"P\");\n }\n }\n }\n\n throw new FileNotFoundException(\"Failed to autodetect key type, specify physical store key with /prod or /test arguments.\");\n }\n\n public static string GetPSPath(PSVersion version)\n {\n switch (version)\n {\n case PSVersion.Vista:\n case PSVersion.Win7:\n return Directory.GetFiles(\n Environment.GetFolderPath(Environment.SpecialFolder.System),\n \"7B296FB0-376B-497e-B012-9C450E1B7327-*.C7483456-A289-439d-8115-601632D005A0\")\n .FirstOrDefault() ?? \"\";\n default:\n string psDir = Environment.ExpandEnvironmentVariables(\n (string)Registry.GetValue(\n @\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform\",\n \"TokenStore\",\n \"\"\n )\n );\n string psPath = Path.Combine(psDir, \"data.dat\");\n\n if (string.IsNullOrEmpty(psDir) || !File.Exists(psPath))\n {\n string[] psDirs =\n {\n @\"spp\\store\",\n @\"spp\\store\\2.0\",\n @\"spp\\store_test\",\n @\"spp\\store_test\\2.0\"\n };\n\n foreach (string dir in psDirs)\n {\n psPath = Path.Combine(\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.System),\n dir\n ),\n \"data.dat\"\n );\n\n if (File.Exists(psPath)) return psPath;\n }\n } \n else\n {\n return psPath;\n }\n\n throw new FileNotFoundException(\"Failed to locate physical store.\");\n }\n }\n\n public static string GetTokensPath(PSVersion version)\n {\n switch (version)\n {\n case PSVersion.Vista:\n return Path.Combine(\n Environment.ExpandEnvironmentVariables(\"%WINDIR%\"),\n @\"ServiceProfiles\\NetworkService\\AppData\\Roaming\\Microsoft\\SoftwareLicensing\\tokens.dat\"\n );\n case PSVersion.Win7:\n return Path.Combine(\n Environment.ExpandEnvironmentVariables(\"%WINDIR%\"),\n @\"ServiceProfiles\\NetworkService\\AppData\\Roaming\\Microsoft\\SoftwareProtectionPlatform\\tokens.dat\"\n );\n default:\n string tokDir = Environment.ExpandEnvironmentVariables(\n (string)Registry.GetValue(\n @\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform\",\n \"TokenStore\",\n \"\"\n )\n );\n string tokPath = Path.Combine(tokDir, \"tokens.dat\");\n\n if (string.IsNullOrEmpty(tokDir) || !File.Exists(tokPath))\n {\n string[] tokDirs =\n {\n @\"spp\\store\",\n @\"spp\\store\\2.0\",\n @\"spp\\store_test\",\n @\"spp\\store_test\\2.0\"\n };\n\n foreach (string dir in tokDirs)\n {\n tokPath = Path.Combine(\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.System),\n dir\n ),\n \"tokens.dat\"\n );\n\n if (File.Exists(tokPath)) return tokPath;\n }\n }\n else\n {\n return tokPath;\n }\n\n throw new FileNotFoundException(\"Failed to locate token store.\");\n }\n }\n\n public static IPhysicalStore GetStore(PSVersion version, bool production)\n {\n string psPath = GetPSPath(version);\n\n switch (version)\n {\n case PSVersion.Vista:\n return new PhysicalStoreVista(psPath, production);\n case PSVersion.Win7:\n return new PhysicalStoreWin7(psPath, production);\n default:\n return new PhysicalStoreModern(psPath, production, version);\n }\n }\n\n public static ITokenStore GetTokenStore(PSVersion version)\n {\n string tokPath = GetTokensPath(version);\n\n return new TokenStoreModern(tokPath);\n }\n\n public static void DumpStore(PSVersion version, bool production, string filePath, string encrFilePath)\n {\n bool manageSpp = false;\n\n if (encrFilePath == null)\n {\n encrFilePath = GetPSPath(version);\n manageSpp = true;\n KillSPP(version);\n }\n\n if (string.IsNullOrEmpty(encrFilePath) || !File.Exists(encrFilePath))\n {\n throw new FileNotFoundException(\"Store does not exist at expected path '\" + encrFilePath + \"'.\");\n }\n\n try\n {\n using (FileStream fs = File.Open(encrFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))\n {\n byte[] encrData = fs.ReadAllBytes();\n File.WriteAllBytes(filePath, PhysStoreCrypto.DecryptPhysicalStore(encrData, production, version));\n }\n Logger.WriteLine(\"Store dumped successfully to '\" + filePath + \"'.\");\n }\n finally\n {\n if (manageSpp)\n {\n RestartSPP(version);\n }\n }\n }\n\n public static void LoadStore(PSVersion version, bool production, string filePath)\n {\n if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))\n {\n throw new FileNotFoundException(\"Store file '\" + filePath + \"' does not exist.\");\n }\n\n KillSPP(version);\n\n using (IPhysicalStore store = GetStore(version, production))\n {\n store.WriteRaw(File.ReadAllBytes(filePath));\n }\n\n RestartSPP(version);\n\n Logger.WriteLine(\"Loaded store file successfully.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/PhysicalStoreModern.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using Crypto;\n\n public class ModernBlock\n {\n public BlockType Type;\n public uint Flags;\n public uint Unknown;\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n public byte[] Data;\n public string DataAsStr\n {\n get\n {\n return Utils.DecodeString(Data);\n }\n set\n {\n Data = Utils.EncodeString(value);\n }\n }\n public uint DataAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Data, 0);\n }\n set\n {\n Data = BitConverter.GetBytes(value);\n }\n }\n\n public void Encode(BinaryWriter writer)\n {\n writer.Write((uint)Type);\n writer.Write(Flags);\n writer.Write((uint)Value.Length);\n writer.Write((uint)Data.Length);\n writer.Write(Unknown);\n writer.Write(Value);\n writer.Write(Data);\n }\n\n public static ModernBlock Decode(BinaryReader reader)\n {\n uint type = reader.ReadUInt32();\n uint flags = reader.ReadUInt32();\n\n uint valueLen = reader.ReadUInt32();\n uint dataLen = reader.ReadUInt32();\n uint unk3 = reader.ReadUInt32();\n\n byte[] value = reader.ReadBytes((int)valueLen);\n byte[] data = reader.ReadBytes((int)dataLen);\n\n return new ModernBlock\n {\n Type = (BlockType)type,\n Flags = flags,\n Unknown = unk3,\n Value = value,\n Data = data,\n };\n }\n }\n\n public sealed class PhysicalStoreModern : IPhysicalStore\n {\n private byte[] PreHeaderBytes = { };\n private readonly Dictionary> Data = new Dictionary>();\n private readonly FileStream TSFile;\n private readonly PSVersion Version;\n private readonly bool Production;\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(PreHeaderBytes);\n writer.Write(Data.Keys.Count);\n\n foreach (string key in Data.Keys)\n {\n List blocks = Data[key];\n byte[] keyNameEnc = Utils.EncodeString(key);\n\n writer.Write(keyNameEnc.Length);\n writer.Write(keyNameEnc);\n writer.Write(blocks.Count);\n writer.Align(4);\n\n foreach (ModernBlock block in blocks)\n {\n block.Encode(writer);\n writer.Align(4);\n }\n }\n\n return writer.GetBytes();\n }\n\n public void Deserialize(byte[] data)\n {\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n PreHeaderBytes = reader.ReadBytes(8);\n\n while (reader.BaseStream.Position < data.Length - 0x4)\n {\n uint numKeys = reader.ReadUInt32();\n\n for (int i = 0; i < numKeys; i++)\n {\n uint lenKeyName = reader.ReadUInt32();\n string keyName = Utils.DecodeString(reader.ReadBytes((int)lenKeyName)); uint numValues = reader.ReadUInt32();\n\n reader.Align(4);\n\n Data[keyName] = new List();\n\n for (int j = 0; j < numValues; j++)\n {\n Data[keyName].Add(ModernBlock.Decode(reader));\n reader.Align(4);\n }\n }\n }\n }\n\n public void AddBlock(PSBlock block)\n {\n if (!Data.ContainsKey(block.KeyAsStr))\n {\n Data[block.KeyAsStr] = new List();\n }\n\n Data[block.KeyAsStr].Add(new ModernBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Unknown = block.Unknown,\n Value = block.Value,\n Data = block.Data\n });\n }\n\n public void AddBlocks(IEnumerable blocks)\n {\n foreach (PSBlock block in blocks)\n {\n AddBlock(block);\n }\n }\n\n public PSBlock GetBlock(string key, string value)\n {\n List blocks = Data[key];\n\n foreach (ModernBlock block in blocks)\n {\n if (block.ValueAsStr == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = Utils.EncodeString(key),\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public PSBlock GetBlock(string key, uint value)\n {\n List blocks = Data[key];\n\n foreach (ModernBlock block in blocks)\n {\n if (block.ValueAsInt == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = Utils.EncodeString(key),\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public void SetBlock(string key, string value, byte[] data)\n {\n List blocks = Data[key];\n\n for (int i = 0; i < blocks.Count; i++)\n {\n ModernBlock block = blocks[i];\n\n if (block.ValueAsStr == value)\n {\n block.Data = data;\n blocks[i] = block;\n break;\n }\n }\n\n Data[key] = blocks;\n }\n\n public void SetBlock(string key, uint value, byte[] data)\n {\n List blocks = Data[key];\n\n for (int i = 0; i < blocks.Count; i++)\n {\n ModernBlock block = blocks[i];\n\n if (block.ValueAsInt == value)\n {\n block.Data = data;\n blocks[i] = block;\n break;\n }\n }\n\n Data[key] = blocks;\n }\n\n public void SetBlock(string key, string value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, string value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void SetBlock(string key, uint value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, uint value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void DeleteBlock(string key, string value)\n {\n if (!Data.ContainsKey(key))\n {\n return;\n }\n\n List blocks = Data[key];\n\n foreach (ModernBlock block in blocks)\n {\n if (block.ValueAsStr == value)\n {\n blocks.Remove(block);\n break;\n }\n }\n\n Data[key] = blocks;\n }\n\n public void DeleteBlock(string key, uint value)\n {\n if (!Data.ContainsKey(key))\n {\n return;\n }\n\n List blocks = Data[key];\n\n foreach (ModernBlock block in blocks)\n {\n if (block.ValueAsInt == value)\n {\n blocks.Remove(block);\n break;\n }\n }\n\n Data[key] = blocks;\n }\n\n public PhysicalStoreModern(string tsPath, bool production, PSVersion version)\n {\n TSFile = File.Open(tsPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n Deserialize(PhysStoreCrypto.DecryptPhysicalStore(TSFile.ReadAllBytes(), production, version));\n TSFile.Seek(0, SeekOrigin.Begin);\n Version = version;\n Production = production;\n }\n\n public void Dispose()\n {\n if (TSFile.CanWrite)\n {\n byte[] data = PhysStoreCrypto.EncryptPhysicalStore(Serialize(), Production, Version);\n TSFile.SetLength(data.LongLength);\n TSFile.Seek(0, SeekOrigin.Begin);\n TSFile.WriteAllBytes(data);\n TSFile.Close();\n }\n }\n\n public byte[] ReadRaw()\n {\n byte[] data = PhysStoreCrypto.DecryptPhysicalStore(TSFile.ReadAllBytes(), Production, Version);\n TSFile.Seek(0, SeekOrigin.Begin);\n return data;\n }\n\n public void WriteRaw(byte[] data)\n {\n byte[] encrData = PhysStoreCrypto.EncryptPhysicalStore(data, Production, Version);\n TSFile.SetLength(encrData.LongLength);\n TSFile.Seek(0, SeekOrigin.Begin);\n TSFile.WriteAllBytes(encrData);\n TSFile.Close();\n }\n\n public IEnumerable FindBlocks(string valueSearch)\n {\n List results = new List();\n\n foreach (string key in Data.Keys)\n {\n List values = Data[key];\n\n foreach (ModernBlock block in values)\n {\n if (block.ValueAsStr.Contains(valueSearch))\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n KeyAsStr = key,\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n }\n\n return results;\n }\n\n public IEnumerable FindBlocks(uint valueSearch)\n {\n List results = new List();\n\n foreach (string key in Data.Keys)\n {\n List values = Data[key];\n\n foreach (ModernBlock block in values)\n {\n if (block.ValueAsInt == valueSearch)\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n KeyAsStr = key,\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n }\n\n return results;\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/PhysicalStoreWin7.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using Crypto;\n\n public class Win7Block\n {\n public BlockType Type;\n public uint Flags;\n public byte[] Key;\n public string KeyAsStr\n {\n get\n {\n return Utils.DecodeString(Key);\n }\n set\n {\n Key = Utils.EncodeString(value);\n }\n }\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n public byte[] Data;\n public string DataAsStr\n {\n get\n {\n return Utils.DecodeString(Data);\n }\n set\n {\n Data = Utils.EncodeString(value);\n }\n }\n public uint DataAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Data, 0);\n }\n set\n {\n Data = BitConverter.GetBytes(value);\n }\n }\n\n internal void Encode(BinaryWriter writer)\n {\n writer.Write((uint)Type);\n writer.Write(Flags);\n writer.Write(Key.Length);\n writer.Write(Value.Length);\n writer.Write(Data.Length);\n writer.Write(Key);\n writer.Write(Value);\n writer.Write(Data);\n }\n\n internal static Win7Block Decode(BinaryReader reader)\n {\n uint type = reader.ReadUInt32();\n uint flags = reader.ReadUInt32();\n\n int keyLen = reader.ReadInt32();\n int valueLen = reader.ReadInt32();\n int dataLen = reader.ReadInt32();\n\n byte[] key = reader.ReadBytes(keyLen);\n byte[] value = reader.ReadBytes(valueLen);\n byte[] data = reader.ReadBytes(dataLen);\n return new Win7Block\n {\n Type = (BlockType)type,\n Flags = flags,\n Key = key,\n Value = value,\n Data = data,\n };\n }\n }\n\n public sealed class PhysicalStoreWin7 : IPhysicalStore\n {\n private byte[] PreHeaderBytes = { };\n private readonly List Blocks = new List();\n private readonly FileStream TSPrimary;\n private readonly FileStream TSSecondary;\n private readonly bool Production;\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(PreHeaderBytes);\n\n foreach (Win7Block block in Blocks)\n {\n block.Encode(writer);\n writer.Align(4);\n }\n\n return writer.GetBytes();\n }\n\n public void Deserialize(byte[] data)\n {\n int len = data.Length;\n\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n PreHeaderBytes = reader.ReadBytes(8);\n\n while (reader.BaseStream.Position < len - 0x14)\n {\n Blocks.Add(Win7Block.Decode(reader));\n reader.Align(4);\n }\n }\n\n public void AddBlock(PSBlock block)\n {\n Blocks.Add(new Win7Block\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n });\n }\n\n public void AddBlocks(IEnumerable blocks)\n {\n foreach (PSBlock block in blocks)\n {\n AddBlock(block);\n }\n }\n\n public PSBlock GetBlock(string key, string value)\n {\n foreach (Win7Block block in Blocks)\n {\n if (block.KeyAsStr == key && block.ValueAsStr == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public PSBlock GetBlock(string key, uint value)\n {\n foreach (Win7Block block in Blocks)\n {\n if (block.KeyAsStr == key && block.ValueAsInt == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public void SetBlock(string key, string value, byte[] data)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n Win7Block block = Blocks[i];\n\n if (block.KeyAsStr == key && block.ValueAsStr == value)\n {\n block.Data = data;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void SetBlock(string key, uint value, byte[] data)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n Win7Block block = Blocks[i];\n\n if (block.KeyAsStr == key && block.ValueAsInt == value)\n {\n block.Data = data;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void SetBlock(string key, string value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, string value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void SetBlock(string key, uint value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, uint value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void DeleteBlock(string key, string value)\n {\n foreach (Win7Block block in Blocks)\n {\n if (block.KeyAsStr == key && block.ValueAsStr == value)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public void DeleteBlock(string key, uint value)\n {\n foreach (Win7Block block in Blocks)\n {\n if (block.KeyAsStr == key && block.ValueAsInt == value)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public PhysicalStoreWin7(string primaryPath, bool production)\n {\n TSPrimary = File.Open(primaryPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n TSSecondary = File.Open(primaryPath.Replace(\"-0.\", \"-1.\"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n Production = production;\n\n Deserialize(PhysStoreCrypto.DecryptPhysicalStore(TSPrimary.ReadAllBytes(), production, PSVersion.Win7));\n TSPrimary.Seek(0, SeekOrigin.Begin);\n }\n\n public void Dispose()\n {\n if (TSPrimary.CanWrite && TSSecondary.CanWrite)\n {\n byte[] data = PhysStoreCrypto.EncryptPhysicalStore(Serialize(), Production, PSVersion.Win7);\n\n TSPrimary.SetLength(data.LongLength);\n TSSecondary.SetLength(data.LongLength);\n\n TSPrimary.Seek(0, SeekOrigin.Begin);\n TSSecondary.Seek(0, SeekOrigin.Begin);\n\n TSPrimary.WriteAllBytes(data);\n TSSecondary.WriteAllBytes(data);\n\n TSPrimary.Close();\n TSSecondary.Close();\n }\n }\n\n public byte[] ReadRaw()\n {\n byte[] data = PhysStoreCrypto.DecryptPhysicalStore(TSPrimary.ReadAllBytes(), Production, PSVersion.Win7);\n TSPrimary.Seek(0, SeekOrigin.Begin);\n return data;\n }\n\n public void WriteRaw(byte[] data)\n {\n byte[] encrData = PhysStoreCrypto.EncryptPhysicalStore(data, Production, PSVersion.Win7);\n\n TSPrimary.SetLength(encrData.LongLength);\n TSSecondary.SetLength(encrData.LongLength);\n\n TSPrimary.Seek(0, SeekOrigin.Begin);\n TSSecondary.Seek(0, SeekOrigin.Begin);\n\n TSPrimary.WriteAllBytes(encrData);\n TSSecondary.WriteAllBytes(encrData);\n\n TSPrimary.Close();\n TSSecondary.Close();\n }\n\n public IEnumerable FindBlocks(string valueSearch)\n {\n List results = new List();\n\n foreach (Win7Block block in Blocks)\n {\n if (block.ValueAsStr.Contains(valueSearch))\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n\n return results;\n }\n\n public IEnumerable FindBlocks(uint valueSearch)\n {\n List results = new List();\n\n foreach (Win7Block block in Blocks)\n {\n if (block.ValueAsInt == valueSearch)\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n\n return results;\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/PhysicalStoreVista.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using Crypto;\n\n public class VistaBlock\n {\n public BlockType Type;\n public uint Flags;\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n public byte[] Data;\n public string DataAsStr\n {\n get\n {\n return Utils.DecodeString(Data);\n }\n set\n {\n Data = Utils.EncodeString(value);\n }\n }\n public uint DataAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Data, 0);\n }\n set\n {\n Data = BitConverter.GetBytes(value);\n }\n }\n\n internal void Encode(BinaryWriter writer)\n {\n writer.Write((uint)Type);\n writer.Write(Flags);\n writer.Write(Value.Length);\n writer.Write(Data.Length);\n writer.Write(Value);\n writer.Write(Data);\n }\n\n internal static VistaBlock Decode(BinaryReader reader)\n {\n uint type = reader.ReadUInt32();\n uint flags = reader.ReadUInt32();\n\n int valueLen = reader.ReadInt32();\n int dataLen = reader.ReadInt32();\n\n byte[] value = reader.ReadBytes(valueLen);\n byte[] data = reader.ReadBytes(dataLen);\n return new VistaBlock\n {\n Type = (BlockType)type,\n Flags = flags,\n Value = value,\n Data = data,\n };\n }\n }\n\n public sealed class PhysicalStoreVista : IPhysicalStore\n {\n private byte[] PreHeaderBytes = { };\n private readonly List Blocks = new List();\n private readonly FileStream TSPrimary;\n private readonly FileStream TSSecondary;\n private readonly bool Production;\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(PreHeaderBytes);\n\n foreach (VistaBlock block in Blocks)\n {\n block.Encode(writer);\n writer.Align(4);\n }\n\n return writer.GetBytes();\n }\n\n public void Deserialize(byte[] data)\n {\n int len = data.Length;\n\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n PreHeaderBytes = reader.ReadBytes(8);\n\n while (reader.BaseStream.Position < len - 0x14)\n {\n Blocks.Add(VistaBlock.Decode(reader));\n reader.Align(4);\n }\n }\n\n public void AddBlock(PSBlock block)\n {\n Blocks.Add(new VistaBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Value = block.Value,\n Data = block.Data\n });\n }\n\n public void AddBlocks(IEnumerable blocks)\n {\n foreach (PSBlock block in blocks)\n {\n AddBlock(block);\n }\n }\n\n public PSBlock GetBlock(string key, string value)\n {\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsStr == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = new byte[0],\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public PSBlock GetBlock(string key, uint value)\n {\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsInt == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = new byte[0],\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public void SetBlock(string key, string value, byte[] data)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n VistaBlock block = Blocks[i];\n\n if (block.ValueAsStr == value)\n {\n block.Data = data;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void SetBlock(string key, uint value, byte[] data)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n VistaBlock block = Blocks[i];\n\n if (block.ValueAsInt == value)\n {\n block.Data = data;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void SetBlock(string key, string value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, string value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void SetBlock(string key, uint value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, uint value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void DeleteBlock(string key, string value)\n {\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsStr == value)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public void DeleteBlock(string key, uint value)\n {\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsInt == value)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public PhysicalStoreVista(string primaryPath, bool production)\n {\n TSPrimary = File.Open(primaryPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n TSSecondary = File.Open(primaryPath.Replace(\"-0.\", \"-1.\"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n Production = production;\n\n Deserialize(PhysStoreCrypto.DecryptPhysicalStore(TSPrimary.ReadAllBytes(), production, PSVersion.Vista));\n TSPrimary.Seek(0, SeekOrigin.Begin);\n }\n\n public void Dispose()\n {\n if (TSPrimary.CanWrite && TSSecondary.CanWrite)\n {\n byte[] data = PhysStoreCrypto.EncryptPhysicalStore(Serialize(), Production, PSVersion.Vista);\n\n TSPrimary.SetLength(data.LongLength);\n TSSecondary.SetLength(data.LongLength);\n\n TSPrimary.Seek(0, SeekOrigin.Begin);\n TSSecondary.Seek(0, SeekOrigin.Begin);\n\n TSPrimary.WriteAllBytes(data);\n TSSecondary.WriteAllBytes(data);\n\n TSPrimary.Close();\n TSSecondary.Close();\n }\n }\n\n public byte[] ReadRaw()\n {\n byte[] data = PhysStoreCrypto.DecryptPhysicalStore(TSPrimary.ReadAllBytes(), Production, PSVersion.Vista);\n TSPrimary.Seek(0, SeekOrigin.Begin);\n return data;\n }\n\n public void WriteRaw(byte[] data)\n {\n byte[] encrData = PhysStoreCrypto.EncryptPhysicalStore(data, Production, PSVersion.Vista);\n\n TSPrimary.SetLength(encrData.LongLength);\n TSSecondary.SetLength(encrData.LongLength);\n\n TSPrimary.Seek(0, SeekOrigin.Begin);\n TSSecondary.Seek(0, SeekOrigin.Begin);\n\n TSPrimary.WriteAllBytes(encrData);\n TSSecondary.WriteAllBytes(encrData);\n\n TSPrimary.Close();\n TSSecondary.Close();\n }\n\n public IEnumerable FindBlocks(string valueSearch)\n {\n List results = new List();\n\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsStr.Contains(valueSearch))\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = new byte[0],\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n\n return results;\n }\n\n public IEnumerable FindBlocks(uint valueSearch)\n {\n List results = new List();\n\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsInt == valueSearch)\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = new byte[0],\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n\n return results;\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/VariableBag.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n\n public enum CRCBlockType : uint\n {\n UINT = 1 << 0,\n STRING = 1 << 1,\n BINARY = 1 << 2\n }\n\n public abstract class CRCBlock\n {\n public CRCBlockType DataType;\n public byte[] Key;\n public string KeyAsStr\n {\n get\n {\n return Utils.DecodeString(Key);\n }\n set\n {\n Key = Utils.EncodeString(value);\n }\n }\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n\n public abstract void Encode(BinaryWriter writer);\n public abstract void Decode(BinaryReader reader);\n public abstract uint CRC();\n }\n\n public class CRCBlockVista : CRCBlock\n {\n public override void Encode(BinaryWriter writer)\n {\n uint crc = CRC();\n writer.Write((uint)DataType);\n writer.Write(0);\n writer.Write(Key.Length);\n writer.Write(Value.Length);\n writer.Write(crc);\n\n writer.Write(Key);\n\n writer.Write(Value);\n }\n\n public override void Decode(BinaryReader reader)\n {\n uint type = reader.ReadUInt32();\n reader.ReadUInt32();\n uint lenName = reader.ReadUInt32();\n uint lenVal = reader.ReadUInt32();\n uint crc = reader.ReadUInt32();\n\n byte[] key = reader.ReadBytes((int)lenName);\n byte[] value = reader.ReadBytes((int)lenVal);\n\n DataType = (CRCBlockType)type;\n Key = key;\n Value = value;\n\n if (CRC() != crc)\n {\n throw new InvalidDataException(\"Invalid CRC in variable bag.\");\n }\n }\n\n public override uint CRC()\n {\n return Utils.CRC32(Value);\n }\n }\n\n public class CRCBlockModern : CRCBlock\n {\n public override void Encode(BinaryWriter writer)\n {\n uint crc = CRC();\n writer.Write(crc);\n writer.Write((uint)DataType);\n writer.Write(Key.Length);\n writer.Write(Value.Length);\n\n writer.Write(Key);\n writer.Align(8);\n\n writer.Write(Value);\n writer.Align(8);\n }\n\n public override void Decode(BinaryReader reader)\n {\n uint crc = reader.ReadUInt32();\n uint type = reader.ReadUInt32();\n uint lenName = reader.ReadUInt32();\n uint lenVal = reader.ReadUInt32();\n\n byte[] key = reader.ReadBytes((int)lenName);\n reader.Align(8);\n\n byte[] value = reader.ReadBytes((int)lenVal);\n reader.Align(8);\n\n DataType = (CRCBlockType)type;\n Key = key;\n Value = value;\n\n if (CRC() != crc)\n {\n throw new InvalidDataException(\"Invalid CRC in variable bag.\");\n }\n }\n\n public override uint CRC()\n {\n BinaryWriter wtemp = new BinaryWriter(new MemoryStream());\n wtemp.Write(0);\n wtemp.Write((uint)DataType);\n wtemp.Write(Key.Length);\n wtemp.Write(Value.Length);\n wtemp.Write(Key);\n wtemp.Write(Value);\n return Utils.CRC32(wtemp.GetBytes());\n }\n }\n\n public class VariableBag\n {\n public List Blocks = new List();\n private readonly PSVersion Version;\n\n private void Deserialize(byte[] data)\n {\n int len = data.Length;\n\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n\n while (reader.BaseStream.Position < len - 0x10)\n {\n CRCBlock block;\n\n if (Version == PSVersion.Vista)\n {\n block = new CRCBlockVista();\n }\n else\n {\n block = new CRCBlockModern();\n }\n\n block.Decode(reader);\n Blocks.Add(block);\n }\n }\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n\n foreach (CRCBlock block in Blocks)\n {\n if (Version == PSVersion.Vista)\n {\n ((CRCBlockVista)block).Encode(writer);\n } else\n {\n ((CRCBlockModern)block).Encode(writer);\n }\n }\n\n return writer.GetBytes();\n }\n\n public CRCBlock GetBlock(string key)\n {\n foreach (CRCBlock block in Blocks)\n {\n if (block.KeyAsStr == key)\n {\n return block;\n }\n }\n\n return null;\n }\n\n public void SetBlock(string key, byte[] value)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n CRCBlock block = Blocks[i];\n\n if (block.KeyAsStr == key)\n {\n block.Value = value;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void DeleteBlock(string key)\n {\n foreach (CRCBlock block in Blocks)\n {\n if (block.KeyAsStr == key)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public VariableBag(byte[] data, PSVersion version)\n {\n Version = version;\n Deserialize(data);\n }\n\n public VariableBag(PSVersion version)\n {\n Version = version;\n }\n }\n}\n"], ["/TSforge/LibTSforge/Crypto/PhysStoreCrypto.cs", "namespace LibTSforge.Crypto\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using System.Linq;\n using System.Text;\n\n public static class PhysStoreCrypto\n {\n public static byte[] DecryptPhysicalStore(byte[] data, bool production, PSVersion version)\n {\n byte[] rsaKey = production ? Keys.PRODUCTION : Keys.TEST;\n BinaryReader br = new BinaryReader(new MemoryStream(data));\n br.BaseStream.Seek(0x10, SeekOrigin.Begin);\n byte[] aesKeySig = br.ReadBytes(0x80);\n byte[] encAesKey = br.ReadBytes(0x80);\n\n if (!CryptoUtils.RSAVerifySignature(rsaKey, encAesKey, aesKeySig))\n {\n throw new Exception(\"Failed to decrypt physical store.\");\n }\n\n byte[] aesKey = CryptoUtils.RSADecrypt(rsaKey, encAesKey);\n byte[] decData = CryptoUtils.AESDecrypt(br.ReadBytes((int)br.BaseStream.Length - 0x110), aesKey);\n byte[] hmacKey = decData.Take(0x10).ToArray(); // SHA-1 salt on Vista\n byte[] hmacSig = decData.Skip(0x10).Take(0x14).ToArray(); // SHA-1 hash on Vista\n byte[] psData = decData.Skip(0x28).ToArray();\n\n if (version != PSVersion.Vista)\n {\n if (!CryptoUtils.HMACVerify(hmacKey, psData, hmacSig))\n {\n throw new InvalidDataException(\"Failed to verify HMAC. Physical store is corrupt.\");\n }\n }\n else\n {\n if (!CryptoUtils.SaltSHAVerify(hmacKey, psData, hmacSig))\n {\n throw new InvalidDataException(\"Failed to verify checksum. Physical store is corrupt.\");\n }\n }\n\n return psData;\n }\n\n public static byte[] EncryptPhysicalStore(byte[] data, bool production, PSVersion version)\n {\n Dictionary versionTable = new Dictionary\n {\n {PSVersion.Vista, 2},\n {PSVersion.Win7, 5},\n {PSVersion.Win8, 1},\n {PSVersion.WinBlue, 2},\n {PSVersion.WinModern, 3}\n };\n\n byte[] rsaKey = production ? Keys.PRODUCTION : Keys.TEST;\n\n byte[] aesKey = Encoding.UTF8.GetBytes(\"massgrave.dev :3\");\n byte[] hmacKey = CryptoUtils.GenerateRandomKey(0x10);\n\n byte[] encAesKey = CryptoUtils.RSAEncrypt(rsaKey, aesKey);\n byte[] aesKeySig = CryptoUtils.RSASign(rsaKey, encAesKey);\n byte[] hmacSig = version != PSVersion.Vista ? CryptoUtils.HMACSign(hmacKey, data) : CryptoUtils.SaltSHASum(hmacKey, data);\n\n byte[] decData = { };\n decData = decData.Concat(hmacKey).Concat(hmacSig).Concat(BitConverter.GetBytes(0)).Concat(data).ToArray();\n byte[] encData = CryptoUtils.AESEncrypt(decData, aesKey);\n\n BinaryWriter bw = new BinaryWriter(new MemoryStream());\n bw.Write(versionTable[version]);\n bw.Write(Encoding.UTF8.GetBytes(\"UNTRUSTSTORE\"));\n bw.Write(aesKeySig);\n bw.Write(encAesKey);\n bw.Write(encData);\n\n return bw.GetBytes();\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/IPhysicalStore.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n\n public class PSBlock\n {\n public BlockType Type;\n public uint Flags;\n public uint Unknown = 0;\n public byte[] Key;\n public string KeyAsStr\n {\n get\n {\n return Utils.DecodeString(Key);\n }\n set\n {\n Key = Utils.EncodeString(value);\n }\n }\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n public byte[] Data;\n public string DataAsStr\n {\n get\n {\n return Utils.DecodeString(Data);\n }\n set\n {\n Data = Utils.EncodeString(value);\n }\n }\n public uint DataAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Data, 0);\n }\n set\n {\n Data = BitConverter.GetBytes(value);\n }\n }\n }\n\n public interface IPhysicalStore : IDisposable\n {\n PSBlock GetBlock(string key, string value);\n PSBlock GetBlock(string key, uint value);\n void AddBlock(PSBlock block);\n void AddBlocks(IEnumerable blocks);\n void SetBlock(string key, string value, byte[] data);\n void SetBlock(string key, string value, string data);\n void SetBlock(string key, string value, uint data);\n void SetBlock(string key, uint value, byte[] data);\n void SetBlock(string key, uint value, string data);\n void SetBlock(string key, uint value, uint data);\n void DeleteBlock(string key, string value);\n void DeleteBlock(string key, uint value);\n byte[] Serialize();\n void Deserialize(byte[] data);\n byte[] ReadRaw();\n void WriteRaw(byte[] data);\n IEnumerable FindBlocks(string valueSearch);\n IEnumerable FindBlocks(uint valueSearch);\n }\n}\n"], ["/TSforge/LibTSforge/SPP/PKeyConfig.cs", "namespace LibTSforge.SPP\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using System.Linq;\n using System.Text;\n using System.Xml;\n\n public enum PKeyAlgorithm\n {\n PKEY2005,\n PKEY2009\n }\n\n public class KeyRange\n {\n public int Start;\n public int End;\n public string EulaType;\n public string PartNumber;\n public bool Valid;\n\n public bool Contains(int n)\n {\n return Start <= n && End <= n;\n }\n }\n\n public class ProductConfig\n {\n public int GroupId;\n public string Edition;\n public string Description;\n public string Channel;\n public bool Randomized;\n public PKeyAlgorithm Algorithm;\n public List Ranges;\n public Guid ActivationId;\n\n private List GetPkeyRanges()\n {\n if (Ranges.Count == 0)\n {\n throw new ArgumentException(\"No key ranges.\");\n }\n\n if (Algorithm == PKeyAlgorithm.PKEY2005)\n {\n return Ranges;\n }\n\n List FilteredRanges = Ranges.Where(r => !r.EulaType.Contains(\"WAU\")).ToList();\n\n if (FilteredRanges.Count == 0)\n {\n throw new NotSupportedException(\"Specified Activation ID is usable only for Windows Anytime Upgrade. Please use a non-WAU Activation ID instead.\");\n }\n\n return FilteredRanges;\n }\n\n public ProductKey GetRandomKey()\n {\n List KeyRanges = GetPkeyRanges();\n Random rnd = new Random();\n\n KeyRange range = KeyRanges[rnd.Next(KeyRanges.Count)];\n int serial = rnd.Next(range.Start, range.End);\n\n return new ProductKey(serial, 0, false, Algorithm, this, range);\n }\n }\n\n public class PKeyConfig\n {\n public readonly Dictionary Products = new Dictionary();\n private readonly List loadedPkeyConfigs = new List();\n\n public void LoadConfig(Guid actId)\n {\n string pkcData;\n Guid pkcFileId = SLApi.GetPkeyConfigFileId(actId);\n\n if (loadedPkeyConfigs.Contains(pkcFileId)) return;\n\n string licConts = SLApi.GetLicenseContents(pkcFileId);\n\n using (TextReader tr = new StringReader(licConts))\n {\n XmlDocument lic = new XmlDocument();\n lic.Load(tr);\n\n XmlNamespaceManager nsmgr = new XmlNamespaceManager(lic.NameTable);\n nsmgr.AddNamespace(\"rg\", \"urn:mpeg:mpeg21:2003:01-REL-R-NS\");\n nsmgr.AddNamespace(\"r\", \"urn:mpeg:mpeg21:2003:01-REL-R-NS\");\n nsmgr.AddNamespace(\"tm\", \"http://www.microsoft.com/DRM/XrML2/TM/v2\");\n\n XmlNode root = lic.DocumentElement;\n XmlNode pkcDataNode = root.SelectSingleNode(\"/rg:licenseGroup/r:license/r:otherInfo/tm:infoTables/tm:infoList/tm:infoBin[@name=\\\"pkeyConfigData\\\"]\", nsmgr);\n pkcData = Encoding.UTF8.GetString(Convert.FromBase64String(pkcDataNode.InnerText));\n }\n\n using (TextReader tr = new StringReader(pkcData))\n {\n XmlDocument lic = new XmlDocument();\n lic.Load(tr);\n\n XmlNamespaceManager nsmgr = new XmlNamespaceManager(lic.NameTable);\n nsmgr.AddNamespace(\"p\", \"http://www.microsoft.com/DRM/PKEY/Configuration/2.0\");\n XmlNodeList configNodes = lic.SelectNodes(\"//p:ProductKeyConfiguration/p:Configurations/p:Configuration\", nsmgr);\n XmlNodeList rangeNodes = lic.SelectNodes(\"//p:ProductKeyConfiguration/p:KeyRanges/p:KeyRange\", nsmgr);\n XmlNodeList pubKeyNodes = lic.SelectNodes(\"//p:ProductKeyConfiguration/p:PublicKeys/p:PublicKey\", nsmgr);\n\n Dictionary algorithms = new Dictionary();\n Dictionary> ranges = new Dictionary>();\n\n Dictionary algoConv = new Dictionary\n {\n { \"msft:rm/algorithm/pkey/2005\", PKeyAlgorithm.PKEY2005 },\n { \"msft:rm/algorithm/pkey/2009\", PKeyAlgorithm.PKEY2009 }\n };\n\n foreach (XmlNode pubKeyNode in pubKeyNodes)\n {\n int group = int.Parse(pubKeyNode.SelectSingleNode(\"./p:GroupId\", nsmgr).InnerText);\n algorithms[group] = algoConv[pubKeyNode.SelectSingleNode(\"./p:AlgorithmId\", nsmgr).InnerText];\n }\n\n foreach (XmlNode rangeNode in rangeNodes)\n {\n string refActIdStr = rangeNode.SelectSingleNode(\"./p:RefActConfigId\", nsmgr).InnerText;\n\n if (!ranges.ContainsKey(refActIdStr))\n {\n ranges[refActIdStr] = new List();\n }\n\n KeyRange keyRange = new KeyRange\n {\n Start = int.Parse(rangeNode.SelectSingleNode(\"./p:Start\", nsmgr).InnerText),\n End = int.Parse(rangeNode.SelectSingleNode(\"./p:End\", nsmgr).InnerText),\n EulaType = rangeNode.SelectSingleNode(\"./p:EulaType\", nsmgr).InnerText,\n PartNumber = rangeNode.SelectSingleNode(\"./p:PartNumber\", nsmgr).InnerText,\n Valid = rangeNode.SelectSingleNode(\"./p:IsValid\", nsmgr).InnerText.ToLower() == \"true\"\n };\n\n ranges[refActIdStr].Add(keyRange);\n }\n\n foreach (XmlNode configNode in configNodes)\n {\n string refActIdStr = configNode.SelectSingleNode(\"./p:ActConfigId\", nsmgr).InnerText;\n Guid refActId = new Guid(refActIdStr);\n int group = int.Parse(configNode.SelectSingleNode(\"./p:RefGroupId\", nsmgr).InnerText);\n List keyRanges = ranges[refActIdStr];\n\n if (keyRanges.Count > 0 && !Products.ContainsKey(refActId))\n {\n ProductConfig productConfig = new ProductConfig\n {\n GroupId = group,\n Edition = configNode.SelectSingleNode(\"./p:EditionId\", nsmgr).InnerText,\n Description = configNode.SelectSingleNode(\"./p:ProductDescription\", nsmgr).InnerText,\n Channel = configNode.SelectSingleNode(\"./p:ProductKeyType\", nsmgr).InnerText,\n Randomized = configNode.SelectSingleNode(\"./p:ProductKeyType\", nsmgr).InnerText.ToLower() == \"true\",\n Algorithm = algorithms[group],\n Ranges = keyRanges,\n ActivationId = refActId\n };\n\n Products[refActId] = productConfig;\n }\n }\n }\n\n loadedPkeyConfigs.Add(pkcFileId);\n }\n\n public ProductConfig MatchParams(int group, int serial)\n {\n foreach (ProductConfig config in Products.Values)\n {\n if (config.GroupId == group)\n {\n foreach (KeyRange range in config.Ranges)\n {\n if (range.Contains(serial))\n {\n return config;\n }\n }\n }\n }\n\n throw new FileNotFoundException(\"Failed to find product matching supplied product key parameters.\");\n }\n\n public void LoadAllConfigs(Guid appId)\n {\n foreach (Guid actId in SLApi.GetActivationIds(appId))\n {\n try\n {\n LoadConfig(actId);\n } \n catch (ArgumentException)\n {\n\n }\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/SPP/SLAPI.cs", "namespace LibTSforge.SPP\n{\n using System;\n using System.Collections.Generic;\n using System.Linq;\n using System.Runtime.InteropServices;\n using System.Text;\n\n public static class SLApi\n {\n private enum SLIDTYPE\n {\n SL_ID_APPLICATION,\n SL_ID_PRODUCT_SKU,\n SL_ID_LICENSE_FILE,\n SL_ID_LICENSE,\n SL_ID_PKEY,\n SL_ID_ALL_LICENSES,\n SL_ID_ALL_LICENSE_FILES,\n SL_ID_STORE_TOKEN,\n SL_ID_LAST\n }\n\n private enum SLDATATYPE\n {\n SL_DATA_NONE,\n SL_DATA_SZ,\n SL_DATA_DWORD,\n SL_DATA_BINARY,\n SL_DATA_MULTI_SZ,\n SL_DATA_SUM\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct SL_LICENSING_STATUS\n {\n public Guid SkuId;\n public uint eStatus;\n public uint dwGraceTime;\n public uint dwTotalGraceDays;\n public uint hrReason;\n public ulong qwValidityExpiration;\n }\n\n public static readonly Guid WINDOWS_APP_ID = new Guid(\"55c92734-d682-4d71-983e-d6ec3f16059f\");\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode, PreserveSig = false)]\n private static extern void SLOpen(out IntPtr hSLC);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode, PreserveSig = false)]\n private static extern void SLClose(IntPtr hSLC);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetWindowsInformationDWORD(string ValueName, ref int Value);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLInstallProofOfPurchase(IntPtr hSLC, string pwszPKeyAlgorithm, string pwszPKeyString, uint cbPKeySpecificData, byte[] pbPKeySpecificData, ref Guid PKeyId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLUninstallProofOfPurchase(IntPtr hSLC, ref Guid PKeyId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetPKeyInformation(IntPtr hSLC, ref Guid pPKeyId, string pwszValueName, out SLDATATYPE peDataType, out uint pcbValue, out IntPtr ppbValue);\n\n [DllImport(\"slcext.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLActivateProduct(IntPtr hSLC, ref Guid pProductSkuId, byte[] cbAppSpecificData, byte[] pvAppSpecificData, byte[] pActivationInfo, string pwszProxyServer, ushort wProxyPort);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGenerateOfflineInstallationId(IntPtr hSLC, ref Guid pProductSkuId, ref string ppwszInstallationId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLDepositOfflineConfirmationId(IntPtr hSLC, ref Guid pProductSkuId, string pwszInstallationId, string pwszConfirmationId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetSLIDList(IntPtr hSLC, SLIDTYPE eQueryIdType, ref Guid pQueryId, SLIDTYPE eReturnIdType, out uint pnReturnIds, out IntPtr ppReturnIds);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode, PreserveSig = false)]\n private static extern void SLGetLicensingStatusInformation(IntPtr hSLC, ref Guid pAppID, IntPtr pProductSkuId, string pwszRightName, out uint pnStatusCount, out IntPtr ppLicensingStatus);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetInstalledProductKeyIds(IntPtr hSLC, ref Guid pProductSkuId, out uint pnProductKeyIds, out IntPtr ppProductKeyIds);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLConsumeWindowsRight(uint unknown);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetProductSkuInformation(IntPtr hSLC, ref Guid pProductSkuId, string pwszValueName, out SLDATATYPE peDataType, out uint pcbValue, out IntPtr ppbValue);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetLicense(IntPtr hSLC, ref Guid pLicenseFileId, out uint pcbLicenseFile, out IntPtr ppbLicenseFile);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLSetCurrentProductKey(IntPtr hSLC, ref Guid pProductSkuId, ref Guid pProductKeyId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLFireEvent(IntPtr hSLC, string pwszEventId, ref Guid pApplicationId);\n\n private class SLContext : IDisposable\n {\n public readonly IntPtr Handle;\n\n public SLContext()\n {\n SLOpen(out Handle);\n }\n\n public void Dispose()\n {\n SLClose(Handle);\n GC.SuppressFinalize(this);\n }\n\n ~SLContext()\n {\n Dispose();\n }\n }\n\n public static Guid GetDefaultActivationID(Guid appId, bool includeActivated)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr pLicStat;\n\n SLGetLicensingStatusInformation(sl.Handle, ref appId, IntPtr.Zero, null, out count, out pLicStat);\n\n unsafe\n {\n SL_LICENSING_STATUS* licensingStatuses = (SL_LICENSING_STATUS*)pLicStat;\n for (int i = 0; i < count; i++)\n {\n SL_LICENSING_STATUS slStatus = licensingStatuses[i];\n\n Guid actId = slStatus.SkuId;\n if (GetInstalledPkeyID(actId) == Guid.Empty) continue;\n if (IsAddon(actId)) continue;\n if (!includeActivated && (slStatus.eStatus == 1)) continue;\n\n return actId;\n }\n }\n\n return Guid.Empty;\n }\n }\n\n public static string GetInstallationID(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n string installationId = null;\n return SLGenerateOfflineInstallationId(sl.Handle, ref actId, ref installationId) == 0 ? installationId : null;\n }\n }\n\n public static Guid GetInstalledPkeyID(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr pProductKeyIds;\n\n uint status = SLGetSLIDList(sl.Handle, SLIDTYPE.SL_ID_PRODUCT_SKU, ref actId, SLIDTYPE.SL_ID_PKEY, out count, out pProductKeyIds);\n\n if (status != 0 || count == 0)\n {\n return Guid.Empty;\n }\n\n unsafe { return *(Guid*)pProductKeyIds; }\n }\n }\n\n public static uint DepositConfirmationID(Guid actId, string installationId, string confirmationId)\n {\n using (SLContext sl = new SLContext())\n {\n return SLDepositOfflineConfirmationId(sl.Handle, ref actId, installationId, confirmationId);\n }\n }\n\n public static void RefreshLicenseStatus()\n {\n SLConsumeWindowsRight(0);\n }\n\n public static void RefreshTrustedTime(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n SLDATATYPE type;\n uint count;\n IntPtr ppbValue;\n\n SLGetProductSkuInformation(sl.Handle, ref actId, \"TrustedTime\", out type, out count, out ppbValue);\n }\n }\n\n public static void FireStateChangedEvent(Guid appId)\n {\n using (SLContext sl = new SLContext())\n {\n SLFireEvent(sl.Handle, \"msft:rm/event/licensingstatechanged\", ref appId);\n }\n }\n\n public static Guid GetAppId(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr pAppIds;\n\n uint status = SLGetSLIDList(sl.Handle, SLIDTYPE.SL_ID_PRODUCT_SKU, ref actId, SLIDTYPE.SL_ID_APPLICATION, out count, out pAppIds);\n\n if (status != 0 || count == 0)\n {\n return Guid.Empty;\n }\n\n unsafe { return *(Guid*)pAppIds; }\n }\n }\n\n public static bool IsAddon(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n SLDATATYPE type;\n IntPtr ppbValue;\n\n uint status = SLGetProductSkuInformation(sl.Handle, ref actId, \"DependsOn\", out type, out count, out ppbValue);\n return (int)status >= 0 && status != 0xC004F012;\n }\n }\n\n public static Guid GetLicenseFileId(Guid licId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr ppReturnLics;\n\n uint status = SLGetSLIDList(sl.Handle, SLIDTYPE.SL_ID_LICENSE, ref licId, SLIDTYPE.SL_ID_LICENSE_FILE, out count, out ppReturnLics);\n\n if (status != 0 || count == 0)\n {\n return Guid.Empty;\n }\n\n unsafe { return *(Guid*)ppReturnLics; }\n }\n }\n\n public static Guid GetPkeyConfigFileId(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n SLDATATYPE type;\n uint len;\n IntPtr ppReturnLics;\n\n uint status = SLGetProductSkuInformation(sl.Handle, ref actId, \"pkeyConfigLicenseId\", out type, out len, out ppReturnLics);\n\n if (status != 0 || len == 0)\n {\n return Guid.Empty;\n }\n\n Guid pkcId = new Guid(Marshal.PtrToStringAuto(ppReturnLics));\n return GetLicenseFileId(pkcId);\n }\n }\n\n public static string GetLicenseContents(Guid fileId)\n {\n if (fileId == Guid.Empty) throw new ArgumentException(\"License contents could not be retrieved.\");\n\n using (SLContext sl = new SLContext())\n {\n uint dataLen;\n IntPtr dataPtr;\n\n if (SLGetLicense(sl.Handle, ref fileId, out dataLen, out dataPtr) != 0)\n {\n return null;\n }\n\n byte[] data = new byte[dataLen];\n Marshal.Copy(dataPtr, data, 0, (int)dataLen);\n\n data = data.Skip(Array.IndexOf(data, (byte)'<')).ToArray();\n return Encoding.UTF8.GetString(data);\n }\n }\n\n public static bool IsPhoneActivatable(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n SLDATATYPE type;\n IntPtr ppbValue;\n\n uint status = SLGetProductSkuInformation(sl.Handle, ref actId, \"msft:sl/EUL/PHONE/PUBLIC\", out type, out count, out ppbValue);\n return status != 0xC004F012;\n }\n }\n\n public static string GetPKeyChannel(Guid pkeyId)\n {\n using (SLContext sl = new SLContext())\n {\n SLDATATYPE type;\n uint len;\n IntPtr ppbValue;\n\n uint status = SLGetPKeyInformation(sl.Handle, ref pkeyId, \"Channel\", out type, out len, out ppbValue);\n\n if (status != 0 || len == 0)\n {\n return null;\n }\n\n return Marshal.PtrToStringAuto(ppbValue);\n }\n }\n\n public static string GetMetaStr(Guid actId, string value)\n {\n using (SLContext sl = new SLContext())\n {\n uint len;\n SLDATATYPE type;\n IntPtr ppbValue;\n\n uint status = SLGetProductSkuInformation(sl.Handle, ref actId, value, out type, out len, out ppbValue);\n\n if (status != 0 || len == 0 || type != SLDATATYPE.SL_DATA_SZ)\n {\n return null;\n }\n\n return Marshal.PtrToStringAuto(ppbValue);\n }\n }\n\n public static List GetActivationIds(Guid appId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr pLicStat;\n\n SLGetLicensingStatusInformation(sl.Handle, ref appId, IntPtr.Zero, null, out count, out pLicStat);\n\n List result = new List();\n\n unsafe\n {\n SL_LICENSING_STATUS* licensingStatuses = (SL_LICENSING_STATUS*)pLicStat;\n for (int i = 0; i < count; i++)\n {\n result.Add(licensingStatuses[i].SkuId);\n }\n }\n\n return result;\n }\n }\n\n public static uint SetCurrentProductKey(Guid actId, Guid pkeyId)\n {\n using (SLContext sl = new SLContext())\n {\n return SLSetCurrentProductKey(sl.Handle, ref actId, ref pkeyId);\n }\n }\n\n public static uint InstallProductKey(ProductKey pkey)\n {\n using (SLContext sl = new SLContext())\n {\n Guid pkeyId = Guid.Empty;\n return SLInstallProofOfPurchase(sl.Handle, pkey.GetAlgoUri(), pkey.ToString(), 0, null, ref pkeyId);\n }\n }\n\n public static void UninstallProductKey(Guid pkeyId)\n {\n using (SLContext sl = new SLContext())\n {\n SLUninstallProofOfPurchase(sl.Handle, ref pkeyId);\n }\n }\n\n public static void UninstallAllProductKeys(Guid appId)\n {\n foreach (Guid actId in GetActivationIds(appId))\n {\n Guid pkeyId = GetInstalledPkeyID(actId);\n if (pkeyId == Guid.Empty) continue;\n if (IsAddon(actId)) continue;\n UninstallProductKey(pkeyId);\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/SPP/ProductKey.cs", "namespace LibTSforge.SPP\n{\n using System;\n using System.IO;\n using System.Linq;\n using Crypto;\n using PhysicalStore;\n\n public class ProductKey\n {\n private static readonly string ALPHABET = \"BCDFGHJKMPQRTVWXY2346789\";\n\n private readonly ulong klow;\n private readonly ulong khigh;\n\n public int Group;\n public int Serial;\n public ulong Security;\n public bool Upgrade;\n public PKeyAlgorithm Algorithm;\n public readonly string EulaType;\n public readonly string PartNumber;\n public readonly string Edition;\n public readonly string Channel;\n public readonly Guid ActivationId;\n\n private string mpc;\n private string pid2;\n\n public byte[] KeyBytes\n {\n get { return BitConverter.GetBytes(klow).Concat(BitConverter.GetBytes(khigh)).ToArray(); }\n }\n\n public ProductKey()\n {\n\n }\n\n public ProductKey(int serial, ulong security, bool upgrade, PKeyAlgorithm algorithm, ProductConfig config, KeyRange range)\n {\n Group = config.GroupId;\n Serial = serial;\n Security = security;\n Upgrade = upgrade;\n Algorithm = algorithm;\n EulaType = range.EulaType;\n PartNumber = range.PartNumber.Split(':', ';')[0];\n Edition = config.Edition;\n Channel = config.Channel;\n ActivationId = config.ActivationId;\n\n klow = ((security & 0x3fff) << 50 | ((ulong)serial & 0x3fffffff) << 20 | ((ulong)Group & 0xfffff));\n khigh = ((upgrade ? (ulong)1 : 0) << 49 | ((security >> 14) & 0x7fffffffff));\n\n uint checksum = Utils.CRC32(KeyBytes) & 0x3ff;\n\n khigh |= ((ulong)checksum << 39);\n }\n\n public string GetAlgoUri()\n {\n return \"msft:rm/algorithm/pkey/\" + (Algorithm == PKeyAlgorithm.PKEY2005 ? \"2005\" : (Algorithm == PKeyAlgorithm.PKEY2009 ? \"2009\" : \"Unknown\"));\n }\n\n public Guid GetPkeyId()\n {\n VariableBag pkb = new VariableBag(PSVersion.WinModern);\n pkb.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingProductKey\",\n ValueAsStr = ToString()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingMiscData\",\n Value = new byte[] { }\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingAlgorithm\",\n ValueAsStr = GetAlgoUri()\n }\n });\n\n return new Guid(CryptoUtils.SHA256Hash(pkb.Serialize()).Take(16).ToArray());\n }\n\n public string GetMPC()\n {\n if (mpc != null)\n {\n return mpc;\n }\n\n int build = Environment.OSVersion.Version.Build;\n\n mpc = build >= 10240 ? \"03612\" :\n build >= 9600 ? \"06401\" :\n build >= 9200 ? \"05426\" :\n \"55041\";\n\n // setup.cfg doesn't exist in Windows 8+\n string setupcfg = string.Format(@\"{0}\\oobe\\{1}\", Environment.SystemDirectory, \"setup.cfg\");\n\n if (!File.Exists(setupcfg) || Edition.Contains(\";\"))\n {\n return mpc;\n }\n\n string mpcKey = string.Format(\"{0}.{1}=\", Utils.GetArchitecture(), Edition);\n string localMPC = File.ReadAllLines(setupcfg).FirstOrDefault(line => line.Contains(mpcKey));\n if (localMPC != null)\n {\n mpc = localMPC.Split('=')[1].Trim();\n }\n\n return mpc;\n }\n\n public string GetPid2()\n {\n if (pid2 != null)\n {\n return pid2;\n }\n\n pid2 = \"\";\n\n if (Algorithm == PKeyAlgorithm.PKEY2005)\n {\n string mpc = GetMPC();\n string serialHigh;\n int serialLow;\n int lastPart;\n\n if (EulaType == \"OEM\")\n {\n serialHigh = \"OEM\";\n serialLow = ((Group / 2) % 100) * 10000 + (Serial / 100000);\n lastPart = Serial % 100000;\n }\n else\n {\n serialHigh = (Serial / 1000000).ToString(\"D3\");\n serialLow = Serial % 1000000;\n lastPart = ((Group / 2) % 100) * 1000 + new Random().Next(1000);\n }\n\n int checksum = 0;\n\n foreach (char c in serialLow.ToString())\n {\n checksum += int.Parse(c.ToString());\n }\n checksum = 7 - (checksum % 7);\n\n pid2 = string.Format(\"{0}-{1}-{2:D6}{3}-{4:D5}\", mpc, serialHigh, serialLow, checksum, lastPart);\n }\n\n return pid2;\n }\n\n public byte[] GetPid3()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(0xA4);\n writer.Write(0x3);\n writer.WriteFixedString(GetPid2(), 24);\n writer.Write(Group);\n writer.WriteFixedString(PartNumber, 16);\n writer.WritePadding(0x6C);\n byte[] data = writer.GetBytes();\n byte[] crc = BitConverter.GetBytes(~Utils.CRC32(data.Reverse().ToArray())).Reverse().ToArray();\n writer.Write(crc);\n\n return writer.GetBytes();\n }\n\n public byte[] GetPid4()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(0x4F8);\n writer.Write(0x4);\n writer.WriteFixedString16(GetExtendedPid(), 0x80);\n writer.WriteFixedString16(ActivationId.ToString(), 0x80);\n writer.WritePadding(0x10);\n writer.WriteFixedString16(Edition, 0x208);\n writer.Write(Upgrade ? (ulong)1 : 0);\n writer.WritePadding(0x50);\n writer.WriteFixedString16(PartNumber, 0x80);\n writer.WriteFixedString16(Channel, 0x80);\n writer.WriteFixedString16(EulaType, 0x80);\n\n return writer.GetBytes();\n }\n\n public string GetExtendedPid()\n {\n string mpc = GetMPC();\n int serialHigh = Serial / 1000000;\n int serialLow = Serial % 1000000;\n int licenseType;\n uint lcid = Utils.GetSystemDefaultLCID();\n int build = Environment.OSVersion.Version.Build;\n int dayOfYear = DateTime.Now.DayOfYear;\n int year = DateTime.Now.Year;\n\n switch (EulaType)\n {\n case \"OEM\":\n licenseType = 2;\n break;\n\n case \"Volume\":\n licenseType = 3;\n break;\n\n default:\n licenseType = 0;\n break;\n }\n\n return string.Format(\n \"{0}-{1:D5}-{2:D3}-{3:D6}-{4:D2}-{5:D4}-{6:D4}.0000-{7:D3}{8:D4}\",\n mpc,\n Group,\n serialHigh,\n serialLow,\n licenseType,\n lcid,\n build,\n dayOfYear,\n year\n );\n }\n\n public byte[] GetPhoneData(PSVersion version)\n {\n if (version == PSVersion.Win7)\n {\n ulong shortauth = ((ulong)Group << 41) | (Security << 31) | ((ulong)Serial << 1) | (Upgrade ? (ulong)1 : 0);\n return BitConverter.GetBytes(shortauth);\n }\n\n int serialHigh = Serial / 1000000;\n int serialLow = Serial % 1000000;\n\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n string algoId = Algorithm == PKeyAlgorithm.PKEY2005 ? \"B8731595-A2F6-430B-A799-FBFFB81A8D73\" : \"660672EF-7809-4CFD-8D54-41B7FB738988\";\n\n writer.Write(new Guid(algoId).ToByteArray());\n writer.Write(Group);\n writer.Write(serialHigh);\n writer.Write(serialLow);\n writer.Write(Upgrade ? 1 : 0);\n writer.Write(Security);\n\n return writer.GetBytes();\n }\n\n public override string ToString()\n {\n string keyStr = \"\";\n Random rnd = new Random(Group * 1000000000 + Serial);\n\n if (Algorithm == PKeyAlgorithm.PKEY2005)\n {\n keyStr = \"H4X3DH4X3DH4X3DH4X3D\";\n\n for (int i = 0; i < 5; i++)\n {\n keyStr += ALPHABET[rnd.Next(24)];\n }\n }\n else if (Algorithm == PKeyAlgorithm.PKEY2009)\n {\n int last = 0;\n byte[] bKey = KeyBytes;\n\n for (int i = 24; i >= 0; i--)\n {\n int current = 0;\n\n for (int j = 14; j >= 0; j--)\n {\n current *= 0x100;\n current += bKey[j];\n bKey[j] = (byte)(current / 24);\n current %= 24;\n last = current;\n }\n\n keyStr = ALPHABET[current] + keyStr;\n }\n\n keyStr = keyStr.Substring(1, last) + \"N\" + keyStr.Substring(last + 1, keyStr.Length - last - 1);\n }\n\n for (int i = 5; i < keyStr.Length; i += 6)\n {\n keyStr = keyStr.Insert(i, \"-\");\n }\n\n return keyStr;\n }\n }\n}\n"], ["/TSforge/LibTSforge/TokenStore/TokenStoreModern.cs", "namespace LibTSforge.TokenStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using System.Linq;\n using Crypto;\n\n public class TokenStoreModern : ITokenStore\n {\n private static readonly uint VERSION = 3;\n private static readonly int ENTRY_SIZE = 0x9E;\n private static readonly int BLOCK_SIZE = 0x4020;\n private static readonly int ENTRIES_PER_BLOCK = BLOCK_SIZE / ENTRY_SIZE;\n private static readonly int BLOCK_PAD_SIZE = 0x66;\n\n private static readonly byte[] CONTS_HEADER = Enumerable.Repeat((byte)0x55, 0x20).ToArray();\n private static readonly byte[] CONTS_FOOTER = Enumerable.Repeat((byte)0xAA, 0x20).ToArray();\n\n private List Entries = new List();\n private readonly FileStream TokensFile;\n\n public void Deserialize()\n {\n if (TokensFile.Length < BLOCK_SIZE) return;\n\n TokensFile.Seek(0x24, SeekOrigin.Begin);\n uint nextBlock;\n\n BinaryReader reader = new BinaryReader(TokensFile);\n do\n {\n reader.ReadUInt32();\n nextBlock = reader.ReadUInt32();\n\n for (int i = 0; i < ENTRIES_PER_BLOCK; i++)\n {\n uint curOffset = reader.ReadUInt32();\n bool populated = reader.ReadUInt32() == 1;\n uint contentOffset = reader.ReadUInt32();\n uint contentLength = reader.ReadUInt32();\n uint allocLength = reader.ReadUInt32();\n byte[] contentData = { };\n\n if (populated)\n {\n reader.BaseStream.Seek(contentOffset + 0x20, SeekOrigin.Begin);\n uint dataLength = reader.ReadUInt32();\n\n if (dataLength != contentLength)\n {\n throw new FormatException(\"Data length in tokens content is inconsistent with entry.\");\n }\n\n reader.ReadBytes(0x20);\n contentData = reader.ReadBytes((int)contentLength);\n }\n\n reader.BaseStream.Seek(curOffset + 0x14, SeekOrigin.Begin);\n\n Entries.Add(new TokenEntry\n {\n Name = reader.ReadNullTerminatedString(0x82),\n Extension = reader.ReadNullTerminatedString(0x8),\n Data = contentData,\n Populated = populated\n });\n }\n\n reader.BaseStream.Seek(nextBlock, SeekOrigin.Begin);\n } while (nextBlock != 0);\n }\n\n public void Serialize()\n {\n MemoryStream tokens = new MemoryStream();\n\n using (BinaryWriter writer = new BinaryWriter(tokens))\n {\n writer.Write(VERSION);\n writer.Write(CONTS_HEADER);\n\n int curBlockOffset = (int)writer.BaseStream.Position;\n int curEntryOffset = curBlockOffset + 0x8;\n int curContsOffset = curBlockOffset + BLOCK_SIZE;\n\n for (int eIndex = 0; eIndex < ((Entries.Count / ENTRIES_PER_BLOCK) + 1) * ENTRIES_PER_BLOCK; eIndex++)\n {\n TokenEntry entry;\n\n if (eIndex < Entries.Count)\n {\n entry = Entries[eIndex];\n }\n else\n {\n entry = new TokenEntry\n {\n Name = \"\",\n Extension = \"\",\n Populated = false,\n Data = new byte[] { }\n };\n }\n\n writer.BaseStream.Seek(curBlockOffset, SeekOrigin.Begin);\n writer.Write(curBlockOffset);\n writer.Write(0);\n\n writer.BaseStream.Seek(curEntryOffset, SeekOrigin.Begin);\n writer.Write(curEntryOffset);\n writer.Write(entry.Populated ? 1 : 0);\n writer.Write(entry.Populated ? curContsOffset : 0);\n writer.Write(entry.Populated ? entry.Data.Length : -1);\n writer.Write(entry.Populated ? entry.Data.Length : -1);\n writer.WriteFixedString16(entry.Name, 0x82);\n writer.WriteFixedString16(entry.Extension, 0x8);\n curEntryOffset = (int)writer.BaseStream.Position;\n\n if (entry.Populated)\n {\n writer.BaseStream.Seek(curContsOffset, SeekOrigin.Begin);\n writer.Write(CONTS_HEADER);\n writer.Write(entry.Data.Length);\n writer.Write(CryptoUtils.SHA256Hash(entry.Data));\n writer.Write(entry.Data);\n writer.Write(CONTS_FOOTER);\n curContsOffset = (int)writer.BaseStream.Position;\n }\n\n if ((eIndex + 1) % ENTRIES_PER_BLOCK == 0 && eIndex != 0)\n {\n if (eIndex < Entries.Count)\n {\n writer.BaseStream.Seek(curBlockOffset + 0x4, SeekOrigin.Begin);\n writer.Write(curContsOffset);\n }\n\n writer.BaseStream.Seek(curEntryOffset, SeekOrigin.Begin);\n writer.WritePadding(BLOCK_PAD_SIZE);\n\n writer.BaseStream.Seek(curBlockOffset, SeekOrigin.Begin);\n byte[] blockData = new byte[BLOCK_SIZE - 0x20];\n\n tokens.Read(blockData, 0, BLOCK_SIZE - 0x20);\n byte[] blockHash = CryptoUtils.SHA256Hash(blockData);\n\n writer.BaseStream.Seek(curBlockOffset + BLOCK_SIZE - 0x20, SeekOrigin.Begin);\n writer.Write(blockHash);\n\n curBlockOffset = curContsOffset;\n curEntryOffset = curBlockOffset + 0x8;\n curContsOffset = curBlockOffset + BLOCK_SIZE;\n }\n }\n\n tokens.SetLength(curBlockOffset);\n }\n\n byte[] tokensData = tokens.ToArray();\n byte[] tokensHash = CryptoUtils.SHA256Hash(tokensData.Take(0x4).Concat(tokensData.Skip(0x24)).ToArray());\n\n tokens = new MemoryStream(tokensData);\n\n BinaryWriter tokWriter = new BinaryWriter(TokensFile);\n using (BinaryReader reader = new BinaryReader(tokens))\n {\n TokensFile.Seek(0, SeekOrigin.Begin);\n TokensFile.SetLength(tokens.Length);\n tokWriter.Write(reader.ReadBytes(0x4));\n reader.ReadBytes(0x20);\n tokWriter.Write(tokensHash);\n tokWriter.Write(reader.ReadBytes((int)reader.BaseStream.Length - 0x4));\n }\n }\n\n public void AddEntry(TokenEntry entry)\n {\n Entries.Add(entry);\n }\n\n public void AddEntries(TokenEntry[] entries)\n {\n Entries.AddRange(entries);\n }\n\n public void DeleteEntry(string name, string ext)\n {\n foreach (TokenEntry entry in Entries)\n {\n if (entry.Name == name && entry.Extension == ext)\n {\n Entries.Remove(entry);\n return;\n }\n }\n }\n\n public void DeleteUnpopEntry(string name, string ext)\n {\n List delEntries = new List();\n foreach (TokenEntry entry in Entries)\n {\n if (entry.Name == name && entry.Extension == ext && !entry.Populated)\n {\n delEntries.Add(entry);\n }\n }\n\n Entries = Entries.Except(delEntries).ToList();\n }\n\n public TokenEntry GetEntry(string name, string ext)\n {\n foreach (TokenEntry entry in Entries)\n {\n if (entry.Name == name && entry.Extension == ext)\n {\n if (!entry.Populated) continue;\n return entry;\n }\n }\n\n return null;\n }\n\n public TokenMeta GetMetaEntry(string name)\n {\n DeleteUnpopEntry(name, \"xml\");\n TokenEntry entry = GetEntry(name, \"xml\");\n TokenMeta meta;\n\n if (entry == null)\n {\n meta = new TokenMeta\n {\n Name = name\n };\n }\n else\n {\n meta = new TokenMeta(entry.Data);\n }\n\n return meta;\n }\n\n public void SetEntry(string name, string ext, byte[] data)\n {\n for (int i = 0; i < Entries.Count; i++)\n {\n TokenEntry entry = Entries[i];\n\n if (entry.Name == name && entry.Extension == ext && entry.Populated)\n {\n entry.Data = data;\n Entries[i] = entry;\n return;\n }\n }\n\n Entries.Add(new TokenEntry\n {\n Populated = true,\n Name = name,\n Extension = ext,\n Data = data\n });\n }\n\n public TokenStoreModern(string tokensPath)\n {\n TokensFile = File.Open(tokensPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n Deserialize();\n }\n\n public void Dispose()\n {\n Serialize();\n TokensFile.Close();\n }\n }\n}\n"], ["/TSforge/LibTSforge/TokenStore/Common.cs", "namespace LibTSforge.TokenStore\n{\n using System.Collections.Generic;\n using System.IO;\n\n public class TokenEntry\n {\n public string Name;\n public string Extension;\n public byte[] Data;\n public bool Populated;\n }\n\n public class TokenMeta\n {\n public string Name;\n public readonly Dictionary Data = new Dictionary();\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(1);\n byte[] nameBytes = Utils.EncodeString(Name);\n writer.Write(nameBytes.Length);\n writer.Write(nameBytes);\n\n foreach (KeyValuePair kv in Data)\n {\n byte[] keyBytes = Utils.EncodeString(kv.Key);\n byte[] valueBytes = Utils.EncodeString(kv.Value);\n writer.Write(keyBytes.Length);\n writer.Write(valueBytes.Length);\n writer.Write(keyBytes);\n writer.Write(valueBytes);\n }\n\n return writer.GetBytes();\n }\n\n private void Deserialize(byte[] data)\n {\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n reader.ReadInt32();\n int nameLen = reader.ReadInt32();\n Name = reader.ReadNullTerminatedString(nameLen);\n\n while (reader.BaseStream.Position < data.Length - 0x8)\n {\n int keyLen = reader.ReadInt32();\n int valueLen = reader.ReadInt32();\n string key = reader.ReadNullTerminatedString(keyLen);\n string value = reader.ReadNullTerminatedString(valueLen);\n Data[key] = value;\n }\n }\n\n public TokenMeta(byte[] data)\n {\n Deserialize(data);\n }\n\n public TokenMeta()\n {\n\n }\n }\n}\n"], ["/TSforge/LibTSforge/SPP/SPSys.cs", "namespace LibTSforge.SPP\n{\n using Microsoft.Win32.SafeHandles;\n using System;\n using System.Runtime.InteropServices;\n\n public class SPSys\n {\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n private static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);\n private static SafeFileHandle CreateFileSafe(string device)\n {\n return new SafeFileHandle(CreateFile(device, 0xC0000000, 0, IntPtr.Zero, 3, 0, IntPtr.Zero), true);\n }\n\n [return: MarshalAs(UnmanagedType.Bool)]\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n private static extern bool DeviceIoControl([In] SafeFileHandle hDevice, [In] uint dwIoControlCode, [In] IntPtr lpInBuffer, [In] int nInBufferSize, [Out] IntPtr lpOutBuffer, [In] int nOutBufferSize, out int lpBytesReturned, [In] IntPtr lpOverlapped);\n\n public static bool IsSpSysRunning()\n {\n SafeFileHandle file = CreateFileSafe(@\"\\\\.\\SpDevice\");\n IntPtr buffer = Marshal.AllocHGlobal(1);\n int bytesReturned;\n DeviceIoControl(file, 0x80006008, IntPtr.Zero, 0, buffer, 1, out bytesReturned, IntPtr.Zero);\n bool running = Marshal.ReadByte(buffer) != 0;\n Marshal.FreeHGlobal(buffer);\n file.Close();\n return running;\n }\n\n public static int ControlSpSys(bool start)\n {\n SafeFileHandle file = CreateFileSafe(@\"\\\\.\\SpDevice\");\n IntPtr buffer = Marshal.AllocHGlobal(4);\n int bytesReturned;\n DeviceIoControl(file, start ? 0x8000a000 : 0x8000a004, IntPtr.Zero, 0, buffer, 4, out bytesReturned, IntPtr.Zero);\n int result = Marshal.ReadInt32(buffer);\n Marshal.FreeHGlobal(buffer);\n file.Close();\n return result;\n }\n }\n}\n"], ["/TSforge/LibTSforge/Crypto/CryptoUtils.cs", "namespace LibTSforge.Crypto\n{\n using System;\n using System.Linq;\n using System.Security.Cryptography;\n\n public static class CryptoUtils\n {\n public static byte[] GenerateRandomKey(int len)\n {\n byte[] rand = new byte[len];\n Random r = new Random();\n r.NextBytes(rand);\n\n return rand;\n }\n\n public static byte[] AESEncrypt(byte[] data, byte[] key)\n {\n using (Aes aes = Aes.Create())\n {\n aes.Key = key;\n aes.Mode = CipherMode.CBC;\n aes.Padding = PaddingMode.PKCS7;\n\n ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, Enumerable.Repeat((byte)0, 16).ToArray());\n byte[] encryptedData = encryptor.TransformFinalBlock(data, 0, data.Length);\n return encryptedData;\n }\n }\n\n public static byte[] AESDecrypt(byte[] data, byte[] key)\n {\n using (Aes aes = Aes.Create())\n {\n aes.Key = key;\n aes.Mode = CipherMode.CBC;\n aes.Padding = PaddingMode.PKCS7;\n\n ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, Enumerable.Repeat((byte)0, 16).ToArray());\n byte[] decryptedData = decryptor.TransformFinalBlock(data, 0, data.Length);\n return decryptedData;\n }\n }\n\n public static byte[] RSADecrypt(byte[] rsaKey, byte[] data)\n {\n\n using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())\n {\n rsa.ImportCspBlob(rsaKey);\n return rsa.Decrypt(data, false);\n }\n }\n\n public static byte[] RSAEncrypt(byte[] rsaKey, byte[] data)\n {\n using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())\n {\n rsa.ImportCspBlob(rsaKey);\n return rsa.Encrypt(data, false);\n }\n }\n\n public static byte[] RSASign(byte[] rsaKey, byte[] data)\n {\n using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())\n {\n rsa.ImportCspBlob(rsaKey);\n RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(rsa);\n formatter.SetHashAlgorithm(\"SHA1\");\n\n byte[] hash;\n using (SHA1 sha1 = SHA1.Create())\n {\n hash = sha1.ComputeHash(data);\n }\n\n return formatter.CreateSignature(hash);\n }\n }\n\n public static bool RSAVerifySignature(byte[] rsaKey, byte[] data, byte[] signature)\n {\n using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())\n {\n rsa.ImportCspBlob(rsaKey);\n RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(rsa);\n deformatter.SetHashAlgorithm(\"SHA1\");\n\n byte[] hash;\n using (SHA1 sha1 = SHA1.Create())\n {\n hash = sha1.ComputeHash(data);\n }\n\n return deformatter.VerifySignature(hash, signature);\n }\n }\n\n public static byte[] HMACSign(byte[] key, byte[] data)\n {\n HMACSHA1 hmac = new HMACSHA1(key);\n return hmac.ComputeHash(data);\n }\n\n public static bool HMACVerify(byte[] key, byte[] data, byte[] signature)\n {\n return Enumerable.SequenceEqual(signature, HMACSign(key, data));\n }\n\n public static byte[] SaltSHASum(byte[] salt, byte[] data)\n {\n SHA1 sha1 = SHA1.Create();\n byte[] sha_data = salt.Concat(data).ToArray();\n return sha1.ComputeHash(sha_data);\n }\n\n public static bool SaltSHAVerify(byte[] salt, byte[] data, byte[] checksum)\n {\n return Enumerable.SequenceEqual(checksum, SaltSHASum(salt, data));\n }\n\n public static byte[] SHA256Hash(byte[] data)\n {\n using (SHA256 sha256 = SHA256.Create())\n {\n return sha256.ComputeHash(data);\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/Common.cs", "namespace LibTSforge\n{\n using System;\n using System.IO;\n using System.Linq;\n using System.Runtime.InteropServices;\n using System.Text;\n\n public enum PSVersion\n {\n Vista,\n Win7,\n Win8,\n WinBlue,\n WinModern\n }\n\n public static class Constants\n {\n public static readonly byte[] UniversalHWIDBlock =\n {\n 0x26, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x01, 0x0c, 0x01, 0x00\n };\n\n public static readonly byte[] KMSv4Response =\n {\n 0x00, 0x00, 0x04, 0x00, 0x62, 0x00, 0x00, 0x00, 0x30, 0x00, 0x35, 0x00, 0x34, 0x00, 0x32, 0x00,\n 0x36, 0x00, 0x2D, 0x00, 0x30, 0x00, 0x30, 0x00, 0x32, 0x00, 0x30, 0x00, 0x36, 0x00, 0x2D, 0x00,\n 0x31, 0x00, 0x36, 0x00, 0x31, 0x00, 0x2D, 0x00, 0x36, 0x00, 0x35, 0x00, 0x35, 0x00, 0x35, 0x00,\n 0x30, 0x00, 0x36, 0x00, 0x2D, 0x00, 0x30, 0x00, 0x33, 0x00, 0x2D, 0x00, 0x31, 0x00, 0x30, 0x00,\n 0x33, 0x00, 0x33, 0x00, 0x2D, 0x00, 0x39, 0x00, 0x32, 0x00, 0x30, 0x00, 0x30, 0x00, 0x2E, 0x00,\n 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x2D, 0x00, 0x30, 0x00, 0x36, 0x00, 0x35, 0x00,\n 0x32, 0x00, 0x30, 0x00, 0x31, 0x00, 0x33, 0x00, 0x00, 0x00, 0xDE, 0x19, 0x02, 0xCF, 0x1F, 0x35,\n 0x97, 0x4E, 0x8A, 0x8F, 0xB8, 0x07, 0xB1, 0x92, 0xB5, 0xB5, 0x97, 0x42, 0xEC, 0x3A, 0x76, 0x84,\n 0xD5, 0x01, 0x32, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00, 0x60, 0x27, 0x00, 0x00, 0xC4, 0x1E,\n 0xAA, 0x8B, 0xDD, 0x0C, 0xAB, 0x55, 0x6A, 0xCE, 0xAF, 0xAC, 0x7F, 0x5F, 0xBD, 0xE9\n };\n\n public static readonly byte[] KMSv5Response =\n {\n 0x00, 0x00, 0x05, 0x00, 0xBE, 0x96, 0xF9, 0x04, 0x54, 0x17, 0x3F, 0xAF, 0xE3, 0x08, 0x50, 0xEB,\n 0x22, 0xBA, 0x53, 0xBF, 0xF2, 0x6A, 0x7B, 0xC9, 0x05, 0x1D, 0xB5, 0x19, 0xDF, 0x98, 0xE2, 0x71,\n 0x4D, 0x00, 0x61, 0xE9, 0x9D, 0x03, 0xFB, 0x31, 0xF9, 0x1F, 0x2E, 0x60, 0x59, 0xC7, 0x73, 0xC8,\n 0xE8, 0xB6, 0xE1, 0x2B, 0x39, 0xC6, 0x35, 0x0E, 0x68, 0x7A, 0xAA, 0x4F, 0x28, 0x23, 0x12, 0x18,\n 0xE3, 0xAA, 0x84, 0x81, 0x6E, 0x82, 0xF0, 0x3F, 0xD9, 0x69, 0xA9, 0xDF, 0xBA, 0x5F, 0xCA, 0x32,\n 0x54, 0xB2, 0x52, 0x3B, 0x3E, 0xD1, 0x5C, 0x65, 0xBC, 0x3E, 0x59, 0x0D, 0x15, 0x9F, 0x37, 0xEC,\n 0x30, 0x9C, 0xCC, 0x1B, 0x39, 0x0D, 0x21, 0x32, 0x29, 0xA2, 0xDD, 0xC7, 0xC1, 0x69, 0xF2, 0x72,\n 0x3F, 0x00, 0x98, 0x1E, 0xF8, 0x9A, 0x79, 0x44, 0x5D, 0x25, 0x80, 0x7B, 0xF5, 0xE1, 0x7C, 0x68,\n 0x25, 0xAA, 0x0D, 0x67, 0x98, 0xE5, 0x59, 0x9B, 0x04, 0xC1, 0x23, 0x33, 0x48, 0xFB, 0x28, 0xD0,\n 0x76, 0xDF, 0x01, 0x56, 0xE7, 0xEC, 0xBF, 0x1A, 0xA2, 0x22, 0x28, 0xCA, 0xB1, 0xB4, 0x4C, 0x30,\n 0x14, 0x6F, 0xD2, 0x2E, 0x01, 0x2A, 0x04, 0xE3, 0xBD, 0xA7, 0x41, 0x2F, 0xC9, 0xEF, 0x53, 0xC0,\n 0x70, 0x48, 0xF1, 0xB2, 0xB6, 0xEA, 0xE7, 0x0F, 0x7A, 0x15, 0xD1, 0xA6, 0xFE, 0x23, 0xC8, 0xF3,\n 0xE1, 0x02, 0x9E, 0xA0, 0x4E, 0xBD, 0xF5, 0xEA, 0x53, 0x74, 0x8E, 0x74, 0xA1, 0xA1, 0xBD, 0xBE,\n 0x66, 0xC4, 0x73, 0x8F, 0x24, 0xA7, 0x2A, 0x2F, 0xE3, 0xD9, 0xF4, 0x28, 0xD9, 0xF8, 0xA3, 0x93,\n 0x03, 0x9E, 0x29, 0xAB\n };\n\n public static readonly byte[] KMSv6Response =\n {\n 0x00, 0x00, 0x06, 0x00, 0x54, 0xD3, 0x40, 0x08, 0xF3, 0xCD, 0x03, 0xEF, 0xC8, 0x15, 0x87, 0x9E,\n 0xCA, 0x2E, 0x85, 0xFB, 0xE6, 0xF6, 0x73, 0x66, 0xFB, 0xDA, 0xBB, 0x7B, 0xB1, 0xBC, 0xD6, 0xF9,\n 0x5C, 0x41, 0xA0, 0xFE, 0xE1, 0x74, 0xC4, 0xBB, 0x91, 0xE5, 0xDE, 0x6D, 0x3A, 0x11, 0xD5, 0xFC,\n 0x68, 0xC0, 0x7B, 0x82, 0xB2, 0x24, 0xD1, 0x85, 0xBA, 0x45, 0xBF, 0xF1, 0x26, 0xFA, 0xA5, 0xC6,\n 0x61, 0x70, 0x69, 0x69, 0x6E, 0x0F, 0x0B, 0x60, 0xB7, 0x3D, 0xE8, 0xF1, 0x47, 0x0B, 0x65, 0xFD,\n 0xA7, 0x30, 0x1E, 0xF6, 0xA4, 0xD0, 0x79, 0xC4, 0x58, 0x8D, 0x81, 0xFD, 0xA7, 0xE7, 0x53, 0xF1,\n 0x67, 0x78, 0xF0, 0x0F, 0x60, 0x8F, 0xC8, 0x16, 0x35, 0x22, 0x94, 0x48, 0xCB, 0x0F, 0x8E, 0xB2,\n 0x1D, 0xF7, 0x3E, 0x28, 0x42, 0x55, 0x6B, 0x07, 0xE3, 0xE8, 0x51, 0xD5, 0xFA, 0x22, 0x0C, 0x86,\n 0x65, 0x0D, 0x3F, 0xDD, 0x8D, 0x9B, 0x1B, 0xC9, 0xD3, 0xB8, 0x3A, 0xEC, 0xF1, 0x11, 0x19, 0x25,\n 0xF7, 0x84, 0x4A, 0x4C, 0x0A, 0xB5, 0x31, 0x94, 0x37, 0x76, 0xCE, 0xE7, 0xAB, 0xA9, 0x69, 0xDF,\n 0xA4, 0xC9, 0x22, 0x6C, 0x23, 0xFF, 0x6B, 0xFC, 0xDA, 0x78, 0xD8, 0xC4, 0x8F, 0x74, 0xBB, 0x26,\n 0x05, 0x00, 0x98, 0x9B, 0xE5, 0xE2, 0xAD, 0x0D, 0x57, 0x95, 0x80, 0x66, 0x8E, 0x43, 0x74, 0x87,\n 0x93, 0x1F, 0xF4, 0xB2, 0x2C, 0x20, 0x5F, 0xD8, 0x9C, 0x4C, 0x56, 0xB3, 0x57, 0x44, 0x62, 0x68,\n 0x8D, 0xAA, 0x40, 0x11, 0x9D, 0x84, 0x62, 0x0E, 0x43, 0x8A, 0x1D, 0xF0, 0x1C, 0x49, 0xD8, 0x56,\n 0xEF, 0x4C, 0xD3, 0x64, 0xBA, 0x0D, 0xEF, 0x87, 0xB5, 0x2C, 0x88, 0xF3, 0x18, 0xFF, 0x3A, 0x8C,\n 0xF5, 0xA6, 0x78, 0x5C, 0x62, 0xE3, 0x9E, 0x4C, 0xB6, 0x31, 0x2D, 0x06, 0x80, 0x92, 0xBC, 0x2E,\n 0x92, 0xA6, 0x56, 0x96\n };\n\n // 2^31 - 8 minutes\n public static readonly ulong TimerMax = (ulong)TimeSpan.FromMinutes(2147483640).Ticks;\n\n public static readonly string ZeroCID = new string('0', 48);\n }\n\n public static class BinaryReaderExt\n {\n public static void Align(this BinaryReader reader, int to)\n {\n int pos = (int)reader.BaseStream.Position;\n reader.BaseStream.Seek(-pos & (to - 1), SeekOrigin.Current);\n }\n\n public static string ReadNullTerminatedString(this BinaryReader reader, int maxLen)\n {\n return Encoding.Unicode.GetString(reader.ReadBytes(maxLen)).Split(new char[] { '\\0' }, 2)[0];\n }\n }\n\n public static class BinaryWriterExt\n {\n public static void Align(this BinaryWriter writer, int to)\n {\n int pos = (int)writer.BaseStream.Position;\n writer.WritePadding(-pos & (to - 1));\n }\n\n public static void WritePadding(this BinaryWriter writer, int len)\n {\n writer.Write(Enumerable.Repeat((byte)0, len).ToArray());\n }\n\n public static void WriteFixedString(this BinaryWriter writer, string str, int bLen)\n {\n writer.Write(Encoding.ASCII.GetBytes(str));\n writer.WritePadding(bLen - str.Length);\n }\n\n public static void WriteFixedString16(this BinaryWriter writer, string str, int bLen)\n {\n byte[] bstr = Utils.EncodeString(str);\n writer.Write(bstr);\n writer.WritePadding(bLen - bstr.Length);\n }\n\n public static byte[] GetBytes(this BinaryWriter writer)\n {\n return ((MemoryStream)writer.BaseStream).ToArray();\n }\n }\n\n public static class ByteArrayExt\n {\n public static byte[] CastToArray(this T data) where T : struct\n {\n int size = Marshal.SizeOf(typeof(T));\n byte[] result = new byte[size];\n GCHandle handle = GCHandle.Alloc(result, GCHandleType.Pinned);\n try\n {\n Marshal.StructureToPtr(data, handle.AddrOfPinnedObject(), false);\n }\n finally\n {\n handle.Free();\n }\n return result;\n }\n }\n\n public static class FileStreamExt\n {\n public static byte[] ReadAllBytes(this FileStream fs)\n {\n BinaryReader br = new BinaryReader(fs);\n return br.ReadBytes((int)fs.Length);\n }\n\n public static void WriteAllBytes(this FileStream fs, byte[] data)\n {\n fs.Seek(0, SeekOrigin.Begin);\n fs.SetLength(data.Length);\n fs.Write(data, 0, data.Length);\n }\n }\n\n public static class Utils\n {\n [DllImport(\"kernel32.dll\")]\n public static extern uint GetSystemDefaultLCID();\n\n [DllImport(\"kernel32.dll\")]\n public static extern bool Wow64EnableWow64FsRedirection(bool Wow64FsEnableRedirection);\n\n public static string DecodeString(byte[] data)\n {\n return Encoding.Unicode.GetString(data).Trim('\\0');\n }\n\n public static byte[] EncodeString(string str)\n {\n return Encoding.Unicode.GetBytes(str + '\\0');\n }\n\n public static uint CRC32(byte[] data)\n {\n const uint polynomial = 0x04C11DB7;\n uint crc = 0xffffffff;\n\n foreach (byte b in data)\n {\n crc ^= (uint)b << 24;\n for (int bit = 0; bit < 8; bit++)\n {\n if ((crc & 0x80000000) != 0)\n {\n crc = (crc << 1) ^ polynomial;\n }\n else\n {\n crc <<= 1;\n }\n }\n }\n return ~crc;\n }\n\n public static string GetArchitecture()\n {\n string arch = Environment.GetEnvironmentVariable(\"PROCESSOR_ARCHITECTURE\", EnvironmentVariableTarget.Machine).ToUpperInvariant();\n return arch == \"AMD64\" ? \"X64\" : arch;\n }\n\n public static PSVersion DetectVersion()\n {\n int build = Environment.OSVersion.Version.Build;\n\n if (build >= 9600) return PSVersion.WinModern;\n if (build >= 6000 && build <= 6003) return PSVersion.Vista;\n if (build >= 7600 && build <= 7602) return PSVersion.Win7;\n if (build == 9200) return PSVersion.Win8;\n\n throw new NotSupportedException(\"Unable to auto-detect version info\");\n }\n }\n\n public static class Logger\n {\n public static bool HideOutput = false;\n\n public static void WriteLine(string line)\n {\n if (!HideOutput) Console.WriteLine(line);\n }\n }\n}\n"], ["/TSforge/LibTSforge/TokenStore/ITokenStore.cs", "namespace LibTSforge.TokenStore\n{\n using System;\n\n public interface ITokenStore : IDisposable\n {\n void Deserialize();\n void Serialize();\n void AddEntry(TokenEntry entry);\n void AddEntries(TokenEntry[] entries);\n void DeleteEntry(string name, string ext);\n void DeleteUnpopEntry(string name, string ext);\n TokenEntry GetEntry(string name, string ext);\n TokenMeta GetMetaEntry(string name);\n void SetEntry(string name, string ext, byte[] data);\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/Common.cs", "namespace LibTSforge.PhysicalStore\n{\n using System.Runtime.InteropServices;\n\n public enum BlockType : uint\n {\n NONE,\n NAMED,\n ATTRIBUTE,\n TIMER\n }\n\n [StructLayout(LayoutKind.Sequential, Pack = 1)]\n public struct Timer\n {\n public ulong Unknown;\n public ulong Time1;\n public ulong Time2;\n public ulong Expiry;\n }\n\n [StructLayout(LayoutKind.Sequential, Pack = 1)]\n public struct VistaTimer\n {\n public ulong Time;\n public ulong Expiry;\n }\n}\n"], ["/TSforge/LibTSforge/Crypto/Keys.cs", "namespace LibTSforge.Crypto\n{\n public static class Keys\n {\n public static readonly byte[] PRODUCTION = {\n 0x07, 0x02, 0x00, 0x00, 0x00, 0xA4, 0x00, 0x00, 0x52, 0x53, 0x41, 0x32, 0x00, 0x04, 0x00, 0x00,\n 0x01, 0x00, 0x01, 0x00, 0x29, 0x87, 0xBA, 0x3F, 0x52, 0x90, 0x57, 0xD8, 0x12, 0x26, 0x6B, 0x38,\n 0xB2, 0x3B, 0xF9, 0x67, 0x08, 0x4F, 0xDD, 0x8B, 0xF5, 0xE3, 0x11, 0xB8, 0x61, 0x3A, 0x33, 0x42,\n 0x51, 0x65, 0x05, 0x86, 0x1E, 0x00, 0x41, 0xDE, 0xC5, 0xDD, 0x44, 0x60, 0x56, 0x3D, 0x14, 0x39,\n 0xB7, 0x43, 0x65, 0xE9, 0xF7, 0x2B, 0xA5, 0xF0, 0xA3, 0x65, 0x68, 0xE9, 0xE4, 0x8B, 0x5C, 0x03,\n 0x2D, 0x36, 0xFE, 0x28, 0x4C, 0xD1, 0x3C, 0x3D, 0xC1, 0x90, 0x75, 0xF9, 0x6E, 0x02, 0xE0, 0x58,\n 0x97, 0x6A, 0xCA, 0x80, 0x02, 0x42, 0x3F, 0x6C, 0x15, 0x85, 0x4D, 0x83, 0x23, 0x6A, 0x95, 0x9E,\n 0x38, 0x52, 0x59, 0x38, 0x6A, 0x99, 0xF0, 0xB5, 0xCD, 0x53, 0x7E, 0x08, 0x7C, 0xB5, 0x51, 0xD3,\n 0x8F, 0xA3, 0x0D, 0xA0, 0xFA, 0x8D, 0x87, 0x3C, 0xFC, 0x59, 0x21, 0xD8, 0x2E, 0xD9, 0x97, 0x8B,\n 0x40, 0x60, 0xB1, 0xD7, 0x2B, 0x0A, 0x6E, 0x60, 0xB5, 0x50, 0xCC, 0x3C, 0xB1, 0x57, 0xE4, 0xB7,\n 0xDC, 0x5A, 0x4D, 0xE1, 0x5C, 0xE0, 0x94, 0x4C, 0x5E, 0x28, 0xFF, 0xFA, 0x80, 0x6A, 0x13, 0x53,\n 0x52, 0xDB, 0xF3, 0x04, 0x92, 0x43, 0x38, 0xB9, 0x1B, 0xD9, 0x85, 0x54, 0x7B, 0x14, 0xC7, 0x89,\n 0x16, 0x8A, 0x4B, 0x82, 0xA1, 0x08, 0x02, 0x99, 0x23, 0x48, 0xDD, 0x75, 0x9C, 0xC8, 0xC1, 0xCE,\n 0xB0, 0xD7, 0x1B, 0xD8, 0xFB, 0x2D, 0xA7, 0x2E, 0x47, 0xA7, 0x18, 0x4B, 0xF6, 0x29, 0x69, 0x44,\n 0x30, 0x33, 0xBA, 0xA7, 0x1F, 0xCE, 0x96, 0x9E, 0x40, 0xE1, 0x43, 0xF0, 0xE0, 0x0D, 0x0A, 0x32,\n 0xB4, 0xEE, 0xA1, 0xC3, 0x5E, 0x9B, 0xC7, 0x7F, 0xF5, 0x9D, 0xD8, 0xF2, 0x0F, 0xD9, 0x8F, 0xAD,\n 0x75, 0x0A, 0x00, 0xD5, 0x25, 0x43, 0xF7, 0xAE, 0x51, 0x7F, 0xB7, 0xDE, 0xB7, 0xAD, 0xFB, 0xCE,\n 0x83, 0xE1, 0x81, 0xFF, 0xDD, 0xA2, 0x77, 0xFE, 0xEB, 0x27, 0x1F, 0x10, 0xFA, 0x82, 0x37, 0xF4,\n 0x7E, 0xCC, 0xE2, 0xA1, 0x58, 0xC8, 0xAF, 0x1D, 0x1A, 0x81, 0x31, 0x6E, 0xF4, 0x8B, 0x63, 0x34,\n 0xF3, 0x05, 0x0F, 0xE1, 0xCC, 0x15, 0xDC, 0xA4, 0x28, 0x7A, 0x9E, 0xEB, 0x62, 0xD8, 0xD8, 0x8C,\n 0x85, 0xD7, 0x07, 0x87, 0x90, 0x2F, 0xF7, 0x1C, 0x56, 0x85, 0x2F, 0xEF, 0x32, 0x37, 0x07, 0xAB,\n 0xB0, 0xE6, 0xB5, 0x02, 0x19, 0x35, 0xAF, 0xDB, 0xD4, 0xA2, 0x9C, 0x36, 0x80, 0xC6, 0xDC, 0x82,\n 0x08, 0xE0, 0xC0, 0x5F, 0x3C, 0x59, 0xAA, 0x4E, 0x26, 0x03, 0x29, 0xB3, 0x62, 0x58, 0x41, 0x59,\n 0x3A, 0x37, 0x43, 0x35, 0xE3, 0x9F, 0x34, 0xE2, 0xA1, 0x04, 0x97, 0x12, 0x9D, 0x8C, 0xAD, 0xF7,\n 0xFB, 0x8C, 0xA1, 0xA2, 0xE9, 0xE4, 0xEF, 0xD9, 0xC5, 0xE5, 0xDF, 0x0E, 0xBF, 0x4A, 0xE0, 0x7A,\n 0x1E, 0x10, 0x50, 0x58, 0x63, 0x51, 0xE1, 0xD4, 0xFE, 0x57, 0xB0, 0x9E, 0xD7, 0xDA, 0x8C, 0xED,\n 0x7D, 0x82, 0xAC, 0x2F, 0x25, 0x58, 0x0A, 0x58, 0xE6, 0xA4, 0xF4, 0x57, 0x4B, 0xA4, 0x1B, 0x65,\n 0xB9, 0x4A, 0x87, 0x46, 0xEB, 0x8C, 0x0F, 0x9A, 0x48, 0x90, 0xF9, 0x9F, 0x76, 0x69, 0x03, 0x72,\n 0x77, 0xEC, 0xC1, 0x42, 0x4C, 0x87, 0xDB, 0x0B, 0x3C, 0xD4, 0x74, 0xEF, 0xE5, 0x34, 0xE0, 0x32,\n 0x45, 0xB0, 0xF8, 0xAB, 0xD5, 0x26, 0x21, 0xD7, 0xD2, 0x98, 0x54, 0x8F, 0x64, 0x88, 0x20, 0x2B,\n 0x14, 0xE3, 0x82, 0xD5, 0x2A, 0x4B, 0x8F, 0x4E, 0x35, 0x20, 0x82, 0x7E, 0x1B, 0xFE, 0xFA, 0x2C,\n 0x79, 0x6C, 0x6E, 0x66, 0x94, 0xBB, 0x0A, 0xEB, 0xBA, 0xD9, 0x70, 0x61, 0xE9, 0x47, 0xB5, 0x82,\n 0xFC, 0x18, 0x3C, 0x66, 0x3A, 0x09, 0x2E, 0x1F, 0x61, 0x74, 0xCA, 0xCB, 0xF6, 0x7A, 0x52, 0x37,\n 0x1D, 0xAC, 0x8D, 0x63, 0x69, 0x84, 0x8E, 0xC7, 0x70, 0x59, 0xDD, 0x2D, 0x91, 0x1E, 0xF7, 0xB1,\n 0x56, 0xED, 0x7A, 0x06, 0x9D, 0x5B, 0x33, 0x15, 0xDD, 0x31, 0xD0, 0xE6, 0x16, 0x07, 0x9B, 0xA5,\n 0x94, 0x06, 0x7D, 0xC1, 0xE9, 0xD6, 0xC8, 0xAF, 0xB4, 0x1E, 0x2D, 0x88, 0x06, 0xA7, 0x63, 0xB8,\n 0xCF, 0xC8, 0xA2, 0x6E, 0x84, 0xB3, 0x8D, 0xE5, 0x47, 0xE6, 0x13, 0x63, 0x8E, 0xD1, 0x7F, 0xD4,\n 0x81, 0x44, 0x38, 0xBF\n };\n\n public static readonly byte[] TEST = {\n 0x07, 0x02, 0x00, 0x00, 0x00, 0xA4, 0x00, 0x00, 0x52, 0x53, 0x41, 0x32, 0x00, 0x04, 0x00, 0x00,\n 0x01, 0x00, 0x01, 0x00, 0x0F, 0xBE, 0x77, 0xB8, 0xDD, 0x54, 0x36, 0xDD, 0x67, 0xD4, 0x17, 0x66,\n 0xC4, 0x13, 0xD1, 0x3F, 0x1E, 0x16, 0x0C, 0x16, 0x35, 0xAB, 0x6D, 0x3D, 0x34, 0x51, 0xED, 0x3F,\n 0x57, 0x14, 0xB6, 0xB7, 0x08, 0xE9, 0xD9, 0x7A, 0x80, 0xB3, 0x5F, 0x9B, 0x3A, 0xFD, 0x9E, 0x37,\n 0x3A, 0x53, 0x72, 0x67, 0x92, 0x60, 0xC3, 0xEF, 0xB5, 0x8E, 0x1E, 0xCF, 0x9D, 0x9C, 0xD3, 0x90,\n 0xE5, 0xDD, 0xF4, 0xDB, 0xF3, 0xD6, 0x65, 0xB3, 0xC1, 0xBD, 0x69, 0xE1, 0x76, 0x95, 0xD9, 0x37,\n 0xB8, 0x5E, 0xCA, 0x3D, 0x98, 0xFC, 0x50, 0x5C, 0x98, 0xAE, 0xE3, 0x7C, 0x4C, 0x27, 0xC3, 0xD0,\n 0xCE, 0x78, 0x06, 0x51, 0x68, 0x23, 0xE6, 0x70, 0xF8, 0x7C, 0xAE, 0x36, 0xBE, 0x41, 0x57, 0xE2,\n 0xC3, 0x2D, 0xAF, 0x21, 0xB1, 0xB3, 0x15, 0x81, 0x19, 0x26, 0x6B, 0x10, 0xB3, 0xE9, 0xD1, 0x45,\n 0x21, 0x77, 0x9C, 0xF6, 0xE1, 0xDD, 0xB6, 0x78, 0x9D, 0x1D, 0x32, 0x61, 0xBC, 0x2B, 0xDB, 0x86,\n 0xFB, 0x07, 0x24, 0x10, 0x19, 0x4F, 0x09, 0x6D, 0x03, 0x90, 0xD4, 0x5E, 0x30, 0x85, 0xC5, 0x58,\n 0x7E, 0x5D, 0xAE, 0x9F, 0x64, 0x93, 0x04, 0x82, 0x09, 0x0E, 0x1C, 0x66, 0xA8, 0x95, 0x91, 0x51,\n 0xB2, 0xED, 0x9A, 0x75, 0x04, 0x87, 0x50, 0xAC, 0xCC, 0x20, 0x06, 0x45, 0xB9, 0x7B, 0x42, 0x53,\n 0x9A, 0xD1, 0x29, 0xFC, 0xEF, 0xB9, 0x47, 0x16, 0x75, 0x69, 0x05, 0x87, 0x2B, 0xCB, 0x54, 0x9C,\n 0x21, 0x2D, 0x50, 0x8E, 0x12, 0xDE, 0xD3, 0x6B, 0xEC, 0x92, 0xA1, 0xB1, 0xE9, 0x4B, 0xBF, 0x6B,\n 0x9A, 0x38, 0xC7, 0x13, 0xFA, 0x78, 0xA1, 0x3C, 0x1E, 0xBB, 0x38, 0x31, 0xBB, 0x0C, 0x9F, 0x70,\n 0x1A, 0x31, 0x00, 0xD7, 0x5A, 0xA5, 0x84, 0x24, 0x89, 0x80, 0xF5, 0x88, 0xC2, 0x31, 0x18, 0xDC,\n 0x53, 0x05, 0x5D, 0xFA, 0x81, 0xDC, 0xE1, 0xCE, 0xA4, 0xAA, 0xBA, 0x07, 0xDA, 0x28, 0x4F, 0x64,\n 0x0E, 0x84, 0x9B, 0x06, 0xDE, 0xC8, 0x78, 0x66, 0x2F, 0x17, 0x25, 0xA8, 0x9C, 0x99, 0xFC, 0xBC,\n 0x7D, 0x01, 0x42, 0xD7, 0x35, 0xBF, 0x19, 0xF6, 0x3F, 0x20, 0xD9, 0x98, 0x9B, 0x5D, 0xDD, 0x39,\n 0xBE, 0x81, 0x00, 0x0B, 0xDE, 0x6F, 0x14, 0xCA, 0x7E, 0xF8, 0xC0, 0x26, 0xA8, 0x1D, 0xD1, 0x16,\n 0x88, 0x64, 0x87, 0x36, 0x45, 0x37, 0x50, 0xDA, 0x6C, 0xEB, 0x85, 0xB5, 0x43, 0x29, 0x88, 0x6F,\n 0x2F, 0xFE, 0x8D, 0x12, 0x8B, 0x72, 0xB7, 0x5A, 0xCB, 0x66, 0xC2, 0x2E, 0x1D, 0x7D, 0x42, 0xA6,\n 0xF4, 0xFE, 0x26, 0x5D, 0x54, 0x9E, 0x77, 0x1D, 0x97, 0xC2, 0xF3, 0xFD, 0x60, 0xB3, 0x22, 0x88,\n 0xCA, 0x27, 0x99, 0xDF, 0xC8, 0xB1, 0xD7, 0xC6, 0x54, 0xA6, 0x50, 0xB9, 0x54, 0xF5, 0xDE, 0xFE,\n 0xE1, 0x81, 0xA2, 0xBE, 0x81, 0x9F, 0x48, 0xFF, 0x2F, 0xB8, 0xA4, 0xB3, 0x17, 0xD8, 0xC1, 0xB9,\n 0x5D, 0x21, 0x3D, 0xA2, 0xED, 0x1C, 0x96, 0x66, 0xEE, 0x1F, 0x47, 0xCF, 0x62, 0xFA, 0xD6, 0xC1,\n 0x87, 0x5B, 0xC4, 0xE5, 0xD9, 0x08, 0x38, 0x22, 0xFA, 0x21, 0xBD, 0xF2, 0x88, 0xDA, 0xE2, 0x24,\n 0x25, 0x1F, 0xF1, 0x0B, 0x2D, 0xAE, 0x04, 0xBE, 0xA6, 0x7F, 0x75, 0x8C, 0xD9, 0x97, 0xE1, 0xCA,\n 0x35, 0xB9, 0xFC, 0x6F, 0x01, 0x68, 0x11, 0xD3, 0x68, 0x32, 0xD0, 0xC1, 0x69, 0xA3, 0xCF, 0x9B,\n 0x10, 0xE4, 0x69, 0xA7, 0xCF, 0xE1, 0xFE, 0x2A, 0x07, 0x9E, 0xC1, 0x37, 0x84, 0x68, 0xE5, 0xC5,\n 0xAB, 0x25, 0xEC, 0x7D, 0x7D, 0x74, 0x6A, 0xD1, 0xD5, 0x4D, 0xD7, 0xE1, 0x7D, 0xDE, 0x30, 0x4B,\n 0xE6, 0x5D, 0xCD, 0x91, 0x59, 0xF6, 0x80, 0xFD, 0xC6, 0x3C, 0xDD, 0x94, 0x7F, 0x15, 0x9D, 0xEF,\n 0x2F, 0x00, 0x62, 0xD7, 0xDA, 0xB9, 0xB3, 0xD9, 0x8D, 0xE8, 0xD7, 0x3C, 0x96, 0x45, 0x5D, 0x1E,\n 0x50, 0xFB, 0xAA, 0x43, 0xD3, 0x47, 0x77, 0x81, 0xE9, 0x67, 0xE4, 0xFE, 0xDF, 0x42, 0x79, 0xCB,\n 0xA7, 0xAD, 0x5D, 0x48, 0xF5, 0xB7, 0x74, 0x96, 0x12, 0x23, 0x06, 0x70, 0x42, 0x68, 0x7A, 0x44,\n 0xFC, 0xA0, 0x31, 0x7F, 0x68, 0xCA, 0xA2, 0x14, 0x5D, 0xA3, 0xCF, 0x42, 0x23, 0xAB, 0x47, 0xF6,\n 0xB2, 0xFC, 0x6D, 0xF1\n };\n }\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 19:06:23", "created_task_model": "DeepSeek-R1", "function_skeleton": "public static void Reset (PSVersion version, bool production) {}", "code_description": "This code segment functions to: Terminate a background service, remove specific timer-related entries from a persistent storage system, and restart the service to apply configuration changes for resetting temporary operational periods."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\n public static void Reset(PSVersion version, bool production)\n {\n var psDb = PhysicalStoreManager.Instance.GetPS(version, production);\n if (psDb != null)\n {\n foreach (var key in LicenseCheckKeys.All)\n {\n psDb.Set(key.Name + \"_check_time\", 0);\n psDb.Set(key.Name + \"_type\", 0);\n }\n }\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 19-06-46"}, "editdistance_info": {"edit_distance": 22.3881, "calculate_time": "2025-08-20 19:06:46", "true_code_clean": "public static void Reset(PSVersion version, bool production)\n {\n SPPUtils.KillSPP(version);\n Logger.WriteLine(\"Writing TrustedStore data...\");\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string value = \"msft:sl/timer\";\n List blocks = store.FindBlocks(value).ToList();\n foreach (PSBlock block in blocks)\n {\n store.DeleteBlock(block.KeyAsStr, block.ValueAsStr);\n }\n }\n SPPUtils.RestartSPP(version);\n Logger.WriteLine(\"Successfully reset all grace and evaluation period timers.\");\n }", "predict_code_clean": "public static void Reset(PSVersion version, bool production)\n {\n var psDb = PhysicalStoreManager.Instance.GetPS(version, production);\n if (psDb != null)\n {\n foreach (var key in LicenseCheckKeys.All)\n {\n psDb.Set(key.Name + \"_check_time\", 0);\n psDb.Set(key.Name + \"_type\", 0);\n }\n }\n }"}} {"repo_name": "TSforge", "file_name": "/TSforge/LibTSforge/SPP/SPSys.cs", "inference_info": {"prefix_code": "namespace LibTSforge.SPP\n{\n using Microsoft.Win32.SafeHandles;\n using System;\n using System.Runtime.InteropServices;\n\n public class SPSys\n {\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n private static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);\n private static SafeFileHandle CreateFileSafe(string device)\n {\n return new SafeFileHandle(CreateFile(device, 0xC0000000, 0, IntPtr.Zero, 3, 0, IntPtr.Zero), true);\n }\n\n [return: MarshalAs(UnmanagedType.Bool)]\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n private static extern bool DeviceIoControl([In] SafeFileHandle hDevice, [In] uint dwIoControlCode, [In] IntPtr lpInBuffer, [In] int nInBufferSize, [Out] IntPtr lpOutBuffer, [In] int nOutBufferSize, out int lpBytesReturned, [In] IntPtr lpOverlapped);\n\n public static bool IsSpSysRunning()\n {\n SafeFileHandle file = CreateFileSafe(@\"\\\\.\\SpDevice\");\n IntPtr buffer = Marshal.AllocHGlobal(1);\n int bytesReturned;\n DeviceIoControl(file, 0x80006008, IntPtr.Zero, 0, buffer, 1, out bytesReturned, IntPtr.Zero);\n bool running = Marshal.ReadByte(buffer) != 0;\n Marshal.FreeHGlobal(buffer);\n file.Close();\n return running;\n }\n\n ", "suffix_code": "\n }\n}\n", "middle_code": "public static int ControlSpSys(bool start)\n {\n SafeFileHandle file = CreateFileSafe(@\"\\\\.\\SpDevice\");\n IntPtr buffer = Marshal.AllocHGlobal(4);\n int bytesReturned;\n DeviceIoControl(file, start ? 0x8000a000 : 0x8000a004, IntPtr.Zero, 0, buffer, 4, out bytesReturned, IntPtr.Zero);\n int result = Marshal.ReadInt32(buffer);\n Marshal.FreeHGlobal(buffer);\n file.Close();\n return result;\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/TSforge/LibTSforge/SPP/SLAPI.cs", "namespace LibTSforge.SPP\n{\n using System;\n using System.Collections.Generic;\n using System.Linq;\n using System.Runtime.InteropServices;\n using System.Text;\n\n public static class SLApi\n {\n private enum SLIDTYPE\n {\n SL_ID_APPLICATION,\n SL_ID_PRODUCT_SKU,\n SL_ID_LICENSE_FILE,\n SL_ID_LICENSE,\n SL_ID_PKEY,\n SL_ID_ALL_LICENSES,\n SL_ID_ALL_LICENSE_FILES,\n SL_ID_STORE_TOKEN,\n SL_ID_LAST\n }\n\n private enum SLDATATYPE\n {\n SL_DATA_NONE,\n SL_DATA_SZ,\n SL_DATA_DWORD,\n SL_DATA_BINARY,\n SL_DATA_MULTI_SZ,\n SL_DATA_SUM\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct SL_LICENSING_STATUS\n {\n public Guid SkuId;\n public uint eStatus;\n public uint dwGraceTime;\n public uint dwTotalGraceDays;\n public uint hrReason;\n public ulong qwValidityExpiration;\n }\n\n public static readonly Guid WINDOWS_APP_ID = new Guid(\"55c92734-d682-4d71-983e-d6ec3f16059f\");\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode, PreserveSig = false)]\n private static extern void SLOpen(out IntPtr hSLC);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode, PreserveSig = false)]\n private static extern void SLClose(IntPtr hSLC);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetWindowsInformationDWORD(string ValueName, ref int Value);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLInstallProofOfPurchase(IntPtr hSLC, string pwszPKeyAlgorithm, string pwszPKeyString, uint cbPKeySpecificData, byte[] pbPKeySpecificData, ref Guid PKeyId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLUninstallProofOfPurchase(IntPtr hSLC, ref Guid PKeyId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetPKeyInformation(IntPtr hSLC, ref Guid pPKeyId, string pwszValueName, out SLDATATYPE peDataType, out uint pcbValue, out IntPtr ppbValue);\n\n [DllImport(\"slcext.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLActivateProduct(IntPtr hSLC, ref Guid pProductSkuId, byte[] cbAppSpecificData, byte[] pvAppSpecificData, byte[] pActivationInfo, string pwszProxyServer, ushort wProxyPort);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGenerateOfflineInstallationId(IntPtr hSLC, ref Guid pProductSkuId, ref string ppwszInstallationId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLDepositOfflineConfirmationId(IntPtr hSLC, ref Guid pProductSkuId, string pwszInstallationId, string pwszConfirmationId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetSLIDList(IntPtr hSLC, SLIDTYPE eQueryIdType, ref Guid pQueryId, SLIDTYPE eReturnIdType, out uint pnReturnIds, out IntPtr ppReturnIds);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode, PreserveSig = false)]\n private static extern void SLGetLicensingStatusInformation(IntPtr hSLC, ref Guid pAppID, IntPtr pProductSkuId, string pwszRightName, out uint pnStatusCount, out IntPtr ppLicensingStatus);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetInstalledProductKeyIds(IntPtr hSLC, ref Guid pProductSkuId, out uint pnProductKeyIds, out IntPtr ppProductKeyIds);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLConsumeWindowsRight(uint unknown);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetProductSkuInformation(IntPtr hSLC, ref Guid pProductSkuId, string pwszValueName, out SLDATATYPE peDataType, out uint pcbValue, out IntPtr ppbValue);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetLicense(IntPtr hSLC, ref Guid pLicenseFileId, out uint pcbLicenseFile, out IntPtr ppbLicenseFile);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLSetCurrentProductKey(IntPtr hSLC, ref Guid pProductSkuId, ref Guid pProductKeyId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLFireEvent(IntPtr hSLC, string pwszEventId, ref Guid pApplicationId);\n\n private class SLContext : IDisposable\n {\n public readonly IntPtr Handle;\n\n public SLContext()\n {\n SLOpen(out Handle);\n }\n\n public void Dispose()\n {\n SLClose(Handle);\n GC.SuppressFinalize(this);\n }\n\n ~SLContext()\n {\n Dispose();\n }\n }\n\n public static Guid GetDefaultActivationID(Guid appId, bool includeActivated)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr pLicStat;\n\n SLGetLicensingStatusInformation(sl.Handle, ref appId, IntPtr.Zero, null, out count, out pLicStat);\n\n unsafe\n {\n SL_LICENSING_STATUS* licensingStatuses = (SL_LICENSING_STATUS*)pLicStat;\n for (int i = 0; i < count; i++)\n {\n SL_LICENSING_STATUS slStatus = licensingStatuses[i];\n\n Guid actId = slStatus.SkuId;\n if (GetInstalledPkeyID(actId) == Guid.Empty) continue;\n if (IsAddon(actId)) continue;\n if (!includeActivated && (slStatus.eStatus == 1)) continue;\n\n return actId;\n }\n }\n\n return Guid.Empty;\n }\n }\n\n public static string GetInstallationID(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n string installationId = null;\n return SLGenerateOfflineInstallationId(sl.Handle, ref actId, ref installationId) == 0 ? installationId : null;\n }\n }\n\n public static Guid GetInstalledPkeyID(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr pProductKeyIds;\n\n uint status = SLGetSLIDList(sl.Handle, SLIDTYPE.SL_ID_PRODUCT_SKU, ref actId, SLIDTYPE.SL_ID_PKEY, out count, out pProductKeyIds);\n\n if (status != 0 || count == 0)\n {\n return Guid.Empty;\n }\n\n unsafe { return *(Guid*)pProductKeyIds; }\n }\n }\n\n public static uint DepositConfirmationID(Guid actId, string installationId, string confirmationId)\n {\n using (SLContext sl = new SLContext())\n {\n return SLDepositOfflineConfirmationId(sl.Handle, ref actId, installationId, confirmationId);\n }\n }\n\n public static void RefreshLicenseStatus()\n {\n SLConsumeWindowsRight(0);\n }\n\n public static void RefreshTrustedTime(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n SLDATATYPE type;\n uint count;\n IntPtr ppbValue;\n\n SLGetProductSkuInformation(sl.Handle, ref actId, \"TrustedTime\", out type, out count, out ppbValue);\n }\n }\n\n public static void FireStateChangedEvent(Guid appId)\n {\n using (SLContext sl = new SLContext())\n {\n SLFireEvent(sl.Handle, \"msft:rm/event/licensingstatechanged\", ref appId);\n }\n }\n\n public static Guid GetAppId(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr pAppIds;\n\n uint status = SLGetSLIDList(sl.Handle, SLIDTYPE.SL_ID_PRODUCT_SKU, ref actId, SLIDTYPE.SL_ID_APPLICATION, out count, out pAppIds);\n\n if (status != 0 || count == 0)\n {\n return Guid.Empty;\n }\n\n unsafe { return *(Guid*)pAppIds; }\n }\n }\n\n public static bool IsAddon(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n SLDATATYPE type;\n IntPtr ppbValue;\n\n uint status = SLGetProductSkuInformation(sl.Handle, ref actId, \"DependsOn\", out type, out count, out ppbValue);\n return (int)status >= 0 && status != 0xC004F012;\n }\n }\n\n public static Guid GetLicenseFileId(Guid licId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr ppReturnLics;\n\n uint status = SLGetSLIDList(sl.Handle, SLIDTYPE.SL_ID_LICENSE, ref licId, SLIDTYPE.SL_ID_LICENSE_FILE, out count, out ppReturnLics);\n\n if (status != 0 || count == 0)\n {\n return Guid.Empty;\n }\n\n unsafe { return *(Guid*)ppReturnLics; }\n }\n }\n\n public static Guid GetPkeyConfigFileId(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n SLDATATYPE type;\n uint len;\n IntPtr ppReturnLics;\n\n uint status = SLGetProductSkuInformation(sl.Handle, ref actId, \"pkeyConfigLicenseId\", out type, out len, out ppReturnLics);\n\n if (status != 0 || len == 0)\n {\n return Guid.Empty;\n }\n\n Guid pkcId = new Guid(Marshal.PtrToStringAuto(ppReturnLics));\n return GetLicenseFileId(pkcId);\n }\n }\n\n public static string GetLicenseContents(Guid fileId)\n {\n if (fileId == Guid.Empty) throw new ArgumentException(\"License contents could not be retrieved.\");\n\n using (SLContext sl = new SLContext())\n {\n uint dataLen;\n IntPtr dataPtr;\n\n if (SLGetLicense(sl.Handle, ref fileId, out dataLen, out dataPtr) != 0)\n {\n return null;\n }\n\n byte[] data = new byte[dataLen];\n Marshal.Copy(dataPtr, data, 0, (int)dataLen);\n\n data = data.Skip(Array.IndexOf(data, (byte)'<')).ToArray();\n return Encoding.UTF8.GetString(data);\n }\n }\n\n public static bool IsPhoneActivatable(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n SLDATATYPE type;\n IntPtr ppbValue;\n\n uint status = SLGetProductSkuInformation(sl.Handle, ref actId, \"msft:sl/EUL/PHONE/PUBLIC\", out type, out count, out ppbValue);\n return status != 0xC004F012;\n }\n }\n\n public static string GetPKeyChannel(Guid pkeyId)\n {\n using (SLContext sl = new SLContext())\n {\n SLDATATYPE type;\n uint len;\n IntPtr ppbValue;\n\n uint status = SLGetPKeyInformation(sl.Handle, ref pkeyId, \"Channel\", out type, out len, out ppbValue);\n\n if (status != 0 || len == 0)\n {\n return null;\n }\n\n return Marshal.PtrToStringAuto(ppbValue);\n }\n }\n\n public static string GetMetaStr(Guid actId, string value)\n {\n using (SLContext sl = new SLContext())\n {\n uint len;\n SLDATATYPE type;\n IntPtr ppbValue;\n\n uint status = SLGetProductSkuInformation(sl.Handle, ref actId, value, out type, out len, out ppbValue);\n\n if (status != 0 || len == 0 || type != SLDATATYPE.SL_DATA_SZ)\n {\n return null;\n }\n\n return Marshal.PtrToStringAuto(ppbValue);\n }\n }\n\n public static List GetActivationIds(Guid appId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr pLicStat;\n\n SLGetLicensingStatusInformation(sl.Handle, ref appId, IntPtr.Zero, null, out count, out pLicStat);\n\n List result = new List();\n\n unsafe\n {\n SL_LICENSING_STATUS* licensingStatuses = (SL_LICENSING_STATUS*)pLicStat;\n for (int i = 0; i < count; i++)\n {\n result.Add(licensingStatuses[i].SkuId);\n }\n }\n\n return result;\n }\n }\n\n public static uint SetCurrentProductKey(Guid actId, Guid pkeyId)\n {\n using (SLContext sl = new SLContext())\n {\n return SLSetCurrentProductKey(sl.Handle, ref actId, ref pkeyId);\n }\n }\n\n public static uint InstallProductKey(ProductKey pkey)\n {\n using (SLContext sl = new SLContext())\n {\n Guid pkeyId = Guid.Empty;\n return SLInstallProofOfPurchase(sl.Handle, pkey.GetAlgoUri(), pkey.ToString(), 0, null, ref pkeyId);\n }\n }\n\n public static void UninstallProductKey(Guid pkeyId)\n {\n using (SLContext sl = new SLContext())\n {\n SLUninstallProofOfPurchase(sl.Handle, ref pkeyId);\n }\n }\n\n public static void UninstallAllProductKeys(Guid appId)\n {\n foreach (Guid actId in GetActivationIds(appId))\n {\n Guid pkeyId = GetInstalledPkeyID(actId);\n if (pkeyId == Guid.Empty) continue;\n if (IsAddon(actId)) continue;\n UninstallProductKey(pkeyId);\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/SPP/SPPUtils.cs", "namespace LibTSforge.SPP\n{\n using Microsoft.Win32;\n using System;\n using System.IO;\n using System.Linq;\n using System.ServiceProcess;\n using Crypto;\n using PhysicalStore;\n using TokenStore;\n\n public static class SPPUtils\n {\n public static void KillSPP(PSVersion version)\n {\n ServiceController sc;\n\n string svcName = version == PSVersion.Vista ? \"slsvc\" : \"sppsvc\";\n\n try\n {\n sc = new ServiceController(svcName);\n\n if (sc.Status == ServiceControllerStatus.Stopped)\n return;\n }\n catch (InvalidOperationException ex)\n {\n throw new InvalidOperationException(string.Format(\"Unable to access {0}: \", svcName) + ex.Message);\n }\n\n Logger.WriteLine(string.Format(\"Stopping {0}...\", svcName));\n\n bool stopped = false;\n\n for (int i = 0; stopped == false && i < 1080; i++)\n {\n try\n {\n if (sc.Status != ServiceControllerStatus.StopPending)\n sc.Stop();\n\n sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromMilliseconds(500));\n }\n catch (System.ServiceProcess.TimeoutException)\n {\n continue;\n }\n catch (InvalidOperationException ex)\n {\n Logger.WriteLine(\"Warning: Stopping sppsvc failed, retrying. Details: \" + ex.Message);\n System.Threading.Thread.Sleep(500);\n continue;\n }\n\n stopped = true;\n }\n\n if (!stopped)\n throw new System.TimeoutException(string.Format(\"Failed to stop {0}\", svcName));\n\n Logger.WriteLine(string.Format(\"{0} stopped successfully.\", svcName));\n\n if (version == PSVersion.Vista && SPSys.IsSpSysRunning())\n {\n Logger.WriteLine(\"Unloading spsys...\");\n\n int status = SPSys.ControlSpSys(false);\n\n if (status < 0)\n {\n throw new IOException(\"Failed to unload spsys\");\n }\n\n Logger.WriteLine(\"spsys unloaded successfully.\");\n }\n }\n\n public static void RestartSPP(PSVersion version)\n {\n if (version == PSVersion.Vista)\n {\n ServiceController sc;\n\n try\n {\n sc = new ServiceController(\"slsvc\");\n\n if (sc.Status == ServiceControllerStatus.Running)\n return;\n }\n catch (InvalidOperationException ex)\n {\n throw new InvalidOperationException(\"Unable to access slsvc: \" + ex.Message);\n }\n\n Logger.WriteLine(\"Starting slsvc...\");\n\n bool started = false;\n\n for (int i = 0; started == false && i < 360; i++)\n {\n try\n {\n if (sc.Status != ServiceControllerStatus.StartPending)\n sc.Start();\n\n sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMilliseconds(500));\n }\n catch (System.ServiceProcess.TimeoutException)\n {\n continue;\n }\n catch (InvalidOperationException ex)\n {\n Logger.WriteLine(\"Warning: Starting slsvc failed, retrying. Details: \" + ex.Message);\n System.Threading.Thread.Sleep(500);\n continue;\n }\n\n started = true;\n }\n\n if (!started)\n throw new System.TimeoutException(\"Failed to start slsvc\");\n\n Logger.WriteLine(\"slsvc started successfully.\");\n }\n\n SLApi.RefreshLicenseStatus();\n }\n\n public static bool DetectCurrentKey()\n {\n SLApi.RefreshLicenseStatus();\n\n using (RegistryKey wpaKey = Registry.LocalMachine.OpenSubKey(@\"SYSTEM\\WPA\"))\n {\n foreach (string subKey in wpaKey.GetSubKeyNames())\n {\n if (subKey.StartsWith(\"8DEC0AF1\"))\n {\n return subKey.Contains(\"P\");\n }\n }\n }\n\n throw new FileNotFoundException(\"Failed to autodetect key type, specify physical store key with /prod or /test arguments.\");\n }\n\n public static string GetPSPath(PSVersion version)\n {\n switch (version)\n {\n case PSVersion.Vista:\n case PSVersion.Win7:\n return Directory.GetFiles(\n Environment.GetFolderPath(Environment.SpecialFolder.System),\n \"7B296FB0-376B-497e-B012-9C450E1B7327-*.C7483456-A289-439d-8115-601632D005A0\")\n .FirstOrDefault() ?? \"\";\n default:\n string psDir = Environment.ExpandEnvironmentVariables(\n (string)Registry.GetValue(\n @\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform\",\n \"TokenStore\",\n \"\"\n )\n );\n string psPath = Path.Combine(psDir, \"data.dat\");\n\n if (string.IsNullOrEmpty(psDir) || !File.Exists(psPath))\n {\n string[] psDirs =\n {\n @\"spp\\store\",\n @\"spp\\store\\2.0\",\n @\"spp\\store_test\",\n @\"spp\\store_test\\2.0\"\n };\n\n foreach (string dir in psDirs)\n {\n psPath = Path.Combine(\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.System),\n dir\n ),\n \"data.dat\"\n );\n\n if (File.Exists(psPath)) return psPath;\n }\n } \n else\n {\n return psPath;\n }\n\n throw new FileNotFoundException(\"Failed to locate physical store.\");\n }\n }\n\n public static string GetTokensPath(PSVersion version)\n {\n switch (version)\n {\n case PSVersion.Vista:\n return Path.Combine(\n Environment.ExpandEnvironmentVariables(\"%WINDIR%\"),\n @\"ServiceProfiles\\NetworkService\\AppData\\Roaming\\Microsoft\\SoftwareLicensing\\tokens.dat\"\n );\n case PSVersion.Win7:\n return Path.Combine(\n Environment.ExpandEnvironmentVariables(\"%WINDIR%\"),\n @\"ServiceProfiles\\NetworkService\\AppData\\Roaming\\Microsoft\\SoftwareProtectionPlatform\\tokens.dat\"\n );\n default:\n string tokDir = Environment.ExpandEnvironmentVariables(\n (string)Registry.GetValue(\n @\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform\",\n \"TokenStore\",\n \"\"\n )\n );\n string tokPath = Path.Combine(tokDir, \"tokens.dat\");\n\n if (string.IsNullOrEmpty(tokDir) || !File.Exists(tokPath))\n {\n string[] tokDirs =\n {\n @\"spp\\store\",\n @\"spp\\store\\2.0\",\n @\"spp\\store_test\",\n @\"spp\\store_test\\2.0\"\n };\n\n foreach (string dir in tokDirs)\n {\n tokPath = Path.Combine(\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.System),\n dir\n ),\n \"tokens.dat\"\n );\n\n if (File.Exists(tokPath)) return tokPath;\n }\n }\n else\n {\n return tokPath;\n }\n\n throw new FileNotFoundException(\"Failed to locate token store.\");\n }\n }\n\n public static IPhysicalStore GetStore(PSVersion version, bool production)\n {\n string psPath = GetPSPath(version);\n\n switch (version)\n {\n case PSVersion.Vista:\n return new PhysicalStoreVista(psPath, production);\n case PSVersion.Win7:\n return new PhysicalStoreWin7(psPath, production);\n default:\n return new PhysicalStoreModern(psPath, production, version);\n }\n }\n\n public static ITokenStore GetTokenStore(PSVersion version)\n {\n string tokPath = GetTokensPath(version);\n\n return new TokenStoreModern(tokPath);\n }\n\n public static void DumpStore(PSVersion version, bool production, string filePath, string encrFilePath)\n {\n bool manageSpp = false;\n\n if (encrFilePath == null)\n {\n encrFilePath = GetPSPath(version);\n manageSpp = true;\n KillSPP(version);\n }\n\n if (string.IsNullOrEmpty(encrFilePath) || !File.Exists(encrFilePath))\n {\n throw new FileNotFoundException(\"Store does not exist at expected path '\" + encrFilePath + \"'.\");\n }\n\n try\n {\n using (FileStream fs = File.Open(encrFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))\n {\n byte[] encrData = fs.ReadAllBytes();\n File.WriteAllBytes(filePath, PhysStoreCrypto.DecryptPhysicalStore(encrData, production, version));\n }\n Logger.WriteLine(\"Store dumped successfully to '\" + filePath + \"'.\");\n }\n finally\n {\n if (manageSpp)\n {\n RestartSPP(version);\n }\n }\n }\n\n public static void LoadStore(PSVersion version, bool production, string filePath)\n {\n if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))\n {\n throw new FileNotFoundException(\"Store file '\" + filePath + \"' does not exist.\");\n }\n\n KillSPP(version);\n\n using (IPhysicalStore store = GetStore(version, production))\n {\n store.WriteRaw(File.ReadAllBytes(filePath));\n }\n\n RestartSPP(version);\n\n Logger.WriteLine(\"Loaded store file successfully.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/Common.cs", "namespace LibTSforge\n{\n using System;\n using System.IO;\n using System.Linq;\n using System.Runtime.InteropServices;\n using System.Text;\n\n public enum PSVersion\n {\n Vista,\n Win7,\n Win8,\n WinBlue,\n WinModern\n }\n\n public static class Constants\n {\n public static readonly byte[] UniversalHWIDBlock =\n {\n 0x26, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x01, 0x0c, 0x01, 0x00\n };\n\n public static readonly byte[] KMSv4Response =\n {\n 0x00, 0x00, 0x04, 0x00, 0x62, 0x00, 0x00, 0x00, 0x30, 0x00, 0x35, 0x00, 0x34, 0x00, 0x32, 0x00,\n 0x36, 0x00, 0x2D, 0x00, 0x30, 0x00, 0x30, 0x00, 0x32, 0x00, 0x30, 0x00, 0x36, 0x00, 0x2D, 0x00,\n 0x31, 0x00, 0x36, 0x00, 0x31, 0x00, 0x2D, 0x00, 0x36, 0x00, 0x35, 0x00, 0x35, 0x00, 0x35, 0x00,\n 0x30, 0x00, 0x36, 0x00, 0x2D, 0x00, 0x30, 0x00, 0x33, 0x00, 0x2D, 0x00, 0x31, 0x00, 0x30, 0x00,\n 0x33, 0x00, 0x33, 0x00, 0x2D, 0x00, 0x39, 0x00, 0x32, 0x00, 0x30, 0x00, 0x30, 0x00, 0x2E, 0x00,\n 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x2D, 0x00, 0x30, 0x00, 0x36, 0x00, 0x35, 0x00,\n 0x32, 0x00, 0x30, 0x00, 0x31, 0x00, 0x33, 0x00, 0x00, 0x00, 0xDE, 0x19, 0x02, 0xCF, 0x1F, 0x35,\n 0x97, 0x4E, 0x8A, 0x8F, 0xB8, 0x07, 0xB1, 0x92, 0xB5, 0xB5, 0x97, 0x42, 0xEC, 0x3A, 0x76, 0x84,\n 0xD5, 0x01, 0x32, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00, 0x60, 0x27, 0x00, 0x00, 0xC4, 0x1E,\n 0xAA, 0x8B, 0xDD, 0x0C, 0xAB, 0x55, 0x6A, 0xCE, 0xAF, 0xAC, 0x7F, 0x5F, 0xBD, 0xE9\n };\n\n public static readonly byte[] KMSv5Response =\n {\n 0x00, 0x00, 0x05, 0x00, 0xBE, 0x96, 0xF9, 0x04, 0x54, 0x17, 0x3F, 0xAF, 0xE3, 0x08, 0x50, 0xEB,\n 0x22, 0xBA, 0x53, 0xBF, 0xF2, 0x6A, 0x7B, 0xC9, 0x05, 0x1D, 0xB5, 0x19, 0xDF, 0x98, 0xE2, 0x71,\n 0x4D, 0x00, 0x61, 0xE9, 0x9D, 0x03, 0xFB, 0x31, 0xF9, 0x1F, 0x2E, 0x60, 0x59, 0xC7, 0x73, 0xC8,\n 0xE8, 0xB6, 0xE1, 0x2B, 0x39, 0xC6, 0x35, 0x0E, 0x68, 0x7A, 0xAA, 0x4F, 0x28, 0x23, 0x12, 0x18,\n 0xE3, 0xAA, 0x84, 0x81, 0x6E, 0x82, 0xF0, 0x3F, 0xD9, 0x69, 0xA9, 0xDF, 0xBA, 0x5F, 0xCA, 0x32,\n 0x54, 0xB2, 0x52, 0x3B, 0x3E, 0xD1, 0x5C, 0x65, 0xBC, 0x3E, 0x59, 0x0D, 0x15, 0x9F, 0x37, 0xEC,\n 0x30, 0x9C, 0xCC, 0x1B, 0x39, 0x0D, 0x21, 0x32, 0x29, 0xA2, 0xDD, 0xC7, 0xC1, 0x69, 0xF2, 0x72,\n 0x3F, 0x00, 0x98, 0x1E, 0xF8, 0x9A, 0x79, 0x44, 0x5D, 0x25, 0x80, 0x7B, 0xF5, 0xE1, 0x7C, 0x68,\n 0x25, 0xAA, 0x0D, 0x67, 0x98, 0xE5, 0x59, 0x9B, 0x04, 0xC1, 0x23, 0x33, 0x48, 0xFB, 0x28, 0xD0,\n 0x76, 0xDF, 0x01, 0x56, 0xE7, 0xEC, 0xBF, 0x1A, 0xA2, 0x22, 0x28, 0xCA, 0xB1, 0xB4, 0x4C, 0x30,\n 0x14, 0x6F, 0xD2, 0x2E, 0x01, 0x2A, 0x04, 0xE3, 0xBD, 0xA7, 0x41, 0x2F, 0xC9, 0xEF, 0x53, 0xC0,\n 0x70, 0x48, 0xF1, 0xB2, 0xB6, 0xEA, 0xE7, 0x0F, 0x7A, 0x15, 0xD1, 0xA6, 0xFE, 0x23, 0xC8, 0xF3,\n 0xE1, 0x02, 0x9E, 0xA0, 0x4E, 0xBD, 0xF5, 0xEA, 0x53, 0x74, 0x8E, 0x74, 0xA1, 0xA1, 0xBD, 0xBE,\n 0x66, 0xC4, 0x73, 0x8F, 0x24, 0xA7, 0x2A, 0x2F, 0xE3, 0xD9, 0xF4, 0x28, 0xD9, 0xF8, 0xA3, 0x93,\n 0x03, 0x9E, 0x29, 0xAB\n };\n\n public static readonly byte[] KMSv6Response =\n {\n 0x00, 0x00, 0x06, 0x00, 0x54, 0xD3, 0x40, 0x08, 0xF3, 0xCD, 0x03, 0xEF, 0xC8, 0x15, 0x87, 0x9E,\n 0xCA, 0x2E, 0x85, 0xFB, 0xE6, 0xF6, 0x73, 0x66, 0xFB, 0xDA, 0xBB, 0x7B, 0xB1, 0xBC, 0xD6, 0xF9,\n 0x5C, 0x41, 0xA0, 0xFE, 0xE1, 0x74, 0xC4, 0xBB, 0x91, 0xE5, 0xDE, 0x6D, 0x3A, 0x11, 0xD5, 0xFC,\n 0x68, 0xC0, 0x7B, 0x82, 0xB2, 0x24, 0xD1, 0x85, 0xBA, 0x45, 0xBF, 0xF1, 0x26, 0xFA, 0xA5, 0xC6,\n 0x61, 0x70, 0x69, 0x69, 0x6E, 0x0F, 0x0B, 0x60, 0xB7, 0x3D, 0xE8, 0xF1, 0x47, 0x0B, 0x65, 0xFD,\n 0xA7, 0x30, 0x1E, 0xF6, 0xA4, 0xD0, 0x79, 0xC4, 0x58, 0x8D, 0x81, 0xFD, 0xA7, 0xE7, 0x53, 0xF1,\n 0x67, 0x78, 0xF0, 0x0F, 0x60, 0x8F, 0xC8, 0x16, 0x35, 0x22, 0x94, 0x48, 0xCB, 0x0F, 0x8E, 0xB2,\n 0x1D, 0xF7, 0x3E, 0x28, 0x42, 0x55, 0x6B, 0x07, 0xE3, 0xE8, 0x51, 0xD5, 0xFA, 0x22, 0x0C, 0x86,\n 0x65, 0x0D, 0x3F, 0xDD, 0x8D, 0x9B, 0x1B, 0xC9, 0xD3, 0xB8, 0x3A, 0xEC, 0xF1, 0x11, 0x19, 0x25,\n 0xF7, 0x84, 0x4A, 0x4C, 0x0A, 0xB5, 0x31, 0x94, 0x37, 0x76, 0xCE, 0xE7, 0xAB, 0xA9, 0x69, 0xDF,\n 0xA4, 0xC9, 0x22, 0x6C, 0x23, 0xFF, 0x6B, 0xFC, 0xDA, 0x78, 0xD8, 0xC4, 0x8F, 0x74, 0xBB, 0x26,\n 0x05, 0x00, 0x98, 0x9B, 0xE5, 0xE2, 0xAD, 0x0D, 0x57, 0x95, 0x80, 0x66, 0x8E, 0x43, 0x74, 0x87,\n 0x93, 0x1F, 0xF4, 0xB2, 0x2C, 0x20, 0x5F, 0xD8, 0x9C, 0x4C, 0x56, 0xB3, 0x57, 0x44, 0x62, 0x68,\n 0x8D, 0xAA, 0x40, 0x11, 0x9D, 0x84, 0x62, 0x0E, 0x43, 0x8A, 0x1D, 0xF0, 0x1C, 0x49, 0xD8, 0x56,\n 0xEF, 0x4C, 0xD3, 0x64, 0xBA, 0x0D, 0xEF, 0x87, 0xB5, 0x2C, 0x88, 0xF3, 0x18, 0xFF, 0x3A, 0x8C,\n 0xF5, 0xA6, 0x78, 0x5C, 0x62, 0xE3, 0x9E, 0x4C, 0xB6, 0x31, 0x2D, 0x06, 0x80, 0x92, 0xBC, 0x2E,\n 0x92, 0xA6, 0x56, 0x96\n };\n\n // 2^31 - 8 minutes\n public static readonly ulong TimerMax = (ulong)TimeSpan.FromMinutes(2147483640).Ticks;\n\n public static readonly string ZeroCID = new string('0', 48);\n }\n\n public static class BinaryReaderExt\n {\n public static void Align(this BinaryReader reader, int to)\n {\n int pos = (int)reader.BaseStream.Position;\n reader.BaseStream.Seek(-pos & (to - 1), SeekOrigin.Current);\n }\n\n public static string ReadNullTerminatedString(this BinaryReader reader, int maxLen)\n {\n return Encoding.Unicode.GetString(reader.ReadBytes(maxLen)).Split(new char[] { '\\0' }, 2)[0];\n }\n }\n\n public static class BinaryWriterExt\n {\n public static void Align(this BinaryWriter writer, int to)\n {\n int pos = (int)writer.BaseStream.Position;\n writer.WritePadding(-pos & (to - 1));\n }\n\n public static void WritePadding(this BinaryWriter writer, int len)\n {\n writer.Write(Enumerable.Repeat((byte)0, len).ToArray());\n }\n\n public static void WriteFixedString(this BinaryWriter writer, string str, int bLen)\n {\n writer.Write(Encoding.ASCII.GetBytes(str));\n writer.WritePadding(bLen - str.Length);\n }\n\n public static void WriteFixedString16(this BinaryWriter writer, string str, int bLen)\n {\n byte[] bstr = Utils.EncodeString(str);\n writer.Write(bstr);\n writer.WritePadding(bLen - bstr.Length);\n }\n\n public static byte[] GetBytes(this BinaryWriter writer)\n {\n return ((MemoryStream)writer.BaseStream).ToArray();\n }\n }\n\n public static class ByteArrayExt\n {\n public static byte[] CastToArray(this T data) where T : struct\n {\n int size = Marshal.SizeOf(typeof(T));\n byte[] result = new byte[size];\n GCHandle handle = GCHandle.Alloc(result, GCHandleType.Pinned);\n try\n {\n Marshal.StructureToPtr(data, handle.AddrOfPinnedObject(), false);\n }\n finally\n {\n handle.Free();\n }\n return result;\n }\n }\n\n public static class FileStreamExt\n {\n public static byte[] ReadAllBytes(this FileStream fs)\n {\n BinaryReader br = new BinaryReader(fs);\n return br.ReadBytes((int)fs.Length);\n }\n\n public static void WriteAllBytes(this FileStream fs, byte[] data)\n {\n fs.Seek(0, SeekOrigin.Begin);\n fs.SetLength(data.Length);\n fs.Write(data, 0, data.Length);\n }\n }\n\n public static class Utils\n {\n [DllImport(\"kernel32.dll\")]\n public static extern uint GetSystemDefaultLCID();\n\n [DllImport(\"kernel32.dll\")]\n public static extern bool Wow64EnableWow64FsRedirection(bool Wow64FsEnableRedirection);\n\n public static string DecodeString(byte[] data)\n {\n return Encoding.Unicode.GetString(data).Trim('\\0');\n }\n\n public static byte[] EncodeString(string str)\n {\n return Encoding.Unicode.GetBytes(str + '\\0');\n }\n\n public static uint CRC32(byte[] data)\n {\n const uint polynomial = 0x04C11DB7;\n uint crc = 0xffffffff;\n\n foreach (byte b in data)\n {\n crc ^= (uint)b << 24;\n for (int bit = 0; bit < 8; bit++)\n {\n if ((crc & 0x80000000) != 0)\n {\n crc = (crc << 1) ^ polynomial;\n }\n else\n {\n crc <<= 1;\n }\n }\n }\n return ~crc;\n }\n\n public static string GetArchitecture()\n {\n string arch = Environment.GetEnvironmentVariable(\"PROCESSOR_ARCHITECTURE\", EnvironmentVariableTarget.Machine).ToUpperInvariant();\n return arch == \"AMD64\" ? \"X64\" : arch;\n }\n\n public static PSVersion DetectVersion()\n {\n int build = Environment.OSVersion.Version.Build;\n\n if (build >= 9600) return PSVersion.WinModern;\n if (build >= 6000 && build <= 6003) return PSVersion.Vista;\n if (build >= 7600 && build <= 7602) return PSVersion.Win7;\n if (build == 9200) return PSVersion.Win8;\n\n throw new NotSupportedException(\"Unable to auto-detect version info\");\n }\n }\n\n public static class Logger\n {\n public static bool HideOutput = false;\n\n public static void WriteLine(string line)\n {\n if (!HideOutput) Console.WriteLine(line);\n }\n }\n}\n"], ["/TSforge/LibTSforge/TokenStore/TokenStoreModern.cs", "namespace LibTSforge.TokenStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using System.Linq;\n using Crypto;\n\n public class TokenStoreModern : ITokenStore\n {\n private static readonly uint VERSION = 3;\n private static readonly int ENTRY_SIZE = 0x9E;\n private static readonly int BLOCK_SIZE = 0x4020;\n private static readonly int ENTRIES_PER_BLOCK = BLOCK_SIZE / ENTRY_SIZE;\n private static readonly int BLOCK_PAD_SIZE = 0x66;\n\n private static readonly byte[] CONTS_HEADER = Enumerable.Repeat((byte)0x55, 0x20).ToArray();\n private static readonly byte[] CONTS_FOOTER = Enumerable.Repeat((byte)0xAA, 0x20).ToArray();\n\n private List Entries = new List();\n private readonly FileStream TokensFile;\n\n public void Deserialize()\n {\n if (TokensFile.Length < BLOCK_SIZE) return;\n\n TokensFile.Seek(0x24, SeekOrigin.Begin);\n uint nextBlock;\n\n BinaryReader reader = new BinaryReader(TokensFile);\n do\n {\n reader.ReadUInt32();\n nextBlock = reader.ReadUInt32();\n\n for (int i = 0; i < ENTRIES_PER_BLOCK; i++)\n {\n uint curOffset = reader.ReadUInt32();\n bool populated = reader.ReadUInt32() == 1;\n uint contentOffset = reader.ReadUInt32();\n uint contentLength = reader.ReadUInt32();\n uint allocLength = reader.ReadUInt32();\n byte[] contentData = { };\n\n if (populated)\n {\n reader.BaseStream.Seek(contentOffset + 0x20, SeekOrigin.Begin);\n uint dataLength = reader.ReadUInt32();\n\n if (dataLength != contentLength)\n {\n throw new FormatException(\"Data length in tokens content is inconsistent with entry.\");\n }\n\n reader.ReadBytes(0x20);\n contentData = reader.ReadBytes((int)contentLength);\n }\n\n reader.BaseStream.Seek(curOffset + 0x14, SeekOrigin.Begin);\n\n Entries.Add(new TokenEntry\n {\n Name = reader.ReadNullTerminatedString(0x82),\n Extension = reader.ReadNullTerminatedString(0x8),\n Data = contentData,\n Populated = populated\n });\n }\n\n reader.BaseStream.Seek(nextBlock, SeekOrigin.Begin);\n } while (nextBlock != 0);\n }\n\n public void Serialize()\n {\n MemoryStream tokens = new MemoryStream();\n\n using (BinaryWriter writer = new BinaryWriter(tokens))\n {\n writer.Write(VERSION);\n writer.Write(CONTS_HEADER);\n\n int curBlockOffset = (int)writer.BaseStream.Position;\n int curEntryOffset = curBlockOffset + 0x8;\n int curContsOffset = curBlockOffset + BLOCK_SIZE;\n\n for (int eIndex = 0; eIndex < ((Entries.Count / ENTRIES_PER_BLOCK) + 1) * ENTRIES_PER_BLOCK; eIndex++)\n {\n TokenEntry entry;\n\n if (eIndex < Entries.Count)\n {\n entry = Entries[eIndex];\n }\n else\n {\n entry = new TokenEntry\n {\n Name = \"\",\n Extension = \"\",\n Populated = false,\n Data = new byte[] { }\n };\n }\n\n writer.BaseStream.Seek(curBlockOffset, SeekOrigin.Begin);\n writer.Write(curBlockOffset);\n writer.Write(0);\n\n writer.BaseStream.Seek(curEntryOffset, SeekOrigin.Begin);\n writer.Write(curEntryOffset);\n writer.Write(entry.Populated ? 1 : 0);\n writer.Write(entry.Populated ? curContsOffset : 0);\n writer.Write(entry.Populated ? entry.Data.Length : -1);\n writer.Write(entry.Populated ? entry.Data.Length : -1);\n writer.WriteFixedString16(entry.Name, 0x82);\n writer.WriteFixedString16(entry.Extension, 0x8);\n curEntryOffset = (int)writer.BaseStream.Position;\n\n if (entry.Populated)\n {\n writer.BaseStream.Seek(curContsOffset, SeekOrigin.Begin);\n writer.Write(CONTS_HEADER);\n writer.Write(entry.Data.Length);\n writer.Write(CryptoUtils.SHA256Hash(entry.Data));\n writer.Write(entry.Data);\n writer.Write(CONTS_FOOTER);\n curContsOffset = (int)writer.BaseStream.Position;\n }\n\n if ((eIndex + 1) % ENTRIES_PER_BLOCK == 0 && eIndex != 0)\n {\n if (eIndex < Entries.Count)\n {\n writer.BaseStream.Seek(curBlockOffset + 0x4, SeekOrigin.Begin);\n writer.Write(curContsOffset);\n }\n\n writer.BaseStream.Seek(curEntryOffset, SeekOrigin.Begin);\n writer.WritePadding(BLOCK_PAD_SIZE);\n\n writer.BaseStream.Seek(curBlockOffset, SeekOrigin.Begin);\n byte[] blockData = new byte[BLOCK_SIZE - 0x20];\n\n tokens.Read(blockData, 0, BLOCK_SIZE - 0x20);\n byte[] blockHash = CryptoUtils.SHA256Hash(blockData);\n\n writer.BaseStream.Seek(curBlockOffset + BLOCK_SIZE - 0x20, SeekOrigin.Begin);\n writer.Write(blockHash);\n\n curBlockOffset = curContsOffset;\n curEntryOffset = curBlockOffset + 0x8;\n curContsOffset = curBlockOffset + BLOCK_SIZE;\n }\n }\n\n tokens.SetLength(curBlockOffset);\n }\n\n byte[] tokensData = tokens.ToArray();\n byte[] tokensHash = CryptoUtils.SHA256Hash(tokensData.Take(0x4).Concat(tokensData.Skip(0x24)).ToArray());\n\n tokens = new MemoryStream(tokensData);\n\n BinaryWriter tokWriter = new BinaryWriter(TokensFile);\n using (BinaryReader reader = new BinaryReader(tokens))\n {\n TokensFile.Seek(0, SeekOrigin.Begin);\n TokensFile.SetLength(tokens.Length);\n tokWriter.Write(reader.ReadBytes(0x4));\n reader.ReadBytes(0x20);\n tokWriter.Write(tokensHash);\n tokWriter.Write(reader.ReadBytes((int)reader.BaseStream.Length - 0x4));\n }\n }\n\n public void AddEntry(TokenEntry entry)\n {\n Entries.Add(entry);\n }\n\n public void AddEntries(TokenEntry[] entries)\n {\n Entries.AddRange(entries);\n }\n\n public void DeleteEntry(string name, string ext)\n {\n foreach (TokenEntry entry in Entries)\n {\n if (entry.Name == name && entry.Extension == ext)\n {\n Entries.Remove(entry);\n return;\n }\n }\n }\n\n public void DeleteUnpopEntry(string name, string ext)\n {\n List delEntries = new List();\n foreach (TokenEntry entry in Entries)\n {\n if (entry.Name == name && entry.Extension == ext && !entry.Populated)\n {\n delEntries.Add(entry);\n }\n }\n\n Entries = Entries.Except(delEntries).ToList();\n }\n\n public TokenEntry GetEntry(string name, string ext)\n {\n foreach (TokenEntry entry in Entries)\n {\n if (entry.Name == name && entry.Extension == ext)\n {\n if (!entry.Populated) continue;\n return entry;\n }\n }\n\n return null;\n }\n\n public TokenMeta GetMetaEntry(string name)\n {\n DeleteUnpopEntry(name, \"xml\");\n TokenEntry entry = GetEntry(name, \"xml\");\n TokenMeta meta;\n\n if (entry == null)\n {\n meta = new TokenMeta\n {\n Name = name\n };\n }\n else\n {\n meta = new TokenMeta(entry.Data);\n }\n\n return meta;\n }\n\n public void SetEntry(string name, string ext, byte[] data)\n {\n for (int i = 0; i < Entries.Count; i++)\n {\n TokenEntry entry = Entries[i];\n\n if (entry.Name == name && entry.Extension == ext && entry.Populated)\n {\n entry.Data = data;\n Entries[i] = entry;\n return;\n }\n }\n\n Entries.Add(new TokenEntry\n {\n Populated = true,\n Name = name,\n Extension = ext,\n Data = data\n });\n }\n\n public TokenStoreModern(string tokensPath)\n {\n TokensFile = File.Open(tokensPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n Deserialize();\n }\n\n public void Dispose()\n {\n Serialize();\n TokensFile.Close();\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/GenPKeyInstall.cs", "namespace LibTSforge.Modifiers\n{\n using System;\n using System.IO;\n using Microsoft.Win32;\n using PhysicalStore;\n using SPP;\n using TokenStore;\n\n public static class GenPKeyInstall\n {\n private static void WritePkey2005RegistryValues(PSVersion version, ProductKey pkey)\n {\n Logger.WriteLine(\"Writing registry data for Windows product key...\");\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"ProductId\", pkey.GetPid2());\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"DigitalProductId\", pkey.GetPid3());\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"DigitalProductId4\", pkey.GetPid4());\n\n if (Registry.GetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Registration\", \"ProductId\", null) != null)\n {\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Registration\", \"ProductId\", pkey.GetPid2());\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Registration\", \"DigitalProductId\", pkey.GetPid3());\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Registration\", \"DigitalProductId4\", pkey.GetPid4());\n }\n\n if (pkey.Channel == \"Volume:CSVLK\" && version != PSVersion.Win7)\n {\n Registry.SetValue(@\"HKEY_USERS\\S-1-5-20\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform\", \"KmsHostConfig\", 1);\n }\n }\n\n public static void InstallGenPKey(PSVersion version, bool production, Guid actId)\n {\n if (version == PSVersion.Vista) throw new NotSupportedException(\"This feature is not supported on Windows Vista/Server 2008.\");\n if (actId == Guid.Empty) throw new ArgumentException(\"Activation ID must be specified for generated product key install.\");\n\n PKeyConfig pkc = new PKeyConfig();\n \n try\n {\n pkc.LoadConfig(actId);\n }\n catch (ArgumentException)\n {\n pkc.LoadAllConfigs(SLApi.GetAppId(actId));\n }\n\n ProductConfig config;\n pkc.Products.TryGetValue(actId, out config);\n\n if (config == null) throw new ArgumentException(\"Activation ID \" + actId + \" not found in PKeyConfig.\");\n\n ProductKey pkey = config.GetRandomKey();\n\n Guid instPkeyId = SLApi.GetInstalledPkeyID(actId);\n if (instPkeyId != Guid.Empty) SLApi.UninstallProductKey(instPkeyId);\n\n if (pkey.Algorithm == PKeyAlgorithm.PKEY2009)\n {\n uint status = SLApi.InstallProductKey(pkey);\n Logger.WriteLine(string.Format(\"Installing generated product key {0} status {1:X}\", pkey, status));\n\n if ((int)status < 0)\n {\n throw new ApplicationException(\"Failed to install generated product key.\");\n }\n\n Logger.WriteLine(\"Successfully deposited generated product key.\");\n return;\n }\n\n Logger.WriteLine(\"Key range is PKEY2005, creating fake key data...\");\n\n if (pkey.Channel == \"Volume:GVLK\" && version == PSVersion.Win7) throw new NotSupportedException(\"Fake GVLK generation is not supported on Windows 7.\");\n\n VariableBag pkb = new VariableBag(version);\n pkb.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingProductKey\",\n ValueAsStr = pkey.ToString()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingMPC\",\n ValueAsStr = pkey.GetMPC()\n },\n new CRCBlockModern {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingPid2\",\n ValueAsStr = pkey.GetPid2()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingPid3\",\n Value = pkey.GetPid3()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingPid4\",\n Value = pkey.GetPid4()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyChannelId\",\n ValueAsStr = pkey.Channel\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingEditionId\",\n ValueAsStr = pkey.Edition\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = (version == PSVersion.Win7) ? \"SppPkeyShortAuthenticator\" : \"SppPkeyPhoneActivationData\",\n Value = pkey.GetPhoneData(version)\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingMiscData\",\n Value = new byte[] { }\n }\n });\n\n Guid appId = SLApi.GetAppId(actId);\n string pkeyId = pkey.GetPkeyId().ToString();\n bool isAddon = SLApi.IsAddon(actId);\n string currEdition = SLApi.GetMetaStr(actId, \"Family\");\n\n if (appId == SLApi.WINDOWS_APP_ID && !isAddon)\n {\n SLApi.UninstallAllProductKeys(appId);\n }\n\n SPPUtils.KillSPP(version);\n\n using (IPhysicalStore ps = SPPUtils.GetStore(version, production))\n {\n using (ITokenStore tks = SPPUtils.GetTokenStore(version))\n {\n Logger.WriteLine(\"Writing to physical store and token store...\");\n\n string suffix = (version == PSVersion.Win8 || version == PSVersion.WinBlue || version == PSVersion.WinModern) ? \"_--\" : \"\";\n string metSuffix = suffix + \"_met\";\n\n if (appId == SLApi.WINDOWS_APP_ID && !isAddon)\n {\n string edTokName = \"msft:spp/token/windows/productkeyid/\" + currEdition;\n\n TokenMeta edToken = tks.GetMetaEntry(edTokName);\n edToken.Data[\"windowsComponentEditionPkeyId\"] = pkeyId;\n edToken.Data[\"windowsComponentEditionSkuId\"] = actId.ToString();\n tks.SetEntry(edTokName, \"xml\", edToken.Serialize());\n\n WritePkey2005RegistryValues(version, pkey);\n }\n\n string uriMapName = \"msft:spp/token/PKeyIdUriMapper\" + metSuffix;\n TokenMeta uriMap = tks.GetMetaEntry(uriMapName);\n uriMap.Data[pkeyId] = pkey.GetAlgoUri();\n tks.SetEntry(uriMapName, \"xml\", uriMap.Serialize());\n\n string skuMetaName = actId + metSuffix;\n TokenMeta skuMeta = tks.GetMetaEntry(skuMetaName);\n\n foreach (string k in skuMeta.Data.Keys)\n {\n if (k.StartsWith(\"pkeyId_\"))\n {\n skuMeta.Data.Remove(k);\n break;\n }\n }\n\n skuMeta.Data[\"pkeyId\"] = pkeyId;\n skuMeta.Data[\"pkeyIdList\"] = pkeyId;\n tks.SetEntry(skuMetaName, \"xml\", skuMeta.Serialize());\n\n string psKey = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n ps.DeleteBlock(psKey, pkeyId);\n ps.AddBlock(new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = (version == PSVersion.WinModern) ? (uint)0x402 : 0x2,\n KeyAsStr = psKey,\n ValueAsStr = pkeyId,\n Data = pkb.Serialize()\n });\n\n string cachePath = SPPUtils.GetTokensPath(version).Replace(\"tokens.dat\", @\"cache\\cache.dat\");\n if (File.Exists(cachePath)) File.Delete(cachePath);\n }\n }\n\n SLApi.RefreshTrustedTime(actId);\n Logger.WriteLine(\"Successfully deposited fake product key.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/SPP/ProductKey.cs", "namespace LibTSforge.SPP\n{\n using System;\n using System.IO;\n using System.Linq;\n using Crypto;\n using PhysicalStore;\n\n public class ProductKey\n {\n private static readonly string ALPHABET = \"BCDFGHJKMPQRTVWXY2346789\";\n\n private readonly ulong klow;\n private readonly ulong khigh;\n\n public int Group;\n public int Serial;\n public ulong Security;\n public bool Upgrade;\n public PKeyAlgorithm Algorithm;\n public readonly string EulaType;\n public readonly string PartNumber;\n public readonly string Edition;\n public readonly string Channel;\n public readonly Guid ActivationId;\n\n private string mpc;\n private string pid2;\n\n public byte[] KeyBytes\n {\n get { return BitConverter.GetBytes(klow).Concat(BitConverter.GetBytes(khigh)).ToArray(); }\n }\n\n public ProductKey()\n {\n\n }\n\n public ProductKey(int serial, ulong security, bool upgrade, PKeyAlgorithm algorithm, ProductConfig config, KeyRange range)\n {\n Group = config.GroupId;\n Serial = serial;\n Security = security;\n Upgrade = upgrade;\n Algorithm = algorithm;\n EulaType = range.EulaType;\n PartNumber = range.PartNumber.Split(':', ';')[0];\n Edition = config.Edition;\n Channel = config.Channel;\n ActivationId = config.ActivationId;\n\n klow = ((security & 0x3fff) << 50 | ((ulong)serial & 0x3fffffff) << 20 | ((ulong)Group & 0xfffff));\n khigh = ((upgrade ? (ulong)1 : 0) << 49 | ((security >> 14) & 0x7fffffffff));\n\n uint checksum = Utils.CRC32(KeyBytes) & 0x3ff;\n\n khigh |= ((ulong)checksum << 39);\n }\n\n public string GetAlgoUri()\n {\n return \"msft:rm/algorithm/pkey/\" + (Algorithm == PKeyAlgorithm.PKEY2005 ? \"2005\" : (Algorithm == PKeyAlgorithm.PKEY2009 ? \"2009\" : \"Unknown\"));\n }\n\n public Guid GetPkeyId()\n {\n VariableBag pkb = new VariableBag(PSVersion.WinModern);\n pkb.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingProductKey\",\n ValueAsStr = ToString()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingMiscData\",\n Value = new byte[] { }\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingAlgorithm\",\n ValueAsStr = GetAlgoUri()\n }\n });\n\n return new Guid(CryptoUtils.SHA256Hash(pkb.Serialize()).Take(16).ToArray());\n }\n\n public string GetMPC()\n {\n if (mpc != null)\n {\n return mpc;\n }\n\n int build = Environment.OSVersion.Version.Build;\n\n mpc = build >= 10240 ? \"03612\" :\n build >= 9600 ? \"06401\" :\n build >= 9200 ? \"05426\" :\n \"55041\";\n\n // setup.cfg doesn't exist in Windows 8+\n string setupcfg = string.Format(@\"{0}\\oobe\\{1}\", Environment.SystemDirectory, \"setup.cfg\");\n\n if (!File.Exists(setupcfg) || Edition.Contains(\";\"))\n {\n return mpc;\n }\n\n string mpcKey = string.Format(\"{0}.{1}=\", Utils.GetArchitecture(), Edition);\n string localMPC = File.ReadAllLines(setupcfg).FirstOrDefault(line => line.Contains(mpcKey));\n if (localMPC != null)\n {\n mpc = localMPC.Split('=')[1].Trim();\n }\n\n return mpc;\n }\n\n public string GetPid2()\n {\n if (pid2 != null)\n {\n return pid2;\n }\n\n pid2 = \"\";\n\n if (Algorithm == PKeyAlgorithm.PKEY2005)\n {\n string mpc = GetMPC();\n string serialHigh;\n int serialLow;\n int lastPart;\n\n if (EulaType == \"OEM\")\n {\n serialHigh = \"OEM\";\n serialLow = ((Group / 2) % 100) * 10000 + (Serial / 100000);\n lastPart = Serial % 100000;\n }\n else\n {\n serialHigh = (Serial / 1000000).ToString(\"D3\");\n serialLow = Serial % 1000000;\n lastPart = ((Group / 2) % 100) * 1000 + new Random().Next(1000);\n }\n\n int checksum = 0;\n\n foreach (char c in serialLow.ToString())\n {\n checksum += int.Parse(c.ToString());\n }\n checksum = 7 - (checksum % 7);\n\n pid2 = string.Format(\"{0}-{1}-{2:D6}{3}-{4:D5}\", mpc, serialHigh, serialLow, checksum, lastPart);\n }\n\n return pid2;\n }\n\n public byte[] GetPid3()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(0xA4);\n writer.Write(0x3);\n writer.WriteFixedString(GetPid2(), 24);\n writer.Write(Group);\n writer.WriteFixedString(PartNumber, 16);\n writer.WritePadding(0x6C);\n byte[] data = writer.GetBytes();\n byte[] crc = BitConverter.GetBytes(~Utils.CRC32(data.Reverse().ToArray())).Reverse().ToArray();\n writer.Write(crc);\n\n return writer.GetBytes();\n }\n\n public byte[] GetPid4()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(0x4F8);\n writer.Write(0x4);\n writer.WriteFixedString16(GetExtendedPid(), 0x80);\n writer.WriteFixedString16(ActivationId.ToString(), 0x80);\n writer.WritePadding(0x10);\n writer.WriteFixedString16(Edition, 0x208);\n writer.Write(Upgrade ? (ulong)1 : 0);\n writer.WritePadding(0x50);\n writer.WriteFixedString16(PartNumber, 0x80);\n writer.WriteFixedString16(Channel, 0x80);\n writer.WriteFixedString16(EulaType, 0x80);\n\n return writer.GetBytes();\n }\n\n public string GetExtendedPid()\n {\n string mpc = GetMPC();\n int serialHigh = Serial / 1000000;\n int serialLow = Serial % 1000000;\n int licenseType;\n uint lcid = Utils.GetSystemDefaultLCID();\n int build = Environment.OSVersion.Version.Build;\n int dayOfYear = DateTime.Now.DayOfYear;\n int year = DateTime.Now.Year;\n\n switch (EulaType)\n {\n case \"OEM\":\n licenseType = 2;\n break;\n\n case \"Volume\":\n licenseType = 3;\n break;\n\n default:\n licenseType = 0;\n break;\n }\n\n return string.Format(\n \"{0}-{1:D5}-{2:D3}-{3:D6}-{4:D2}-{5:D4}-{6:D4}.0000-{7:D3}{8:D4}\",\n mpc,\n Group,\n serialHigh,\n serialLow,\n licenseType,\n lcid,\n build,\n dayOfYear,\n year\n );\n }\n\n public byte[] GetPhoneData(PSVersion version)\n {\n if (version == PSVersion.Win7)\n {\n ulong shortauth = ((ulong)Group << 41) | (Security << 31) | ((ulong)Serial << 1) | (Upgrade ? (ulong)1 : 0);\n return BitConverter.GetBytes(shortauth);\n }\n\n int serialHigh = Serial / 1000000;\n int serialLow = Serial % 1000000;\n\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n string algoId = Algorithm == PKeyAlgorithm.PKEY2005 ? \"B8731595-A2F6-430B-A799-FBFFB81A8D73\" : \"660672EF-7809-4CFD-8D54-41B7FB738988\";\n\n writer.Write(new Guid(algoId).ToByteArray());\n writer.Write(Group);\n writer.Write(serialHigh);\n writer.Write(serialLow);\n writer.Write(Upgrade ? 1 : 0);\n writer.Write(Security);\n\n return writer.GetBytes();\n }\n\n public override string ToString()\n {\n string keyStr = \"\";\n Random rnd = new Random(Group * 1000000000 + Serial);\n\n if (Algorithm == PKeyAlgorithm.PKEY2005)\n {\n keyStr = \"H4X3DH4X3DH4X3DH4X3D\";\n\n for (int i = 0; i < 5; i++)\n {\n keyStr += ALPHABET[rnd.Next(24)];\n }\n }\n else if (Algorithm == PKeyAlgorithm.PKEY2009)\n {\n int last = 0;\n byte[] bKey = KeyBytes;\n\n for (int i = 24; i >= 0; i--)\n {\n int current = 0;\n\n for (int j = 14; j >= 0; j--)\n {\n current *= 0x100;\n current += bKey[j];\n bKey[j] = (byte)(current / 24);\n current %= 24;\n last = current;\n }\n\n keyStr = ALPHABET[current] + keyStr;\n }\n\n keyStr = keyStr.Substring(1, last) + \"N\" + keyStr.Substring(last + 1, keyStr.Length - last - 1);\n }\n\n for (int i = 5; i < keyStr.Length; i += 6)\n {\n keyStr = keyStr.Insert(i, \"-\");\n }\n\n return keyStr;\n }\n }\n}\n"], ["/TSforge/LibTSforge/SPP/PKeyConfig.cs", "namespace LibTSforge.SPP\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using System.Linq;\n using System.Text;\n using System.Xml;\n\n public enum PKeyAlgorithm\n {\n PKEY2005,\n PKEY2009\n }\n\n public class KeyRange\n {\n public int Start;\n public int End;\n public string EulaType;\n public string PartNumber;\n public bool Valid;\n\n public bool Contains(int n)\n {\n return Start <= n && End <= n;\n }\n }\n\n public class ProductConfig\n {\n public int GroupId;\n public string Edition;\n public string Description;\n public string Channel;\n public bool Randomized;\n public PKeyAlgorithm Algorithm;\n public List Ranges;\n public Guid ActivationId;\n\n private List GetPkeyRanges()\n {\n if (Ranges.Count == 0)\n {\n throw new ArgumentException(\"No key ranges.\");\n }\n\n if (Algorithm == PKeyAlgorithm.PKEY2005)\n {\n return Ranges;\n }\n\n List FilteredRanges = Ranges.Where(r => !r.EulaType.Contains(\"WAU\")).ToList();\n\n if (FilteredRanges.Count == 0)\n {\n throw new NotSupportedException(\"Specified Activation ID is usable only for Windows Anytime Upgrade. Please use a non-WAU Activation ID instead.\");\n }\n\n return FilteredRanges;\n }\n\n public ProductKey GetRandomKey()\n {\n List KeyRanges = GetPkeyRanges();\n Random rnd = new Random();\n\n KeyRange range = KeyRanges[rnd.Next(KeyRanges.Count)];\n int serial = rnd.Next(range.Start, range.End);\n\n return new ProductKey(serial, 0, false, Algorithm, this, range);\n }\n }\n\n public class PKeyConfig\n {\n public readonly Dictionary Products = new Dictionary();\n private readonly List loadedPkeyConfigs = new List();\n\n public void LoadConfig(Guid actId)\n {\n string pkcData;\n Guid pkcFileId = SLApi.GetPkeyConfigFileId(actId);\n\n if (loadedPkeyConfigs.Contains(pkcFileId)) return;\n\n string licConts = SLApi.GetLicenseContents(pkcFileId);\n\n using (TextReader tr = new StringReader(licConts))\n {\n XmlDocument lic = new XmlDocument();\n lic.Load(tr);\n\n XmlNamespaceManager nsmgr = new XmlNamespaceManager(lic.NameTable);\n nsmgr.AddNamespace(\"rg\", \"urn:mpeg:mpeg21:2003:01-REL-R-NS\");\n nsmgr.AddNamespace(\"r\", \"urn:mpeg:mpeg21:2003:01-REL-R-NS\");\n nsmgr.AddNamespace(\"tm\", \"http://www.microsoft.com/DRM/XrML2/TM/v2\");\n\n XmlNode root = lic.DocumentElement;\n XmlNode pkcDataNode = root.SelectSingleNode(\"/rg:licenseGroup/r:license/r:otherInfo/tm:infoTables/tm:infoList/tm:infoBin[@name=\\\"pkeyConfigData\\\"]\", nsmgr);\n pkcData = Encoding.UTF8.GetString(Convert.FromBase64String(pkcDataNode.InnerText));\n }\n\n using (TextReader tr = new StringReader(pkcData))\n {\n XmlDocument lic = new XmlDocument();\n lic.Load(tr);\n\n XmlNamespaceManager nsmgr = new XmlNamespaceManager(lic.NameTable);\n nsmgr.AddNamespace(\"p\", \"http://www.microsoft.com/DRM/PKEY/Configuration/2.0\");\n XmlNodeList configNodes = lic.SelectNodes(\"//p:ProductKeyConfiguration/p:Configurations/p:Configuration\", nsmgr);\n XmlNodeList rangeNodes = lic.SelectNodes(\"//p:ProductKeyConfiguration/p:KeyRanges/p:KeyRange\", nsmgr);\n XmlNodeList pubKeyNodes = lic.SelectNodes(\"//p:ProductKeyConfiguration/p:PublicKeys/p:PublicKey\", nsmgr);\n\n Dictionary algorithms = new Dictionary();\n Dictionary> ranges = new Dictionary>();\n\n Dictionary algoConv = new Dictionary\n {\n { \"msft:rm/algorithm/pkey/2005\", PKeyAlgorithm.PKEY2005 },\n { \"msft:rm/algorithm/pkey/2009\", PKeyAlgorithm.PKEY2009 }\n };\n\n foreach (XmlNode pubKeyNode in pubKeyNodes)\n {\n int group = int.Parse(pubKeyNode.SelectSingleNode(\"./p:GroupId\", nsmgr).InnerText);\n algorithms[group] = algoConv[pubKeyNode.SelectSingleNode(\"./p:AlgorithmId\", nsmgr).InnerText];\n }\n\n foreach (XmlNode rangeNode in rangeNodes)\n {\n string refActIdStr = rangeNode.SelectSingleNode(\"./p:RefActConfigId\", nsmgr).InnerText;\n\n if (!ranges.ContainsKey(refActIdStr))\n {\n ranges[refActIdStr] = new List();\n }\n\n KeyRange keyRange = new KeyRange\n {\n Start = int.Parse(rangeNode.SelectSingleNode(\"./p:Start\", nsmgr).InnerText),\n End = int.Parse(rangeNode.SelectSingleNode(\"./p:End\", nsmgr).InnerText),\n EulaType = rangeNode.SelectSingleNode(\"./p:EulaType\", nsmgr).InnerText,\n PartNumber = rangeNode.SelectSingleNode(\"./p:PartNumber\", nsmgr).InnerText,\n Valid = rangeNode.SelectSingleNode(\"./p:IsValid\", nsmgr).InnerText.ToLower() == \"true\"\n };\n\n ranges[refActIdStr].Add(keyRange);\n }\n\n foreach (XmlNode configNode in configNodes)\n {\n string refActIdStr = configNode.SelectSingleNode(\"./p:ActConfigId\", nsmgr).InnerText;\n Guid refActId = new Guid(refActIdStr);\n int group = int.Parse(configNode.SelectSingleNode(\"./p:RefGroupId\", nsmgr).InnerText);\n List keyRanges = ranges[refActIdStr];\n\n if (keyRanges.Count > 0 && !Products.ContainsKey(refActId))\n {\n ProductConfig productConfig = new ProductConfig\n {\n GroupId = group,\n Edition = configNode.SelectSingleNode(\"./p:EditionId\", nsmgr).InnerText,\n Description = configNode.SelectSingleNode(\"./p:ProductDescription\", nsmgr).InnerText,\n Channel = configNode.SelectSingleNode(\"./p:ProductKeyType\", nsmgr).InnerText,\n Randomized = configNode.SelectSingleNode(\"./p:ProductKeyType\", nsmgr).InnerText.ToLower() == \"true\",\n Algorithm = algorithms[group],\n Ranges = keyRanges,\n ActivationId = refActId\n };\n\n Products[refActId] = productConfig;\n }\n }\n }\n\n loadedPkeyConfigs.Add(pkcFileId);\n }\n\n public ProductConfig MatchParams(int group, int serial)\n {\n foreach (ProductConfig config in Products.Values)\n {\n if (config.GroupId == group)\n {\n foreach (KeyRange range in config.Ranges)\n {\n if (range.Contains(serial))\n {\n return config;\n }\n }\n }\n }\n\n throw new FileNotFoundException(\"Failed to find product matching supplied product key parameters.\");\n }\n\n public void LoadAllConfigs(Guid appId)\n {\n foreach (Guid actId in SLApi.GetActivationIds(appId))\n {\n try\n {\n LoadConfig(actId);\n } \n catch (ArgumentException)\n {\n\n }\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/PhysicalStoreModern.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using Crypto;\n\n public class ModernBlock\n {\n public BlockType Type;\n public uint Flags;\n public uint Unknown;\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n public byte[] Data;\n public string DataAsStr\n {\n get\n {\n return Utils.DecodeString(Data);\n }\n set\n {\n Data = Utils.EncodeString(value);\n }\n }\n public uint DataAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Data, 0);\n }\n set\n {\n Data = BitConverter.GetBytes(value);\n }\n }\n\n public void Encode(BinaryWriter writer)\n {\n writer.Write((uint)Type);\n writer.Write(Flags);\n writer.Write((uint)Value.Length);\n writer.Write((uint)Data.Length);\n writer.Write(Unknown);\n writer.Write(Value);\n writer.Write(Data);\n }\n\n public static ModernBlock Decode(BinaryReader reader)\n {\n uint type = reader.ReadUInt32();\n uint flags = reader.ReadUInt32();\n\n uint valueLen = reader.ReadUInt32();\n uint dataLen = reader.ReadUInt32();\n uint unk3 = reader.ReadUInt32();\n\n byte[] value = reader.ReadBytes((int)valueLen);\n byte[] data = reader.ReadBytes((int)dataLen);\n\n return new ModernBlock\n {\n Type = (BlockType)type,\n Flags = flags,\n Unknown = unk3,\n Value = value,\n Data = data,\n };\n }\n }\n\n public sealed class PhysicalStoreModern : IPhysicalStore\n {\n private byte[] PreHeaderBytes = { };\n private readonly Dictionary> Data = new Dictionary>();\n private readonly FileStream TSFile;\n private readonly PSVersion Version;\n private readonly bool Production;\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(PreHeaderBytes);\n writer.Write(Data.Keys.Count);\n\n foreach (string key in Data.Keys)\n {\n List blocks = Data[key];\n byte[] keyNameEnc = Utils.EncodeString(key);\n\n writer.Write(keyNameEnc.Length);\n writer.Write(keyNameEnc);\n writer.Write(blocks.Count);\n writer.Align(4);\n\n foreach (ModernBlock block in blocks)\n {\n block.Encode(writer);\n writer.Align(4);\n }\n }\n\n return writer.GetBytes();\n }\n\n public void Deserialize(byte[] data)\n {\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n PreHeaderBytes = reader.ReadBytes(8);\n\n while (reader.BaseStream.Position < data.Length - 0x4)\n {\n uint numKeys = reader.ReadUInt32();\n\n for (int i = 0; i < numKeys; i++)\n {\n uint lenKeyName = reader.ReadUInt32();\n string keyName = Utils.DecodeString(reader.ReadBytes((int)lenKeyName)); uint numValues = reader.ReadUInt32();\n\n reader.Align(4);\n\n Data[keyName] = new List();\n\n for (int j = 0; j < numValues; j++)\n {\n Data[keyName].Add(ModernBlock.Decode(reader));\n reader.Align(4);\n }\n }\n }\n }\n\n public void AddBlock(PSBlock block)\n {\n if (!Data.ContainsKey(block.KeyAsStr))\n {\n Data[block.KeyAsStr] = new List();\n }\n\n Data[block.KeyAsStr].Add(new ModernBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Unknown = block.Unknown,\n Value = block.Value,\n Data = block.Data\n });\n }\n\n public void AddBlocks(IEnumerable blocks)\n {\n foreach (PSBlock block in blocks)\n {\n AddBlock(block);\n }\n }\n\n public PSBlock GetBlock(string key, string value)\n {\n List blocks = Data[key];\n\n foreach (ModernBlock block in blocks)\n {\n if (block.ValueAsStr == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = Utils.EncodeString(key),\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public PSBlock GetBlock(string key, uint value)\n {\n List blocks = Data[key];\n\n foreach (ModernBlock block in blocks)\n {\n if (block.ValueAsInt == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = Utils.EncodeString(key),\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public void SetBlock(string key, string value, byte[] data)\n {\n List blocks = Data[key];\n\n for (int i = 0; i < blocks.Count; i++)\n {\n ModernBlock block = blocks[i];\n\n if (block.ValueAsStr == value)\n {\n block.Data = data;\n blocks[i] = block;\n break;\n }\n }\n\n Data[key] = blocks;\n }\n\n public void SetBlock(string key, uint value, byte[] data)\n {\n List blocks = Data[key];\n\n for (int i = 0; i < blocks.Count; i++)\n {\n ModernBlock block = blocks[i];\n\n if (block.ValueAsInt == value)\n {\n block.Data = data;\n blocks[i] = block;\n break;\n }\n }\n\n Data[key] = blocks;\n }\n\n public void SetBlock(string key, string value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, string value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void SetBlock(string key, uint value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, uint value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void DeleteBlock(string key, string value)\n {\n if (!Data.ContainsKey(key))\n {\n return;\n }\n\n List blocks = Data[key];\n\n foreach (ModernBlock block in blocks)\n {\n if (block.ValueAsStr == value)\n {\n blocks.Remove(block);\n break;\n }\n }\n\n Data[key] = blocks;\n }\n\n public void DeleteBlock(string key, uint value)\n {\n if (!Data.ContainsKey(key))\n {\n return;\n }\n\n List blocks = Data[key];\n\n foreach (ModernBlock block in blocks)\n {\n if (block.ValueAsInt == value)\n {\n blocks.Remove(block);\n break;\n }\n }\n\n Data[key] = blocks;\n }\n\n public PhysicalStoreModern(string tsPath, bool production, PSVersion version)\n {\n TSFile = File.Open(tsPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n Deserialize(PhysStoreCrypto.DecryptPhysicalStore(TSFile.ReadAllBytes(), production, version));\n TSFile.Seek(0, SeekOrigin.Begin);\n Version = version;\n Production = production;\n }\n\n public void Dispose()\n {\n if (TSFile.CanWrite)\n {\n byte[] data = PhysStoreCrypto.EncryptPhysicalStore(Serialize(), Production, Version);\n TSFile.SetLength(data.LongLength);\n TSFile.Seek(0, SeekOrigin.Begin);\n TSFile.WriteAllBytes(data);\n TSFile.Close();\n }\n }\n\n public byte[] ReadRaw()\n {\n byte[] data = PhysStoreCrypto.DecryptPhysicalStore(TSFile.ReadAllBytes(), Production, Version);\n TSFile.Seek(0, SeekOrigin.Begin);\n return data;\n }\n\n public void WriteRaw(byte[] data)\n {\n byte[] encrData = PhysStoreCrypto.EncryptPhysicalStore(data, Production, Version);\n TSFile.SetLength(encrData.LongLength);\n TSFile.Seek(0, SeekOrigin.Begin);\n TSFile.WriteAllBytes(encrData);\n TSFile.Close();\n }\n\n public IEnumerable FindBlocks(string valueSearch)\n {\n List results = new List();\n\n foreach (string key in Data.Keys)\n {\n List values = Data[key];\n\n foreach (ModernBlock block in values)\n {\n if (block.ValueAsStr.Contains(valueSearch))\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n KeyAsStr = key,\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n }\n\n return results;\n }\n\n public IEnumerable FindBlocks(uint valueSearch)\n {\n List results = new List();\n\n foreach (string key in Data.Keys)\n {\n List values = Data[key];\n\n foreach (ModernBlock block in values)\n {\n if (block.ValueAsInt == valueSearch)\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n KeyAsStr = key,\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n }\n\n return results;\n }\n }\n}\n"], ["/TSforge/LibTSforge/Activators/ZeroCID.cs", "namespace LibTSforge.Activators\n{\n using System;\n using System.IO;\n using System.Linq;\n using Crypto;\n using PhysicalStore;\n using SPP;\n\n public static class ZeroCID\n {\n private static void Deposit(Guid actId, string instId)\n {\n uint status = SLApi.DepositConfirmationID(actId, instId, Constants.ZeroCID);\n Logger.WriteLine(string.Format(\"Depositing fake CID status {0:X}\", status));\n\n if (status != 0)\n {\n throw new InvalidOperationException(\"Failed to deposit fake CID.\");\n }\n }\n\n public static void Activate(PSVersion version, bool production, Guid actId)\n {\n Guid appId;\n\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, false);\n\n if (actId == Guid.Empty)\n {\n throw new NotSupportedException(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n if (!SLApi.IsPhoneActivatable(actId))\n {\n throw new NotSupportedException(\"Phone license is unavailable for this product.\");\n }\n\n string instId = SLApi.GetInstallationID(actId);\n Guid pkeyId = SLApi.GetInstalledPkeyID(actId);\n\n if (version == PSVersion.Vista || version == PSVersion.Win7)\n {\n Deposit(actId, instId);\n }\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n byte[] hwidBlock = Constants.UniversalHWIDBlock;\n\n Logger.WriteLine(\"Activation ID: \" + actId);\n Logger.WriteLine(\"Installation ID: \" + instId);\n Logger.WriteLine(\"Product Key ID: \" + pkeyId);\n\n byte[] iidHash;\n\n if (version == PSVersion.Vista)\n {\n iidHash = CryptoUtils.SHA256Hash(Utils.EncodeString(instId)).Take(0x10).ToArray();\n }\n else if (version == PSVersion.Win7)\n {\n iidHash = CryptoUtils.SHA256Hash(Utils.EncodeString(instId));\n }\n else\n {\n iidHash = CryptoUtils.SHA256Hash(Utils.EncodeString(instId + '\\0' + Constants.ZeroCID));\n }\n\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n PSBlock keyBlock = store.GetBlock(key, pkeyId.ToString());\n\n if (keyBlock == null)\n {\n throw new InvalidDataException(\"Failed to get product key data for activation ID \" + actId + \".\");\n }\n\n VariableBag pkb = new VariableBag(keyBlock.Data, version);\n\n byte[] pkeyData;\n\n if (version == PSVersion.Vista)\n {\n pkeyData = pkb.GetBlock(\"PKeyBasicInfo\").Value;\n string uniqueId = Utils.DecodeString(pkeyData.Skip(0x120).Take(0x80).ToArray());\n string extPid = Utils.DecodeString(pkeyData.Skip(0x1A0).Take(0x80).ToArray());\n\n uint group;\n uint.TryParse(extPid.Split('-')[1], out group);\n\n if (group == 0)\n {\n throw new FormatException(\"Extended PID has invalid format.\");\n }\n\n ulong shortauth;\n\n try\n {\n shortauth = BitConverter.ToUInt64(Convert.FromBase64String(uniqueId.Split('&')[1]), 0);\n } \n catch\n {\n throw new FormatException(\"Key Unique ID has invalid format.\");\n }\n\n shortauth |= (ulong)group << 41;\n pkeyData = BitConverter.GetBytes(shortauth);\n }\n else if (version == PSVersion.Win7)\n {\n pkeyData = pkb.GetBlock(\"SppPkeyShortAuthenticator\").Value;\n }\n else\n {\n pkeyData = pkb.GetBlock(\"SppPkeyPhoneActivationData\").Value;\n }\n\n pkb.DeleteBlock(\"SppPkeyVirtual\");\n store.SetBlock(key, pkeyId.ToString(), pkb.Serialize());\n\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(iidHash.Length);\n writer.Write(iidHash);\n writer.Write(hwidBlock.Length);\n writer.Write(hwidBlock);\n byte[] tsHwidData = writer.GetBytes();\n\n writer = new BinaryWriter(new MemoryStream());\n writer.Write(iidHash.Length);\n writer.Write(iidHash);\n writer.Write(pkeyData.Length);\n writer.Write(pkeyData);\n byte[] tsPkeyInfoData = writer.GetBytes();\n\n string phoneVersion = version == PSVersion.Vista ? \"6.0\" : \"7.0\";\n Guid indexSlid = version == PSVersion.Vista ? actId : pkeyId;\n string hwidBlockName = string.Format(\"msft:Windows/{0}/Phone/Cached/HwidBlock/{1}\", phoneVersion, indexSlid);\n string pkeyInfoName = string.Format(\"msft:Windows/{0}/Phone/Cached/PKeyInfo/{1}\", phoneVersion, indexSlid);\n\n store.DeleteBlock(key, hwidBlockName);\n store.DeleteBlock(key, pkeyInfoName);\n\n store.AddBlocks(new[] {\n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = 0,\n KeyAsStr = key,\n ValueAsStr = hwidBlockName,\n Data = tsHwidData\n }, \n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = 0,\n KeyAsStr = key,\n ValueAsStr = pkeyInfoName,\n Data = tsPkeyInfoData\n }\n });\n }\n\n if (version != PSVersion.Vista && version != PSVersion.Win7)\n {\n Deposit(actId, instId);\n }\n\n SPPUtils.RestartSPP(version);\n SLApi.FireStateChangedEvent(appId);\n Logger.WriteLine(\"Activated using ZeroCID successfully.\");\n }\n }\n}\n"], ["/TSforge/TSforgeCLI/Program.cs", "namespace TSforgeCLI\n{\n using System;\n using LibTSforge;\n using LibTSforge.Activators;\n using LibTSforge.Modifiers;\n using LibTSforge.SPP;\n\n public class Program\n {\n private class Options\n {\n public bool Dump;\n public string DumpFilePath = \"dump.dat\";\n public string EncrFilePath;\n public bool Load;\n public string LoadFilePath = \"load.dat\";\n public bool KMS4k;\n public bool AVMA4k;\n public bool ZCID;\n public bool TimerReset;\n public bool RearmReset;\n public bool DeleteUniqueId;\n public bool InstallGenPKey;\n public bool KMSHostCharge;\n public bool TamperedFlagsDelete;\n public bool KeyChangeLockDelete;\n public bool SetIIDParams;\n public bool? Production;\n public PSVersion? Version;\n public Guid ActivationId = Guid.Empty;\n public bool ShowHelp;\n public PKeyAlgorithm? Algorithm;\n public int Group;\n public int Serial;\n public ulong Security;\n }\n\n public static void Main(string[] args)\n {\n Logger.WriteLine(\"TSforge (c) MASSGRAVE 2025\");\n\n Utils.Wow64EnableWow64FsRedirection(false);\n\n try\n {\n if (args.Length == 0)\n {\n DisplayUsage();\n return;\n }\n\n Options options = ParseArguments(args);\n\n if (options.ShowHelp)\n {\n DisplayUsage();\n return;\n }\n\n PSVersion version = options.Version ?? Utils.DetectVersion();\n bool production = options.Production ?? SPPUtils.DetectCurrentKey();\n\n if (options.Dump)\n {\n SPPUtils.DumpStore(version, production, options.DumpFilePath, options.EncrFilePath);\n }\n else if (options.Load)\n {\n SPPUtils.LoadStore(version, production, options.LoadFilePath);\n }\n else if (options.KMS4k)\n {\n KMS4k.Activate(version, production, options.ActivationId);\n }\n else if (options.AVMA4k)\n {\n AVMA4k.Activate(version, production, options.ActivationId);\n }\n else if (options.ZCID)\n {\n ZeroCID.Activate(version, production, options.ActivationId);\n }\n else if (options.TimerReset)\n {\n GracePeriodReset.Reset(version, production);\n }\n else if (options.DeleteUniqueId)\n {\n UniqueIdDelete.DeleteUniqueId(version, production, options.ActivationId);\n }\n else if (options.RearmReset)\n {\n RearmReset.Reset(version, production);\n }\n else if (options.InstallGenPKey)\n {\n GenPKeyInstall.InstallGenPKey(version, production, options.ActivationId);\n }\n else if (options.KMSHostCharge)\n {\n KMSHostCharge.Charge(version, production, options.ActivationId);\n }\n else if (options.TamperedFlagsDelete)\n {\n TamperedFlagsDelete.DeleteTamperFlags(version, production);\n }\n else if (options.KeyChangeLockDelete)\n {\n KeyChangeLockDelete.Delete(version, production);\n } \n else if (options.SetIIDParams)\n {\n SetIIDParams.SetParams(version, production, options.ActivationId, options.Algorithm.Value, options.Group, options.Serial, options.Security);\n }\n else\n {\n DisplayUsage();\n }\n }\n catch (Exception e)\n {\n#if DEBUG\n throw;\n#else\n Logger.WriteLine(\"Fatal error: \" + e.ToString());\n Environment.Exit(1);\n#endif\n }\n }\n\n private static Options ParseArguments(string[] args)\n {\n Options options = new Options();\n for (int i = 0; i < args.Length; i++)\n {\n string arg = args[i].Trim().ToLowerInvariant();\n switch (arg)\n {\n case \"/dump\":\n options.Dump = true;\n if (i + 1 < args.Length && !args[i + 1].StartsWith(\"/\"))\n {\n options.DumpFilePath = args[++i];\n }\n if (i + 1 < args.Length && !args[i + 1].StartsWith(\"/\"))\n {\n options.EncrFilePath = args[++i];\n }\n break;\n case \"/load\":\n options.Load = true;\n if (i + 1 < args.Length && !args[i + 1].StartsWith(\"/\"))\n {\n options.LoadFilePath = args[++i];\n }\n break;\n case \"/kms4k\":\n options.KMS4k = true;\n break;\n case \"/avma4k\":\n options.AVMA4k = true;\n break;\n case \"/zcid\":\n options.ZCID = true;\n break;\n case \"/ver\":\n options.Version = i + 1 < args.Length ? ParseVersion(args[++i]) : throw new ArgumentException(\"/ver requires a version argument.\");\n break;\n case \"/rtmr\":\n options.TimerReset = true;\n break;\n case \"/?\":\n options.ShowHelp = true;\n break;\n case \"/duid\":\n options.DeleteUniqueId = true;\n break;\n case \"/rrmc\":\n options.RearmReset = true;\n break;\n case \"/igpk\":\n options.InstallGenPKey = true;\n break;\n case \"/kmsc\":\n options.KMSHostCharge = true;\n break;\n case \"/test\":\n options.Production = false;\n break;\n case \"/prod\":\n options.Production = true;\n break;\n case \"/ctpr\":\n options.TamperedFlagsDelete = true;\n break;\n case \"/revl\":\n options.KeyChangeLockDelete = true;\n break;\n case \"/siid\":\n options.SetIIDParams = true;\n\n if (args.Length - i - 1 < 4) throw new ArgumentException(\"Not enough arguments specified.\");\n\n string algoType = args[++i];\n\n if (algoType == \"5\")\n {\n options.Algorithm = PKeyAlgorithm.PKEY2005;\n }\n else if (algoType == \"9\")\n {\n options.Algorithm = PKeyAlgorithm.PKEY2009;\n } \n else \n { \n throw new ArgumentException(\"Invalid key algorithm specified.\");\n }\n\n try\n {\n options.Group = int.Parse(args[++i]);\n options.Serial = int.Parse(args[++i]);\n options.Security = ulong.Parse(args[++i]);\n } \n catch\n {\n throw new ArgumentException(\"Failed to parse key parameters.\");\n }\n\n break;\n default:\n try\n {\n options.ActivationId = new Guid(arg);\n }\n catch (FormatException)\n {\n Logger.WriteLine(\"Argument doesn't exist or the specified activation ID is invalid.\");\n options.ShowHelp = true;\n }\n break;\n }\n }\n\n return options;\n }\n\n private static void DisplayUsage()\n {\n string exeName = typeof(Program).Namespace;\n Logger.WriteLine(\"Usage: \" + exeName + \" [/dump ()] [/load ] [/kms4k] [/avma4k] [/zcid] [/rtmr] [/duid] [/igpk] [/kmsc] [/ctpr] [/revl] [/siid <5/9> ] [/prod] [/test] [] [/ver ]\");\n Logger.WriteLine(\"Options:\");\n Logger.WriteLine(\"\\t/dump () Dump and decrypt the physical store to the specified path.\");\n Logger.WriteLine(\"\\t/load Load and re-encrypt the physical store from the specified path.\");\n Logger.WriteLine(\"\\t/kms4k Activate using KMS4k. Only supports KMS-activatable editions.\");\n Logger.WriteLine(\"\\t/avma4k Activate using AVMA4k. Only supports Windows Server 2012 R2+.\");\n Logger.WriteLine(\"\\t/zcid Activate using ZeroCID. Only supports phone-activatable editions.\");\n Logger.WriteLine(\"\\t/rtmr Reset grace/evaluation period timers.\");\n Logger.WriteLine(\"\\t/rrmc Reset the rearm count.\");\n Logger.WriteLine(\"\\t/duid Delete product key Unique ID used in online key validation.\");\n Logger.WriteLine(\"\\t/igpk Install auto-generated/fake product key according to the specified Activation ID\");\n Logger.WriteLine(\"\\t/kmsc Reset the charged count on the local KMS server to 25. Requires an activated KMS host.\");\n Logger.WriteLine(\"\\t/ctpr Remove the tamper flags that get set in the physical store when sppsvc detects an attempt to tamper with it.\");\n Logger.WriteLine(\"\\t/revl Remove the key change lock in evaluation edition store.\");\n Logger.WriteLine(\"\\t/siid <5/9> Set Installation ID parameters independently of installed key. 5/9 argument specifies PKEY200[5/9] key algorithm.\");\n Logger.WriteLine(\"\\t/prod Use SPP production key.\");\n Logger.WriteLine(\"\\t/test Use SPP test key.\");\n Logger.WriteLine(\"\\t/ver Override the detected version. Available versions: vista, 7, 8, blue, modern.\");\n Logger.WriteLine(\"\\t A specific activation ID. Useful if you want to activate specific addons like ESU.\");\n Logger.WriteLine(\"\\t/? Display this help message.\");\n }\n\n private static PSVersion ParseVersion(string ver)\n {\n switch (ver.Trim().ToLowerInvariant())\n {\n case \"vista\": return PSVersion.Vista;\n case \"7\": return PSVersion.Win7;\n case \"8\": return PSVersion.Win8;\n case \"blue\": return PSVersion.WinBlue;\n case \"modern\": return PSVersion.WinModern;\n default: throw new ArgumentException(\"Invalid version specified.\");\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/PhysicalStoreWin7.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using Crypto;\n\n public class Win7Block\n {\n public BlockType Type;\n public uint Flags;\n public byte[] Key;\n public string KeyAsStr\n {\n get\n {\n return Utils.DecodeString(Key);\n }\n set\n {\n Key = Utils.EncodeString(value);\n }\n }\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n public byte[] Data;\n public string DataAsStr\n {\n get\n {\n return Utils.DecodeString(Data);\n }\n set\n {\n Data = Utils.EncodeString(value);\n }\n }\n public uint DataAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Data, 0);\n }\n set\n {\n Data = BitConverter.GetBytes(value);\n }\n }\n\n internal void Encode(BinaryWriter writer)\n {\n writer.Write((uint)Type);\n writer.Write(Flags);\n writer.Write(Key.Length);\n writer.Write(Value.Length);\n writer.Write(Data.Length);\n writer.Write(Key);\n writer.Write(Value);\n writer.Write(Data);\n }\n\n internal static Win7Block Decode(BinaryReader reader)\n {\n uint type = reader.ReadUInt32();\n uint flags = reader.ReadUInt32();\n\n int keyLen = reader.ReadInt32();\n int valueLen = reader.ReadInt32();\n int dataLen = reader.ReadInt32();\n\n byte[] key = reader.ReadBytes(keyLen);\n byte[] value = reader.ReadBytes(valueLen);\n byte[] data = reader.ReadBytes(dataLen);\n return new Win7Block\n {\n Type = (BlockType)type,\n Flags = flags,\n Key = key,\n Value = value,\n Data = data,\n };\n }\n }\n\n public sealed class PhysicalStoreWin7 : IPhysicalStore\n {\n private byte[] PreHeaderBytes = { };\n private readonly List Blocks = new List();\n private readonly FileStream TSPrimary;\n private readonly FileStream TSSecondary;\n private readonly bool Production;\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(PreHeaderBytes);\n\n foreach (Win7Block block in Blocks)\n {\n block.Encode(writer);\n writer.Align(4);\n }\n\n return writer.GetBytes();\n }\n\n public void Deserialize(byte[] data)\n {\n int len = data.Length;\n\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n PreHeaderBytes = reader.ReadBytes(8);\n\n while (reader.BaseStream.Position < len - 0x14)\n {\n Blocks.Add(Win7Block.Decode(reader));\n reader.Align(4);\n }\n }\n\n public void AddBlock(PSBlock block)\n {\n Blocks.Add(new Win7Block\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n });\n }\n\n public void AddBlocks(IEnumerable blocks)\n {\n foreach (PSBlock block in blocks)\n {\n AddBlock(block);\n }\n }\n\n public PSBlock GetBlock(string key, string value)\n {\n foreach (Win7Block block in Blocks)\n {\n if (block.KeyAsStr == key && block.ValueAsStr == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public PSBlock GetBlock(string key, uint value)\n {\n foreach (Win7Block block in Blocks)\n {\n if (block.KeyAsStr == key && block.ValueAsInt == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public void SetBlock(string key, string value, byte[] data)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n Win7Block block = Blocks[i];\n\n if (block.KeyAsStr == key && block.ValueAsStr == value)\n {\n block.Data = data;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void SetBlock(string key, uint value, byte[] data)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n Win7Block block = Blocks[i];\n\n if (block.KeyAsStr == key && block.ValueAsInt == value)\n {\n block.Data = data;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void SetBlock(string key, string value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, string value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void SetBlock(string key, uint value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, uint value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void DeleteBlock(string key, string value)\n {\n foreach (Win7Block block in Blocks)\n {\n if (block.KeyAsStr == key && block.ValueAsStr == value)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public void DeleteBlock(string key, uint value)\n {\n foreach (Win7Block block in Blocks)\n {\n if (block.KeyAsStr == key && block.ValueAsInt == value)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public PhysicalStoreWin7(string primaryPath, bool production)\n {\n TSPrimary = File.Open(primaryPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n TSSecondary = File.Open(primaryPath.Replace(\"-0.\", \"-1.\"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n Production = production;\n\n Deserialize(PhysStoreCrypto.DecryptPhysicalStore(TSPrimary.ReadAllBytes(), production, PSVersion.Win7));\n TSPrimary.Seek(0, SeekOrigin.Begin);\n }\n\n public void Dispose()\n {\n if (TSPrimary.CanWrite && TSSecondary.CanWrite)\n {\n byte[] data = PhysStoreCrypto.EncryptPhysicalStore(Serialize(), Production, PSVersion.Win7);\n\n TSPrimary.SetLength(data.LongLength);\n TSSecondary.SetLength(data.LongLength);\n\n TSPrimary.Seek(0, SeekOrigin.Begin);\n TSSecondary.Seek(0, SeekOrigin.Begin);\n\n TSPrimary.WriteAllBytes(data);\n TSSecondary.WriteAllBytes(data);\n\n TSPrimary.Close();\n TSSecondary.Close();\n }\n }\n\n public byte[] ReadRaw()\n {\n byte[] data = PhysStoreCrypto.DecryptPhysicalStore(TSPrimary.ReadAllBytes(), Production, PSVersion.Win7);\n TSPrimary.Seek(0, SeekOrigin.Begin);\n return data;\n }\n\n public void WriteRaw(byte[] data)\n {\n byte[] encrData = PhysStoreCrypto.EncryptPhysicalStore(data, Production, PSVersion.Win7);\n\n TSPrimary.SetLength(encrData.LongLength);\n TSSecondary.SetLength(encrData.LongLength);\n\n TSPrimary.Seek(0, SeekOrigin.Begin);\n TSSecondary.Seek(0, SeekOrigin.Begin);\n\n TSPrimary.WriteAllBytes(encrData);\n TSSecondary.WriteAllBytes(encrData);\n\n TSPrimary.Close();\n TSSecondary.Close();\n }\n\n public IEnumerable FindBlocks(string valueSearch)\n {\n List results = new List();\n\n foreach (Win7Block block in Blocks)\n {\n if (block.ValueAsStr.Contains(valueSearch))\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n\n return results;\n }\n\n public IEnumerable FindBlocks(uint valueSearch)\n {\n List results = new List();\n\n foreach (Win7Block block in Blocks)\n {\n if (block.ValueAsInt == valueSearch)\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n\n return results;\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/PhysicalStoreVista.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using Crypto;\n\n public class VistaBlock\n {\n public BlockType Type;\n public uint Flags;\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n public byte[] Data;\n public string DataAsStr\n {\n get\n {\n return Utils.DecodeString(Data);\n }\n set\n {\n Data = Utils.EncodeString(value);\n }\n }\n public uint DataAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Data, 0);\n }\n set\n {\n Data = BitConverter.GetBytes(value);\n }\n }\n\n internal void Encode(BinaryWriter writer)\n {\n writer.Write((uint)Type);\n writer.Write(Flags);\n writer.Write(Value.Length);\n writer.Write(Data.Length);\n writer.Write(Value);\n writer.Write(Data);\n }\n\n internal static VistaBlock Decode(BinaryReader reader)\n {\n uint type = reader.ReadUInt32();\n uint flags = reader.ReadUInt32();\n\n int valueLen = reader.ReadInt32();\n int dataLen = reader.ReadInt32();\n\n byte[] value = reader.ReadBytes(valueLen);\n byte[] data = reader.ReadBytes(dataLen);\n return new VistaBlock\n {\n Type = (BlockType)type,\n Flags = flags,\n Value = value,\n Data = data,\n };\n }\n }\n\n public sealed class PhysicalStoreVista : IPhysicalStore\n {\n private byte[] PreHeaderBytes = { };\n private readonly List Blocks = new List();\n private readonly FileStream TSPrimary;\n private readonly FileStream TSSecondary;\n private readonly bool Production;\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(PreHeaderBytes);\n\n foreach (VistaBlock block in Blocks)\n {\n block.Encode(writer);\n writer.Align(4);\n }\n\n return writer.GetBytes();\n }\n\n public void Deserialize(byte[] data)\n {\n int len = data.Length;\n\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n PreHeaderBytes = reader.ReadBytes(8);\n\n while (reader.BaseStream.Position < len - 0x14)\n {\n Blocks.Add(VistaBlock.Decode(reader));\n reader.Align(4);\n }\n }\n\n public void AddBlock(PSBlock block)\n {\n Blocks.Add(new VistaBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Value = block.Value,\n Data = block.Data\n });\n }\n\n public void AddBlocks(IEnumerable blocks)\n {\n foreach (PSBlock block in blocks)\n {\n AddBlock(block);\n }\n }\n\n public PSBlock GetBlock(string key, string value)\n {\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsStr == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = new byte[0],\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public PSBlock GetBlock(string key, uint value)\n {\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsInt == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = new byte[0],\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public void SetBlock(string key, string value, byte[] data)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n VistaBlock block = Blocks[i];\n\n if (block.ValueAsStr == value)\n {\n block.Data = data;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void SetBlock(string key, uint value, byte[] data)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n VistaBlock block = Blocks[i];\n\n if (block.ValueAsInt == value)\n {\n block.Data = data;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void SetBlock(string key, string value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, string value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void SetBlock(string key, uint value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, uint value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void DeleteBlock(string key, string value)\n {\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsStr == value)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public void DeleteBlock(string key, uint value)\n {\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsInt == value)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public PhysicalStoreVista(string primaryPath, bool production)\n {\n TSPrimary = File.Open(primaryPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n TSSecondary = File.Open(primaryPath.Replace(\"-0.\", \"-1.\"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n Production = production;\n\n Deserialize(PhysStoreCrypto.DecryptPhysicalStore(TSPrimary.ReadAllBytes(), production, PSVersion.Vista));\n TSPrimary.Seek(0, SeekOrigin.Begin);\n }\n\n public void Dispose()\n {\n if (TSPrimary.CanWrite && TSSecondary.CanWrite)\n {\n byte[] data = PhysStoreCrypto.EncryptPhysicalStore(Serialize(), Production, PSVersion.Vista);\n\n TSPrimary.SetLength(data.LongLength);\n TSSecondary.SetLength(data.LongLength);\n\n TSPrimary.Seek(0, SeekOrigin.Begin);\n TSSecondary.Seek(0, SeekOrigin.Begin);\n\n TSPrimary.WriteAllBytes(data);\n TSSecondary.WriteAllBytes(data);\n\n TSPrimary.Close();\n TSSecondary.Close();\n }\n }\n\n public byte[] ReadRaw()\n {\n byte[] data = PhysStoreCrypto.DecryptPhysicalStore(TSPrimary.ReadAllBytes(), Production, PSVersion.Vista);\n TSPrimary.Seek(0, SeekOrigin.Begin);\n return data;\n }\n\n public void WriteRaw(byte[] data)\n {\n byte[] encrData = PhysStoreCrypto.EncryptPhysicalStore(data, Production, PSVersion.Vista);\n\n TSPrimary.SetLength(encrData.LongLength);\n TSSecondary.SetLength(encrData.LongLength);\n\n TSPrimary.Seek(0, SeekOrigin.Begin);\n TSSecondary.Seek(0, SeekOrigin.Begin);\n\n TSPrimary.WriteAllBytes(encrData);\n TSSecondary.WriteAllBytes(encrData);\n\n TSPrimary.Close();\n TSSecondary.Close();\n }\n\n public IEnumerable FindBlocks(string valueSearch)\n {\n List results = new List();\n\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsStr.Contains(valueSearch))\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = new byte[0],\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n\n return results;\n }\n\n public IEnumerable FindBlocks(uint valueSearch)\n {\n List results = new List();\n\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsInt == valueSearch)\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = new byte[0],\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n\n return results;\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/KMSHostCharge.cs", "namespace LibTSforge.Modifiers\n{\n using System;\n using System.IO;\n using PhysicalStore;\n using SPP;\n\n public static class KMSHostCharge\n {\n public static void Charge(PSVersion version, bool production, Guid actId)\n {\n if (actId == Guid.Empty)\n {\n actId = SLApi.GetDefaultActivationID(SLApi.WINDOWS_APP_ID, true);\n\n if (actId == Guid.Empty)\n {\n throw new NotSupportedException(\"No applicable activation IDs found.\");\n }\n }\n\n if (SLApi.GetPKeyChannel(SLApi.GetInstalledPkeyID(actId)) != \"Volume:CSVLK\")\n {\n throw new NotSupportedException(\"Non-Volume:CSVLK product key installed.\");\n }\n\n Guid appId = SLApi.GetAppId(actId);\n int totalClients = 50;\n int currClients = 25;\n byte[] hwidBlock = Constants.UniversalHWIDBlock;\n string key = string.Format(\"SPPSVC\\\\{0}\", appId);\n long ldapTimestamp = DateTime.Now.ToFileTime();\n\n byte[] cmidGuids = { };\n byte[] reqCounts = { };\n byte[] kmsChargeData = { };\n\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n\n if (version == PSVersion.Vista)\n {\n writer.Write(new byte[44]);\n writer.Seek(0, SeekOrigin.Begin);\n\n writer.Write(totalClients);\n writer.Write(43200);\n writer.Write(32);\n\n writer.Seek(20, SeekOrigin.Begin);\n writer.Write((byte)currClients);\n\n writer.Seek(32, SeekOrigin.Begin);\n writer.Write((byte)currClients);\n\n writer.Seek(0, SeekOrigin.End);\n\n for (int i = 0; i < currClients; i++)\n {\n writer.Write(Guid.NewGuid().ToByteArray());\n writer.Write(ldapTimestamp - (10 * (i + 1)));\n }\n\n kmsChargeData = writer.GetBytes();\n } \n else\n {\n for (int i = 0; i < currClients; i++)\n {\n writer.Write(ldapTimestamp - (10 * (i + 1)));\n writer.Write(Guid.NewGuid().ToByteArray());\n }\n\n cmidGuids = writer.GetBytes();\n\n writer = new BinaryWriter(new MemoryStream());\n\n writer.Write(new byte[40]);\n\n writer.Seek(4, SeekOrigin.Begin);\n writer.Write((byte)currClients);\n\n writer.Seek(24, SeekOrigin.Begin);\n writer.Write((byte)currClients);\n\n reqCounts = writer.GetBytes();\n }\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n if (version != PSVersion.Vista)\n {\n VariableBag kmsCountData = new VariableBag(version);\n kmsCountData.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppBindingLicenseData\",\n Value = hwidBlock\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.UINT,\n Key = new byte[] { },\n ValueAsInt = (uint)totalClients\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.UINT,\n Key = new byte[] { },\n ValueAsInt = 1051200000\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.UINT,\n Key = new byte[] { },\n ValueAsInt = (uint)currClients\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n Key = new byte[] { },\n Value = cmidGuids\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n Key = new byte[] { },\n Value = reqCounts\n }\n });\n\n kmsChargeData = kmsCountData.Serialize();\n }\n\n string countVal = version == PSVersion.Vista ? \"C8F6FFF1-79CE-404C-B150-F97991273DF1\" : string.Format(\"msft:spp/kms/host/2.0/store/counters/{0}\", appId);\n\n store.DeleteBlock(key, countVal);\n store.AddBlock(new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = (version == PSVersion.WinModern) ? (uint)0x400 : 0,\n KeyAsStr = key,\n ValueAsStr = countVal,\n Data = kmsChargeData\n });\n\n Logger.WriteLine(string.Format(\"Set charge count to {0} successfully.\", currClients));\n }\n\n SPPUtils.RestartSPP(version);\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/VariableBag.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n\n public enum CRCBlockType : uint\n {\n UINT = 1 << 0,\n STRING = 1 << 1,\n BINARY = 1 << 2\n }\n\n public abstract class CRCBlock\n {\n public CRCBlockType DataType;\n public byte[] Key;\n public string KeyAsStr\n {\n get\n {\n return Utils.DecodeString(Key);\n }\n set\n {\n Key = Utils.EncodeString(value);\n }\n }\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n\n public abstract void Encode(BinaryWriter writer);\n public abstract void Decode(BinaryReader reader);\n public abstract uint CRC();\n }\n\n public class CRCBlockVista : CRCBlock\n {\n public override void Encode(BinaryWriter writer)\n {\n uint crc = CRC();\n writer.Write((uint)DataType);\n writer.Write(0);\n writer.Write(Key.Length);\n writer.Write(Value.Length);\n writer.Write(crc);\n\n writer.Write(Key);\n\n writer.Write(Value);\n }\n\n public override void Decode(BinaryReader reader)\n {\n uint type = reader.ReadUInt32();\n reader.ReadUInt32();\n uint lenName = reader.ReadUInt32();\n uint lenVal = reader.ReadUInt32();\n uint crc = reader.ReadUInt32();\n\n byte[] key = reader.ReadBytes((int)lenName);\n byte[] value = reader.ReadBytes((int)lenVal);\n\n DataType = (CRCBlockType)type;\n Key = key;\n Value = value;\n\n if (CRC() != crc)\n {\n throw new InvalidDataException(\"Invalid CRC in variable bag.\");\n }\n }\n\n public override uint CRC()\n {\n return Utils.CRC32(Value);\n }\n }\n\n public class CRCBlockModern : CRCBlock\n {\n public override void Encode(BinaryWriter writer)\n {\n uint crc = CRC();\n writer.Write(crc);\n writer.Write((uint)DataType);\n writer.Write(Key.Length);\n writer.Write(Value.Length);\n\n writer.Write(Key);\n writer.Align(8);\n\n writer.Write(Value);\n writer.Align(8);\n }\n\n public override void Decode(BinaryReader reader)\n {\n uint crc = reader.ReadUInt32();\n uint type = reader.ReadUInt32();\n uint lenName = reader.ReadUInt32();\n uint lenVal = reader.ReadUInt32();\n\n byte[] key = reader.ReadBytes((int)lenName);\n reader.Align(8);\n\n byte[] value = reader.ReadBytes((int)lenVal);\n reader.Align(8);\n\n DataType = (CRCBlockType)type;\n Key = key;\n Value = value;\n\n if (CRC() != crc)\n {\n throw new InvalidDataException(\"Invalid CRC in variable bag.\");\n }\n }\n\n public override uint CRC()\n {\n BinaryWriter wtemp = new BinaryWriter(new MemoryStream());\n wtemp.Write(0);\n wtemp.Write((uint)DataType);\n wtemp.Write(Key.Length);\n wtemp.Write(Value.Length);\n wtemp.Write(Key);\n wtemp.Write(Value);\n return Utils.CRC32(wtemp.GetBytes());\n }\n }\n\n public class VariableBag\n {\n public List Blocks = new List();\n private readonly PSVersion Version;\n\n private void Deserialize(byte[] data)\n {\n int len = data.Length;\n\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n\n while (reader.BaseStream.Position < len - 0x10)\n {\n CRCBlock block;\n\n if (Version == PSVersion.Vista)\n {\n block = new CRCBlockVista();\n }\n else\n {\n block = new CRCBlockModern();\n }\n\n block.Decode(reader);\n Blocks.Add(block);\n }\n }\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n\n foreach (CRCBlock block in Blocks)\n {\n if (Version == PSVersion.Vista)\n {\n ((CRCBlockVista)block).Encode(writer);\n } else\n {\n ((CRCBlockModern)block).Encode(writer);\n }\n }\n\n return writer.GetBytes();\n }\n\n public CRCBlock GetBlock(string key)\n {\n foreach (CRCBlock block in Blocks)\n {\n if (block.KeyAsStr == key)\n {\n return block;\n }\n }\n\n return null;\n }\n\n public void SetBlock(string key, byte[] value)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n CRCBlock block = Blocks[i];\n\n if (block.KeyAsStr == key)\n {\n block.Value = value;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void DeleteBlock(string key)\n {\n foreach (CRCBlock block in Blocks)\n {\n if (block.KeyAsStr == key)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public VariableBag(byte[] data, PSVersion version)\n {\n Version = version;\n Deserialize(data);\n }\n\n public VariableBag(PSVersion version)\n {\n Version = version;\n }\n }\n}\n"], ["/TSforge/LibTSforge/Activators/KMS4K.cs", "namespace LibTSforge.Activators\n{\n using System;\n using System.IO;\n using PhysicalStore;\n using SPP;\n\n public class KMS4k\n {\n public static void Activate(PSVersion version, bool production, Guid actId)\n {\n Guid appId;\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, true);\n\n if (actId == Guid.Empty)\n {\n throw new NotSupportedException(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n if (SLApi.GetPKeyChannel(SLApi.GetInstalledPkeyID(actId)) != \"Volume:GVLK\")\n {\n throw new NotSupportedException(\"Non-Volume:GVLK product key installed.\");\n }\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n\n ulong unknown = 0;\n ulong time1;\n ulong time2 = (ulong)DateTime.UtcNow.ToFileTime();\n ulong expiry = Constants.TimerMax;\n\n if (version == PSVersion.Vista || version == PSVersion.Win7)\n {\n unknown = 0x800000000;\n time1 = 0;\n }\n else\n {\n long creationTime = BitConverter.ToInt64(store.GetBlock(\"__##USERSEP##\\\\$$_RESERVED_$$\\\\NAMESPACE__\", \"__##USERSEP-RESERVED##__$$GLOBAL-CREATION-TIME$$\").Data, 0);\n long tickCount = BitConverter.ToInt64(store.GetBlock(\"__##USERSEP##\\\\$$_RESERVED_$$\\\\NAMESPACE__\", \"__##USERSEP-RESERVED##__$$GLOBAL-TICKCOUNT-UPTIME$$\").Data, 0);\n long deltaTime = BitConverter.ToInt64(store.GetBlock(key, \"__##USERSEP-RESERVED##__$$UP-TIME-DELTA$$\").Data, 0);\n\n time1 = (ulong)(creationTime + tickCount + deltaTime);\n time2 /= 10000;\n expiry /= 10000;\n }\n\n if (version == PSVersion.Vista)\n {\n VistaTimer vistaTimer = new VistaTimer\n {\n Time = time2,\n Expiry = Constants.TimerMax\n };\n\n string vistaTimerName = string.Format(\"msft:sl/timer/VLExpiration/VOLUME/{0}/{1}\", appId, actId);\n\n store.DeleteBlock(key, vistaTimerName);\n store.DeleteBlock(key, actId.ToString());\n\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(Constants.KMSv4Response.Length);\n writer.Write(Constants.KMSv4Response);\n writer.Write(Constants.UniversalHWIDBlock);\n byte[] kmsData = writer.GetBytes();\n\n store.AddBlocks(new[]\n {\n new PSBlock\n {\n Type = BlockType.TIMER,\n Flags = 0,\n KeyAsStr = key,\n ValueAsStr = vistaTimerName,\n Data = vistaTimer.CastToArray()\n },\n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = 0,\n KeyAsStr = key,\n ValueAsStr = actId.ToString(),\n Data = kmsData\n }\n });\n }\n else\n {\n byte[] hwidBlock = Constants.UniversalHWIDBlock;\n byte[] kmsResp;\n\n switch (version)\n {\n case PSVersion.Win7:\n kmsResp = Constants.KMSv4Response;\n break;\n case PSVersion.Win8:\n kmsResp = Constants.KMSv5Response;\n break;\n case PSVersion.WinBlue:\n case PSVersion.WinModern:\n kmsResp = Constants.KMSv6Response;\n break;\n default:\n throw new NotSupportedException(\"Unsupported PSVersion.\");\n }\n\n VariableBag kmsBinding = new VariableBag(version);\n\n kmsBinding.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n Key = new byte[] { },\n Value = kmsResp\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"msft:rm/algorithm/hwid/4.0\"\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppBindingLicenseData\",\n Value = hwidBlock\n }\n });\n\n if (version == PSVersion.WinModern)\n {\n kmsBinding.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"massgrave.dev\"\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"6969\"\n }\n });\n }\n\n byte[] kmsBindingData = kmsBinding.Serialize();\n\n Timer kmsTimer = new Timer\n {\n Unknown = unknown,\n Time1 = time1,\n Time2 = time2,\n Expiry = expiry\n };\n\n string storeVal = string.Format(\"msft:spp/kms/bind/2.0/store/{0}/{1}\", appId, actId);\n string timerVal = string.Format(\"msft:spp/kms/bind/2.0/timer/{0}/{1}\", appId, actId);\n\n store.DeleteBlock(key, storeVal);\n store.DeleteBlock(key, timerVal);\n\n store.AddBlocks(new[]\n {\n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = (version == PSVersion.WinModern) ? (uint)0x400 : 0,\n KeyAsStr = key,\n ValueAsStr = storeVal,\n Data = kmsBindingData\n },\n new PSBlock\n {\n Type = BlockType.TIMER,\n Flags = (version == PSVersion.Win7) ? (uint)0 : 0x4,\n KeyAsStr = key,\n ValueAsStr = timerVal,\n Data = kmsTimer.CastToArray()\n }\n });\n }\n }\n\n SPPUtils.RestartSPP(version);\n SLApi.FireStateChangedEvent(appId);\n Logger.WriteLine(\"Activated using KMS4k successfully.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/Common.cs", "namespace LibTSforge.PhysicalStore\n{\n using System.Runtime.InteropServices;\n\n public enum BlockType : uint\n {\n NONE,\n NAMED,\n ATTRIBUTE,\n TIMER\n }\n\n [StructLayout(LayoutKind.Sequential, Pack = 1)]\n public struct Timer\n {\n public ulong Unknown;\n public ulong Time1;\n public ulong Time2;\n public ulong Expiry;\n }\n\n [StructLayout(LayoutKind.Sequential, Pack = 1)]\n public struct VistaTimer\n {\n public ulong Time;\n public ulong Expiry;\n }\n}\n"], ["/TSforge/LibTSforge/Crypto/PhysStoreCrypto.cs", "namespace LibTSforge.Crypto\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using System.Linq;\n using System.Text;\n\n public static class PhysStoreCrypto\n {\n public static byte[] DecryptPhysicalStore(byte[] data, bool production, PSVersion version)\n {\n byte[] rsaKey = production ? Keys.PRODUCTION : Keys.TEST;\n BinaryReader br = new BinaryReader(new MemoryStream(data));\n br.BaseStream.Seek(0x10, SeekOrigin.Begin);\n byte[] aesKeySig = br.ReadBytes(0x80);\n byte[] encAesKey = br.ReadBytes(0x80);\n\n if (!CryptoUtils.RSAVerifySignature(rsaKey, encAesKey, aesKeySig))\n {\n throw new Exception(\"Failed to decrypt physical store.\");\n }\n\n byte[] aesKey = CryptoUtils.RSADecrypt(rsaKey, encAesKey);\n byte[] decData = CryptoUtils.AESDecrypt(br.ReadBytes((int)br.BaseStream.Length - 0x110), aesKey);\n byte[] hmacKey = decData.Take(0x10).ToArray(); // SHA-1 salt on Vista\n byte[] hmacSig = decData.Skip(0x10).Take(0x14).ToArray(); // SHA-1 hash on Vista\n byte[] psData = decData.Skip(0x28).ToArray();\n\n if (version != PSVersion.Vista)\n {\n if (!CryptoUtils.HMACVerify(hmacKey, psData, hmacSig))\n {\n throw new InvalidDataException(\"Failed to verify HMAC. Physical store is corrupt.\");\n }\n }\n else\n {\n if (!CryptoUtils.SaltSHAVerify(hmacKey, psData, hmacSig))\n {\n throw new InvalidDataException(\"Failed to verify checksum. Physical store is corrupt.\");\n }\n }\n\n return psData;\n }\n\n public static byte[] EncryptPhysicalStore(byte[] data, bool production, PSVersion version)\n {\n Dictionary versionTable = new Dictionary\n {\n {PSVersion.Vista, 2},\n {PSVersion.Win7, 5},\n {PSVersion.Win8, 1},\n {PSVersion.WinBlue, 2},\n {PSVersion.WinModern, 3}\n };\n\n byte[] rsaKey = production ? Keys.PRODUCTION : Keys.TEST;\n\n byte[] aesKey = Encoding.UTF8.GetBytes(\"massgrave.dev :3\");\n byte[] hmacKey = CryptoUtils.GenerateRandomKey(0x10);\n\n byte[] encAesKey = CryptoUtils.RSAEncrypt(rsaKey, aesKey);\n byte[] aesKeySig = CryptoUtils.RSASign(rsaKey, encAesKey);\n byte[] hmacSig = version != PSVersion.Vista ? CryptoUtils.HMACSign(hmacKey, data) : CryptoUtils.SaltSHASum(hmacKey, data);\n\n byte[] decData = { };\n decData = decData.Concat(hmacKey).Concat(hmacSig).Concat(BitConverter.GetBytes(0)).Concat(data).ToArray();\n byte[] encData = CryptoUtils.AESEncrypt(decData, aesKey);\n\n BinaryWriter bw = new BinaryWriter(new MemoryStream());\n bw.Write(versionTable[version]);\n bw.Write(Encoding.UTF8.GetBytes(\"UNTRUSTSTORE\"));\n bw.Write(aesKeySig);\n bw.Write(encAesKey);\n bw.Write(encData);\n\n return bw.GetBytes();\n }\n }\n}\n"], ["/TSforge/LibTSforge/Activators/AVMA4K.cs", "namespace LibTSforge.Activators\n{\n using System;\n using PhysicalStore;\n using SPP;\n\n public static class AVMA4k\n {\n public static void Activate(PSVersion version, bool production, Guid actId)\n {\n if (version != PSVersion.WinModern && version != PSVersion.WinBlue)\n {\n throw new NotSupportedException(\"AVMA licenses are not available for this product.\");\n }\n\n Guid appId;\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, false);\n\n if (actId == Guid.Empty)\n {\n throw new NotSupportedException(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n if (SLApi.GetPKeyChannel(SLApi.GetInstalledPkeyID(actId)) != \"VT:IA\")\n {\n throw new NotSupportedException(\"Non-VT:IA product key installed.\");\n }\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n\n long creationTime = BitConverter.ToInt64(store.GetBlock(\"__##USERSEP##\\\\$$_RESERVED_$$\\\\NAMESPACE__\", \"__##USERSEP-RESERVED##__$$GLOBAL-CREATION-TIME$$\").Data, 0);\n long tickCount = BitConverter.ToInt64(store.GetBlock(\"__##USERSEP##\\\\$$_RESERVED_$$\\\\NAMESPACE__\", \"__##USERSEP-RESERVED##__$$GLOBAL-TICKCOUNT-UPTIME$$\").Data, 0);\n long deltaTime = BitConverter.ToInt64(store.GetBlock(key, \"__##USERSEP-RESERVED##__$$UP-TIME-DELTA$$\").Data, 0);\n\n const ulong unknown = 0;\n ulong time1 = (ulong)(creationTime + tickCount + deltaTime);\n ulong crcBindTime = (ulong)DateTime.UtcNow.ToFileTime();\n ulong timerTime = crcBindTime / 10000;\n ulong expiry = Constants.TimerMax / 10000;\n\n VariableBag avmaBinding = new VariableBag(version);\n\n avmaBinding.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n Key = new byte[] { },\n Value = BitConverter.GetBytes(crcBindTime),\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"AVMA4K\",\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"00491-50000-00001-AA666\",\n }\n });\n\n byte[] avmaBindingData = avmaBinding.Serialize();\n\n Timer avmaTimer = new Timer\n {\n Unknown = unknown,\n Time1 = time1,\n Time2 = timerTime,\n Expiry = expiry\n };\n\n string storeVal = string.Format(\"msft:spp/ia/bind/1.0/store/{0}/{1}\", appId, actId);\n string timerVal = string.Format(\"msft:spp/ia/bind/1.0/timer/{0}/{1}\", appId, actId);\n\n store.DeleteBlock(key, storeVal);\n store.DeleteBlock(key, timerVal);\n\n store.AddBlocks(new[]\n {\n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = 0x400,\n KeyAsStr = key,\n ValueAsStr = storeVal,\n Data = avmaBindingData,\n },\n new PSBlock\n {\n Type = BlockType.TIMER,\n Flags = 0x4,\n KeyAsStr = key,\n ValueAsStr = timerVal,\n Data = avmaTimer.CastToArray()\n }\n });\n }\n\n SLApi.RefreshLicenseStatus();\n SLApi.FireStateChangedEvent(appId);\n Logger.WriteLine(\"Activated using AVMA4k successfully.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/TokenStore/Common.cs", "namespace LibTSforge.TokenStore\n{\n using System.Collections.Generic;\n using System.IO;\n\n public class TokenEntry\n {\n public string Name;\n public string Extension;\n public byte[] Data;\n public bool Populated;\n }\n\n public class TokenMeta\n {\n public string Name;\n public readonly Dictionary Data = new Dictionary();\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(1);\n byte[] nameBytes = Utils.EncodeString(Name);\n writer.Write(nameBytes.Length);\n writer.Write(nameBytes);\n\n foreach (KeyValuePair kv in Data)\n {\n byte[] keyBytes = Utils.EncodeString(kv.Key);\n byte[] valueBytes = Utils.EncodeString(kv.Value);\n writer.Write(keyBytes.Length);\n writer.Write(valueBytes.Length);\n writer.Write(keyBytes);\n writer.Write(valueBytes);\n }\n\n return writer.GetBytes();\n }\n\n private void Deserialize(byte[] data)\n {\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n reader.ReadInt32();\n int nameLen = reader.ReadInt32();\n Name = reader.ReadNullTerminatedString(nameLen);\n\n while (reader.BaseStream.Position < data.Length - 0x8)\n {\n int keyLen = reader.ReadInt32();\n int valueLen = reader.ReadInt32();\n string key = reader.ReadNullTerminatedString(keyLen);\n string value = reader.ReadNullTerminatedString(valueLen);\n Data[key] = value;\n }\n }\n\n public TokenMeta(byte[] data)\n {\n Deserialize(data);\n }\n\n public TokenMeta()\n {\n\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/TamperedFlagsDelete.cs", "namespace LibTSforge.Modifiers\n{\n using System.Linq;\n using PhysicalStore;\n using SPP;\n\n public static class TamperedFlagsDelete\n {\n public static void DeleteTamperFlags(PSVersion version, bool production)\n {\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n if (version == PSVersion.Vista)\n {\n DeleteFlag(store, \"6BE8425B-E3CF-4e86-A6AF-5863E3DCB606\");\n }\n else if (version == PSVersion.Win7)\n {\n SetFlag(store, 0xA0001);\n }\n else\n {\n DeleteFlag(store, \"__##USERSEP-RESERVED##__$$RECREATED-FLAG$$\");\n DeleteFlag(store, \"__##USERSEP-RESERVED##__$$RECOVERED-FLAG$$\");\n }\n\n Logger.WriteLine(\"Successfully cleared the tamper state.\");\n }\n\n SPPUtils.RestartSPP(version);\n }\n\n private static void DeleteFlag(IPhysicalStore store, string flag)\n {\n store.FindBlocks(flag).ToList().ForEach(block => store.DeleteBlock(block.KeyAsStr, block.ValueAsStr));\n }\n\n private static void SetFlag(IPhysicalStore store, uint flag)\n {\n store.FindBlocks(flag).ToList().ForEach(block => store.SetBlock(block.KeyAsStr, block.ValueAsInt, new byte[8]));\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/SetIIDParams.cs", "namespace LibTSforge.Modifiers\n{\n using PhysicalStore;\n using SPP;\n using System.IO;\n using System;\n\n public static class SetIIDParams\n {\n public static void SetParams(PSVersion version, bool production, Guid actId, PKeyAlgorithm algorithm, int group, int serial, ulong security)\n {\n if (version == PSVersion.Vista) throw new NotSupportedException(\"This feature is not supported on Windows Vista/Server 2008.\");\n\n Guid appId;\n\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, true);\n\n if (actId == Guid.Empty)\n {\n throw new Exception(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n Guid pkeyId = SLApi.GetInstalledPkeyID(actId);\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n PSBlock keyBlock = store.GetBlock(key, pkeyId.ToString());\n\n if (keyBlock == null)\n {\n throw new InvalidDataException(\"Failed to get product key data for activation ID \" + actId + \".\");\n }\n\n VariableBag pkb = new VariableBag(keyBlock.Data, version);\n\n ProductKey pkey = new ProductKey\n {\n Group = group,\n Serial = serial,\n Security = security,\n Algorithm = algorithm,\n Upgrade = false\n };\n\n string blockName = version == PSVersion.Win7 ? \"SppPkeyShortAuthenticator\" : \"SppPkeyPhoneActivationData\";\n pkb.SetBlock(blockName, pkey.GetPhoneData(version));\n store.SetBlock(key, pkeyId.ToString(), pkb.Serialize());\n }\n\n Logger.WriteLine(\"Successfully set IID parameters.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/IPhysicalStore.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n\n public class PSBlock\n {\n public BlockType Type;\n public uint Flags;\n public uint Unknown = 0;\n public byte[] Key;\n public string KeyAsStr\n {\n get\n {\n return Utils.DecodeString(Key);\n }\n set\n {\n Key = Utils.EncodeString(value);\n }\n }\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n public byte[] Data;\n public string DataAsStr\n {\n get\n {\n return Utils.DecodeString(Data);\n }\n set\n {\n Data = Utils.EncodeString(value);\n }\n }\n public uint DataAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Data, 0);\n }\n set\n {\n Data = BitConverter.GetBytes(value);\n }\n }\n }\n\n public interface IPhysicalStore : IDisposable\n {\n PSBlock GetBlock(string key, string value);\n PSBlock GetBlock(string key, uint value);\n void AddBlock(PSBlock block);\n void AddBlocks(IEnumerable blocks);\n void SetBlock(string key, string value, byte[] data);\n void SetBlock(string key, string value, string data);\n void SetBlock(string key, string value, uint data);\n void SetBlock(string key, uint value, byte[] data);\n void SetBlock(string key, uint value, string data);\n void SetBlock(string key, uint value, uint data);\n void DeleteBlock(string key, string value);\n void DeleteBlock(string key, uint value);\n byte[] Serialize();\n void Deserialize(byte[] data);\n byte[] ReadRaw();\n void WriteRaw(byte[] data);\n IEnumerable FindBlocks(string valueSearch);\n IEnumerable FindBlocks(uint valueSearch);\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/RearmReset.cs", "namespace LibTSforge.Modifiers\n{\n using System.Collections.Generic;\n using System.Linq;\n using PhysicalStore;\n using SPP;\n\n public static class RearmReset\n {\n public static void Reset(PSVersion version, bool production)\n {\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n List blocks;\n\n if (version == PSVersion.Vista)\n {\n blocks = store.FindBlocks(\"740D70D8-6448-4b2f-9063-4A7A463600C5\").ToList();\n }\n else if (version == PSVersion.Win7)\n {\n blocks = store.FindBlocks(0xA0000).ToList();\n }\n else\n {\n blocks = store.FindBlocks(\"__##USERSEP-RESERVED##__$$REARM-COUNT$$\").ToList();\n }\n\n foreach (PSBlock block in blocks)\n {\n if (version == PSVersion.Vista)\n {\n store.DeleteBlock(block.KeyAsStr, block.ValueAsStr);\n }\n else if (version == PSVersion.Win7)\n {\n store.SetBlock(block.KeyAsStr, block.ValueAsInt, new byte[8]);\n }\n else\n {\n store.SetBlock(block.KeyAsStr, block.ValueAsStr, new byte[8]);\n }\n }\n\n Logger.WriteLine(\"Successfully reset all rearm counters.\");\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/UniqueIdDelete.cs", "namespace LibTSforge.Modifiers\n{\n using System;\n using PhysicalStore;\n using SPP;\n\n public static class UniqueIdDelete\n {\n public static void DeleteUniqueId(PSVersion version, bool production, Guid actId)\n {\n if (version == PSVersion.Vista) throw new NotSupportedException(\"This feature is not supported on Windows Vista/Server 2008.\");\n\n Guid appId;\n\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, true);\n\n if (actId == Guid.Empty)\n {\n throw new Exception(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n Guid pkeyId = SLApi.GetInstalledPkeyID(actId);\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n PSBlock keyBlock = store.GetBlock(key, pkeyId.ToString());\n\n if (keyBlock == null)\n {\n throw new Exception(\"No product key found.\");\n }\n\n VariableBag pkb = new VariableBag(keyBlock.Data, version);\n\n pkb.DeleteBlock(\"SppPkeyUniqueIdToken\");\n\n store.SetBlock(key, pkeyId.ToString(), pkb.Serialize());\n }\n\n Logger.WriteLine(\"Successfully removed Unique ID for product key ID \" + pkeyId);\n }\n }\n}\n"], ["/TSforge/LibTSforge/Crypto/CryptoUtils.cs", "namespace LibTSforge.Crypto\n{\n using System;\n using System.Linq;\n using System.Security.Cryptography;\n\n public static class CryptoUtils\n {\n public static byte[] GenerateRandomKey(int len)\n {\n byte[] rand = new byte[len];\n Random r = new Random();\n r.NextBytes(rand);\n\n return rand;\n }\n\n public static byte[] AESEncrypt(byte[] data, byte[] key)\n {\n using (Aes aes = Aes.Create())\n {\n aes.Key = key;\n aes.Mode = CipherMode.CBC;\n aes.Padding = PaddingMode.PKCS7;\n\n ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, Enumerable.Repeat((byte)0, 16).ToArray());\n byte[] encryptedData = encryptor.TransformFinalBlock(data, 0, data.Length);\n return encryptedData;\n }\n }\n\n public static byte[] AESDecrypt(byte[] data, byte[] key)\n {\n using (Aes aes = Aes.Create())\n {\n aes.Key = key;\n aes.Mode = CipherMode.CBC;\n aes.Padding = PaddingMode.PKCS7;\n\n ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, Enumerable.Repeat((byte)0, 16).ToArray());\n byte[] decryptedData = decryptor.TransformFinalBlock(data, 0, data.Length);\n return decryptedData;\n }\n }\n\n public static byte[] RSADecrypt(byte[] rsaKey, byte[] data)\n {\n\n using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())\n {\n rsa.ImportCspBlob(rsaKey);\n return rsa.Decrypt(data, false);\n }\n }\n\n public static byte[] RSAEncrypt(byte[] rsaKey, byte[] data)\n {\n using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())\n {\n rsa.ImportCspBlob(rsaKey);\n return rsa.Encrypt(data, false);\n }\n }\n\n public static byte[] RSASign(byte[] rsaKey, byte[] data)\n {\n using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())\n {\n rsa.ImportCspBlob(rsaKey);\n RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(rsa);\n formatter.SetHashAlgorithm(\"SHA1\");\n\n byte[] hash;\n using (SHA1 sha1 = SHA1.Create())\n {\n hash = sha1.ComputeHash(data);\n }\n\n return formatter.CreateSignature(hash);\n }\n }\n\n public static bool RSAVerifySignature(byte[] rsaKey, byte[] data, byte[] signature)\n {\n using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())\n {\n rsa.ImportCspBlob(rsaKey);\n RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(rsa);\n deformatter.SetHashAlgorithm(\"SHA1\");\n\n byte[] hash;\n using (SHA1 sha1 = SHA1.Create())\n {\n hash = sha1.ComputeHash(data);\n }\n\n return deformatter.VerifySignature(hash, signature);\n }\n }\n\n public static byte[] HMACSign(byte[] key, byte[] data)\n {\n HMACSHA1 hmac = new HMACSHA1(key);\n return hmac.ComputeHash(data);\n }\n\n public static bool HMACVerify(byte[] key, byte[] data, byte[] signature)\n {\n return Enumerable.SequenceEqual(signature, HMACSign(key, data));\n }\n\n public static byte[] SaltSHASum(byte[] salt, byte[] data)\n {\n SHA1 sha1 = SHA1.Create();\n byte[] sha_data = salt.Concat(data).ToArray();\n return sha1.ComputeHash(sha_data);\n }\n\n public static bool SaltSHAVerify(byte[] salt, byte[] data, byte[] checksum)\n {\n return Enumerable.SequenceEqual(checksum, SaltSHASum(salt, data));\n }\n\n public static byte[] SHA256Hash(byte[] data)\n {\n using (SHA256 sha256 = SHA256.Create())\n {\n return sha256.ComputeHash(data);\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/Crypto/Keys.cs", "namespace LibTSforge.Crypto\n{\n public static class Keys\n {\n public static readonly byte[] PRODUCTION = {\n 0x07, 0x02, 0x00, 0x00, 0x00, 0xA4, 0x00, 0x00, 0x52, 0x53, 0x41, 0x32, 0x00, 0x04, 0x00, 0x00,\n 0x01, 0x00, 0x01, 0x00, 0x29, 0x87, 0xBA, 0x3F, 0x52, 0x90, 0x57, 0xD8, 0x12, 0x26, 0x6B, 0x38,\n 0xB2, 0x3B, 0xF9, 0x67, 0x08, 0x4F, 0xDD, 0x8B, 0xF5, 0xE3, 0x11, 0xB8, 0x61, 0x3A, 0x33, 0x42,\n 0x51, 0x65, 0x05, 0x86, 0x1E, 0x00, 0x41, 0xDE, 0xC5, 0xDD, 0x44, 0x60, 0x56, 0x3D, 0x14, 0x39,\n 0xB7, 0x43, 0x65, 0xE9, 0xF7, 0x2B, 0xA5, 0xF0, 0xA3, 0x65, 0x68, 0xE9, 0xE4, 0x8B, 0x5C, 0x03,\n 0x2D, 0x36, 0xFE, 0x28, 0x4C, 0xD1, 0x3C, 0x3D, 0xC1, 0x90, 0x75, 0xF9, 0x6E, 0x02, 0xE0, 0x58,\n 0x97, 0x6A, 0xCA, 0x80, 0x02, 0x42, 0x3F, 0x6C, 0x15, 0x85, 0x4D, 0x83, 0x23, 0x6A, 0x95, 0x9E,\n 0x38, 0x52, 0x59, 0x38, 0x6A, 0x99, 0xF0, 0xB5, 0xCD, 0x53, 0x7E, 0x08, 0x7C, 0xB5, 0x51, 0xD3,\n 0x8F, 0xA3, 0x0D, 0xA0, 0xFA, 0x8D, 0x87, 0x3C, 0xFC, 0x59, 0x21, 0xD8, 0x2E, 0xD9, 0x97, 0x8B,\n 0x40, 0x60, 0xB1, 0xD7, 0x2B, 0x0A, 0x6E, 0x60, 0xB5, 0x50, 0xCC, 0x3C, 0xB1, 0x57, 0xE4, 0xB7,\n 0xDC, 0x5A, 0x4D, 0xE1, 0x5C, 0xE0, 0x94, 0x4C, 0x5E, 0x28, 0xFF, 0xFA, 0x80, 0x6A, 0x13, 0x53,\n 0x52, 0xDB, 0xF3, 0x04, 0x92, 0x43, 0x38, 0xB9, 0x1B, 0xD9, 0x85, 0x54, 0x7B, 0x14, 0xC7, 0x89,\n 0x16, 0x8A, 0x4B, 0x82, 0xA1, 0x08, 0x02, 0x99, 0x23, 0x48, 0xDD, 0x75, 0x9C, 0xC8, 0xC1, 0xCE,\n 0xB0, 0xD7, 0x1B, 0xD8, 0xFB, 0x2D, 0xA7, 0x2E, 0x47, 0xA7, 0x18, 0x4B, 0xF6, 0x29, 0x69, 0x44,\n 0x30, 0x33, 0xBA, 0xA7, 0x1F, 0xCE, 0x96, 0x9E, 0x40, 0xE1, 0x43, 0xF0, 0xE0, 0x0D, 0x0A, 0x32,\n 0xB4, 0xEE, 0xA1, 0xC3, 0x5E, 0x9B, 0xC7, 0x7F, 0xF5, 0x9D, 0xD8, 0xF2, 0x0F, 0xD9, 0x8F, 0xAD,\n 0x75, 0x0A, 0x00, 0xD5, 0x25, 0x43, 0xF7, 0xAE, 0x51, 0x7F, 0xB7, 0xDE, 0xB7, 0xAD, 0xFB, 0xCE,\n 0x83, 0xE1, 0x81, 0xFF, 0xDD, 0xA2, 0x77, 0xFE, 0xEB, 0x27, 0x1F, 0x10, 0xFA, 0x82, 0x37, 0xF4,\n 0x7E, 0xCC, 0xE2, 0xA1, 0x58, 0xC8, 0xAF, 0x1D, 0x1A, 0x81, 0x31, 0x6E, 0xF4, 0x8B, 0x63, 0x34,\n 0xF3, 0x05, 0x0F, 0xE1, 0xCC, 0x15, 0xDC, 0xA4, 0x28, 0x7A, 0x9E, 0xEB, 0x62, 0xD8, 0xD8, 0x8C,\n 0x85, 0xD7, 0x07, 0x87, 0x90, 0x2F, 0xF7, 0x1C, 0x56, 0x85, 0x2F, 0xEF, 0x32, 0x37, 0x07, 0xAB,\n 0xB0, 0xE6, 0xB5, 0x02, 0x19, 0x35, 0xAF, 0xDB, 0xD4, 0xA2, 0x9C, 0x36, 0x80, 0xC6, 0xDC, 0x82,\n 0x08, 0xE0, 0xC0, 0x5F, 0x3C, 0x59, 0xAA, 0x4E, 0x26, 0x03, 0x29, 0xB3, 0x62, 0x58, 0x41, 0x59,\n 0x3A, 0x37, 0x43, 0x35, 0xE3, 0x9F, 0x34, 0xE2, 0xA1, 0x04, 0x97, 0x12, 0x9D, 0x8C, 0xAD, 0xF7,\n 0xFB, 0x8C, 0xA1, 0xA2, 0xE9, 0xE4, 0xEF, 0xD9, 0xC5, 0xE5, 0xDF, 0x0E, 0xBF, 0x4A, 0xE0, 0x7A,\n 0x1E, 0x10, 0x50, 0x58, 0x63, 0x51, 0xE1, 0xD4, 0xFE, 0x57, 0xB0, 0x9E, 0xD7, 0xDA, 0x8C, 0xED,\n 0x7D, 0x82, 0xAC, 0x2F, 0x25, 0x58, 0x0A, 0x58, 0xE6, 0xA4, 0xF4, 0x57, 0x4B, 0xA4, 0x1B, 0x65,\n 0xB9, 0x4A, 0x87, 0x46, 0xEB, 0x8C, 0x0F, 0x9A, 0x48, 0x90, 0xF9, 0x9F, 0x76, 0x69, 0x03, 0x72,\n 0x77, 0xEC, 0xC1, 0x42, 0x4C, 0x87, 0xDB, 0x0B, 0x3C, 0xD4, 0x74, 0xEF, 0xE5, 0x34, 0xE0, 0x32,\n 0x45, 0xB0, 0xF8, 0xAB, 0xD5, 0x26, 0x21, 0xD7, 0xD2, 0x98, 0x54, 0x8F, 0x64, 0x88, 0x20, 0x2B,\n 0x14, 0xE3, 0x82, 0xD5, 0x2A, 0x4B, 0x8F, 0x4E, 0x35, 0x20, 0x82, 0x7E, 0x1B, 0xFE, 0xFA, 0x2C,\n 0x79, 0x6C, 0x6E, 0x66, 0x94, 0xBB, 0x0A, 0xEB, 0xBA, 0xD9, 0x70, 0x61, 0xE9, 0x47, 0xB5, 0x82,\n 0xFC, 0x18, 0x3C, 0x66, 0x3A, 0x09, 0x2E, 0x1F, 0x61, 0x74, 0xCA, 0xCB, 0xF6, 0x7A, 0x52, 0x37,\n 0x1D, 0xAC, 0x8D, 0x63, 0x69, 0x84, 0x8E, 0xC7, 0x70, 0x59, 0xDD, 0x2D, 0x91, 0x1E, 0xF7, 0xB1,\n 0x56, 0xED, 0x7A, 0x06, 0x9D, 0x5B, 0x33, 0x15, 0xDD, 0x31, 0xD0, 0xE6, 0x16, 0x07, 0x9B, 0xA5,\n 0x94, 0x06, 0x7D, 0xC1, 0xE9, 0xD6, 0xC8, 0xAF, 0xB4, 0x1E, 0x2D, 0x88, 0x06, 0xA7, 0x63, 0xB8,\n 0xCF, 0xC8, 0xA2, 0x6E, 0x84, 0xB3, 0x8D, 0xE5, 0x47, 0xE6, 0x13, 0x63, 0x8E, 0xD1, 0x7F, 0xD4,\n 0x81, 0x44, 0x38, 0xBF\n };\n\n public static readonly byte[] TEST = {\n 0x07, 0x02, 0x00, 0x00, 0x00, 0xA4, 0x00, 0x00, 0x52, 0x53, 0x41, 0x32, 0x00, 0x04, 0x00, 0x00,\n 0x01, 0x00, 0x01, 0x00, 0x0F, 0xBE, 0x77, 0xB8, 0xDD, 0x54, 0x36, 0xDD, 0x67, 0xD4, 0x17, 0x66,\n 0xC4, 0x13, 0xD1, 0x3F, 0x1E, 0x16, 0x0C, 0x16, 0x35, 0xAB, 0x6D, 0x3D, 0x34, 0x51, 0xED, 0x3F,\n 0x57, 0x14, 0xB6, 0xB7, 0x08, 0xE9, 0xD9, 0x7A, 0x80, 0xB3, 0x5F, 0x9B, 0x3A, 0xFD, 0x9E, 0x37,\n 0x3A, 0x53, 0x72, 0x67, 0x92, 0x60, 0xC3, 0xEF, 0xB5, 0x8E, 0x1E, 0xCF, 0x9D, 0x9C, 0xD3, 0x90,\n 0xE5, 0xDD, 0xF4, 0xDB, 0xF3, 0xD6, 0x65, 0xB3, 0xC1, 0xBD, 0x69, 0xE1, 0x76, 0x95, 0xD9, 0x37,\n 0xB8, 0x5E, 0xCA, 0x3D, 0x98, 0xFC, 0x50, 0x5C, 0x98, 0xAE, 0xE3, 0x7C, 0x4C, 0x27, 0xC3, 0xD0,\n 0xCE, 0x78, 0x06, 0x51, 0x68, 0x23, 0xE6, 0x70, 0xF8, 0x7C, 0xAE, 0x36, 0xBE, 0x41, 0x57, 0xE2,\n 0xC3, 0x2D, 0xAF, 0x21, 0xB1, 0xB3, 0x15, 0x81, 0x19, 0x26, 0x6B, 0x10, 0xB3, 0xE9, 0xD1, 0x45,\n 0x21, 0x77, 0x9C, 0xF6, 0xE1, 0xDD, 0xB6, 0x78, 0x9D, 0x1D, 0x32, 0x61, 0xBC, 0x2B, 0xDB, 0x86,\n 0xFB, 0x07, 0x24, 0x10, 0x19, 0x4F, 0x09, 0x6D, 0x03, 0x90, 0xD4, 0x5E, 0x30, 0x85, 0xC5, 0x58,\n 0x7E, 0x5D, 0xAE, 0x9F, 0x64, 0x93, 0x04, 0x82, 0x09, 0x0E, 0x1C, 0x66, 0xA8, 0x95, 0x91, 0x51,\n 0xB2, 0xED, 0x9A, 0x75, 0x04, 0x87, 0x50, 0xAC, 0xCC, 0x20, 0x06, 0x45, 0xB9, 0x7B, 0x42, 0x53,\n 0x9A, 0xD1, 0x29, 0xFC, 0xEF, 0xB9, 0x47, 0x16, 0x75, 0x69, 0x05, 0x87, 0x2B, 0xCB, 0x54, 0x9C,\n 0x21, 0x2D, 0x50, 0x8E, 0x12, 0xDE, 0xD3, 0x6B, 0xEC, 0x92, 0xA1, 0xB1, 0xE9, 0x4B, 0xBF, 0x6B,\n 0x9A, 0x38, 0xC7, 0x13, 0xFA, 0x78, 0xA1, 0x3C, 0x1E, 0xBB, 0x38, 0x31, 0xBB, 0x0C, 0x9F, 0x70,\n 0x1A, 0x31, 0x00, 0xD7, 0x5A, 0xA5, 0x84, 0x24, 0x89, 0x80, 0xF5, 0x88, 0xC2, 0x31, 0x18, 0xDC,\n 0x53, 0x05, 0x5D, 0xFA, 0x81, 0xDC, 0xE1, 0xCE, 0xA4, 0xAA, 0xBA, 0x07, 0xDA, 0x28, 0x4F, 0x64,\n 0x0E, 0x84, 0x9B, 0x06, 0xDE, 0xC8, 0x78, 0x66, 0x2F, 0x17, 0x25, 0xA8, 0x9C, 0x99, 0xFC, 0xBC,\n 0x7D, 0x01, 0x42, 0xD7, 0x35, 0xBF, 0x19, 0xF6, 0x3F, 0x20, 0xD9, 0x98, 0x9B, 0x5D, 0xDD, 0x39,\n 0xBE, 0x81, 0x00, 0x0B, 0xDE, 0x6F, 0x14, 0xCA, 0x7E, 0xF8, 0xC0, 0x26, 0xA8, 0x1D, 0xD1, 0x16,\n 0x88, 0x64, 0x87, 0x36, 0x45, 0x37, 0x50, 0xDA, 0x6C, 0xEB, 0x85, 0xB5, 0x43, 0x29, 0x88, 0x6F,\n 0x2F, 0xFE, 0x8D, 0x12, 0x8B, 0x72, 0xB7, 0x5A, 0xCB, 0x66, 0xC2, 0x2E, 0x1D, 0x7D, 0x42, 0xA6,\n 0xF4, 0xFE, 0x26, 0x5D, 0x54, 0x9E, 0x77, 0x1D, 0x97, 0xC2, 0xF3, 0xFD, 0x60, 0xB3, 0x22, 0x88,\n 0xCA, 0x27, 0x99, 0xDF, 0xC8, 0xB1, 0xD7, 0xC6, 0x54, 0xA6, 0x50, 0xB9, 0x54, 0xF5, 0xDE, 0xFE,\n 0xE1, 0x81, 0xA2, 0xBE, 0x81, 0x9F, 0x48, 0xFF, 0x2F, 0xB8, 0xA4, 0xB3, 0x17, 0xD8, 0xC1, 0xB9,\n 0x5D, 0x21, 0x3D, 0xA2, 0xED, 0x1C, 0x96, 0x66, 0xEE, 0x1F, 0x47, 0xCF, 0x62, 0xFA, 0xD6, 0xC1,\n 0x87, 0x5B, 0xC4, 0xE5, 0xD9, 0x08, 0x38, 0x22, 0xFA, 0x21, 0xBD, 0xF2, 0x88, 0xDA, 0xE2, 0x24,\n 0x25, 0x1F, 0xF1, 0x0B, 0x2D, 0xAE, 0x04, 0xBE, 0xA6, 0x7F, 0x75, 0x8C, 0xD9, 0x97, 0xE1, 0xCA,\n 0x35, 0xB9, 0xFC, 0x6F, 0x01, 0x68, 0x11, 0xD3, 0x68, 0x32, 0xD0, 0xC1, 0x69, 0xA3, 0xCF, 0x9B,\n 0x10, 0xE4, 0x69, 0xA7, 0xCF, 0xE1, 0xFE, 0x2A, 0x07, 0x9E, 0xC1, 0x37, 0x84, 0x68, 0xE5, 0xC5,\n 0xAB, 0x25, 0xEC, 0x7D, 0x7D, 0x74, 0x6A, 0xD1, 0xD5, 0x4D, 0xD7, 0xE1, 0x7D, 0xDE, 0x30, 0x4B,\n 0xE6, 0x5D, 0xCD, 0x91, 0x59, 0xF6, 0x80, 0xFD, 0xC6, 0x3C, 0xDD, 0x94, 0x7F, 0x15, 0x9D, 0xEF,\n 0x2F, 0x00, 0x62, 0xD7, 0xDA, 0xB9, 0xB3, 0xD9, 0x8D, 0xE8, 0xD7, 0x3C, 0x96, 0x45, 0x5D, 0x1E,\n 0x50, 0xFB, 0xAA, 0x43, 0xD3, 0x47, 0x77, 0x81, 0xE9, 0x67, 0xE4, 0xFE, 0xDF, 0x42, 0x79, 0xCB,\n 0xA7, 0xAD, 0x5D, 0x48, 0xF5, 0xB7, 0x74, 0x96, 0x12, 0x23, 0x06, 0x70, 0x42, 0x68, 0x7A, 0x44,\n 0xFC, 0xA0, 0x31, 0x7F, 0x68, 0xCA, 0xA2, 0x14, 0x5D, 0xA3, 0xCF, 0x42, 0x23, 0xAB, 0x47, 0xF6,\n 0xB2, 0xFC, 0x6D, 0xF1\n };\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/KeyChangeLockDelete.cs", "namespace LibTSforge.Modifiers\n{\n using System.Collections.Generic;\n using System.Linq;\n using PhysicalStore;\n using SPP;\n using System;\n\n public static class KeyChangeLockDelete\n {\n public static void Delete(PSVersion version, bool production)\n {\n if (version == PSVersion.Vista) throw new NotSupportedException(\"This feature is not supported on Windows Vista/Server 2008.\");\n\n SPPUtils.KillSPP(version);\n Logger.WriteLine(\"Writing TrustedStore data...\");\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n List values = new List\n {\n \"msft:spp/timebased/AB\",\n \"msft:spp/timebased/CD\"\n };\n List blocks = new List();\n foreach (string value in values)\n {\n blocks.AddRange(store.FindBlocks(value).ToList());\n }\n foreach (PSBlock block in blocks)\n {\n store.DeleteBlock(block.KeyAsStr, block.ValueAsStr);\n }\n }\n Logger.WriteLine(\"Successfully removed the key change lock.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/GracePeriodReset.cs", "namespace LibTSforge.Modifiers\n{\n using System.Collections.Generic;\n using System.Linq;\n using PhysicalStore;\n using SPP;\n\n public static class GracePeriodReset\n {\n public static void Reset(PSVersion version, bool production)\n {\n SPPUtils.KillSPP(version);\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string value = \"msft:sl/timer\";\n List blocks = store.FindBlocks(value).ToList();\n\n foreach (PSBlock block in blocks)\n {\n store.DeleteBlock(block.KeyAsStr, block.ValueAsStr);\n }\n }\n\n SPPUtils.RestartSPP(version);\n Logger.WriteLine(\"Successfully reset all grace and evaluation period timers.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/TokenStore/ITokenStore.cs", "namespace LibTSforge.TokenStore\n{\n using System;\n\n public interface ITokenStore : IDisposable\n {\n void Deserialize();\n void Serialize();\n void AddEntry(TokenEntry entry);\n void AddEntries(TokenEntry[] entries);\n void DeleteEntry(string name, string ext);\n void DeleteUnpopEntry(string name, string ext);\n TokenEntry GetEntry(string name, string ext);\n TokenMeta GetMetaEntry(string name);\n void SetEntry(string name, string ext, byte[] data);\n }\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 19:06:23", "created_task_model": "DeepSeek-R1", "function_skeleton": "public static int ControlSpSys (bool start) {}", "code_description": "This code segment functions to: Execute conditional system-level operations on a hardware device by sending control commands and retrieving status information based on boolean input parameters."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\n public static int ControlSpSys(bool start)\n {\n using (SafeFileHandle file = CreateFileSafe(@\"\\\\.\\SpDevice\"))\n {\n if (file.IsInvalid)\n {\n return Marshal.GetLastWin32Error();\n }\n\n IntPtr inBuffer = Marshal.AllocHGlobal(1);\n try\n {\n Marshal.WriteByte(inBuffer, start ? (byte)1 : (byte)0);\n uint controlCode = start ? 0x8000600C : 0x80006010;\n int bytesReturned;\n if (!DeviceIoControl(file, controlCode, inBuffer, 1, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero))\n {\n return Marshal.GetLastWin32Error();\n }\n return 0;\n }\n finally\n {\n Marshal.FreeHGlobal(inBuffer);\n }\n }\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 19-07-07"}, "editdistance_info": {"edit_distance": 39.3782, "calculate_time": "2025-08-20 19:07:07", "true_code_clean": "public static int ControlSpSys(bool start)\n {\n SafeFileHandle file = CreateFileSafe(@\"\\\\.\\SpDevice\");\n IntPtr buffer = Marshal.AllocHGlobal(4);\n int bytesReturned;\n DeviceIoControl(file, start ? 0x8000a000 : 0x8000a004, IntPtr.Zero, 0, buffer, 4, out bytesReturned, IntPtr.Zero);\n int result = Marshal.ReadInt32(buffer);\n Marshal.FreeHGlobal(buffer);\n file.Close();\n return result;\n }", "predict_code_clean": "public static int ControlSpSys(bool start)\n {\n using (SafeFileHandle file = CreateFileSafe(@\"\\\\.\\SpDevice\"))\n {\n if (file.IsInvalid)\n {\n return Marshal.GetLastWin32Error();\n }\n IntPtr inBuffer = Marshal.AllocHGlobal(1);\n try\n {\n Marshal.WriteByte(inBuffer, start ? (byte)1 : (byte)0);\n uint controlCode = start ? 0x8000600C : 0x80006010;\n int bytesReturned;\n if (!DeviceIoControl(file, controlCode, inBuffer, 1, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero))\n {\n return Marshal.GetLastWin32Error();\n }\n return 0;\n }\n finally\n {\n Marshal.FreeHGlobal(inBuffer);\n }\n }\n }"}} {"repo_name": "TSforge", "file_name": "/TSforge/LibTSforge/Crypto/PhysStoreCrypto.cs", "inference_info": {"prefix_code": "namespace LibTSforge.Crypto\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using System.Linq;\n using System.Text;\n\n public static class PhysStoreCrypto\n {\n public static byte[] DecryptPhysicalStore(byte[] data, bool production, PSVersion version)\n {\n byte[] rsaKey = production ? Keys.PRODUCTION : Keys.TEST;\n BinaryReader br = new BinaryReader(new MemoryStream(data));\n br.BaseStream.Seek(0x10, SeekOrigin.Begin);\n byte[] aesKeySig = br.ReadBytes(0x80);\n byte[] encAesKey = br.ReadBytes(0x80);\n\n if (!CryptoUtils.RSAVerifySignature(rsaKey, encAesKey, aesKeySig))\n {\n throw new Exception(\"Failed to decrypt physical store.\");\n }\n\n byte[] aesKey = CryptoUtils.RSADecrypt(rsaKey, encAesKey);\n byte[] decData = CryptoUtils.AESDecrypt(br.ReadBytes((int)br.BaseStream.Length - 0x110), aesKey);\n byte[] hmacKey = decData.Take(0x10).ToArray(); // SHA-1 salt on Vista\n byte[] hmacSig = decData.Skip(0x10).Take(0x14).ToArray(); // SHA-1 hash on Vista\n byte[] psData = decData.Skip(0x28).ToArray();\n\n if (version != PSVersion.Vista)\n {\n if (!CryptoUtils.HMACVerify(hmacKey, psData, hmacSig))\n {\n throw new InvalidDataException(\"Failed to verify HMAC. Physical store is corrupt.\");\n }\n }\n else\n {\n if (!CryptoUtils.SaltSHAVerify(hmacKey, psData, hmacSig))\n {\n throw new InvalidDataException(\"Failed to verify checksum. Physical store is corrupt.\");\n }\n }\n\n return psData;\n }\n\n ", "suffix_code": "\n }\n}\n", "middle_code": "public static byte[] EncryptPhysicalStore(byte[] data, bool production, PSVersion version)\n {\n Dictionary versionTable = new Dictionary\n {\n {PSVersion.Vista, 2},\n {PSVersion.Win7, 5},\n {PSVersion.Win8, 1},\n {PSVersion.WinBlue, 2},\n {PSVersion.WinModern, 3}\n };\n byte[] rsaKey = production ? Keys.PRODUCTION : Keys.TEST;\n byte[] aesKey = Encoding.UTF8.GetBytes(\"massgrave.dev :3\");\n byte[] hmacKey = CryptoUtils.GenerateRandomKey(0x10);\n byte[] encAesKey = CryptoUtils.RSAEncrypt(rsaKey, aesKey);\n byte[] aesKeySig = CryptoUtils.RSASign(rsaKey, encAesKey);\n byte[] hmacSig = version != PSVersion.Vista ? CryptoUtils.HMACSign(hmacKey, data) : CryptoUtils.SaltSHASum(hmacKey, data);\n byte[] decData = { };\n decData = decData.Concat(hmacKey).Concat(hmacSig).Concat(BitConverter.GetBytes(0)).Concat(data).ToArray();\n byte[] encData = CryptoUtils.AESEncrypt(decData, aesKey);\n BinaryWriter bw = new BinaryWriter(new MemoryStream());\n bw.Write(versionTable[version]);\n bw.Write(Encoding.UTF8.GetBytes(\"UNTRUSTSTORE\"));\n bw.Write(aesKeySig);\n bw.Write(encAesKey);\n bw.Write(encData);\n return bw.GetBytes();\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/TSforge/LibTSforge/Crypto/CryptoUtils.cs", "namespace LibTSforge.Crypto\n{\n using System;\n using System.Linq;\n using System.Security.Cryptography;\n\n public static class CryptoUtils\n {\n public static byte[] GenerateRandomKey(int len)\n {\n byte[] rand = new byte[len];\n Random r = new Random();\n r.NextBytes(rand);\n\n return rand;\n }\n\n public static byte[] AESEncrypt(byte[] data, byte[] key)\n {\n using (Aes aes = Aes.Create())\n {\n aes.Key = key;\n aes.Mode = CipherMode.CBC;\n aes.Padding = PaddingMode.PKCS7;\n\n ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, Enumerable.Repeat((byte)0, 16).ToArray());\n byte[] encryptedData = encryptor.TransformFinalBlock(data, 0, data.Length);\n return encryptedData;\n }\n }\n\n public static byte[] AESDecrypt(byte[] data, byte[] key)\n {\n using (Aes aes = Aes.Create())\n {\n aes.Key = key;\n aes.Mode = CipherMode.CBC;\n aes.Padding = PaddingMode.PKCS7;\n\n ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, Enumerable.Repeat((byte)0, 16).ToArray());\n byte[] decryptedData = decryptor.TransformFinalBlock(data, 0, data.Length);\n return decryptedData;\n }\n }\n\n public static byte[] RSADecrypt(byte[] rsaKey, byte[] data)\n {\n\n using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())\n {\n rsa.ImportCspBlob(rsaKey);\n return rsa.Decrypt(data, false);\n }\n }\n\n public static byte[] RSAEncrypt(byte[] rsaKey, byte[] data)\n {\n using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())\n {\n rsa.ImportCspBlob(rsaKey);\n return rsa.Encrypt(data, false);\n }\n }\n\n public static byte[] RSASign(byte[] rsaKey, byte[] data)\n {\n using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())\n {\n rsa.ImportCspBlob(rsaKey);\n RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(rsa);\n formatter.SetHashAlgorithm(\"SHA1\");\n\n byte[] hash;\n using (SHA1 sha1 = SHA1.Create())\n {\n hash = sha1.ComputeHash(data);\n }\n\n return formatter.CreateSignature(hash);\n }\n }\n\n public static bool RSAVerifySignature(byte[] rsaKey, byte[] data, byte[] signature)\n {\n using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())\n {\n rsa.ImportCspBlob(rsaKey);\n RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(rsa);\n deformatter.SetHashAlgorithm(\"SHA1\");\n\n byte[] hash;\n using (SHA1 sha1 = SHA1.Create())\n {\n hash = sha1.ComputeHash(data);\n }\n\n return deformatter.VerifySignature(hash, signature);\n }\n }\n\n public static byte[] HMACSign(byte[] key, byte[] data)\n {\n HMACSHA1 hmac = new HMACSHA1(key);\n return hmac.ComputeHash(data);\n }\n\n public static bool HMACVerify(byte[] key, byte[] data, byte[] signature)\n {\n return Enumerable.SequenceEqual(signature, HMACSign(key, data));\n }\n\n public static byte[] SaltSHASum(byte[] salt, byte[] data)\n {\n SHA1 sha1 = SHA1.Create();\n byte[] sha_data = salt.Concat(data).ToArray();\n return sha1.ComputeHash(sha_data);\n }\n\n public static bool SaltSHAVerify(byte[] salt, byte[] data, byte[] checksum)\n {\n return Enumerable.SequenceEqual(checksum, SaltSHASum(salt, data));\n }\n\n public static byte[] SHA256Hash(byte[] data)\n {\n using (SHA256 sha256 = SHA256.Create())\n {\n return sha256.ComputeHash(data);\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/Activators/ZeroCID.cs", "namespace LibTSforge.Activators\n{\n using System;\n using System.IO;\n using System.Linq;\n using Crypto;\n using PhysicalStore;\n using SPP;\n\n public static class ZeroCID\n {\n private static void Deposit(Guid actId, string instId)\n {\n uint status = SLApi.DepositConfirmationID(actId, instId, Constants.ZeroCID);\n Logger.WriteLine(string.Format(\"Depositing fake CID status {0:X}\", status));\n\n if (status != 0)\n {\n throw new InvalidOperationException(\"Failed to deposit fake CID.\");\n }\n }\n\n public static void Activate(PSVersion version, bool production, Guid actId)\n {\n Guid appId;\n\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, false);\n\n if (actId == Guid.Empty)\n {\n throw new NotSupportedException(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n if (!SLApi.IsPhoneActivatable(actId))\n {\n throw new NotSupportedException(\"Phone license is unavailable for this product.\");\n }\n\n string instId = SLApi.GetInstallationID(actId);\n Guid pkeyId = SLApi.GetInstalledPkeyID(actId);\n\n if (version == PSVersion.Vista || version == PSVersion.Win7)\n {\n Deposit(actId, instId);\n }\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n byte[] hwidBlock = Constants.UniversalHWIDBlock;\n\n Logger.WriteLine(\"Activation ID: \" + actId);\n Logger.WriteLine(\"Installation ID: \" + instId);\n Logger.WriteLine(\"Product Key ID: \" + pkeyId);\n\n byte[] iidHash;\n\n if (version == PSVersion.Vista)\n {\n iidHash = CryptoUtils.SHA256Hash(Utils.EncodeString(instId)).Take(0x10).ToArray();\n }\n else if (version == PSVersion.Win7)\n {\n iidHash = CryptoUtils.SHA256Hash(Utils.EncodeString(instId));\n }\n else\n {\n iidHash = CryptoUtils.SHA256Hash(Utils.EncodeString(instId + '\\0' + Constants.ZeroCID));\n }\n\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n PSBlock keyBlock = store.GetBlock(key, pkeyId.ToString());\n\n if (keyBlock == null)\n {\n throw new InvalidDataException(\"Failed to get product key data for activation ID \" + actId + \".\");\n }\n\n VariableBag pkb = new VariableBag(keyBlock.Data, version);\n\n byte[] pkeyData;\n\n if (version == PSVersion.Vista)\n {\n pkeyData = pkb.GetBlock(\"PKeyBasicInfo\").Value;\n string uniqueId = Utils.DecodeString(pkeyData.Skip(0x120).Take(0x80).ToArray());\n string extPid = Utils.DecodeString(pkeyData.Skip(0x1A0).Take(0x80).ToArray());\n\n uint group;\n uint.TryParse(extPid.Split('-')[1], out group);\n\n if (group == 0)\n {\n throw new FormatException(\"Extended PID has invalid format.\");\n }\n\n ulong shortauth;\n\n try\n {\n shortauth = BitConverter.ToUInt64(Convert.FromBase64String(uniqueId.Split('&')[1]), 0);\n } \n catch\n {\n throw new FormatException(\"Key Unique ID has invalid format.\");\n }\n\n shortauth |= (ulong)group << 41;\n pkeyData = BitConverter.GetBytes(shortauth);\n }\n else if (version == PSVersion.Win7)\n {\n pkeyData = pkb.GetBlock(\"SppPkeyShortAuthenticator\").Value;\n }\n else\n {\n pkeyData = pkb.GetBlock(\"SppPkeyPhoneActivationData\").Value;\n }\n\n pkb.DeleteBlock(\"SppPkeyVirtual\");\n store.SetBlock(key, pkeyId.ToString(), pkb.Serialize());\n\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(iidHash.Length);\n writer.Write(iidHash);\n writer.Write(hwidBlock.Length);\n writer.Write(hwidBlock);\n byte[] tsHwidData = writer.GetBytes();\n\n writer = new BinaryWriter(new MemoryStream());\n writer.Write(iidHash.Length);\n writer.Write(iidHash);\n writer.Write(pkeyData.Length);\n writer.Write(pkeyData);\n byte[] tsPkeyInfoData = writer.GetBytes();\n\n string phoneVersion = version == PSVersion.Vista ? \"6.0\" : \"7.0\";\n Guid indexSlid = version == PSVersion.Vista ? actId : pkeyId;\n string hwidBlockName = string.Format(\"msft:Windows/{0}/Phone/Cached/HwidBlock/{1}\", phoneVersion, indexSlid);\n string pkeyInfoName = string.Format(\"msft:Windows/{0}/Phone/Cached/PKeyInfo/{1}\", phoneVersion, indexSlid);\n\n store.DeleteBlock(key, hwidBlockName);\n store.DeleteBlock(key, pkeyInfoName);\n\n store.AddBlocks(new[] {\n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = 0,\n KeyAsStr = key,\n ValueAsStr = hwidBlockName,\n Data = tsHwidData\n }, \n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = 0,\n KeyAsStr = key,\n ValueAsStr = pkeyInfoName,\n Data = tsPkeyInfoData\n }\n });\n }\n\n if (version != PSVersion.Vista && version != PSVersion.Win7)\n {\n Deposit(actId, instId);\n }\n\n SPPUtils.RestartSPP(version);\n SLApi.FireStateChangedEvent(appId);\n Logger.WriteLine(\"Activated using ZeroCID successfully.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/SPP/SPPUtils.cs", "namespace LibTSforge.SPP\n{\n using Microsoft.Win32;\n using System;\n using System.IO;\n using System.Linq;\n using System.ServiceProcess;\n using Crypto;\n using PhysicalStore;\n using TokenStore;\n\n public static class SPPUtils\n {\n public static void KillSPP(PSVersion version)\n {\n ServiceController sc;\n\n string svcName = version == PSVersion.Vista ? \"slsvc\" : \"sppsvc\";\n\n try\n {\n sc = new ServiceController(svcName);\n\n if (sc.Status == ServiceControllerStatus.Stopped)\n return;\n }\n catch (InvalidOperationException ex)\n {\n throw new InvalidOperationException(string.Format(\"Unable to access {0}: \", svcName) + ex.Message);\n }\n\n Logger.WriteLine(string.Format(\"Stopping {0}...\", svcName));\n\n bool stopped = false;\n\n for (int i = 0; stopped == false && i < 1080; i++)\n {\n try\n {\n if (sc.Status != ServiceControllerStatus.StopPending)\n sc.Stop();\n\n sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromMilliseconds(500));\n }\n catch (System.ServiceProcess.TimeoutException)\n {\n continue;\n }\n catch (InvalidOperationException ex)\n {\n Logger.WriteLine(\"Warning: Stopping sppsvc failed, retrying. Details: \" + ex.Message);\n System.Threading.Thread.Sleep(500);\n continue;\n }\n\n stopped = true;\n }\n\n if (!stopped)\n throw new System.TimeoutException(string.Format(\"Failed to stop {0}\", svcName));\n\n Logger.WriteLine(string.Format(\"{0} stopped successfully.\", svcName));\n\n if (version == PSVersion.Vista && SPSys.IsSpSysRunning())\n {\n Logger.WriteLine(\"Unloading spsys...\");\n\n int status = SPSys.ControlSpSys(false);\n\n if (status < 0)\n {\n throw new IOException(\"Failed to unload spsys\");\n }\n\n Logger.WriteLine(\"spsys unloaded successfully.\");\n }\n }\n\n public static void RestartSPP(PSVersion version)\n {\n if (version == PSVersion.Vista)\n {\n ServiceController sc;\n\n try\n {\n sc = new ServiceController(\"slsvc\");\n\n if (sc.Status == ServiceControllerStatus.Running)\n return;\n }\n catch (InvalidOperationException ex)\n {\n throw new InvalidOperationException(\"Unable to access slsvc: \" + ex.Message);\n }\n\n Logger.WriteLine(\"Starting slsvc...\");\n\n bool started = false;\n\n for (int i = 0; started == false && i < 360; i++)\n {\n try\n {\n if (sc.Status != ServiceControllerStatus.StartPending)\n sc.Start();\n\n sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMilliseconds(500));\n }\n catch (System.ServiceProcess.TimeoutException)\n {\n continue;\n }\n catch (InvalidOperationException ex)\n {\n Logger.WriteLine(\"Warning: Starting slsvc failed, retrying. Details: \" + ex.Message);\n System.Threading.Thread.Sleep(500);\n continue;\n }\n\n started = true;\n }\n\n if (!started)\n throw new System.TimeoutException(\"Failed to start slsvc\");\n\n Logger.WriteLine(\"slsvc started successfully.\");\n }\n\n SLApi.RefreshLicenseStatus();\n }\n\n public static bool DetectCurrentKey()\n {\n SLApi.RefreshLicenseStatus();\n\n using (RegistryKey wpaKey = Registry.LocalMachine.OpenSubKey(@\"SYSTEM\\WPA\"))\n {\n foreach (string subKey in wpaKey.GetSubKeyNames())\n {\n if (subKey.StartsWith(\"8DEC0AF1\"))\n {\n return subKey.Contains(\"P\");\n }\n }\n }\n\n throw new FileNotFoundException(\"Failed to autodetect key type, specify physical store key with /prod or /test arguments.\");\n }\n\n public static string GetPSPath(PSVersion version)\n {\n switch (version)\n {\n case PSVersion.Vista:\n case PSVersion.Win7:\n return Directory.GetFiles(\n Environment.GetFolderPath(Environment.SpecialFolder.System),\n \"7B296FB0-376B-497e-B012-9C450E1B7327-*.C7483456-A289-439d-8115-601632D005A0\")\n .FirstOrDefault() ?? \"\";\n default:\n string psDir = Environment.ExpandEnvironmentVariables(\n (string)Registry.GetValue(\n @\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform\",\n \"TokenStore\",\n \"\"\n )\n );\n string psPath = Path.Combine(psDir, \"data.dat\");\n\n if (string.IsNullOrEmpty(psDir) || !File.Exists(psPath))\n {\n string[] psDirs =\n {\n @\"spp\\store\",\n @\"spp\\store\\2.0\",\n @\"spp\\store_test\",\n @\"spp\\store_test\\2.0\"\n };\n\n foreach (string dir in psDirs)\n {\n psPath = Path.Combine(\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.System),\n dir\n ),\n \"data.dat\"\n );\n\n if (File.Exists(psPath)) return psPath;\n }\n } \n else\n {\n return psPath;\n }\n\n throw new FileNotFoundException(\"Failed to locate physical store.\");\n }\n }\n\n public static string GetTokensPath(PSVersion version)\n {\n switch (version)\n {\n case PSVersion.Vista:\n return Path.Combine(\n Environment.ExpandEnvironmentVariables(\"%WINDIR%\"),\n @\"ServiceProfiles\\NetworkService\\AppData\\Roaming\\Microsoft\\SoftwareLicensing\\tokens.dat\"\n );\n case PSVersion.Win7:\n return Path.Combine(\n Environment.ExpandEnvironmentVariables(\"%WINDIR%\"),\n @\"ServiceProfiles\\NetworkService\\AppData\\Roaming\\Microsoft\\SoftwareProtectionPlatform\\tokens.dat\"\n );\n default:\n string tokDir = Environment.ExpandEnvironmentVariables(\n (string)Registry.GetValue(\n @\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform\",\n \"TokenStore\",\n \"\"\n )\n );\n string tokPath = Path.Combine(tokDir, \"tokens.dat\");\n\n if (string.IsNullOrEmpty(tokDir) || !File.Exists(tokPath))\n {\n string[] tokDirs =\n {\n @\"spp\\store\",\n @\"spp\\store\\2.0\",\n @\"spp\\store_test\",\n @\"spp\\store_test\\2.0\"\n };\n\n foreach (string dir in tokDirs)\n {\n tokPath = Path.Combine(\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.System),\n dir\n ),\n \"tokens.dat\"\n );\n\n if (File.Exists(tokPath)) return tokPath;\n }\n }\n else\n {\n return tokPath;\n }\n\n throw new FileNotFoundException(\"Failed to locate token store.\");\n }\n }\n\n public static IPhysicalStore GetStore(PSVersion version, bool production)\n {\n string psPath = GetPSPath(version);\n\n switch (version)\n {\n case PSVersion.Vista:\n return new PhysicalStoreVista(psPath, production);\n case PSVersion.Win7:\n return new PhysicalStoreWin7(psPath, production);\n default:\n return new PhysicalStoreModern(psPath, production, version);\n }\n }\n\n public static ITokenStore GetTokenStore(PSVersion version)\n {\n string tokPath = GetTokensPath(version);\n\n return new TokenStoreModern(tokPath);\n }\n\n public static void DumpStore(PSVersion version, bool production, string filePath, string encrFilePath)\n {\n bool manageSpp = false;\n\n if (encrFilePath == null)\n {\n encrFilePath = GetPSPath(version);\n manageSpp = true;\n KillSPP(version);\n }\n\n if (string.IsNullOrEmpty(encrFilePath) || !File.Exists(encrFilePath))\n {\n throw new FileNotFoundException(\"Store does not exist at expected path '\" + encrFilePath + \"'.\");\n }\n\n try\n {\n using (FileStream fs = File.Open(encrFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))\n {\n byte[] encrData = fs.ReadAllBytes();\n File.WriteAllBytes(filePath, PhysStoreCrypto.DecryptPhysicalStore(encrData, production, version));\n }\n Logger.WriteLine(\"Store dumped successfully to '\" + filePath + \"'.\");\n }\n finally\n {\n if (manageSpp)\n {\n RestartSPP(version);\n }\n }\n }\n\n public static void LoadStore(PSVersion version, bool production, string filePath)\n {\n if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))\n {\n throw new FileNotFoundException(\"Store file '\" + filePath + \"' does not exist.\");\n }\n\n KillSPP(version);\n\n using (IPhysicalStore store = GetStore(version, production))\n {\n store.WriteRaw(File.ReadAllBytes(filePath));\n }\n\n RestartSPP(version);\n\n Logger.WriteLine(\"Loaded store file successfully.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/SPP/ProductKey.cs", "namespace LibTSforge.SPP\n{\n using System;\n using System.IO;\n using System.Linq;\n using Crypto;\n using PhysicalStore;\n\n public class ProductKey\n {\n private static readonly string ALPHABET = \"BCDFGHJKMPQRTVWXY2346789\";\n\n private readonly ulong klow;\n private readonly ulong khigh;\n\n public int Group;\n public int Serial;\n public ulong Security;\n public bool Upgrade;\n public PKeyAlgorithm Algorithm;\n public readonly string EulaType;\n public readonly string PartNumber;\n public readonly string Edition;\n public readonly string Channel;\n public readonly Guid ActivationId;\n\n private string mpc;\n private string pid2;\n\n public byte[] KeyBytes\n {\n get { return BitConverter.GetBytes(klow).Concat(BitConverter.GetBytes(khigh)).ToArray(); }\n }\n\n public ProductKey()\n {\n\n }\n\n public ProductKey(int serial, ulong security, bool upgrade, PKeyAlgorithm algorithm, ProductConfig config, KeyRange range)\n {\n Group = config.GroupId;\n Serial = serial;\n Security = security;\n Upgrade = upgrade;\n Algorithm = algorithm;\n EulaType = range.EulaType;\n PartNumber = range.PartNumber.Split(':', ';')[0];\n Edition = config.Edition;\n Channel = config.Channel;\n ActivationId = config.ActivationId;\n\n klow = ((security & 0x3fff) << 50 | ((ulong)serial & 0x3fffffff) << 20 | ((ulong)Group & 0xfffff));\n khigh = ((upgrade ? (ulong)1 : 0) << 49 | ((security >> 14) & 0x7fffffffff));\n\n uint checksum = Utils.CRC32(KeyBytes) & 0x3ff;\n\n khigh |= ((ulong)checksum << 39);\n }\n\n public string GetAlgoUri()\n {\n return \"msft:rm/algorithm/pkey/\" + (Algorithm == PKeyAlgorithm.PKEY2005 ? \"2005\" : (Algorithm == PKeyAlgorithm.PKEY2009 ? \"2009\" : \"Unknown\"));\n }\n\n public Guid GetPkeyId()\n {\n VariableBag pkb = new VariableBag(PSVersion.WinModern);\n pkb.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingProductKey\",\n ValueAsStr = ToString()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingMiscData\",\n Value = new byte[] { }\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingAlgorithm\",\n ValueAsStr = GetAlgoUri()\n }\n });\n\n return new Guid(CryptoUtils.SHA256Hash(pkb.Serialize()).Take(16).ToArray());\n }\n\n public string GetMPC()\n {\n if (mpc != null)\n {\n return mpc;\n }\n\n int build = Environment.OSVersion.Version.Build;\n\n mpc = build >= 10240 ? \"03612\" :\n build >= 9600 ? \"06401\" :\n build >= 9200 ? \"05426\" :\n \"55041\";\n\n // setup.cfg doesn't exist in Windows 8+\n string setupcfg = string.Format(@\"{0}\\oobe\\{1}\", Environment.SystemDirectory, \"setup.cfg\");\n\n if (!File.Exists(setupcfg) || Edition.Contains(\";\"))\n {\n return mpc;\n }\n\n string mpcKey = string.Format(\"{0}.{1}=\", Utils.GetArchitecture(), Edition);\n string localMPC = File.ReadAllLines(setupcfg).FirstOrDefault(line => line.Contains(mpcKey));\n if (localMPC != null)\n {\n mpc = localMPC.Split('=')[1].Trim();\n }\n\n return mpc;\n }\n\n public string GetPid2()\n {\n if (pid2 != null)\n {\n return pid2;\n }\n\n pid2 = \"\";\n\n if (Algorithm == PKeyAlgorithm.PKEY2005)\n {\n string mpc = GetMPC();\n string serialHigh;\n int serialLow;\n int lastPart;\n\n if (EulaType == \"OEM\")\n {\n serialHigh = \"OEM\";\n serialLow = ((Group / 2) % 100) * 10000 + (Serial / 100000);\n lastPart = Serial % 100000;\n }\n else\n {\n serialHigh = (Serial / 1000000).ToString(\"D3\");\n serialLow = Serial % 1000000;\n lastPart = ((Group / 2) % 100) * 1000 + new Random().Next(1000);\n }\n\n int checksum = 0;\n\n foreach (char c in serialLow.ToString())\n {\n checksum += int.Parse(c.ToString());\n }\n checksum = 7 - (checksum % 7);\n\n pid2 = string.Format(\"{0}-{1}-{2:D6}{3}-{4:D5}\", mpc, serialHigh, serialLow, checksum, lastPart);\n }\n\n return pid2;\n }\n\n public byte[] GetPid3()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(0xA4);\n writer.Write(0x3);\n writer.WriteFixedString(GetPid2(), 24);\n writer.Write(Group);\n writer.WriteFixedString(PartNumber, 16);\n writer.WritePadding(0x6C);\n byte[] data = writer.GetBytes();\n byte[] crc = BitConverter.GetBytes(~Utils.CRC32(data.Reverse().ToArray())).Reverse().ToArray();\n writer.Write(crc);\n\n return writer.GetBytes();\n }\n\n public byte[] GetPid4()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(0x4F8);\n writer.Write(0x4);\n writer.WriteFixedString16(GetExtendedPid(), 0x80);\n writer.WriteFixedString16(ActivationId.ToString(), 0x80);\n writer.WritePadding(0x10);\n writer.WriteFixedString16(Edition, 0x208);\n writer.Write(Upgrade ? (ulong)1 : 0);\n writer.WritePadding(0x50);\n writer.WriteFixedString16(PartNumber, 0x80);\n writer.WriteFixedString16(Channel, 0x80);\n writer.WriteFixedString16(EulaType, 0x80);\n\n return writer.GetBytes();\n }\n\n public string GetExtendedPid()\n {\n string mpc = GetMPC();\n int serialHigh = Serial / 1000000;\n int serialLow = Serial % 1000000;\n int licenseType;\n uint lcid = Utils.GetSystemDefaultLCID();\n int build = Environment.OSVersion.Version.Build;\n int dayOfYear = DateTime.Now.DayOfYear;\n int year = DateTime.Now.Year;\n\n switch (EulaType)\n {\n case \"OEM\":\n licenseType = 2;\n break;\n\n case \"Volume\":\n licenseType = 3;\n break;\n\n default:\n licenseType = 0;\n break;\n }\n\n return string.Format(\n \"{0}-{1:D5}-{2:D3}-{3:D6}-{4:D2}-{5:D4}-{6:D4}.0000-{7:D3}{8:D4}\",\n mpc,\n Group,\n serialHigh,\n serialLow,\n licenseType,\n lcid,\n build,\n dayOfYear,\n year\n );\n }\n\n public byte[] GetPhoneData(PSVersion version)\n {\n if (version == PSVersion.Win7)\n {\n ulong shortauth = ((ulong)Group << 41) | (Security << 31) | ((ulong)Serial << 1) | (Upgrade ? (ulong)1 : 0);\n return BitConverter.GetBytes(shortauth);\n }\n\n int serialHigh = Serial / 1000000;\n int serialLow = Serial % 1000000;\n\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n string algoId = Algorithm == PKeyAlgorithm.PKEY2005 ? \"B8731595-A2F6-430B-A799-FBFFB81A8D73\" : \"660672EF-7809-4CFD-8D54-41B7FB738988\";\n\n writer.Write(new Guid(algoId).ToByteArray());\n writer.Write(Group);\n writer.Write(serialHigh);\n writer.Write(serialLow);\n writer.Write(Upgrade ? 1 : 0);\n writer.Write(Security);\n\n return writer.GetBytes();\n }\n\n public override string ToString()\n {\n string keyStr = \"\";\n Random rnd = new Random(Group * 1000000000 + Serial);\n\n if (Algorithm == PKeyAlgorithm.PKEY2005)\n {\n keyStr = \"H4X3DH4X3DH4X3DH4X3D\";\n\n for (int i = 0; i < 5; i++)\n {\n keyStr += ALPHABET[rnd.Next(24)];\n }\n }\n else if (Algorithm == PKeyAlgorithm.PKEY2009)\n {\n int last = 0;\n byte[] bKey = KeyBytes;\n\n for (int i = 24; i >= 0; i--)\n {\n int current = 0;\n\n for (int j = 14; j >= 0; j--)\n {\n current *= 0x100;\n current += bKey[j];\n bKey[j] = (byte)(current / 24);\n current %= 24;\n last = current;\n }\n\n keyStr = ALPHABET[current] + keyStr;\n }\n\n keyStr = keyStr.Substring(1, last) + \"N\" + keyStr.Substring(last + 1, keyStr.Length - last - 1);\n }\n\n for (int i = 5; i < keyStr.Length; i += 6)\n {\n keyStr = keyStr.Insert(i, \"-\");\n }\n\n return keyStr;\n }\n }\n}\n"], ["/TSforge/LibTSforge/TokenStore/TokenStoreModern.cs", "namespace LibTSforge.TokenStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using System.Linq;\n using Crypto;\n\n public class TokenStoreModern : ITokenStore\n {\n private static readonly uint VERSION = 3;\n private static readonly int ENTRY_SIZE = 0x9E;\n private static readonly int BLOCK_SIZE = 0x4020;\n private static readonly int ENTRIES_PER_BLOCK = BLOCK_SIZE / ENTRY_SIZE;\n private static readonly int BLOCK_PAD_SIZE = 0x66;\n\n private static readonly byte[] CONTS_HEADER = Enumerable.Repeat((byte)0x55, 0x20).ToArray();\n private static readonly byte[] CONTS_FOOTER = Enumerable.Repeat((byte)0xAA, 0x20).ToArray();\n\n private List Entries = new List();\n private readonly FileStream TokensFile;\n\n public void Deserialize()\n {\n if (TokensFile.Length < BLOCK_SIZE) return;\n\n TokensFile.Seek(0x24, SeekOrigin.Begin);\n uint nextBlock;\n\n BinaryReader reader = new BinaryReader(TokensFile);\n do\n {\n reader.ReadUInt32();\n nextBlock = reader.ReadUInt32();\n\n for (int i = 0; i < ENTRIES_PER_BLOCK; i++)\n {\n uint curOffset = reader.ReadUInt32();\n bool populated = reader.ReadUInt32() == 1;\n uint contentOffset = reader.ReadUInt32();\n uint contentLength = reader.ReadUInt32();\n uint allocLength = reader.ReadUInt32();\n byte[] contentData = { };\n\n if (populated)\n {\n reader.BaseStream.Seek(contentOffset + 0x20, SeekOrigin.Begin);\n uint dataLength = reader.ReadUInt32();\n\n if (dataLength != contentLength)\n {\n throw new FormatException(\"Data length in tokens content is inconsistent with entry.\");\n }\n\n reader.ReadBytes(0x20);\n contentData = reader.ReadBytes((int)contentLength);\n }\n\n reader.BaseStream.Seek(curOffset + 0x14, SeekOrigin.Begin);\n\n Entries.Add(new TokenEntry\n {\n Name = reader.ReadNullTerminatedString(0x82),\n Extension = reader.ReadNullTerminatedString(0x8),\n Data = contentData,\n Populated = populated\n });\n }\n\n reader.BaseStream.Seek(nextBlock, SeekOrigin.Begin);\n } while (nextBlock != 0);\n }\n\n public void Serialize()\n {\n MemoryStream tokens = new MemoryStream();\n\n using (BinaryWriter writer = new BinaryWriter(tokens))\n {\n writer.Write(VERSION);\n writer.Write(CONTS_HEADER);\n\n int curBlockOffset = (int)writer.BaseStream.Position;\n int curEntryOffset = curBlockOffset + 0x8;\n int curContsOffset = curBlockOffset + BLOCK_SIZE;\n\n for (int eIndex = 0; eIndex < ((Entries.Count / ENTRIES_PER_BLOCK) + 1) * ENTRIES_PER_BLOCK; eIndex++)\n {\n TokenEntry entry;\n\n if (eIndex < Entries.Count)\n {\n entry = Entries[eIndex];\n }\n else\n {\n entry = new TokenEntry\n {\n Name = \"\",\n Extension = \"\",\n Populated = false,\n Data = new byte[] { }\n };\n }\n\n writer.BaseStream.Seek(curBlockOffset, SeekOrigin.Begin);\n writer.Write(curBlockOffset);\n writer.Write(0);\n\n writer.BaseStream.Seek(curEntryOffset, SeekOrigin.Begin);\n writer.Write(curEntryOffset);\n writer.Write(entry.Populated ? 1 : 0);\n writer.Write(entry.Populated ? curContsOffset : 0);\n writer.Write(entry.Populated ? entry.Data.Length : -1);\n writer.Write(entry.Populated ? entry.Data.Length : -1);\n writer.WriteFixedString16(entry.Name, 0x82);\n writer.WriteFixedString16(entry.Extension, 0x8);\n curEntryOffset = (int)writer.BaseStream.Position;\n\n if (entry.Populated)\n {\n writer.BaseStream.Seek(curContsOffset, SeekOrigin.Begin);\n writer.Write(CONTS_HEADER);\n writer.Write(entry.Data.Length);\n writer.Write(CryptoUtils.SHA256Hash(entry.Data));\n writer.Write(entry.Data);\n writer.Write(CONTS_FOOTER);\n curContsOffset = (int)writer.BaseStream.Position;\n }\n\n if ((eIndex + 1) % ENTRIES_PER_BLOCK == 0 && eIndex != 0)\n {\n if (eIndex < Entries.Count)\n {\n writer.BaseStream.Seek(curBlockOffset + 0x4, SeekOrigin.Begin);\n writer.Write(curContsOffset);\n }\n\n writer.BaseStream.Seek(curEntryOffset, SeekOrigin.Begin);\n writer.WritePadding(BLOCK_PAD_SIZE);\n\n writer.BaseStream.Seek(curBlockOffset, SeekOrigin.Begin);\n byte[] blockData = new byte[BLOCK_SIZE - 0x20];\n\n tokens.Read(blockData, 0, BLOCK_SIZE - 0x20);\n byte[] blockHash = CryptoUtils.SHA256Hash(blockData);\n\n writer.BaseStream.Seek(curBlockOffset + BLOCK_SIZE - 0x20, SeekOrigin.Begin);\n writer.Write(blockHash);\n\n curBlockOffset = curContsOffset;\n curEntryOffset = curBlockOffset + 0x8;\n curContsOffset = curBlockOffset + BLOCK_SIZE;\n }\n }\n\n tokens.SetLength(curBlockOffset);\n }\n\n byte[] tokensData = tokens.ToArray();\n byte[] tokensHash = CryptoUtils.SHA256Hash(tokensData.Take(0x4).Concat(tokensData.Skip(0x24)).ToArray());\n\n tokens = new MemoryStream(tokensData);\n\n BinaryWriter tokWriter = new BinaryWriter(TokensFile);\n using (BinaryReader reader = new BinaryReader(tokens))\n {\n TokensFile.Seek(0, SeekOrigin.Begin);\n TokensFile.SetLength(tokens.Length);\n tokWriter.Write(reader.ReadBytes(0x4));\n reader.ReadBytes(0x20);\n tokWriter.Write(tokensHash);\n tokWriter.Write(reader.ReadBytes((int)reader.BaseStream.Length - 0x4));\n }\n }\n\n public void AddEntry(TokenEntry entry)\n {\n Entries.Add(entry);\n }\n\n public void AddEntries(TokenEntry[] entries)\n {\n Entries.AddRange(entries);\n }\n\n public void DeleteEntry(string name, string ext)\n {\n foreach (TokenEntry entry in Entries)\n {\n if (entry.Name == name && entry.Extension == ext)\n {\n Entries.Remove(entry);\n return;\n }\n }\n }\n\n public void DeleteUnpopEntry(string name, string ext)\n {\n List delEntries = new List();\n foreach (TokenEntry entry in Entries)\n {\n if (entry.Name == name && entry.Extension == ext && !entry.Populated)\n {\n delEntries.Add(entry);\n }\n }\n\n Entries = Entries.Except(delEntries).ToList();\n }\n\n public TokenEntry GetEntry(string name, string ext)\n {\n foreach (TokenEntry entry in Entries)\n {\n if (entry.Name == name && entry.Extension == ext)\n {\n if (!entry.Populated) continue;\n return entry;\n }\n }\n\n return null;\n }\n\n public TokenMeta GetMetaEntry(string name)\n {\n DeleteUnpopEntry(name, \"xml\");\n TokenEntry entry = GetEntry(name, \"xml\");\n TokenMeta meta;\n\n if (entry == null)\n {\n meta = new TokenMeta\n {\n Name = name\n };\n }\n else\n {\n meta = new TokenMeta(entry.Data);\n }\n\n return meta;\n }\n\n public void SetEntry(string name, string ext, byte[] data)\n {\n for (int i = 0; i < Entries.Count; i++)\n {\n TokenEntry entry = Entries[i];\n\n if (entry.Name == name && entry.Extension == ext && entry.Populated)\n {\n entry.Data = data;\n Entries[i] = entry;\n return;\n }\n }\n\n Entries.Add(new TokenEntry\n {\n Populated = true,\n Name = name,\n Extension = ext,\n Data = data\n });\n }\n\n public TokenStoreModern(string tokensPath)\n {\n TokensFile = File.Open(tokensPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n Deserialize();\n }\n\n public void Dispose()\n {\n Serialize();\n TokensFile.Close();\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/KMSHostCharge.cs", "namespace LibTSforge.Modifiers\n{\n using System;\n using System.IO;\n using PhysicalStore;\n using SPP;\n\n public static class KMSHostCharge\n {\n public static void Charge(PSVersion version, bool production, Guid actId)\n {\n if (actId == Guid.Empty)\n {\n actId = SLApi.GetDefaultActivationID(SLApi.WINDOWS_APP_ID, true);\n\n if (actId == Guid.Empty)\n {\n throw new NotSupportedException(\"No applicable activation IDs found.\");\n }\n }\n\n if (SLApi.GetPKeyChannel(SLApi.GetInstalledPkeyID(actId)) != \"Volume:CSVLK\")\n {\n throw new NotSupportedException(\"Non-Volume:CSVLK product key installed.\");\n }\n\n Guid appId = SLApi.GetAppId(actId);\n int totalClients = 50;\n int currClients = 25;\n byte[] hwidBlock = Constants.UniversalHWIDBlock;\n string key = string.Format(\"SPPSVC\\\\{0}\", appId);\n long ldapTimestamp = DateTime.Now.ToFileTime();\n\n byte[] cmidGuids = { };\n byte[] reqCounts = { };\n byte[] kmsChargeData = { };\n\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n\n if (version == PSVersion.Vista)\n {\n writer.Write(new byte[44]);\n writer.Seek(0, SeekOrigin.Begin);\n\n writer.Write(totalClients);\n writer.Write(43200);\n writer.Write(32);\n\n writer.Seek(20, SeekOrigin.Begin);\n writer.Write((byte)currClients);\n\n writer.Seek(32, SeekOrigin.Begin);\n writer.Write((byte)currClients);\n\n writer.Seek(0, SeekOrigin.End);\n\n for (int i = 0; i < currClients; i++)\n {\n writer.Write(Guid.NewGuid().ToByteArray());\n writer.Write(ldapTimestamp - (10 * (i + 1)));\n }\n\n kmsChargeData = writer.GetBytes();\n } \n else\n {\n for (int i = 0; i < currClients; i++)\n {\n writer.Write(ldapTimestamp - (10 * (i + 1)));\n writer.Write(Guid.NewGuid().ToByteArray());\n }\n\n cmidGuids = writer.GetBytes();\n\n writer = new BinaryWriter(new MemoryStream());\n\n writer.Write(new byte[40]);\n\n writer.Seek(4, SeekOrigin.Begin);\n writer.Write((byte)currClients);\n\n writer.Seek(24, SeekOrigin.Begin);\n writer.Write((byte)currClients);\n\n reqCounts = writer.GetBytes();\n }\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n if (version != PSVersion.Vista)\n {\n VariableBag kmsCountData = new VariableBag(version);\n kmsCountData.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppBindingLicenseData\",\n Value = hwidBlock\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.UINT,\n Key = new byte[] { },\n ValueAsInt = (uint)totalClients\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.UINT,\n Key = new byte[] { },\n ValueAsInt = 1051200000\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.UINT,\n Key = new byte[] { },\n ValueAsInt = (uint)currClients\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n Key = new byte[] { },\n Value = cmidGuids\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n Key = new byte[] { },\n Value = reqCounts\n }\n });\n\n kmsChargeData = kmsCountData.Serialize();\n }\n\n string countVal = version == PSVersion.Vista ? \"C8F6FFF1-79CE-404C-B150-F97991273DF1\" : string.Format(\"msft:spp/kms/host/2.0/store/counters/{0}\", appId);\n\n store.DeleteBlock(key, countVal);\n store.AddBlock(new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = (version == PSVersion.WinModern) ? (uint)0x400 : 0,\n KeyAsStr = key,\n ValueAsStr = countVal,\n Data = kmsChargeData\n });\n\n Logger.WriteLine(string.Format(\"Set charge count to {0} successfully.\", currClients));\n }\n\n SPPUtils.RestartSPP(version);\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/PhysicalStoreVista.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using Crypto;\n\n public class VistaBlock\n {\n public BlockType Type;\n public uint Flags;\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n public byte[] Data;\n public string DataAsStr\n {\n get\n {\n return Utils.DecodeString(Data);\n }\n set\n {\n Data = Utils.EncodeString(value);\n }\n }\n public uint DataAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Data, 0);\n }\n set\n {\n Data = BitConverter.GetBytes(value);\n }\n }\n\n internal void Encode(BinaryWriter writer)\n {\n writer.Write((uint)Type);\n writer.Write(Flags);\n writer.Write(Value.Length);\n writer.Write(Data.Length);\n writer.Write(Value);\n writer.Write(Data);\n }\n\n internal static VistaBlock Decode(BinaryReader reader)\n {\n uint type = reader.ReadUInt32();\n uint flags = reader.ReadUInt32();\n\n int valueLen = reader.ReadInt32();\n int dataLen = reader.ReadInt32();\n\n byte[] value = reader.ReadBytes(valueLen);\n byte[] data = reader.ReadBytes(dataLen);\n return new VistaBlock\n {\n Type = (BlockType)type,\n Flags = flags,\n Value = value,\n Data = data,\n };\n }\n }\n\n public sealed class PhysicalStoreVista : IPhysicalStore\n {\n private byte[] PreHeaderBytes = { };\n private readonly List Blocks = new List();\n private readonly FileStream TSPrimary;\n private readonly FileStream TSSecondary;\n private readonly bool Production;\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(PreHeaderBytes);\n\n foreach (VistaBlock block in Blocks)\n {\n block.Encode(writer);\n writer.Align(4);\n }\n\n return writer.GetBytes();\n }\n\n public void Deserialize(byte[] data)\n {\n int len = data.Length;\n\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n PreHeaderBytes = reader.ReadBytes(8);\n\n while (reader.BaseStream.Position < len - 0x14)\n {\n Blocks.Add(VistaBlock.Decode(reader));\n reader.Align(4);\n }\n }\n\n public void AddBlock(PSBlock block)\n {\n Blocks.Add(new VistaBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Value = block.Value,\n Data = block.Data\n });\n }\n\n public void AddBlocks(IEnumerable blocks)\n {\n foreach (PSBlock block in blocks)\n {\n AddBlock(block);\n }\n }\n\n public PSBlock GetBlock(string key, string value)\n {\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsStr == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = new byte[0],\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public PSBlock GetBlock(string key, uint value)\n {\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsInt == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = new byte[0],\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public void SetBlock(string key, string value, byte[] data)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n VistaBlock block = Blocks[i];\n\n if (block.ValueAsStr == value)\n {\n block.Data = data;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void SetBlock(string key, uint value, byte[] data)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n VistaBlock block = Blocks[i];\n\n if (block.ValueAsInt == value)\n {\n block.Data = data;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void SetBlock(string key, string value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, string value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void SetBlock(string key, uint value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, uint value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void DeleteBlock(string key, string value)\n {\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsStr == value)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public void DeleteBlock(string key, uint value)\n {\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsInt == value)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public PhysicalStoreVista(string primaryPath, bool production)\n {\n TSPrimary = File.Open(primaryPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n TSSecondary = File.Open(primaryPath.Replace(\"-0.\", \"-1.\"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n Production = production;\n\n Deserialize(PhysStoreCrypto.DecryptPhysicalStore(TSPrimary.ReadAllBytes(), production, PSVersion.Vista));\n TSPrimary.Seek(0, SeekOrigin.Begin);\n }\n\n public void Dispose()\n {\n if (TSPrimary.CanWrite && TSSecondary.CanWrite)\n {\n byte[] data = PhysStoreCrypto.EncryptPhysicalStore(Serialize(), Production, PSVersion.Vista);\n\n TSPrimary.SetLength(data.LongLength);\n TSSecondary.SetLength(data.LongLength);\n\n TSPrimary.Seek(0, SeekOrigin.Begin);\n TSSecondary.Seek(0, SeekOrigin.Begin);\n\n TSPrimary.WriteAllBytes(data);\n TSSecondary.WriteAllBytes(data);\n\n TSPrimary.Close();\n TSSecondary.Close();\n }\n }\n\n public byte[] ReadRaw()\n {\n byte[] data = PhysStoreCrypto.DecryptPhysicalStore(TSPrimary.ReadAllBytes(), Production, PSVersion.Vista);\n TSPrimary.Seek(0, SeekOrigin.Begin);\n return data;\n }\n\n public void WriteRaw(byte[] data)\n {\n byte[] encrData = PhysStoreCrypto.EncryptPhysicalStore(data, Production, PSVersion.Vista);\n\n TSPrimary.SetLength(encrData.LongLength);\n TSSecondary.SetLength(encrData.LongLength);\n\n TSPrimary.Seek(0, SeekOrigin.Begin);\n TSSecondary.Seek(0, SeekOrigin.Begin);\n\n TSPrimary.WriteAllBytes(encrData);\n TSSecondary.WriteAllBytes(encrData);\n\n TSPrimary.Close();\n TSSecondary.Close();\n }\n\n public IEnumerable FindBlocks(string valueSearch)\n {\n List results = new List();\n\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsStr.Contains(valueSearch))\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = new byte[0],\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n\n return results;\n }\n\n public IEnumerable FindBlocks(uint valueSearch)\n {\n List results = new List();\n\n foreach (VistaBlock block in Blocks)\n {\n if (block.ValueAsInt == valueSearch)\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = new byte[0],\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n\n return results;\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/GenPKeyInstall.cs", "namespace LibTSforge.Modifiers\n{\n using System;\n using System.IO;\n using Microsoft.Win32;\n using PhysicalStore;\n using SPP;\n using TokenStore;\n\n public static class GenPKeyInstall\n {\n private static void WritePkey2005RegistryValues(PSVersion version, ProductKey pkey)\n {\n Logger.WriteLine(\"Writing registry data for Windows product key...\");\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"ProductId\", pkey.GetPid2());\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"DigitalProductId\", pkey.GetPid3());\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\", \"DigitalProductId4\", pkey.GetPid4());\n\n if (Registry.GetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Registration\", \"ProductId\", null) != null)\n {\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Registration\", \"ProductId\", pkey.GetPid2());\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Registration\", \"DigitalProductId\", pkey.GetPid3());\n Registry.SetValue(@\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Registration\", \"DigitalProductId4\", pkey.GetPid4());\n }\n\n if (pkey.Channel == \"Volume:CSVLK\" && version != PSVersion.Win7)\n {\n Registry.SetValue(@\"HKEY_USERS\\S-1-5-20\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform\", \"KmsHostConfig\", 1);\n }\n }\n\n public static void InstallGenPKey(PSVersion version, bool production, Guid actId)\n {\n if (version == PSVersion.Vista) throw new NotSupportedException(\"This feature is not supported on Windows Vista/Server 2008.\");\n if (actId == Guid.Empty) throw new ArgumentException(\"Activation ID must be specified for generated product key install.\");\n\n PKeyConfig pkc = new PKeyConfig();\n \n try\n {\n pkc.LoadConfig(actId);\n }\n catch (ArgumentException)\n {\n pkc.LoadAllConfigs(SLApi.GetAppId(actId));\n }\n\n ProductConfig config;\n pkc.Products.TryGetValue(actId, out config);\n\n if (config == null) throw new ArgumentException(\"Activation ID \" + actId + \" not found in PKeyConfig.\");\n\n ProductKey pkey = config.GetRandomKey();\n\n Guid instPkeyId = SLApi.GetInstalledPkeyID(actId);\n if (instPkeyId != Guid.Empty) SLApi.UninstallProductKey(instPkeyId);\n\n if (pkey.Algorithm == PKeyAlgorithm.PKEY2009)\n {\n uint status = SLApi.InstallProductKey(pkey);\n Logger.WriteLine(string.Format(\"Installing generated product key {0} status {1:X}\", pkey, status));\n\n if ((int)status < 0)\n {\n throw new ApplicationException(\"Failed to install generated product key.\");\n }\n\n Logger.WriteLine(\"Successfully deposited generated product key.\");\n return;\n }\n\n Logger.WriteLine(\"Key range is PKEY2005, creating fake key data...\");\n\n if (pkey.Channel == \"Volume:GVLK\" && version == PSVersion.Win7) throw new NotSupportedException(\"Fake GVLK generation is not supported on Windows 7.\");\n\n VariableBag pkb = new VariableBag(version);\n pkb.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingProductKey\",\n ValueAsStr = pkey.ToString()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingMPC\",\n ValueAsStr = pkey.GetMPC()\n },\n new CRCBlockModern {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingPid2\",\n ValueAsStr = pkey.GetPid2()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingPid3\",\n Value = pkey.GetPid3()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingPid4\",\n Value = pkey.GetPid4()\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyChannelId\",\n ValueAsStr = pkey.Channel\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n KeyAsStr = \"SppPkeyBindingEditionId\",\n ValueAsStr = pkey.Edition\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = (version == PSVersion.Win7) ? \"SppPkeyShortAuthenticator\" : \"SppPkeyPhoneActivationData\",\n Value = pkey.GetPhoneData(version)\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppPkeyBindingMiscData\",\n Value = new byte[] { }\n }\n });\n\n Guid appId = SLApi.GetAppId(actId);\n string pkeyId = pkey.GetPkeyId().ToString();\n bool isAddon = SLApi.IsAddon(actId);\n string currEdition = SLApi.GetMetaStr(actId, \"Family\");\n\n if (appId == SLApi.WINDOWS_APP_ID && !isAddon)\n {\n SLApi.UninstallAllProductKeys(appId);\n }\n\n SPPUtils.KillSPP(version);\n\n using (IPhysicalStore ps = SPPUtils.GetStore(version, production))\n {\n using (ITokenStore tks = SPPUtils.GetTokenStore(version))\n {\n Logger.WriteLine(\"Writing to physical store and token store...\");\n\n string suffix = (version == PSVersion.Win8 || version == PSVersion.WinBlue || version == PSVersion.WinModern) ? \"_--\" : \"\";\n string metSuffix = suffix + \"_met\";\n\n if (appId == SLApi.WINDOWS_APP_ID && !isAddon)\n {\n string edTokName = \"msft:spp/token/windows/productkeyid/\" + currEdition;\n\n TokenMeta edToken = tks.GetMetaEntry(edTokName);\n edToken.Data[\"windowsComponentEditionPkeyId\"] = pkeyId;\n edToken.Data[\"windowsComponentEditionSkuId\"] = actId.ToString();\n tks.SetEntry(edTokName, \"xml\", edToken.Serialize());\n\n WritePkey2005RegistryValues(version, pkey);\n }\n\n string uriMapName = \"msft:spp/token/PKeyIdUriMapper\" + metSuffix;\n TokenMeta uriMap = tks.GetMetaEntry(uriMapName);\n uriMap.Data[pkeyId] = pkey.GetAlgoUri();\n tks.SetEntry(uriMapName, \"xml\", uriMap.Serialize());\n\n string skuMetaName = actId + metSuffix;\n TokenMeta skuMeta = tks.GetMetaEntry(skuMetaName);\n\n foreach (string k in skuMeta.Data.Keys)\n {\n if (k.StartsWith(\"pkeyId_\"))\n {\n skuMeta.Data.Remove(k);\n break;\n }\n }\n\n skuMeta.Data[\"pkeyId\"] = pkeyId;\n skuMeta.Data[\"pkeyIdList\"] = pkeyId;\n tks.SetEntry(skuMetaName, \"xml\", skuMeta.Serialize());\n\n string psKey = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n ps.DeleteBlock(psKey, pkeyId);\n ps.AddBlock(new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = (version == PSVersion.WinModern) ? (uint)0x402 : 0x2,\n KeyAsStr = psKey,\n ValueAsStr = pkeyId,\n Data = pkb.Serialize()\n });\n\n string cachePath = SPPUtils.GetTokensPath(version).Replace(\"tokens.dat\", @\"cache\\cache.dat\");\n if (File.Exists(cachePath)) File.Delete(cachePath);\n }\n }\n\n SLApi.RefreshTrustedTime(actId);\n Logger.WriteLine(\"Successfully deposited fake product key.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/PhysicalStoreModern.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using Crypto;\n\n public class ModernBlock\n {\n public BlockType Type;\n public uint Flags;\n public uint Unknown;\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n public byte[] Data;\n public string DataAsStr\n {\n get\n {\n return Utils.DecodeString(Data);\n }\n set\n {\n Data = Utils.EncodeString(value);\n }\n }\n public uint DataAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Data, 0);\n }\n set\n {\n Data = BitConverter.GetBytes(value);\n }\n }\n\n public void Encode(BinaryWriter writer)\n {\n writer.Write((uint)Type);\n writer.Write(Flags);\n writer.Write((uint)Value.Length);\n writer.Write((uint)Data.Length);\n writer.Write(Unknown);\n writer.Write(Value);\n writer.Write(Data);\n }\n\n public static ModernBlock Decode(BinaryReader reader)\n {\n uint type = reader.ReadUInt32();\n uint flags = reader.ReadUInt32();\n\n uint valueLen = reader.ReadUInt32();\n uint dataLen = reader.ReadUInt32();\n uint unk3 = reader.ReadUInt32();\n\n byte[] value = reader.ReadBytes((int)valueLen);\n byte[] data = reader.ReadBytes((int)dataLen);\n\n return new ModernBlock\n {\n Type = (BlockType)type,\n Flags = flags,\n Unknown = unk3,\n Value = value,\n Data = data,\n };\n }\n }\n\n public sealed class PhysicalStoreModern : IPhysicalStore\n {\n private byte[] PreHeaderBytes = { };\n private readonly Dictionary> Data = new Dictionary>();\n private readonly FileStream TSFile;\n private readonly PSVersion Version;\n private readonly bool Production;\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(PreHeaderBytes);\n writer.Write(Data.Keys.Count);\n\n foreach (string key in Data.Keys)\n {\n List blocks = Data[key];\n byte[] keyNameEnc = Utils.EncodeString(key);\n\n writer.Write(keyNameEnc.Length);\n writer.Write(keyNameEnc);\n writer.Write(blocks.Count);\n writer.Align(4);\n\n foreach (ModernBlock block in blocks)\n {\n block.Encode(writer);\n writer.Align(4);\n }\n }\n\n return writer.GetBytes();\n }\n\n public void Deserialize(byte[] data)\n {\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n PreHeaderBytes = reader.ReadBytes(8);\n\n while (reader.BaseStream.Position < data.Length - 0x4)\n {\n uint numKeys = reader.ReadUInt32();\n\n for (int i = 0; i < numKeys; i++)\n {\n uint lenKeyName = reader.ReadUInt32();\n string keyName = Utils.DecodeString(reader.ReadBytes((int)lenKeyName)); uint numValues = reader.ReadUInt32();\n\n reader.Align(4);\n\n Data[keyName] = new List();\n\n for (int j = 0; j < numValues; j++)\n {\n Data[keyName].Add(ModernBlock.Decode(reader));\n reader.Align(4);\n }\n }\n }\n }\n\n public void AddBlock(PSBlock block)\n {\n if (!Data.ContainsKey(block.KeyAsStr))\n {\n Data[block.KeyAsStr] = new List();\n }\n\n Data[block.KeyAsStr].Add(new ModernBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Unknown = block.Unknown,\n Value = block.Value,\n Data = block.Data\n });\n }\n\n public void AddBlocks(IEnumerable blocks)\n {\n foreach (PSBlock block in blocks)\n {\n AddBlock(block);\n }\n }\n\n public PSBlock GetBlock(string key, string value)\n {\n List blocks = Data[key];\n\n foreach (ModernBlock block in blocks)\n {\n if (block.ValueAsStr == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = Utils.EncodeString(key),\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public PSBlock GetBlock(string key, uint value)\n {\n List blocks = Data[key];\n\n foreach (ModernBlock block in blocks)\n {\n if (block.ValueAsInt == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = Utils.EncodeString(key),\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public void SetBlock(string key, string value, byte[] data)\n {\n List blocks = Data[key];\n\n for (int i = 0; i < blocks.Count; i++)\n {\n ModernBlock block = blocks[i];\n\n if (block.ValueAsStr == value)\n {\n block.Data = data;\n blocks[i] = block;\n break;\n }\n }\n\n Data[key] = blocks;\n }\n\n public void SetBlock(string key, uint value, byte[] data)\n {\n List blocks = Data[key];\n\n for (int i = 0; i < blocks.Count; i++)\n {\n ModernBlock block = blocks[i];\n\n if (block.ValueAsInt == value)\n {\n block.Data = data;\n blocks[i] = block;\n break;\n }\n }\n\n Data[key] = blocks;\n }\n\n public void SetBlock(string key, string value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, string value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void SetBlock(string key, uint value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, uint value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void DeleteBlock(string key, string value)\n {\n if (!Data.ContainsKey(key))\n {\n return;\n }\n\n List blocks = Data[key];\n\n foreach (ModernBlock block in blocks)\n {\n if (block.ValueAsStr == value)\n {\n blocks.Remove(block);\n break;\n }\n }\n\n Data[key] = blocks;\n }\n\n public void DeleteBlock(string key, uint value)\n {\n if (!Data.ContainsKey(key))\n {\n return;\n }\n\n List blocks = Data[key];\n\n foreach (ModernBlock block in blocks)\n {\n if (block.ValueAsInt == value)\n {\n blocks.Remove(block);\n break;\n }\n }\n\n Data[key] = blocks;\n }\n\n public PhysicalStoreModern(string tsPath, bool production, PSVersion version)\n {\n TSFile = File.Open(tsPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n Deserialize(PhysStoreCrypto.DecryptPhysicalStore(TSFile.ReadAllBytes(), production, version));\n TSFile.Seek(0, SeekOrigin.Begin);\n Version = version;\n Production = production;\n }\n\n public void Dispose()\n {\n if (TSFile.CanWrite)\n {\n byte[] data = PhysStoreCrypto.EncryptPhysicalStore(Serialize(), Production, Version);\n TSFile.SetLength(data.LongLength);\n TSFile.Seek(0, SeekOrigin.Begin);\n TSFile.WriteAllBytes(data);\n TSFile.Close();\n }\n }\n\n public byte[] ReadRaw()\n {\n byte[] data = PhysStoreCrypto.DecryptPhysicalStore(TSFile.ReadAllBytes(), Production, Version);\n TSFile.Seek(0, SeekOrigin.Begin);\n return data;\n }\n\n public void WriteRaw(byte[] data)\n {\n byte[] encrData = PhysStoreCrypto.EncryptPhysicalStore(data, Production, Version);\n TSFile.SetLength(encrData.LongLength);\n TSFile.Seek(0, SeekOrigin.Begin);\n TSFile.WriteAllBytes(encrData);\n TSFile.Close();\n }\n\n public IEnumerable FindBlocks(string valueSearch)\n {\n List results = new List();\n\n foreach (string key in Data.Keys)\n {\n List values = Data[key];\n\n foreach (ModernBlock block in values)\n {\n if (block.ValueAsStr.Contains(valueSearch))\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n KeyAsStr = key,\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n }\n\n return results;\n }\n\n public IEnumerable FindBlocks(uint valueSearch)\n {\n List results = new List();\n\n foreach (string key in Data.Keys)\n {\n List values = Data[key];\n\n foreach (ModernBlock block in values)\n {\n if (block.ValueAsInt == valueSearch)\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n KeyAsStr = key,\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n }\n\n return results;\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/PhysicalStoreWin7.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using Crypto;\n\n public class Win7Block\n {\n public BlockType Type;\n public uint Flags;\n public byte[] Key;\n public string KeyAsStr\n {\n get\n {\n return Utils.DecodeString(Key);\n }\n set\n {\n Key = Utils.EncodeString(value);\n }\n }\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n public byte[] Data;\n public string DataAsStr\n {\n get\n {\n return Utils.DecodeString(Data);\n }\n set\n {\n Data = Utils.EncodeString(value);\n }\n }\n public uint DataAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Data, 0);\n }\n set\n {\n Data = BitConverter.GetBytes(value);\n }\n }\n\n internal void Encode(BinaryWriter writer)\n {\n writer.Write((uint)Type);\n writer.Write(Flags);\n writer.Write(Key.Length);\n writer.Write(Value.Length);\n writer.Write(Data.Length);\n writer.Write(Key);\n writer.Write(Value);\n writer.Write(Data);\n }\n\n internal static Win7Block Decode(BinaryReader reader)\n {\n uint type = reader.ReadUInt32();\n uint flags = reader.ReadUInt32();\n\n int keyLen = reader.ReadInt32();\n int valueLen = reader.ReadInt32();\n int dataLen = reader.ReadInt32();\n\n byte[] key = reader.ReadBytes(keyLen);\n byte[] value = reader.ReadBytes(valueLen);\n byte[] data = reader.ReadBytes(dataLen);\n return new Win7Block\n {\n Type = (BlockType)type,\n Flags = flags,\n Key = key,\n Value = value,\n Data = data,\n };\n }\n }\n\n public sealed class PhysicalStoreWin7 : IPhysicalStore\n {\n private byte[] PreHeaderBytes = { };\n private readonly List Blocks = new List();\n private readonly FileStream TSPrimary;\n private readonly FileStream TSSecondary;\n private readonly bool Production;\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(PreHeaderBytes);\n\n foreach (Win7Block block in Blocks)\n {\n block.Encode(writer);\n writer.Align(4);\n }\n\n return writer.GetBytes();\n }\n\n public void Deserialize(byte[] data)\n {\n int len = data.Length;\n\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n PreHeaderBytes = reader.ReadBytes(8);\n\n while (reader.BaseStream.Position < len - 0x14)\n {\n Blocks.Add(Win7Block.Decode(reader));\n reader.Align(4);\n }\n }\n\n public void AddBlock(PSBlock block)\n {\n Blocks.Add(new Win7Block\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n });\n }\n\n public void AddBlocks(IEnumerable blocks)\n {\n foreach (PSBlock block in blocks)\n {\n AddBlock(block);\n }\n }\n\n public PSBlock GetBlock(string key, string value)\n {\n foreach (Win7Block block in Blocks)\n {\n if (block.KeyAsStr == key && block.ValueAsStr == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public PSBlock GetBlock(string key, uint value)\n {\n foreach (Win7Block block in Blocks)\n {\n if (block.KeyAsStr == key && block.ValueAsInt == value)\n {\n return new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n };\n }\n }\n\n return null;\n }\n\n public void SetBlock(string key, string value, byte[] data)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n Win7Block block = Blocks[i];\n\n if (block.KeyAsStr == key && block.ValueAsStr == value)\n {\n block.Data = data;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void SetBlock(string key, uint value, byte[] data)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n Win7Block block = Blocks[i];\n\n if (block.KeyAsStr == key && block.ValueAsInt == value)\n {\n block.Data = data;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void SetBlock(string key, string value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, string value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void SetBlock(string key, uint value, string data)\n {\n SetBlock(key, value, Utils.EncodeString(data));\n }\n\n public void SetBlock(string key, uint value, uint data)\n {\n SetBlock(key, value, BitConverter.GetBytes(data));\n }\n\n public void DeleteBlock(string key, string value)\n {\n foreach (Win7Block block in Blocks)\n {\n if (block.KeyAsStr == key && block.ValueAsStr == value)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public void DeleteBlock(string key, uint value)\n {\n foreach (Win7Block block in Blocks)\n {\n if (block.KeyAsStr == key && block.ValueAsInt == value)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public PhysicalStoreWin7(string primaryPath, bool production)\n {\n TSPrimary = File.Open(primaryPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n TSSecondary = File.Open(primaryPath.Replace(\"-0.\", \"-1.\"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);\n Production = production;\n\n Deserialize(PhysStoreCrypto.DecryptPhysicalStore(TSPrimary.ReadAllBytes(), production, PSVersion.Win7));\n TSPrimary.Seek(0, SeekOrigin.Begin);\n }\n\n public void Dispose()\n {\n if (TSPrimary.CanWrite && TSSecondary.CanWrite)\n {\n byte[] data = PhysStoreCrypto.EncryptPhysicalStore(Serialize(), Production, PSVersion.Win7);\n\n TSPrimary.SetLength(data.LongLength);\n TSSecondary.SetLength(data.LongLength);\n\n TSPrimary.Seek(0, SeekOrigin.Begin);\n TSSecondary.Seek(0, SeekOrigin.Begin);\n\n TSPrimary.WriteAllBytes(data);\n TSSecondary.WriteAllBytes(data);\n\n TSPrimary.Close();\n TSSecondary.Close();\n }\n }\n\n public byte[] ReadRaw()\n {\n byte[] data = PhysStoreCrypto.DecryptPhysicalStore(TSPrimary.ReadAllBytes(), Production, PSVersion.Win7);\n TSPrimary.Seek(0, SeekOrigin.Begin);\n return data;\n }\n\n public void WriteRaw(byte[] data)\n {\n byte[] encrData = PhysStoreCrypto.EncryptPhysicalStore(data, Production, PSVersion.Win7);\n\n TSPrimary.SetLength(encrData.LongLength);\n TSSecondary.SetLength(encrData.LongLength);\n\n TSPrimary.Seek(0, SeekOrigin.Begin);\n TSSecondary.Seek(0, SeekOrigin.Begin);\n\n TSPrimary.WriteAllBytes(encrData);\n TSSecondary.WriteAllBytes(encrData);\n\n TSPrimary.Close();\n TSSecondary.Close();\n }\n\n public IEnumerable FindBlocks(string valueSearch)\n {\n List results = new List();\n\n foreach (Win7Block block in Blocks)\n {\n if (block.ValueAsStr.Contains(valueSearch))\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n\n return results;\n }\n\n public IEnumerable FindBlocks(uint valueSearch)\n {\n List results = new List();\n\n foreach (Win7Block block in Blocks)\n {\n if (block.ValueAsInt == valueSearch)\n {\n results.Add(new PSBlock\n {\n Type = block.Type,\n Flags = block.Flags,\n Key = block.Key,\n Value = block.Value,\n Data = block.Data\n });\n }\n }\n\n return results;\n }\n }\n}\n"], ["/TSforge/LibTSforge/Activators/KMS4K.cs", "namespace LibTSforge.Activators\n{\n using System;\n using System.IO;\n using PhysicalStore;\n using SPP;\n\n public class KMS4k\n {\n public static void Activate(PSVersion version, bool production, Guid actId)\n {\n Guid appId;\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, true);\n\n if (actId == Guid.Empty)\n {\n throw new NotSupportedException(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n if (SLApi.GetPKeyChannel(SLApi.GetInstalledPkeyID(actId)) != \"Volume:GVLK\")\n {\n throw new NotSupportedException(\"Non-Volume:GVLK product key installed.\");\n }\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n\n ulong unknown = 0;\n ulong time1;\n ulong time2 = (ulong)DateTime.UtcNow.ToFileTime();\n ulong expiry = Constants.TimerMax;\n\n if (version == PSVersion.Vista || version == PSVersion.Win7)\n {\n unknown = 0x800000000;\n time1 = 0;\n }\n else\n {\n long creationTime = BitConverter.ToInt64(store.GetBlock(\"__##USERSEP##\\\\$$_RESERVED_$$\\\\NAMESPACE__\", \"__##USERSEP-RESERVED##__$$GLOBAL-CREATION-TIME$$\").Data, 0);\n long tickCount = BitConverter.ToInt64(store.GetBlock(\"__##USERSEP##\\\\$$_RESERVED_$$\\\\NAMESPACE__\", \"__##USERSEP-RESERVED##__$$GLOBAL-TICKCOUNT-UPTIME$$\").Data, 0);\n long deltaTime = BitConverter.ToInt64(store.GetBlock(key, \"__##USERSEP-RESERVED##__$$UP-TIME-DELTA$$\").Data, 0);\n\n time1 = (ulong)(creationTime + tickCount + deltaTime);\n time2 /= 10000;\n expiry /= 10000;\n }\n\n if (version == PSVersion.Vista)\n {\n VistaTimer vistaTimer = new VistaTimer\n {\n Time = time2,\n Expiry = Constants.TimerMax\n };\n\n string vistaTimerName = string.Format(\"msft:sl/timer/VLExpiration/VOLUME/{0}/{1}\", appId, actId);\n\n store.DeleteBlock(key, vistaTimerName);\n store.DeleteBlock(key, actId.ToString());\n\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(Constants.KMSv4Response.Length);\n writer.Write(Constants.KMSv4Response);\n writer.Write(Constants.UniversalHWIDBlock);\n byte[] kmsData = writer.GetBytes();\n\n store.AddBlocks(new[]\n {\n new PSBlock\n {\n Type = BlockType.TIMER,\n Flags = 0,\n KeyAsStr = key,\n ValueAsStr = vistaTimerName,\n Data = vistaTimer.CastToArray()\n },\n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = 0,\n KeyAsStr = key,\n ValueAsStr = actId.ToString(),\n Data = kmsData\n }\n });\n }\n else\n {\n byte[] hwidBlock = Constants.UniversalHWIDBlock;\n byte[] kmsResp;\n\n switch (version)\n {\n case PSVersion.Win7:\n kmsResp = Constants.KMSv4Response;\n break;\n case PSVersion.Win8:\n kmsResp = Constants.KMSv5Response;\n break;\n case PSVersion.WinBlue:\n case PSVersion.WinModern:\n kmsResp = Constants.KMSv6Response;\n break;\n default:\n throw new NotSupportedException(\"Unsupported PSVersion.\");\n }\n\n VariableBag kmsBinding = new VariableBag(version);\n\n kmsBinding.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n Key = new byte[] { },\n Value = kmsResp\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"msft:rm/algorithm/hwid/4.0\"\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n KeyAsStr = \"SppBindingLicenseData\",\n Value = hwidBlock\n }\n });\n\n if (version == PSVersion.WinModern)\n {\n kmsBinding.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"massgrave.dev\"\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"6969\"\n }\n });\n }\n\n byte[] kmsBindingData = kmsBinding.Serialize();\n\n Timer kmsTimer = new Timer\n {\n Unknown = unknown,\n Time1 = time1,\n Time2 = time2,\n Expiry = expiry\n };\n\n string storeVal = string.Format(\"msft:spp/kms/bind/2.0/store/{0}/{1}\", appId, actId);\n string timerVal = string.Format(\"msft:spp/kms/bind/2.0/timer/{0}/{1}\", appId, actId);\n\n store.DeleteBlock(key, storeVal);\n store.DeleteBlock(key, timerVal);\n\n store.AddBlocks(new[]\n {\n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = (version == PSVersion.WinModern) ? (uint)0x400 : 0,\n KeyAsStr = key,\n ValueAsStr = storeVal,\n Data = kmsBindingData\n },\n new PSBlock\n {\n Type = BlockType.TIMER,\n Flags = (version == PSVersion.Win7) ? (uint)0 : 0x4,\n KeyAsStr = key,\n ValueAsStr = timerVal,\n Data = kmsTimer.CastToArray()\n }\n });\n }\n }\n\n SPPUtils.RestartSPP(version);\n SLApi.FireStateChangedEvent(appId);\n Logger.WriteLine(\"Activated using KMS4k successfully.\");\n }\n }\n}\n"], ["/TSforge/TSforgeCLI/Program.cs", "namespace TSforgeCLI\n{\n using System;\n using LibTSforge;\n using LibTSforge.Activators;\n using LibTSforge.Modifiers;\n using LibTSforge.SPP;\n\n public class Program\n {\n private class Options\n {\n public bool Dump;\n public string DumpFilePath = \"dump.dat\";\n public string EncrFilePath;\n public bool Load;\n public string LoadFilePath = \"load.dat\";\n public bool KMS4k;\n public bool AVMA4k;\n public bool ZCID;\n public bool TimerReset;\n public bool RearmReset;\n public bool DeleteUniqueId;\n public bool InstallGenPKey;\n public bool KMSHostCharge;\n public bool TamperedFlagsDelete;\n public bool KeyChangeLockDelete;\n public bool SetIIDParams;\n public bool? Production;\n public PSVersion? Version;\n public Guid ActivationId = Guid.Empty;\n public bool ShowHelp;\n public PKeyAlgorithm? Algorithm;\n public int Group;\n public int Serial;\n public ulong Security;\n }\n\n public static void Main(string[] args)\n {\n Logger.WriteLine(\"TSforge (c) MASSGRAVE 2025\");\n\n Utils.Wow64EnableWow64FsRedirection(false);\n\n try\n {\n if (args.Length == 0)\n {\n DisplayUsage();\n return;\n }\n\n Options options = ParseArguments(args);\n\n if (options.ShowHelp)\n {\n DisplayUsage();\n return;\n }\n\n PSVersion version = options.Version ?? Utils.DetectVersion();\n bool production = options.Production ?? SPPUtils.DetectCurrentKey();\n\n if (options.Dump)\n {\n SPPUtils.DumpStore(version, production, options.DumpFilePath, options.EncrFilePath);\n }\n else if (options.Load)\n {\n SPPUtils.LoadStore(version, production, options.LoadFilePath);\n }\n else if (options.KMS4k)\n {\n KMS4k.Activate(version, production, options.ActivationId);\n }\n else if (options.AVMA4k)\n {\n AVMA4k.Activate(version, production, options.ActivationId);\n }\n else if (options.ZCID)\n {\n ZeroCID.Activate(version, production, options.ActivationId);\n }\n else if (options.TimerReset)\n {\n GracePeriodReset.Reset(version, production);\n }\n else if (options.DeleteUniqueId)\n {\n UniqueIdDelete.DeleteUniqueId(version, production, options.ActivationId);\n }\n else if (options.RearmReset)\n {\n RearmReset.Reset(version, production);\n }\n else if (options.InstallGenPKey)\n {\n GenPKeyInstall.InstallGenPKey(version, production, options.ActivationId);\n }\n else if (options.KMSHostCharge)\n {\n KMSHostCharge.Charge(version, production, options.ActivationId);\n }\n else if (options.TamperedFlagsDelete)\n {\n TamperedFlagsDelete.DeleteTamperFlags(version, production);\n }\n else if (options.KeyChangeLockDelete)\n {\n KeyChangeLockDelete.Delete(version, production);\n } \n else if (options.SetIIDParams)\n {\n SetIIDParams.SetParams(version, production, options.ActivationId, options.Algorithm.Value, options.Group, options.Serial, options.Security);\n }\n else\n {\n DisplayUsage();\n }\n }\n catch (Exception e)\n {\n#if DEBUG\n throw;\n#else\n Logger.WriteLine(\"Fatal error: \" + e.ToString());\n Environment.Exit(1);\n#endif\n }\n }\n\n private static Options ParseArguments(string[] args)\n {\n Options options = new Options();\n for (int i = 0; i < args.Length; i++)\n {\n string arg = args[i].Trim().ToLowerInvariant();\n switch (arg)\n {\n case \"/dump\":\n options.Dump = true;\n if (i + 1 < args.Length && !args[i + 1].StartsWith(\"/\"))\n {\n options.DumpFilePath = args[++i];\n }\n if (i + 1 < args.Length && !args[i + 1].StartsWith(\"/\"))\n {\n options.EncrFilePath = args[++i];\n }\n break;\n case \"/load\":\n options.Load = true;\n if (i + 1 < args.Length && !args[i + 1].StartsWith(\"/\"))\n {\n options.LoadFilePath = args[++i];\n }\n break;\n case \"/kms4k\":\n options.KMS4k = true;\n break;\n case \"/avma4k\":\n options.AVMA4k = true;\n break;\n case \"/zcid\":\n options.ZCID = true;\n break;\n case \"/ver\":\n options.Version = i + 1 < args.Length ? ParseVersion(args[++i]) : throw new ArgumentException(\"/ver requires a version argument.\");\n break;\n case \"/rtmr\":\n options.TimerReset = true;\n break;\n case \"/?\":\n options.ShowHelp = true;\n break;\n case \"/duid\":\n options.DeleteUniqueId = true;\n break;\n case \"/rrmc\":\n options.RearmReset = true;\n break;\n case \"/igpk\":\n options.InstallGenPKey = true;\n break;\n case \"/kmsc\":\n options.KMSHostCharge = true;\n break;\n case \"/test\":\n options.Production = false;\n break;\n case \"/prod\":\n options.Production = true;\n break;\n case \"/ctpr\":\n options.TamperedFlagsDelete = true;\n break;\n case \"/revl\":\n options.KeyChangeLockDelete = true;\n break;\n case \"/siid\":\n options.SetIIDParams = true;\n\n if (args.Length - i - 1 < 4) throw new ArgumentException(\"Not enough arguments specified.\");\n\n string algoType = args[++i];\n\n if (algoType == \"5\")\n {\n options.Algorithm = PKeyAlgorithm.PKEY2005;\n }\n else if (algoType == \"9\")\n {\n options.Algorithm = PKeyAlgorithm.PKEY2009;\n } \n else \n { \n throw new ArgumentException(\"Invalid key algorithm specified.\");\n }\n\n try\n {\n options.Group = int.Parse(args[++i]);\n options.Serial = int.Parse(args[++i]);\n options.Security = ulong.Parse(args[++i]);\n } \n catch\n {\n throw new ArgumentException(\"Failed to parse key parameters.\");\n }\n\n break;\n default:\n try\n {\n options.ActivationId = new Guid(arg);\n }\n catch (FormatException)\n {\n Logger.WriteLine(\"Argument doesn't exist or the specified activation ID is invalid.\");\n options.ShowHelp = true;\n }\n break;\n }\n }\n\n return options;\n }\n\n private static void DisplayUsage()\n {\n string exeName = typeof(Program).Namespace;\n Logger.WriteLine(\"Usage: \" + exeName + \" [/dump ()] [/load ] [/kms4k] [/avma4k] [/zcid] [/rtmr] [/duid] [/igpk] [/kmsc] [/ctpr] [/revl] [/siid <5/9> ] [/prod] [/test] [] [/ver ]\");\n Logger.WriteLine(\"Options:\");\n Logger.WriteLine(\"\\t/dump () Dump and decrypt the physical store to the specified path.\");\n Logger.WriteLine(\"\\t/load Load and re-encrypt the physical store from the specified path.\");\n Logger.WriteLine(\"\\t/kms4k Activate using KMS4k. Only supports KMS-activatable editions.\");\n Logger.WriteLine(\"\\t/avma4k Activate using AVMA4k. Only supports Windows Server 2012 R2+.\");\n Logger.WriteLine(\"\\t/zcid Activate using ZeroCID. Only supports phone-activatable editions.\");\n Logger.WriteLine(\"\\t/rtmr Reset grace/evaluation period timers.\");\n Logger.WriteLine(\"\\t/rrmc Reset the rearm count.\");\n Logger.WriteLine(\"\\t/duid Delete product key Unique ID used in online key validation.\");\n Logger.WriteLine(\"\\t/igpk Install auto-generated/fake product key according to the specified Activation ID\");\n Logger.WriteLine(\"\\t/kmsc Reset the charged count on the local KMS server to 25. Requires an activated KMS host.\");\n Logger.WriteLine(\"\\t/ctpr Remove the tamper flags that get set in the physical store when sppsvc detects an attempt to tamper with it.\");\n Logger.WriteLine(\"\\t/revl Remove the key change lock in evaluation edition store.\");\n Logger.WriteLine(\"\\t/siid <5/9> Set Installation ID parameters independently of installed key. 5/9 argument specifies PKEY200[5/9] key algorithm.\");\n Logger.WriteLine(\"\\t/prod Use SPP production key.\");\n Logger.WriteLine(\"\\t/test Use SPP test key.\");\n Logger.WriteLine(\"\\t/ver Override the detected version. Available versions: vista, 7, 8, blue, modern.\");\n Logger.WriteLine(\"\\t A specific activation ID. Useful if you want to activate specific addons like ESU.\");\n Logger.WriteLine(\"\\t/? Display this help message.\");\n }\n\n private static PSVersion ParseVersion(string ver)\n {\n switch (ver.Trim().ToLowerInvariant())\n {\n case \"vista\": return PSVersion.Vista;\n case \"7\": return PSVersion.Win7;\n case \"8\": return PSVersion.Win8;\n case \"blue\": return PSVersion.WinBlue;\n case \"modern\": return PSVersion.WinModern;\n default: throw new ArgumentException(\"Invalid version specified.\");\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/VariableBag.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n\n public enum CRCBlockType : uint\n {\n UINT = 1 << 0,\n STRING = 1 << 1,\n BINARY = 1 << 2\n }\n\n public abstract class CRCBlock\n {\n public CRCBlockType DataType;\n public byte[] Key;\n public string KeyAsStr\n {\n get\n {\n return Utils.DecodeString(Key);\n }\n set\n {\n Key = Utils.EncodeString(value);\n }\n }\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n\n public abstract void Encode(BinaryWriter writer);\n public abstract void Decode(BinaryReader reader);\n public abstract uint CRC();\n }\n\n public class CRCBlockVista : CRCBlock\n {\n public override void Encode(BinaryWriter writer)\n {\n uint crc = CRC();\n writer.Write((uint)DataType);\n writer.Write(0);\n writer.Write(Key.Length);\n writer.Write(Value.Length);\n writer.Write(crc);\n\n writer.Write(Key);\n\n writer.Write(Value);\n }\n\n public override void Decode(BinaryReader reader)\n {\n uint type = reader.ReadUInt32();\n reader.ReadUInt32();\n uint lenName = reader.ReadUInt32();\n uint lenVal = reader.ReadUInt32();\n uint crc = reader.ReadUInt32();\n\n byte[] key = reader.ReadBytes((int)lenName);\n byte[] value = reader.ReadBytes((int)lenVal);\n\n DataType = (CRCBlockType)type;\n Key = key;\n Value = value;\n\n if (CRC() != crc)\n {\n throw new InvalidDataException(\"Invalid CRC in variable bag.\");\n }\n }\n\n public override uint CRC()\n {\n return Utils.CRC32(Value);\n }\n }\n\n public class CRCBlockModern : CRCBlock\n {\n public override void Encode(BinaryWriter writer)\n {\n uint crc = CRC();\n writer.Write(crc);\n writer.Write((uint)DataType);\n writer.Write(Key.Length);\n writer.Write(Value.Length);\n\n writer.Write(Key);\n writer.Align(8);\n\n writer.Write(Value);\n writer.Align(8);\n }\n\n public override void Decode(BinaryReader reader)\n {\n uint crc = reader.ReadUInt32();\n uint type = reader.ReadUInt32();\n uint lenName = reader.ReadUInt32();\n uint lenVal = reader.ReadUInt32();\n\n byte[] key = reader.ReadBytes((int)lenName);\n reader.Align(8);\n\n byte[] value = reader.ReadBytes((int)lenVal);\n reader.Align(8);\n\n DataType = (CRCBlockType)type;\n Key = key;\n Value = value;\n\n if (CRC() != crc)\n {\n throw new InvalidDataException(\"Invalid CRC in variable bag.\");\n }\n }\n\n public override uint CRC()\n {\n BinaryWriter wtemp = new BinaryWriter(new MemoryStream());\n wtemp.Write(0);\n wtemp.Write((uint)DataType);\n wtemp.Write(Key.Length);\n wtemp.Write(Value.Length);\n wtemp.Write(Key);\n wtemp.Write(Value);\n return Utils.CRC32(wtemp.GetBytes());\n }\n }\n\n public class VariableBag\n {\n public List Blocks = new List();\n private readonly PSVersion Version;\n\n private void Deserialize(byte[] data)\n {\n int len = data.Length;\n\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n\n while (reader.BaseStream.Position < len - 0x10)\n {\n CRCBlock block;\n\n if (Version == PSVersion.Vista)\n {\n block = new CRCBlockVista();\n }\n else\n {\n block = new CRCBlockModern();\n }\n\n block.Decode(reader);\n Blocks.Add(block);\n }\n }\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n\n foreach (CRCBlock block in Blocks)\n {\n if (Version == PSVersion.Vista)\n {\n ((CRCBlockVista)block).Encode(writer);\n } else\n {\n ((CRCBlockModern)block).Encode(writer);\n }\n }\n\n return writer.GetBytes();\n }\n\n public CRCBlock GetBlock(string key)\n {\n foreach (CRCBlock block in Blocks)\n {\n if (block.KeyAsStr == key)\n {\n return block;\n }\n }\n\n return null;\n }\n\n public void SetBlock(string key, byte[] value)\n {\n for (int i = 0; i < Blocks.Count; i++)\n {\n CRCBlock block = Blocks[i];\n\n if (block.KeyAsStr == key)\n {\n block.Value = value;\n Blocks[i] = block;\n break;\n }\n }\n }\n\n public void DeleteBlock(string key)\n {\n foreach (CRCBlock block in Blocks)\n {\n if (block.KeyAsStr == key)\n {\n Blocks.Remove(block);\n return;\n }\n }\n }\n\n public VariableBag(byte[] data, PSVersion version)\n {\n Version = version;\n Deserialize(data);\n }\n\n public VariableBag(PSVersion version)\n {\n Version = version;\n }\n }\n}\n"], ["/TSforge/LibTSforge/SPP/SLAPI.cs", "namespace LibTSforge.SPP\n{\n using System;\n using System.Collections.Generic;\n using System.Linq;\n using System.Runtime.InteropServices;\n using System.Text;\n\n public static class SLApi\n {\n private enum SLIDTYPE\n {\n SL_ID_APPLICATION,\n SL_ID_PRODUCT_SKU,\n SL_ID_LICENSE_FILE,\n SL_ID_LICENSE,\n SL_ID_PKEY,\n SL_ID_ALL_LICENSES,\n SL_ID_ALL_LICENSE_FILES,\n SL_ID_STORE_TOKEN,\n SL_ID_LAST\n }\n\n private enum SLDATATYPE\n {\n SL_DATA_NONE,\n SL_DATA_SZ,\n SL_DATA_DWORD,\n SL_DATA_BINARY,\n SL_DATA_MULTI_SZ,\n SL_DATA_SUM\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct SL_LICENSING_STATUS\n {\n public Guid SkuId;\n public uint eStatus;\n public uint dwGraceTime;\n public uint dwTotalGraceDays;\n public uint hrReason;\n public ulong qwValidityExpiration;\n }\n\n public static readonly Guid WINDOWS_APP_ID = new Guid(\"55c92734-d682-4d71-983e-d6ec3f16059f\");\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode, PreserveSig = false)]\n private static extern void SLOpen(out IntPtr hSLC);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode, PreserveSig = false)]\n private static extern void SLClose(IntPtr hSLC);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetWindowsInformationDWORD(string ValueName, ref int Value);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLInstallProofOfPurchase(IntPtr hSLC, string pwszPKeyAlgorithm, string pwszPKeyString, uint cbPKeySpecificData, byte[] pbPKeySpecificData, ref Guid PKeyId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLUninstallProofOfPurchase(IntPtr hSLC, ref Guid PKeyId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetPKeyInformation(IntPtr hSLC, ref Guid pPKeyId, string pwszValueName, out SLDATATYPE peDataType, out uint pcbValue, out IntPtr ppbValue);\n\n [DllImport(\"slcext.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLActivateProduct(IntPtr hSLC, ref Guid pProductSkuId, byte[] cbAppSpecificData, byte[] pvAppSpecificData, byte[] pActivationInfo, string pwszProxyServer, ushort wProxyPort);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGenerateOfflineInstallationId(IntPtr hSLC, ref Guid pProductSkuId, ref string ppwszInstallationId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLDepositOfflineConfirmationId(IntPtr hSLC, ref Guid pProductSkuId, string pwszInstallationId, string pwszConfirmationId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetSLIDList(IntPtr hSLC, SLIDTYPE eQueryIdType, ref Guid pQueryId, SLIDTYPE eReturnIdType, out uint pnReturnIds, out IntPtr ppReturnIds);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode, PreserveSig = false)]\n private static extern void SLGetLicensingStatusInformation(IntPtr hSLC, ref Guid pAppID, IntPtr pProductSkuId, string pwszRightName, out uint pnStatusCount, out IntPtr ppLicensingStatus);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetInstalledProductKeyIds(IntPtr hSLC, ref Guid pProductSkuId, out uint pnProductKeyIds, out IntPtr ppProductKeyIds);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLConsumeWindowsRight(uint unknown);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetProductSkuInformation(IntPtr hSLC, ref Guid pProductSkuId, string pwszValueName, out SLDATATYPE peDataType, out uint pcbValue, out IntPtr ppbValue);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLGetLicense(IntPtr hSLC, ref Guid pLicenseFileId, out uint pcbLicenseFile, out IntPtr ppbLicenseFile);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLSetCurrentProductKey(IntPtr hSLC, ref Guid pProductSkuId, ref Guid pProductKeyId);\n\n [DllImport(\"slc.dll\", CharSet = CharSet.Unicode)]\n private static extern uint SLFireEvent(IntPtr hSLC, string pwszEventId, ref Guid pApplicationId);\n\n private class SLContext : IDisposable\n {\n public readonly IntPtr Handle;\n\n public SLContext()\n {\n SLOpen(out Handle);\n }\n\n public void Dispose()\n {\n SLClose(Handle);\n GC.SuppressFinalize(this);\n }\n\n ~SLContext()\n {\n Dispose();\n }\n }\n\n public static Guid GetDefaultActivationID(Guid appId, bool includeActivated)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr pLicStat;\n\n SLGetLicensingStatusInformation(sl.Handle, ref appId, IntPtr.Zero, null, out count, out pLicStat);\n\n unsafe\n {\n SL_LICENSING_STATUS* licensingStatuses = (SL_LICENSING_STATUS*)pLicStat;\n for (int i = 0; i < count; i++)\n {\n SL_LICENSING_STATUS slStatus = licensingStatuses[i];\n\n Guid actId = slStatus.SkuId;\n if (GetInstalledPkeyID(actId) == Guid.Empty) continue;\n if (IsAddon(actId)) continue;\n if (!includeActivated && (slStatus.eStatus == 1)) continue;\n\n return actId;\n }\n }\n\n return Guid.Empty;\n }\n }\n\n public static string GetInstallationID(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n string installationId = null;\n return SLGenerateOfflineInstallationId(sl.Handle, ref actId, ref installationId) == 0 ? installationId : null;\n }\n }\n\n public static Guid GetInstalledPkeyID(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr pProductKeyIds;\n\n uint status = SLGetSLIDList(sl.Handle, SLIDTYPE.SL_ID_PRODUCT_SKU, ref actId, SLIDTYPE.SL_ID_PKEY, out count, out pProductKeyIds);\n\n if (status != 0 || count == 0)\n {\n return Guid.Empty;\n }\n\n unsafe { return *(Guid*)pProductKeyIds; }\n }\n }\n\n public static uint DepositConfirmationID(Guid actId, string installationId, string confirmationId)\n {\n using (SLContext sl = new SLContext())\n {\n return SLDepositOfflineConfirmationId(sl.Handle, ref actId, installationId, confirmationId);\n }\n }\n\n public static void RefreshLicenseStatus()\n {\n SLConsumeWindowsRight(0);\n }\n\n public static void RefreshTrustedTime(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n SLDATATYPE type;\n uint count;\n IntPtr ppbValue;\n\n SLGetProductSkuInformation(sl.Handle, ref actId, \"TrustedTime\", out type, out count, out ppbValue);\n }\n }\n\n public static void FireStateChangedEvent(Guid appId)\n {\n using (SLContext sl = new SLContext())\n {\n SLFireEvent(sl.Handle, \"msft:rm/event/licensingstatechanged\", ref appId);\n }\n }\n\n public static Guid GetAppId(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr pAppIds;\n\n uint status = SLGetSLIDList(sl.Handle, SLIDTYPE.SL_ID_PRODUCT_SKU, ref actId, SLIDTYPE.SL_ID_APPLICATION, out count, out pAppIds);\n\n if (status != 0 || count == 0)\n {\n return Guid.Empty;\n }\n\n unsafe { return *(Guid*)pAppIds; }\n }\n }\n\n public static bool IsAddon(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n SLDATATYPE type;\n IntPtr ppbValue;\n\n uint status = SLGetProductSkuInformation(sl.Handle, ref actId, \"DependsOn\", out type, out count, out ppbValue);\n return (int)status >= 0 && status != 0xC004F012;\n }\n }\n\n public static Guid GetLicenseFileId(Guid licId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr ppReturnLics;\n\n uint status = SLGetSLIDList(sl.Handle, SLIDTYPE.SL_ID_LICENSE, ref licId, SLIDTYPE.SL_ID_LICENSE_FILE, out count, out ppReturnLics);\n\n if (status != 0 || count == 0)\n {\n return Guid.Empty;\n }\n\n unsafe { return *(Guid*)ppReturnLics; }\n }\n }\n\n public static Guid GetPkeyConfigFileId(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n SLDATATYPE type;\n uint len;\n IntPtr ppReturnLics;\n\n uint status = SLGetProductSkuInformation(sl.Handle, ref actId, \"pkeyConfigLicenseId\", out type, out len, out ppReturnLics);\n\n if (status != 0 || len == 0)\n {\n return Guid.Empty;\n }\n\n Guid pkcId = new Guid(Marshal.PtrToStringAuto(ppReturnLics));\n return GetLicenseFileId(pkcId);\n }\n }\n\n public static string GetLicenseContents(Guid fileId)\n {\n if (fileId == Guid.Empty) throw new ArgumentException(\"License contents could not be retrieved.\");\n\n using (SLContext sl = new SLContext())\n {\n uint dataLen;\n IntPtr dataPtr;\n\n if (SLGetLicense(sl.Handle, ref fileId, out dataLen, out dataPtr) != 0)\n {\n return null;\n }\n\n byte[] data = new byte[dataLen];\n Marshal.Copy(dataPtr, data, 0, (int)dataLen);\n\n data = data.Skip(Array.IndexOf(data, (byte)'<')).ToArray();\n return Encoding.UTF8.GetString(data);\n }\n }\n\n public static bool IsPhoneActivatable(Guid actId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n SLDATATYPE type;\n IntPtr ppbValue;\n\n uint status = SLGetProductSkuInformation(sl.Handle, ref actId, \"msft:sl/EUL/PHONE/PUBLIC\", out type, out count, out ppbValue);\n return status != 0xC004F012;\n }\n }\n\n public static string GetPKeyChannel(Guid pkeyId)\n {\n using (SLContext sl = new SLContext())\n {\n SLDATATYPE type;\n uint len;\n IntPtr ppbValue;\n\n uint status = SLGetPKeyInformation(sl.Handle, ref pkeyId, \"Channel\", out type, out len, out ppbValue);\n\n if (status != 0 || len == 0)\n {\n return null;\n }\n\n return Marshal.PtrToStringAuto(ppbValue);\n }\n }\n\n public static string GetMetaStr(Guid actId, string value)\n {\n using (SLContext sl = new SLContext())\n {\n uint len;\n SLDATATYPE type;\n IntPtr ppbValue;\n\n uint status = SLGetProductSkuInformation(sl.Handle, ref actId, value, out type, out len, out ppbValue);\n\n if (status != 0 || len == 0 || type != SLDATATYPE.SL_DATA_SZ)\n {\n return null;\n }\n\n return Marshal.PtrToStringAuto(ppbValue);\n }\n }\n\n public static List GetActivationIds(Guid appId)\n {\n using (SLContext sl = new SLContext())\n {\n uint count;\n IntPtr pLicStat;\n\n SLGetLicensingStatusInformation(sl.Handle, ref appId, IntPtr.Zero, null, out count, out pLicStat);\n\n List result = new List();\n\n unsafe\n {\n SL_LICENSING_STATUS* licensingStatuses = (SL_LICENSING_STATUS*)pLicStat;\n for (int i = 0; i < count; i++)\n {\n result.Add(licensingStatuses[i].SkuId);\n }\n }\n\n return result;\n }\n }\n\n public static uint SetCurrentProductKey(Guid actId, Guid pkeyId)\n {\n using (SLContext sl = new SLContext())\n {\n return SLSetCurrentProductKey(sl.Handle, ref actId, ref pkeyId);\n }\n }\n\n public static uint InstallProductKey(ProductKey pkey)\n {\n using (SLContext sl = new SLContext())\n {\n Guid pkeyId = Guid.Empty;\n return SLInstallProofOfPurchase(sl.Handle, pkey.GetAlgoUri(), pkey.ToString(), 0, null, ref pkeyId);\n }\n }\n\n public static void UninstallProductKey(Guid pkeyId)\n {\n using (SLContext sl = new SLContext())\n {\n SLUninstallProofOfPurchase(sl.Handle, ref pkeyId);\n }\n }\n\n public static void UninstallAllProductKeys(Guid appId)\n {\n foreach (Guid actId in GetActivationIds(appId))\n {\n Guid pkeyId = GetInstalledPkeyID(actId);\n if (pkeyId == Guid.Empty) continue;\n if (IsAddon(actId)) continue;\n UninstallProductKey(pkeyId);\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/SetIIDParams.cs", "namespace LibTSforge.Modifiers\n{\n using PhysicalStore;\n using SPP;\n using System.IO;\n using System;\n\n public static class SetIIDParams\n {\n public static void SetParams(PSVersion version, bool production, Guid actId, PKeyAlgorithm algorithm, int group, int serial, ulong security)\n {\n if (version == PSVersion.Vista) throw new NotSupportedException(\"This feature is not supported on Windows Vista/Server 2008.\");\n\n Guid appId;\n\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, true);\n\n if (actId == Guid.Empty)\n {\n throw new Exception(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n Guid pkeyId = SLApi.GetInstalledPkeyID(actId);\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n PSBlock keyBlock = store.GetBlock(key, pkeyId.ToString());\n\n if (keyBlock == null)\n {\n throw new InvalidDataException(\"Failed to get product key data for activation ID \" + actId + \".\");\n }\n\n VariableBag pkb = new VariableBag(keyBlock.Data, version);\n\n ProductKey pkey = new ProductKey\n {\n Group = group,\n Serial = serial,\n Security = security,\n Algorithm = algorithm,\n Upgrade = false\n };\n\n string blockName = version == PSVersion.Win7 ? \"SppPkeyShortAuthenticator\" : \"SppPkeyPhoneActivationData\";\n pkb.SetBlock(blockName, pkey.GetPhoneData(version));\n store.SetBlock(key, pkeyId.ToString(), pkb.Serialize());\n }\n\n Logger.WriteLine(\"Successfully set IID parameters.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/SPP/PKeyConfig.cs", "namespace LibTSforge.SPP\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using System.Linq;\n using System.Text;\n using System.Xml;\n\n public enum PKeyAlgorithm\n {\n PKEY2005,\n PKEY2009\n }\n\n public class KeyRange\n {\n public int Start;\n public int End;\n public string EulaType;\n public string PartNumber;\n public bool Valid;\n\n public bool Contains(int n)\n {\n return Start <= n && End <= n;\n }\n }\n\n public class ProductConfig\n {\n public int GroupId;\n public string Edition;\n public string Description;\n public string Channel;\n public bool Randomized;\n public PKeyAlgorithm Algorithm;\n public List Ranges;\n public Guid ActivationId;\n\n private List GetPkeyRanges()\n {\n if (Ranges.Count == 0)\n {\n throw new ArgumentException(\"No key ranges.\");\n }\n\n if (Algorithm == PKeyAlgorithm.PKEY2005)\n {\n return Ranges;\n }\n\n List FilteredRanges = Ranges.Where(r => !r.EulaType.Contains(\"WAU\")).ToList();\n\n if (FilteredRanges.Count == 0)\n {\n throw new NotSupportedException(\"Specified Activation ID is usable only for Windows Anytime Upgrade. Please use a non-WAU Activation ID instead.\");\n }\n\n return FilteredRanges;\n }\n\n public ProductKey GetRandomKey()\n {\n List KeyRanges = GetPkeyRanges();\n Random rnd = new Random();\n\n KeyRange range = KeyRanges[rnd.Next(KeyRanges.Count)];\n int serial = rnd.Next(range.Start, range.End);\n\n return new ProductKey(serial, 0, false, Algorithm, this, range);\n }\n }\n\n public class PKeyConfig\n {\n public readonly Dictionary Products = new Dictionary();\n private readonly List loadedPkeyConfigs = new List();\n\n public void LoadConfig(Guid actId)\n {\n string pkcData;\n Guid pkcFileId = SLApi.GetPkeyConfigFileId(actId);\n\n if (loadedPkeyConfigs.Contains(pkcFileId)) return;\n\n string licConts = SLApi.GetLicenseContents(pkcFileId);\n\n using (TextReader tr = new StringReader(licConts))\n {\n XmlDocument lic = new XmlDocument();\n lic.Load(tr);\n\n XmlNamespaceManager nsmgr = new XmlNamespaceManager(lic.NameTable);\n nsmgr.AddNamespace(\"rg\", \"urn:mpeg:mpeg21:2003:01-REL-R-NS\");\n nsmgr.AddNamespace(\"r\", \"urn:mpeg:mpeg21:2003:01-REL-R-NS\");\n nsmgr.AddNamespace(\"tm\", \"http://www.microsoft.com/DRM/XrML2/TM/v2\");\n\n XmlNode root = lic.DocumentElement;\n XmlNode pkcDataNode = root.SelectSingleNode(\"/rg:licenseGroup/r:license/r:otherInfo/tm:infoTables/tm:infoList/tm:infoBin[@name=\\\"pkeyConfigData\\\"]\", nsmgr);\n pkcData = Encoding.UTF8.GetString(Convert.FromBase64String(pkcDataNode.InnerText));\n }\n\n using (TextReader tr = new StringReader(pkcData))\n {\n XmlDocument lic = new XmlDocument();\n lic.Load(tr);\n\n XmlNamespaceManager nsmgr = new XmlNamespaceManager(lic.NameTable);\n nsmgr.AddNamespace(\"p\", \"http://www.microsoft.com/DRM/PKEY/Configuration/2.0\");\n XmlNodeList configNodes = lic.SelectNodes(\"//p:ProductKeyConfiguration/p:Configurations/p:Configuration\", nsmgr);\n XmlNodeList rangeNodes = lic.SelectNodes(\"//p:ProductKeyConfiguration/p:KeyRanges/p:KeyRange\", nsmgr);\n XmlNodeList pubKeyNodes = lic.SelectNodes(\"//p:ProductKeyConfiguration/p:PublicKeys/p:PublicKey\", nsmgr);\n\n Dictionary algorithms = new Dictionary();\n Dictionary> ranges = new Dictionary>();\n\n Dictionary algoConv = new Dictionary\n {\n { \"msft:rm/algorithm/pkey/2005\", PKeyAlgorithm.PKEY2005 },\n { \"msft:rm/algorithm/pkey/2009\", PKeyAlgorithm.PKEY2009 }\n };\n\n foreach (XmlNode pubKeyNode in pubKeyNodes)\n {\n int group = int.Parse(pubKeyNode.SelectSingleNode(\"./p:GroupId\", nsmgr).InnerText);\n algorithms[group] = algoConv[pubKeyNode.SelectSingleNode(\"./p:AlgorithmId\", nsmgr).InnerText];\n }\n\n foreach (XmlNode rangeNode in rangeNodes)\n {\n string refActIdStr = rangeNode.SelectSingleNode(\"./p:RefActConfigId\", nsmgr).InnerText;\n\n if (!ranges.ContainsKey(refActIdStr))\n {\n ranges[refActIdStr] = new List();\n }\n\n KeyRange keyRange = new KeyRange\n {\n Start = int.Parse(rangeNode.SelectSingleNode(\"./p:Start\", nsmgr).InnerText),\n End = int.Parse(rangeNode.SelectSingleNode(\"./p:End\", nsmgr).InnerText),\n EulaType = rangeNode.SelectSingleNode(\"./p:EulaType\", nsmgr).InnerText,\n PartNumber = rangeNode.SelectSingleNode(\"./p:PartNumber\", nsmgr).InnerText,\n Valid = rangeNode.SelectSingleNode(\"./p:IsValid\", nsmgr).InnerText.ToLower() == \"true\"\n };\n\n ranges[refActIdStr].Add(keyRange);\n }\n\n foreach (XmlNode configNode in configNodes)\n {\n string refActIdStr = configNode.SelectSingleNode(\"./p:ActConfigId\", nsmgr).InnerText;\n Guid refActId = new Guid(refActIdStr);\n int group = int.Parse(configNode.SelectSingleNode(\"./p:RefGroupId\", nsmgr).InnerText);\n List keyRanges = ranges[refActIdStr];\n\n if (keyRanges.Count > 0 && !Products.ContainsKey(refActId))\n {\n ProductConfig productConfig = new ProductConfig\n {\n GroupId = group,\n Edition = configNode.SelectSingleNode(\"./p:EditionId\", nsmgr).InnerText,\n Description = configNode.SelectSingleNode(\"./p:ProductDescription\", nsmgr).InnerText,\n Channel = configNode.SelectSingleNode(\"./p:ProductKeyType\", nsmgr).InnerText,\n Randomized = configNode.SelectSingleNode(\"./p:ProductKeyType\", nsmgr).InnerText.ToLower() == \"true\",\n Algorithm = algorithms[group],\n Ranges = keyRanges,\n ActivationId = refActId\n };\n\n Products[refActId] = productConfig;\n }\n }\n }\n\n loadedPkeyConfigs.Add(pkcFileId);\n }\n\n public ProductConfig MatchParams(int group, int serial)\n {\n foreach (ProductConfig config in Products.Values)\n {\n if (config.GroupId == group)\n {\n foreach (KeyRange range in config.Ranges)\n {\n if (range.Contains(serial))\n {\n return config;\n }\n }\n }\n }\n\n throw new FileNotFoundException(\"Failed to find product matching supplied product key parameters.\");\n }\n\n public void LoadAllConfigs(Guid appId)\n {\n foreach (Guid actId in SLApi.GetActivationIds(appId))\n {\n try\n {\n LoadConfig(actId);\n } \n catch (ArgumentException)\n {\n\n }\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/Activators/AVMA4K.cs", "namespace LibTSforge.Activators\n{\n using System;\n using PhysicalStore;\n using SPP;\n\n public static class AVMA4k\n {\n public static void Activate(PSVersion version, bool production, Guid actId)\n {\n if (version != PSVersion.WinModern && version != PSVersion.WinBlue)\n {\n throw new NotSupportedException(\"AVMA licenses are not available for this product.\");\n }\n\n Guid appId;\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, false);\n\n if (actId == Guid.Empty)\n {\n throw new NotSupportedException(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n if (SLApi.GetPKeyChannel(SLApi.GetInstalledPkeyID(actId)) != \"VT:IA\")\n {\n throw new NotSupportedException(\"Non-VT:IA product key installed.\");\n }\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n\n long creationTime = BitConverter.ToInt64(store.GetBlock(\"__##USERSEP##\\\\$$_RESERVED_$$\\\\NAMESPACE__\", \"__##USERSEP-RESERVED##__$$GLOBAL-CREATION-TIME$$\").Data, 0);\n long tickCount = BitConverter.ToInt64(store.GetBlock(\"__##USERSEP##\\\\$$_RESERVED_$$\\\\NAMESPACE__\", \"__##USERSEP-RESERVED##__$$GLOBAL-TICKCOUNT-UPTIME$$\").Data, 0);\n long deltaTime = BitConverter.ToInt64(store.GetBlock(key, \"__##USERSEP-RESERVED##__$$UP-TIME-DELTA$$\").Data, 0);\n\n const ulong unknown = 0;\n ulong time1 = (ulong)(creationTime + tickCount + deltaTime);\n ulong crcBindTime = (ulong)DateTime.UtcNow.ToFileTime();\n ulong timerTime = crcBindTime / 10000;\n ulong expiry = Constants.TimerMax / 10000;\n\n VariableBag avmaBinding = new VariableBag(version);\n\n avmaBinding.Blocks.AddRange(new[]\n {\n new CRCBlockModern\n {\n DataType = CRCBlockType.BINARY,\n Key = new byte[] { },\n Value = BitConverter.GetBytes(crcBindTime),\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"AVMA4K\",\n },\n new CRCBlockModern\n {\n DataType = CRCBlockType.STRING,\n Key = new byte[] { },\n ValueAsStr = \"00491-50000-00001-AA666\",\n }\n });\n\n byte[] avmaBindingData = avmaBinding.Serialize();\n\n Timer avmaTimer = new Timer\n {\n Unknown = unknown,\n Time1 = time1,\n Time2 = timerTime,\n Expiry = expiry\n };\n\n string storeVal = string.Format(\"msft:spp/ia/bind/1.0/store/{0}/{1}\", appId, actId);\n string timerVal = string.Format(\"msft:spp/ia/bind/1.0/timer/{0}/{1}\", appId, actId);\n\n store.DeleteBlock(key, storeVal);\n store.DeleteBlock(key, timerVal);\n\n store.AddBlocks(new[]\n {\n new PSBlock\n {\n Type = BlockType.NAMED,\n Flags = 0x400,\n KeyAsStr = key,\n ValueAsStr = storeVal,\n Data = avmaBindingData,\n },\n new PSBlock\n {\n Type = BlockType.TIMER,\n Flags = 0x4,\n KeyAsStr = key,\n ValueAsStr = timerVal,\n Data = avmaTimer.CastToArray()\n }\n });\n }\n\n SLApi.RefreshLicenseStatus();\n SLApi.FireStateChangedEvent(appId);\n Logger.WriteLine(\"Activated using AVMA4k successfully.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/Common.cs", "namespace LibTSforge\n{\n using System;\n using System.IO;\n using System.Linq;\n using System.Runtime.InteropServices;\n using System.Text;\n\n public enum PSVersion\n {\n Vista,\n Win7,\n Win8,\n WinBlue,\n WinModern\n }\n\n public static class Constants\n {\n public static readonly byte[] UniversalHWIDBlock =\n {\n 0x26, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x01, 0x0c, 0x01, 0x00\n };\n\n public static readonly byte[] KMSv4Response =\n {\n 0x00, 0x00, 0x04, 0x00, 0x62, 0x00, 0x00, 0x00, 0x30, 0x00, 0x35, 0x00, 0x34, 0x00, 0x32, 0x00,\n 0x36, 0x00, 0x2D, 0x00, 0x30, 0x00, 0x30, 0x00, 0x32, 0x00, 0x30, 0x00, 0x36, 0x00, 0x2D, 0x00,\n 0x31, 0x00, 0x36, 0x00, 0x31, 0x00, 0x2D, 0x00, 0x36, 0x00, 0x35, 0x00, 0x35, 0x00, 0x35, 0x00,\n 0x30, 0x00, 0x36, 0x00, 0x2D, 0x00, 0x30, 0x00, 0x33, 0x00, 0x2D, 0x00, 0x31, 0x00, 0x30, 0x00,\n 0x33, 0x00, 0x33, 0x00, 0x2D, 0x00, 0x39, 0x00, 0x32, 0x00, 0x30, 0x00, 0x30, 0x00, 0x2E, 0x00,\n 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x2D, 0x00, 0x30, 0x00, 0x36, 0x00, 0x35, 0x00,\n 0x32, 0x00, 0x30, 0x00, 0x31, 0x00, 0x33, 0x00, 0x00, 0x00, 0xDE, 0x19, 0x02, 0xCF, 0x1F, 0x35,\n 0x97, 0x4E, 0x8A, 0x8F, 0xB8, 0x07, 0xB1, 0x92, 0xB5, 0xB5, 0x97, 0x42, 0xEC, 0x3A, 0x76, 0x84,\n 0xD5, 0x01, 0x32, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00, 0x60, 0x27, 0x00, 0x00, 0xC4, 0x1E,\n 0xAA, 0x8B, 0xDD, 0x0C, 0xAB, 0x55, 0x6A, 0xCE, 0xAF, 0xAC, 0x7F, 0x5F, 0xBD, 0xE9\n };\n\n public static readonly byte[] KMSv5Response =\n {\n 0x00, 0x00, 0x05, 0x00, 0xBE, 0x96, 0xF9, 0x04, 0x54, 0x17, 0x3F, 0xAF, 0xE3, 0x08, 0x50, 0xEB,\n 0x22, 0xBA, 0x53, 0xBF, 0xF2, 0x6A, 0x7B, 0xC9, 0x05, 0x1D, 0xB5, 0x19, 0xDF, 0x98, 0xE2, 0x71,\n 0x4D, 0x00, 0x61, 0xE9, 0x9D, 0x03, 0xFB, 0x31, 0xF9, 0x1F, 0x2E, 0x60, 0x59, 0xC7, 0x73, 0xC8,\n 0xE8, 0xB6, 0xE1, 0x2B, 0x39, 0xC6, 0x35, 0x0E, 0x68, 0x7A, 0xAA, 0x4F, 0x28, 0x23, 0x12, 0x18,\n 0xE3, 0xAA, 0x84, 0x81, 0x6E, 0x82, 0xF0, 0x3F, 0xD9, 0x69, 0xA9, 0xDF, 0xBA, 0x5F, 0xCA, 0x32,\n 0x54, 0xB2, 0x52, 0x3B, 0x3E, 0xD1, 0x5C, 0x65, 0xBC, 0x3E, 0x59, 0x0D, 0x15, 0x9F, 0x37, 0xEC,\n 0x30, 0x9C, 0xCC, 0x1B, 0x39, 0x0D, 0x21, 0x32, 0x29, 0xA2, 0xDD, 0xC7, 0xC1, 0x69, 0xF2, 0x72,\n 0x3F, 0x00, 0x98, 0x1E, 0xF8, 0x9A, 0x79, 0x44, 0x5D, 0x25, 0x80, 0x7B, 0xF5, 0xE1, 0x7C, 0x68,\n 0x25, 0xAA, 0x0D, 0x67, 0x98, 0xE5, 0x59, 0x9B, 0x04, 0xC1, 0x23, 0x33, 0x48, 0xFB, 0x28, 0xD0,\n 0x76, 0xDF, 0x01, 0x56, 0xE7, 0xEC, 0xBF, 0x1A, 0xA2, 0x22, 0x28, 0xCA, 0xB1, 0xB4, 0x4C, 0x30,\n 0x14, 0x6F, 0xD2, 0x2E, 0x01, 0x2A, 0x04, 0xE3, 0xBD, 0xA7, 0x41, 0x2F, 0xC9, 0xEF, 0x53, 0xC0,\n 0x70, 0x48, 0xF1, 0xB2, 0xB6, 0xEA, 0xE7, 0x0F, 0x7A, 0x15, 0xD1, 0xA6, 0xFE, 0x23, 0xC8, 0xF3,\n 0xE1, 0x02, 0x9E, 0xA0, 0x4E, 0xBD, 0xF5, 0xEA, 0x53, 0x74, 0x8E, 0x74, 0xA1, 0xA1, 0xBD, 0xBE,\n 0x66, 0xC4, 0x73, 0x8F, 0x24, 0xA7, 0x2A, 0x2F, 0xE3, 0xD9, 0xF4, 0x28, 0xD9, 0xF8, 0xA3, 0x93,\n 0x03, 0x9E, 0x29, 0xAB\n };\n\n public static readonly byte[] KMSv6Response =\n {\n 0x00, 0x00, 0x06, 0x00, 0x54, 0xD3, 0x40, 0x08, 0xF3, 0xCD, 0x03, 0xEF, 0xC8, 0x15, 0x87, 0x9E,\n 0xCA, 0x2E, 0x85, 0xFB, 0xE6, 0xF6, 0x73, 0x66, 0xFB, 0xDA, 0xBB, 0x7B, 0xB1, 0xBC, 0xD6, 0xF9,\n 0x5C, 0x41, 0xA0, 0xFE, 0xE1, 0x74, 0xC4, 0xBB, 0x91, 0xE5, 0xDE, 0x6D, 0x3A, 0x11, 0xD5, 0xFC,\n 0x68, 0xC0, 0x7B, 0x82, 0xB2, 0x24, 0xD1, 0x85, 0xBA, 0x45, 0xBF, 0xF1, 0x26, 0xFA, 0xA5, 0xC6,\n 0x61, 0x70, 0x69, 0x69, 0x6E, 0x0F, 0x0B, 0x60, 0xB7, 0x3D, 0xE8, 0xF1, 0x47, 0x0B, 0x65, 0xFD,\n 0xA7, 0x30, 0x1E, 0xF6, 0xA4, 0xD0, 0x79, 0xC4, 0x58, 0x8D, 0x81, 0xFD, 0xA7, 0xE7, 0x53, 0xF1,\n 0x67, 0x78, 0xF0, 0x0F, 0x60, 0x8F, 0xC8, 0x16, 0x35, 0x22, 0x94, 0x48, 0xCB, 0x0F, 0x8E, 0xB2,\n 0x1D, 0xF7, 0x3E, 0x28, 0x42, 0x55, 0x6B, 0x07, 0xE3, 0xE8, 0x51, 0xD5, 0xFA, 0x22, 0x0C, 0x86,\n 0x65, 0x0D, 0x3F, 0xDD, 0x8D, 0x9B, 0x1B, 0xC9, 0xD3, 0xB8, 0x3A, 0xEC, 0xF1, 0x11, 0x19, 0x25,\n 0xF7, 0x84, 0x4A, 0x4C, 0x0A, 0xB5, 0x31, 0x94, 0x37, 0x76, 0xCE, 0xE7, 0xAB, 0xA9, 0x69, 0xDF,\n 0xA4, 0xC9, 0x22, 0x6C, 0x23, 0xFF, 0x6B, 0xFC, 0xDA, 0x78, 0xD8, 0xC4, 0x8F, 0x74, 0xBB, 0x26,\n 0x05, 0x00, 0x98, 0x9B, 0xE5, 0xE2, 0xAD, 0x0D, 0x57, 0x95, 0x80, 0x66, 0x8E, 0x43, 0x74, 0x87,\n 0x93, 0x1F, 0xF4, 0xB2, 0x2C, 0x20, 0x5F, 0xD8, 0x9C, 0x4C, 0x56, 0xB3, 0x57, 0x44, 0x62, 0x68,\n 0x8D, 0xAA, 0x40, 0x11, 0x9D, 0x84, 0x62, 0x0E, 0x43, 0x8A, 0x1D, 0xF0, 0x1C, 0x49, 0xD8, 0x56,\n 0xEF, 0x4C, 0xD3, 0x64, 0xBA, 0x0D, 0xEF, 0x87, 0xB5, 0x2C, 0x88, 0xF3, 0x18, 0xFF, 0x3A, 0x8C,\n 0xF5, 0xA6, 0x78, 0x5C, 0x62, 0xE3, 0x9E, 0x4C, 0xB6, 0x31, 0x2D, 0x06, 0x80, 0x92, 0xBC, 0x2E,\n 0x92, 0xA6, 0x56, 0x96\n };\n\n // 2^31 - 8 minutes\n public static readonly ulong TimerMax = (ulong)TimeSpan.FromMinutes(2147483640).Ticks;\n\n public static readonly string ZeroCID = new string('0', 48);\n }\n\n public static class BinaryReaderExt\n {\n public static void Align(this BinaryReader reader, int to)\n {\n int pos = (int)reader.BaseStream.Position;\n reader.BaseStream.Seek(-pos & (to - 1), SeekOrigin.Current);\n }\n\n public static string ReadNullTerminatedString(this BinaryReader reader, int maxLen)\n {\n return Encoding.Unicode.GetString(reader.ReadBytes(maxLen)).Split(new char[] { '\\0' }, 2)[0];\n }\n }\n\n public static class BinaryWriterExt\n {\n public static void Align(this BinaryWriter writer, int to)\n {\n int pos = (int)writer.BaseStream.Position;\n writer.WritePadding(-pos & (to - 1));\n }\n\n public static void WritePadding(this BinaryWriter writer, int len)\n {\n writer.Write(Enumerable.Repeat((byte)0, len).ToArray());\n }\n\n public static void WriteFixedString(this BinaryWriter writer, string str, int bLen)\n {\n writer.Write(Encoding.ASCII.GetBytes(str));\n writer.WritePadding(bLen - str.Length);\n }\n\n public static void WriteFixedString16(this BinaryWriter writer, string str, int bLen)\n {\n byte[] bstr = Utils.EncodeString(str);\n writer.Write(bstr);\n writer.WritePadding(bLen - bstr.Length);\n }\n\n public static byte[] GetBytes(this BinaryWriter writer)\n {\n return ((MemoryStream)writer.BaseStream).ToArray();\n }\n }\n\n public static class ByteArrayExt\n {\n public static byte[] CastToArray(this T data) where T : struct\n {\n int size = Marshal.SizeOf(typeof(T));\n byte[] result = new byte[size];\n GCHandle handle = GCHandle.Alloc(result, GCHandleType.Pinned);\n try\n {\n Marshal.StructureToPtr(data, handle.AddrOfPinnedObject(), false);\n }\n finally\n {\n handle.Free();\n }\n return result;\n }\n }\n\n public static class FileStreamExt\n {\n public static byte[] ReadAllBytes(this FileStream fs)\n {\n BinaryReader br = new BinaryReader(fs);\n return br.ReadBytes((int)fs.Length);\n }\n\n public static void WriteAllBytes(this FileStream fs, byte[] data)\n {\n fs.Seek(0, SeekOrigin.Begin);\n fs.SetLength(data.Length);\n fs.Write(data, 0, data.Length);\n }\n }\n\n public static class Utils\n {\n [DllImport(\"kernel32.dll\")]\n public static extern uint GetSystemDefaultLCID();\n\n [DllImport(\"kernel32.dll\")]\n public static extern bool Wow64EnableWow64FsRedirection(bool Wow64FsEnableRedirection);\n\n public static string DecodeString(byte[] data)\n {\n return Encoding.Unicode.GetString(data).Trim('\\0');\n }\n\n public static byte[] EncodeString(string str)\n {\n return Encoding.Unicode.GetBytes(str + '\\0');\n }\n\n public static uint CRC32(byte[] data)\n {\n const uint polynomial = 0x04C11DB7;\n uint crc = 0xffffffff;\n\n foreach (byte b in data)\n {\n crc ^= (uint)b << 24;\n for (int bit = 0; bit < 8; bit++)\n {\n if ((crc & 0x80000000) != 0)\n {\n crc = (crc << 1) ^ polynomial;\n }\n else\n {\n crc <<= 1;\n }\n }\n }\n return ~crc;\n }\n\n public static string GetArchitecture()\n {\n string arch = Environment.GetEnvironmentVariable(\"PROCESSOR_ARCHITECTURE\", EnvironmentVariableTarget.Machine).ToUpperInvariant();\n return arch == \"AMD64\" ? \"X64\" : arch;\n }\n\n public static PSVersion DetectVersion()\n {\n int build = Environment.OSVersion.Version.Build;\n\n if (build >= 9600) return PSVersion.WinModern;\n if (build >= 6000 && build <= 6003) return PSVersion.Vista;\n if (build >= 7600 && build <= 7602) return PSVersion.Win7;\n if (build == 9200) return PSVersion.Win8;\n\n throw new NotSupportedException(\"Unable to auto-detect version info\");\n }\n }\n\n public static class Logger\n {\n public static bool HideOutput = false;\n\n public static void WriteLine(string line)\n {\n if (!HideOutput) Console.WriteLine(line);\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/RearmReset.cs", "namespace LibTSforge.Modifiers\n{\n using System.Collections.Generic;\n using System.Linq;\n using PhysicalStore;\n using SPP;\n\n public static class RearmReset\n {\n public static void Reset(PSVersion version, bool production)\n {\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n List blocks;\n\n if (version == PSVersion.Vista)\n {\n blocks = store.FindBlocks(\"740D70D8-6448-4b2f-9063-4A7A463600C5\").ToList();\n }\n else if (version == PSVersion.Win7)\n {\n blocks = store.FindBlocks(0xA0000).ToList();\n }\n else\n {\n blocks = store.FindBlocks(\"__##USERSEP-RESERVED##__$$REARM-COUNT$$\").ToList();\n }\n\n foreach (PSBlock block in blocks)\n {\n if (version == PSVersion.Vista)\n {\n store.DeleteBlock(block.KeyAsStr, block.ValueAsStr);\n }\n else if (version == PSVersion.Win7)\n {\n store.SetBlock(block.KeyAsStr, block.ValueAsInt, new byte[8]);\n }\n else\n {\n store.SetBlock(block.KeyAsStr, block.ValueAsStr, new byte[8]);\n }\n }\n\n Logger.WriteLine(\"Successfully reset all rearm counters.\");\n }\n }\n }\n}\n"], ["/TSforge/LibTSforge/TokenStore/Common.cs", "namespace LibTSforge.TokenStore\n{\n using System.Collections.Generic;\n using System.IO;\n\n public class TokenEntry\n {\n public string Name;\n public string Extension;\n public byte[] Data;\n public bool Populated;\n }\n\n public class TokenMeta\n {\n public string Name;\n public readonly Dictionary Data = new Dictionary();\n\n public byte[] Serialize()\n {\n BinaryWriter writer = new BinaryWriter(new MemoryStream());\n writer.Write(1);\n byte[] nameBytes = Utils.EncodeString(Name);\n writer.Write(nameBytes.Length);\n writer.Write(nameBytes);\n\n foreach (KeyValuePair kv in Data)\n {\n byte[] keyBytes = Utils.EncodeString(kv.Key);\n byte[] valueBytes = Utils.EncodeString(kv.Value);\n writer.Write(keyBytes.Length);\n writer.Write(valueBytes.Length);\n writer.Write(keyBytes);\n writer.Write(valueBytes);\n }\n\n return writer.GetBytes();\n }\n\n private void Deserialize(byte[] data)\n {\n BinaryReader reader = new BinaryReader(new MemoryStream(data));\n reader.ReadInt32();\n int nameLen = reader.ReadInt32();\n Name = reader.ReadNullTerminatedString(nameLen);\n\n while (reader.BaseStream.Position < data.Length - 0x8)\n {\n int keyLen = reader.ReadInt32();\n int valueLen = reader.ReadInt32();\n string key = reader.ReadNullTerminatedString(keyLen);\n string value = reader.ReadNullTerminatedString(valueLen);\n Data[key] = value;\n }\n }\n\n public TokenMeta(byte[] data)\n {\n Deserialize(data);\n }\n\n public TokenMeta()\n {\n\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/TamperedFlagsDelete.cs", "namespace LibTSforge.Modifiers\n{\n using System.Linq;\n using PhysicalStore;\n using SPP;\n\n public static class TamperedFlagsDelete\n {\n public static void DeleteTamperFlags(PSVersion version, bool production)\n {\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n if (version == PSVersion.Vista)\n {\n DeleteFlag(store, \"6BE8425B-E3CF-4e86-A6AF-5863E3DCB606\");\n }\n else if (version == PSVersion.Win7)\n {\n SetFlag(store, 0xA0001);\n }\n else\n {\n DeleteFlag(store, \"__##USERSEP-RESERVED##__$$RECREATED-FLAG$$\");\n DeleteFlag(store, \"__##USERSEP-RESERVED##__$$RECOVERED-FLAG$$\");\n }\n\n Logger.WriteLine(\"Successfully cleared the tamper state.\");\n }\n\n SPPUtils.RestartSPP(version);\n }\n\n private static void DeleteFlag(IPhysicalStore store, string flag)\n {\n store.FindBlocks(flag).ToList().ForEach(block => store.DeleteBlock(block.KeyAsStr, block.ValueAsStr));\n }\n\n private static void SetFlag(IPhysicalStore store, uint flag)\n {\n store.FindBlocks(flag).ToList().ForEach(block => store.SetBlock(block.KeyAsStr, block.ValueAsInt, new byte[8]));\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/KeyChangeLockDelete.cs", "namespace LibTSforge.Modifiers\n{\n using System.Collections.Generic;\n using System.Linq;\n using PhysicalStore;\n using SPP;\n using System;\n\n public static class KeyChangeLockDelete\n {\n public static void Delete(PSVersion version, bool production)\n {\n if (version == PSVersion.Vista) throw new NotSupportedException(\"This feature is not supported on Windows Vista/Server 2008.\");\n\n SPPUtils.KillSPP(version);\n Logger.WriteLine(\"Writing TrustedStore data...\");\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n List values = new List\n {\n \"msft:spp/timebased/AB\",\n \"msft:spp/timebased/CD\"\n };\n List blocks = new List();\n foreach (string value in values)\n {\n blocks.AddRange(store.FindBlocks(value).ToList());\n }\n foreach (PSBlock block in blocks)\n {\n store.DeleteBlock(block.KeyAsStr, block.ValueAsStr);\n }\n }\n Logger.WriteLine(\"Successfully removed the key change lock.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/UniqueIdDelete.cs", "namespace LibTSforge.Modifiers\n{\n using System;\n using PhysicalStore;\n using SPP;\n\n public static class UniqueIdDelete\n {\n public static void DeleteUniqueId(PSVersion version, bool production, Guid actId)\n {\n if (version == PSVersion.Vista) throw new NotSupportedException(\"This feature is not supported on Windows Vista/Server 2008.\");\n\n Guid appId;\n\n if (actId == Guid.Empty)\n {\n appId = SLApi.WINDOWS_APP_ID;\n actId = SLApi.GetDefaultActivationID(appId, true);\n\n if (actId == Guid.Empty)\n {\n throw new Exception(\"No applicable activation IDs found.\");\n }\n }\n else\n {\n appId = SLApi.GetAppId(actId);\n }\n\n Guid pkeyId = SLApi.GetInstalledPkeyID(actId);\n\n SPPUtils.KillSPP(version);\n\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string key = string.Format(\"SPPSVC\\\\{0}\\\\{1}\", appId, actId);\n PSBlock keyBlock = store.GetBlock(key, pkeyId.ToString());\n\n if (keyBlock == null)\n {\n throw new Exception(\"No product key found.\");\n }\n\n VariableBag pkb = new VariableBag(keyBlock.Data, version);\n\n pkb.DeleteBlock(\"SppPkeyUniqueIdToken\");\n\n store.SetBlock(key, pkeyId.ToString(), pkb.Serialize());\n }\n\n Logger.WriteLine(\"Successfully removed Unique ID for product key ID \" + pkeyId);\n }\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/IPhysicalStore.cs", "namespace LibTSforge.PhysicalStore\n{\n using System;\n using System.Collections.Generic;\n\n public class PSBlock\n {\n public BlockType Type;\n public uint Flags;\n public uint Unknown = 0;\n public byte[] Key;\n public string KeyAsStr\n {\n get\n {\n return Utils.DecodeString(Key);\n }\n set\n {\n Key = Utils.EncodeString(value);\n }\n }\n public byte[] Value;\n public string ValueAsStr\n {\n get\n {\n return Utils.DecodeString(Value);\n }\n set\n {\n Value = Utils.EncodeString(value);\n }\n }\n public uint ValueAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Value, 0);\n }\n set\n {\n Value = BitConverter.GetBytes(value);\n }\n }\n public byte[] Data;\n public string DataAsStr\n {\n get\n {\n return Utils.DecodeString(Data);\n }\n set\n {\n Data = Utils.EncodeString(value);\n }\n }\n public uint DataAsInt\n {\n get\n {\n return BitConverter.ToUInt32(Data, 0);\n }\n set\n {\n Data = BitConverter.GetBytes(value);\n }\n }\n }\n\n public interface IPhysicalStore : IDisposable\n {\n PSBlock GetBlock(string key, string value);\n PSBlock GetBlock(string key, uint value);\n void AddBlock(PSBlock block);\n void AddBlocks(IEnumerable blocks);\n void SetBlock(string key, string value, byte[] data);\n void SetBlock(string key, string value, string data);\n void SetBlock(string key, string value, uint data);\n void SetBlock(string key, uint value, byte[] data);\n void SetBlock(string key, uint value, string data);\n void SetBlock(string key, uint value, uint data);\n void DeleteBlock(string key, string value);\n void DeleteBlock(string key, uint value);\n byte[] Serialize();\n void Deserialize(byte[] data);\n byte[] ReadRaw();\n void WriteRaw(byte[] data);\n IEnumerable FindBlocks(string valueSearch);\n IEnumerable FindBlocks(uint valueSearch);\n }\n}\n"], ["/TSforge/LibTSforge/Modifiers/GracePeriodReset.cs", "namespace LibTSforge.Modifiers\n{\n using System.Collections.Generic;\n using System.Linq;\n using PhysicalStore;\n using SPP;\n\n public static class GracePeriodReset\n {\n public static void Reset(PSVersion version, bool production)\n {\n SPPUtils.KillSPP(version);\n Logger.WriteLine(\"Writing TrustedStore data...\");\n\n using (IPhysicalStore store = SPPUtils.GetStore(version, production))\n {\n string value = \"msft:sl/timer\";\n List blocks = store.FindBlocks(value).ToList();\n\n foreach (PSBlock block in blocks)\n {\n store.DeleteBlock(block.KeyAsStr, block.ValueAsStr);\n }\n }\n\n SPPUtils.RestartSPP(version);\n Logger.WriteLine(\"Successfully reset all grace and evaluation period timers.\");\n }\n }\n}\n"], ["/TSforge/LibTSforge/SPP/SPSys.cs", "namespace LibTSforge.SPP\n{\n using Microsoft.Win32.SafeHandles;\n using System;\n using System.Runtime.InteropServices;\n\n public class SPSys\n {\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n private static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);\n private static SafeFileHandle CreateFileSafe(string device)\n {\n return new SafeFileHandle(CreateFile(device, 0xC0000000, 0, IntPtr.Zero, 3, 0, IntPtr.Zero), true);\n }\n\n [return: MarshalAs(UnmanagedType.Bool)]\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n private static extern bool DeviceIoControl([In] SafeFileHandle hDevice, [In] uint dwIoControlCode, [In] IntPtr lpInBuffer, [In] int nInBufferSize, [Out] IntPtr lpOutBuffer, [In] int nOutBufferSize, out int lpBytesReturned, [In] IntPtr lpOverlapped);\n\n public static bool IsSpSysRunning()\n {\n SafeFileHandle file = CreateFileSafe(@\"\\\\.\\SpDevice\");\n IntPtr buffer = Marshal.AllocHGlobal(1);\n int bytesReturned;\n DeviceIoControl(file, 0x80006008, IntPtr.Zero, 0, buffer, 1, out bytesReturned, IntPtr.Zero);\n bool running = Marshal.ReadByte(buffer) != 0;\n Marshal.FreeHGlobal(buffer);\n file.Close();\n return running;\n }\n\n public static int ControlSpSys(bool start)\n {\n SafeFileHandle file = CreateFileSafe(@\"\\\\.\\SpDevice\");\n IntPtr buffer = Marshal.AllocHGlobal(4);\n int bytesReturned;\n DeviceIoControl(file, start ? 0x8000a000 : 0x8000a004, IntPtr.Zero, 0, buffer, 4, out bytesReturned, IntPtr.Zero);\n int result = Marshal.ReadInt32(buffer);\n Marshal.FreeHGlobal(buffer);\n file.Close();\n return result;\n }\n }\n}\n"], ["/TSforge/LibTSforge/Crypto/Keys.cs", "namespace LibTSforge.Crypto\n{\n public static class Keys\n {\n public static readonly byte[] PRODUCTION = {\n 0x07, 0x02, 0x00, 0x00, 0x00, 0xA4, 0x00, 0x00, 0x52, 0x53, 0x41, 0x32, 0x00, 0x04, 0x00, 0x00,\n 0x01, 0x00, 0x01, 0x00, 0x29, 0x87, 0xBA, 0x3F, 0x52, 0x90, 0x57, 0xD8, 0x12, 0x26, 0x6B, 0x38,\n 0xB2, 0x3B, 0xF9, 0x67, 0x08, 0x4F, 0xDD, 0x8B, 0xF5, 0xE3, 0x11, 0xB8, 0x61, 0x3A, 0x33, 0x42,\n 0x51, 0x65, 0x05, 0x86, 0x1E, 0x00, 0x41, 0xDE, 0xC5, 0xDD, 0x44, 0x60, 0x56, 0x3D, 0x14, 0x39,\n 0xB7, 0x43, 0x65, 0xE9, 0xF7, 0x2B, 0xA5, 0xF0, 0xA3, 0x65, 0x68, 0xE9, 0xE4, 0x8B, 0x5C, 0x03,\n 0x2D, 0x36, 0xFE, 0x28, 0x4C, 0xD1, 0x3C, 0x3D, 0xC1, 0x90, 0x75, 0xF9, 0x6E, 0x02, 0xE0, 0x58,\n 0x97, 0x6A, 0xCA, 0x80, 0x02, 0x42, 0x3F, 0x6C, 0x15, 0x85, 0x4D, 0x83, 0x23, 0x6A, 0x95, 0x9E,\n 0x38, 0x52, 0x59, 0x38, 0x6A, 0x99, 0xF0, 0xB5, 0xCD, 0x53, 0x7E, 0x08, 0x7C, 0xB5, 0x51, 0xD3,\n 0x8F, 0xA3, 0x0D, 0xA0, 0xFA, 0x8D, 0x87, 0x3C, 0xFC, 0x59, 0x21, 0xD8, 0x2E, 0xD9, 0x97, 0x8B,\n 0x40, 0x60, 0xB1, 0xD7, 0x2B, 0x0A, 0x6E, 0x60, 0xB5, 0x50, 0xCC, 0x3C, 0xB1, 0x57, 0xE4, 0xB7,\n 0xDC, 0x5A, 0x4D, 0xE1, 0x5C, 0xE0, 0x94, 0x4C, 0x5E, 0x28, 0xFF, 0xFA, 0x80, 0x6A, 0x13, 0x53,\n 0x52, 0xDB, 0xF3, 0x04, 0x92, 0x43, 0x38, 0xB9, 0x1B, 0xD9, 0x85, 0x54, 0x7B, 0x14, 0xC7, 0x89,\n 0x16, 0x8A, 0x4B, 0x82, 0xA1, 0x08, 0x02, 0x99, 0x23, 0x48, 0xDD, 0x75, 0x9C, 0xC8, 0xC1, 0xCE,\n 0xB0, 0xD7, 0x1B, 0xD8, 0xFB, 0x2D, 0xA7, 0x2E, 0x47, 0xA7, 0x18, 0x4B, 0xF6, 0x29, 0x69, 0x44,\n 0x30, 0x33, 0xBA, 0xA7, 0x1F, 0xCE, 0x96, 0x9E, 0x40, 0xE1, 0x43, 0xF0, 0xE0, 0x0D, 0x0A, 0x32,\n 0xB4, 0xEE, 0xA1, 0xC3, 0x5E, 0x9B, 0xC7, 0x7F, 0xF5, 0x9D, 0xD8, 0xF2, 0x0F, 0xD9, 0x8F, 0xAD,\n 0x75, 0x0A, 0x00, 0xD5, 0x25, 0x43, 0xF7, 0xAE, 0x51, 0x7F, 0xB7, 0xDE, 0xB7, 0xAD, 0xFB, 0xCE,\n 0x83, 0xE1, 0x81, 0xFF, 0xDD, 0xA2, 0x77, 0xFE, 0xEB, 0x27, 0x1F, 0x10, 0xFA, 0x82, 0x37, 0xF4,\n 0x7E, 0xCC, 0xE2, 0xA1, 0x58, 0xC8, 0xAF, 0x1D, 0x1A, 0x81, 0x31, 0x6E, 0xF4, 0x8B, 0x63, 0x34,\n 0xF3, 0x05, 0x0F, 0xE1, 0xCC, 0x15, 0xDC, 0xA4, 0x28, 0x7A, 0x9E, 0xEB, 0x62, 0xD8, 0xD8, 0x8C,\n 0x85, 0xD7, 0x07, 0x87, 0x90, 0x2F, 0xF7, 0x1C, 0x56, 0x85, 0x2F, 0xEF, 0x32, 0x37, 0x07, 0xAB,\n 0xB0, 0xE6, 0xB5, 0x02, 0x19, 0x35, 0xAF, 0xDB, 0xD4, 0xA2, 0x9C, 0x36, 0x80, 0xC6, 0xDC, 0x82,\n 0x08, 0xE0, 0xC0, 0x5F, 0x3C, 0x59, 0xAA, 0x4E, 0x26, 0x03, 0x29, 0xB3, 0x62, 0x58, 0x41, 0x59,\n 0x3A, 0x37, 0x43, 0x35, 0xE3, 0x9F, 0x34, 0xE2, 0xA1, 0x04, 0x97, 0x12, 0x9D, 0x8C, 0xAD, 0xF7,\n 0xFB, 0x8C, 0xA1, 0xA2, 0xE9, 0xE4, 0xEF, 0xD9, 0xC5, 0xE5, 0xDF, 0x0E, 0xBF, 0x4A, 0xE0, 0x7A,\n 0x1E, 0x10, 0x50, 0x58, 0x63, 0x51, 0xE1, 0xD4, 0xFE, 0x57, 0xB0, 0x9E, 0xD7, 0xDA, 0x8C, 0xED,\n 0x7D, 0x82, 0xAC, 0x2F, 0x25, 0x58, 0x0A, 0x58, 0xE6, 0xA4, 0xF4, 0x57, 0x4B, 0xA4, 0x1B, 0x65,\n 0xB9, 0x4A, 0x87, 0x46, 0xEB, 0x8C, 0x0F, 0x9A, 0x48, 0x90, 0xF9, 0x9F, 0x76, 0x69, 0x03, 0x72,\n 0x77, 0xEC, 0xC1, 0x42, 0x4C, 0x87, 0xDB, 0x0B, 0x3C, 0xD4, 0x74, 0xEF, 0xE5, 0x34, 0xE0, 0x32,\n 0x45, 0xB0, 0xF8, 0xAB, 0xD5, 0x26, 0x21, 0xD7, 0xD2, 0x98, 0x54, 0x8F, 0x64, 0x88, 0x20, 0x2B,\n 0x14, 0xE3, 0x82, 0xD5, 0x2A, 0x4B, 0x8F, 0x4E, 0x35, 0x20, 0x82, 0x7E, 0x1B, 0xFE, 0xFA, 0x2C,\n 0x79, 0x6C, 0x6E, 0x66, 0x94, 0xBB, 0x0A, 0xEB, 0xBA, 0xD9, 0x70, 0x61, 0xE9, 0x47, 0xB5, 0x82,\n 0xFC, 0x18, 0x3C, 0x66, 0x3A, 0x09, 0x2E, 0x1F, 0x61, 0x74, 0xCA, 0xCB, 0xF6, 0x7A, 0x52, 0x37,\n 0x1D, 0xAC, 0x8D, 0x63, 0x69, 0x84, 0x8E, 0xC7, 0x70, 0x59, 0xDD, 0x2D, 0x91, 0x1E, 0xF7, 0xB1,\n 0x56, 0xED, 0x7A, 0x06, 0x9D, 0x5B, 0x33, 0x15, 0xDD, 0x31, 0xD0, 0xE6, 0x16, 0x07, 0x9B, 0xA5,\n 0x94, 0x06, 0x7D, 0xC1, 0xE9, 0xD6, 0xC8, 0xAF, 0xB4, 0x1E, 0x2D, 0x88, 0x06, 0xA7, 0x63, 0xB8,\n 0xCF, 0xC8, 0xA2, 0x6E, 0x84, 0xB3, 0x8D, 0xE5, 0x47, 0xE6, 0x13, 0x63, 0x8E, 0xD1, 0x7F, 0xD4,\n 0x81, 0x44, 0x38, 0xBF\n };\n\n public static readonly byte[] TEST = {\n 0x07, 0x02, 0x00, 0x00, 0x00, 0xA4, 0x00, 0x00, 0x52, 0x53, 0x41, 0x32, 0x00, 0x04, 0x00, 0x00,\n 0x01, 0x00, 0x01, 0x00, 0x0F, 0xBE, 0x77, 0xB8, 0xDD, 0x54, 0x36, 0xDD, 0x67, 0xD4, 0x17, 0x66,\n 0xC4, 0x13, 0xD1, 0x3F, 0x1E, 0x16, 0x0C, 0x16, 0x35, 0xAB, 0x6D, 0x3D, 0x34, 0x51, 0xED, 0x3F,\n 0x57, 0x14, 0xB6, 0xB7, 0x08, 0xE9, 0xD9, 0x7A, 0x80, 0xB3, 0x5F, 0x9B, 0x3A, 0xFD, 0x9E, 0x37,\n 0x3A, 0x53, 0x72, 0x67, 0x92, 0x60, 0xC3, 0xEF, 0xB5, 0x8E, 0x1E, 0xCF, 0x9D, 0x9C, 0xD3, 0x90,\n 0xE5, 0xDD, 0xF4, 0xDB, 0xF3, 0xD6, 0x65, 0xB3, 0xC1, 0xBD, 0x69, 0xE1, 0x76, 0x95, 0xD9, 0x37,\n 0xB8, 0x5E, 0xCA, 0x3D, 0x98, 0xFC, 0x50, 0x5C, 0x98, 0xAE, 0xE3, 0x7C, 0x4C, 0x27, 0xC3, 0xD0,\n 0xCE, 0x78, 0x06, 0x51, 0x68, 0x23, 0xE6, 0x70, 0xF8, 0x7C, 0xAE, 0x36, 0xBE, 0x41, 0x57, 0xE2,\n 0xC3, 0x2D, 0xAF, 0x21, 0xB1, 0xB3, 0x15, 0x81, 0x19, 0x26, 0x6B, 0x10, 0xB3, 0xE9, 0xD1, 0x45,\n 0x21, 0x77, 0x9C, 0xF6, 0xE1, 0xDD, 0xB6, 0x78, 0x9D, 0x1D, 0x32, 0x61, 0xBC, 0x2B, 0xDB, 0x86,\n 0xFB, 0x07, 0x24, 0x10, 0x19, 0x4F, 0x09, 0x6D, 0x03, 0x90, 0xD4, 0x5E, 0x30, 0x85, 0xC5, 0x58,\n 0x7E, 0x5D, 0xAE, 0x9F, 0x64, 0x93, 0x04, 0x82, 0x09, 0x0E, 0x1C, 0x66, 0xA8, 0x95, 0x91, 0x51,\n 0xB2, 0xED, 0x9A, 0x75, 0x04, 0x87, 0x50, 0xAC, 0xCC, 0x20, 0x06, 0x45, 0xB9, 0x7B, 0x42, 0x53,\n 0x9A, 0xD1, 0x29, 0xFC, 0xEF, 0xB9, 0x47, 0x16, 0x75, 0x69, 0x05, 0x87, 0x2B, 0xCB, 0x54, 0x9C,\n 0x21, 0x2D, 0x50, 0x8E, 0x12, 0xDE, 0xD3, 0x6B, 0xEC, 0x92, 0xA1, 0xB1, 0xE9, 0x4B, 0xBF, 0x6B,\n 0x9A, 0x38, 0xC7, 0x13, 0xFA, 0x78, 0xA1, 0x3C, 0x1E, 0xBB, 0x38, 0x31, 0xBB, 0x0C, 0x9F, 0x70,\n 0x1A, 0x31, 0x00, 0xD7, 0x5A, 0xA5, 0x84, 0x24, 0x89, 0x80, 0xF5, 0x88, 0xC2, 0x31, 0x18, 0xDC,\n 0x53, 0x05, 0x5D, 0xFA, 0x81, 0xDC, 0xE1, 0xCE, 0xA4, 0xAA, 0xBA, 0x07, 0xDA, 0x28, 0x4F, 0x64,\n 0x0E, 0x84, 0x9B, 0x06, 0xDE, 0xC8, 0x78, 0x66, 0x2F, 0x17, 0x25, 0xA8, 0x9C, 0x99, 0xFC, 0xBC,\n 0x7D, 0x01, 0x42, 0xD7, 0x35, 0xBF, 0x19, 0xF6, 0x3F, 0x20, 0xD9, 0x98, 0x9B, 0x5D, 0xDD, 0x39,\n 0xBE, 0x81, 0x00, 0x0B, 0xDE, 0x6F, 0x14, 0xCA, 0x7E, 0xF8, 0xC0, 0x26, 0xA8, 0x1D, 0xD1, 0x16,\n 0x88, 0x64, 0x87, 0x36, 0x45, 0x37, 0x50, 0xDA, 0x6C, 0xEB, 0x85, 0xB5, 0x43, 0x29, 0x88, 0x6F,\n 0x2F, 0xFE, 0x8D, 0x12, 0x8B, 0x72, 0xB7, 0x5A, 0xCB, 0x66, 0xC2, 0x2E, 0x1D, 0x7D, 0x42, 0xA6,\n 0xF4, 0xFE, 0x26, 0x5D, 0x54, 0x9E, 0x77, 0x1D, 0x97, 0xC2, 0xF3, 0xFD, 0x60, 0xB3, 0x22, 0x88,\n 0xCA, 0x27, 0x99, 0xDF, 0xC8, 0xB1, 0xD7, 0xC6, 0x54, 0xA6, 0x50, 0xB9, 0x54, 0xF5, 0xDE, 0xFE,\n 0xE1, 0x81, 0xA2, 0xBE, 0x81, 0x9F, 0x48, 0xFF, 0x2F, 0xB8, 0xA4, 0xB3, 0x17, 0xD8, 0xC1, 0xB9,\n 0x5D, 0x21, 0x3D, 0xA2, 0xED, 0x1C, 0x96, 0x66, 0xEE, 0x1F, 0x47, 0xCF, 0x62, 0xFA, 0xD6, 0xC1,\n 0x87, 0x5B, 0xC4, 0xE5, 0xD9, 0x08, 0x38, 0x22, 0xFA, 0x21, 0xBD, 0xF2, 0x88, 0xDA, 0xE2, 0x24,\n 0x25, 0x1F, 0xF1, 0x0B, 0x2D, 0xAE, 0x04, 0xBE, 0xA6, 0x7F, 0x75, 0x8C, 0xD9, 0x97, 0xE1, 0xCA,\n 0x35, 0xB9, 0xFC, 0x6F, 0x01, 0x68, 0x11, 0xD3, 0x68, 0x32, 0xD0, 0xC1, 0x69, 0xA3, 0xCF, 0x9B,\n 0x10, 0xE4, 0x69, 0xA7, 0xCF, 0xE1, 0xFE, 0x2A, 0x07, 0x9E, 0xC1, 0x37, 0x84, 0x68, 0xE5, 0xC5,\n 0xAB, 0x25, 0xEC, 0x7D, 0x7D, 0x74, 0x6A, 0xD1, 0xD5, 0x4D, 0xD7, 0xE1, 0x7D, 0xDE, 0x30, 0x4B,\n 0xE6, 0x5D, 0xCD, 0x91, 0x59, 0xF6, 0x80, 0xFD, 0xC6, 0x3C, 0xDD, 0x94, 0x7F, 0x15, 0x9D, 0xEF,\n 0x2F, 0x00, 0x62, 0xD7, 0xDA, 0xB9, 0xB3, 0xD9, 0x8D, 0xE8, 0xD7, 0x3C, 0x96, 0x45, 0x5D, 0x1E,\n 0x50, 0xFB, 0xAA, 0x43, 0xD3, 0x47, 0x77, 0x81, 0xE9, 0x67, 0xE4, 0xFE, 0xDF, 0x42, 0x79, 0xCB,\n 0xA7, 0xAD, 0x5D, 0x48, 0xF5, 0xB7, 0x74, 0x96, 0x12, 0x23, 0x06, 0x70, 0x42, 0x68, 0x7A, 0x44,\n 0xFC, 0xA0, 0x31, 0x7F, 0x68, 0xCA, 0xA2, 0x14, 0x5D, 0xA3, 0xCF, 0x42, 0x23, 0xAB, 0x47, 0xF6,\n 0xB2, 0xFC, 0x6D, 0xF1\n };\n }\n}\n"], ["/TSforge/LibTSforge/TokenStore/ITokenStore.cs", "namespace LibTSforge.TokenStore\n{\n using System;\n\n public interface ITokenStore : IDisposable\n {\n void Deserialize();\n void Serialize();\n void AddEntry(TokenEntry entry);\n void AddEntries(TokenEntry[] entries);\n void DeleteEntry(string name, string ext);\n void DeleteUnpopEntry(string name, string ext);\n TokenEntry GetEntry(string name, string ext);\n TokenMeta GetMetaEntry(string name);\n void SetEntry(string name, string ext, byte[] data);\n }\n}\n"], ["/TSforge/LibTSforge/PhysicalStore/Common.cs", "namespace LibTSforge.PhysicalStore\n{\n using System.Runtime.InteropServices;\n\n public enum BlockType : uint\n {\n NONE,\n NAMED,\n ATTRIBUTE,\n TIMER\n }\n\n [StructLayout(LayoutKind.Sequential, Pack = 1)]\n public struct Timer\n {\n public ulong Unknown;\n public ulong Time1;\n public ulong Time2;\n public ulong Expiry;\n }\n\n [StructLayout(LayoutKind.Sequential, Pack = 1)]\n public struct VistaTimer\n {\n public ulong Time;\n public ulong Expiry;\n }\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 19:06:43", "created_task_model": "DeepSeek-R1", "function_skeleton": "public static byte[] EncryptPhysicalStore (byte[] data, bool production, PSVersion version) {}", "code_description": "This code segment functions to: Encrypt input data using cryptographic algorithms, generate security signatures based on version-specific protocols, and package multiple encrypted components into a structured binary format with version-specific metadata."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\n public static byte[] EncryptPhysicalStore(byte[] data, bool production, PSVersion version)\n {\n byte[] rsaKey = production ? Keys.PRODUCTION : Keys.TEST;\n byte[] aesKey = CryptoUtils.GenerateRandomBytes(32);\n byte[] encAesKey = CryptoUtils.RSAEncrypt(rsaKey, aesKey);\n byte[] aesKeySig = CryptoUtils.RSASignature(rsaKey, encAesKey);\n \n byte[] hmacKey = CryptoUtils.GenerateRandomBytes(0x10);\n byte[] hmacSig;\n if (version != PSVersion.Vista)\n {\n hmacSig = CryptoUtils.HMACCompute(hmacKey, data);\n }\n else\n {\n hmacSig = CryptoUtils.SaltSHACompute(hmacKey, data);\n }\n\n byte[] payload = new byte[0x28 + data.Length];\n Buffer.BlockCopy(hmacKey, 0, payload, 0, 0x10);\n Buffer.BlockCopy(hmacSig, 0, payload, 0x10, 0x14);\n Buffer.BlockCopy(data, 0, payload, 0x28, data.Length);\n byte[] encPayload = CryptoUtils.AESEncrypt(payload, aesKey);\n\n using (MemoryStream ms = new MemoryStream())\n {\n ms.Write(new byte[0x10], 0, 0x10); // Reserved header space\n ms.Write(aesKeySig, 0, 0x80);\n ms.Write(encAesKey, 0, 0x80);\n ms.Write(encPayload, 0, encPayload.Length);\n return ms.ToArray();\n }\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 19-08-07"}, "editdistance_info": {"edit_distance": 21.5084, "calculate_time": "2025-08-20 19:08:07", "true_code_clean": "public static byte[] EncryptPhysicalStore(byte[] data, bool production, PSVersion version)\n {\n Dictionary versionTable = new Dictionary\n {\n {PSVersion.Vista, 2},\n {PSVersion.Win7, 5},\n {PSVersion.Win8, 1},\n {PSVersion.WinBlue, 2},\n {PSVersion.WinModern, 3}\n };\n byte[] rsaKey = production ? Keys.PRODUCTION : Keys.TEST;\n byte[] aesKey = Encoding.UTF8.GetBytes(\"massgrave.dev :3\");\n byte[] hmacKey = CryptoUtils.GenerateRandomKey(0x10);\n byte[] encAesKey = CryptoUtils.RSAEncrypt(rsaKey, aesKey);\n byte[] aesKeySig = CryptoUtils.RSASign(rsaKey, encAesKey);\n byte[] hmacSig = version != PSVersion.Vista ? CryptoUtils.HMACSign(hmacKey, data) : CryptoUtils.SaltSHASum(hmacKey, data);\n byte[] decData = { };\n decData = decData.Concat(hmacKey).Concat(hmacSig).Concat(BitConverter.GetBytes(0)).Concat(data).ToArray();\n byte[] encData = CryptoUtils.AESEncrypt(decData, aesKey);\n BinaryWriter bw = new BinaryWriter(new MemoryStream());\n bw.Write(versionTable[version]);\n bw.Write(Encoding.UTF8.GetBytes(\"UNTRUSTSTORE\"));\n bw.Write(aesKeySig);\n bw.Write(encAesKey);\n bw.Write(encData);\n return bw.GetBytes();\n }", "predict_code_clean": "public static byte[] EncryptPhysicalStore(byte[] data, bool production, PSVersion version)\n {\n byte[] rsaKey = production ? Keys.PRODUCTION : Keys.TEST;\n byte[] aesKey = CryptoUtils.GenerateRandomBytes(32);\n byte[] encAesKey = CryptoUtils.RSAEncrypt(rsaKey, aesKey);\n byte[] aesKeySig = CryptoUtils.RSASignature(rsaKey, encAesKey);\n byte[] hmacKey = CryptoUtils.GenerateRandomBytes(0x10);\n byte[] hmacSig;\n if (version != PSVersion.Vista)\n {\n hmacSig = CryptoUtils.HMACCompute(hmacKey, data);\n }\n else\n {\n hmacSig = CryptoUtils.SaltSHACompute(hmacKey, data);\n }\n byte[] payload = new byte[0x28 + data.Length];\n Buffer.BlockCopy(hmacKey, 0, payload, 0, 0x10);\n Buffer.BlockCopy(hmacSig, 0, payload, 0x10, 0x14);\n Buffer.BlockCopy(data, 0, payload, 0x28, data.Length);\n byte[] encPayload = CryptoUtils.AESEncrypt(payload, aesKey);\n using (MemoryStream ms = new MemoryStream())\n {\n ms.Write(new byte[0x10], 0, 0x10); \n ms.Write(aesKeySig, 0, 0x80);\n ms.Write(encAesKey, 0, 0x80);\n ms.Write(encPayload, 0, encPayload.Length);\n return ms.ToArray();\n }\n }"}}