From 6ab80c5f5b3684d8fb5970dffcaf161a38176276 Mon Sep 17 00:00:00 2001 From: JFronny <33260128+JFronny@users.noreply.github.com> Date: Sun, 24 May 2020 14:07:04 +0200 Subject: [PATCH] Add Files --- .gitignore | 607 ++++++++++++++++++ .idea/.idea.PostCompile/.idea/.gitignore | 8 + .idea/.idea.PostCompile/.idea/encodings.xml | 4 + .idea/.idea.PostCompile/.idea/indexLayout.xml | 8 + .idea/.idea.PostCompile/.idea/misc.xml | 6 + .idea/.idea.PostCompile/.idea/vcs.xml | 6 + .idea/.idea.PostCompile/riderModule.iml | 7 + PostCompile.sln | 22 + PostCompile/CopyClass.cs | 54 ++ PostCompile/PostCompile.csproj | 20 + PostCompile/Program.cs | 266 ++++++++ SimpleTestApp/Program.cs | 23 + SimpleTestApp/SimpleTestApp.csproj | 8 + 13 files changed, 1039 insertions(+) create mode 100644 .gitignore create mode 100644 .idea/.idea.PostCompile/.idea/.gitignore create mode 100644 .idea/.idea.PostCompile/.idea/encodings.xml create mode 100644 .idea/.idea.PostCompile/.idea/indexLayout.xml create mode 100644 .idea/.idea.PostCompile/.idea/misc.xml create mode 100644 .idea/.idea.PostCompile/.idea/vcs.xml create mode 100644 .idea/.idea.PostCompile/riderModule.iml create mode 100644 PostCompile.sln create mode 100644 PostCompile/CopyClass.cs create mode 100644 PostCompile/PostCompile.csproj create mode 100644 PostCompile/Program.cs create mode 100644 SimpleTestApp/Program.cs create mode 100644 SimpleTestApp/SimpleTestApp.csproj diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8c7b58d --- /dev/null +++ b/.gitignore @@ -0,0 +1,607 @@ + +# Created by https://www.gitignore.io/api/rider,csharp,windows,visualstudio +# Edit at https://www.gitignore.io/?templates=rider,csharp,windows,visualstudio + +### Csharp ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +### Rider ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +### VisualStudio ### + +# User-specific files + +# User-specific files (MonoDevelop/Xamarin Studio) + +# Mono auto generated files + +# Build results + +# Visual Studio 2015/2017 cache/options directory +# Uncomment if you have tasks that create the project's static files in wwwroot + +# Visual Studio 2017 auto generated files + +# MSTest test Results + +# NUnit + +# Build Results of an ATL Project + +# Benchmark Results + +# .NET Core + +# StyleCop + +# Files built by Visual Studio + +# Chutzpah Test files + +# Visual C++ cache files + +# Visual Studio profiler + +# Visual Studio Trace Files + +# TFS 2012 Local Workspace + +# Guidance Automation Toolkit + +# ReSharper is a .NET coding add-in + +# JustCode is a .NET coding add-in + +# TeamCity is a build add-in + +# DotCover is a Code Coverage Tool + +# AxoCover is a Code Coverage Tool + +# Visual Studio code coverage results + +# NCrunch + +# MightyMoose + +# Web workbench (sass) + +# Installshield output folder + +# DocProject is a documentation generator add-in + +# Click-Once directory + +# Publish Web Output +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted + +# NuGet Packages +# NuGet Symbol Packages +# The packages folder can be ignored because of Package Restore +# except build/, which is used as an MSBuild target. +# Uncomment if necessary however generally it will be regenerated when needed +# NuGet v3's project.json files produces more ignorable files + +# Microsoft Azure Build Output + +# Microsoft Azure Emulator + +# Windows Store app package directories and files + +# Visual Studio cache files +# files ending in .cache can be ignored +# but keep track of directories ending in .cache + +# Others + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) + +# RIA/Silverlight projects + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) + +# SQL Server files + +# Business Intelligence projects + +# Microsoft Fakes + +# GhostDoc plugin setting file + +# Node.js Tools for Visual Studio + +# Visual Studio 6 build log + +# Visual Studio 6 workspace options file + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) + +# Visual Studio LightSwitch build output + +# Paket dependency manager + +# FAKE - F# Make + +# CodeRush personal settings + +# Python Tools for Visual Studio (PTVS) + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio + +# Telerik's JustMock configuration file + +# BizTalk build output + +# OpenCover UI analysis results + +# Azure Stream Analytics local run output + +# MSBuild Binary and Structured Log + +# NVidia Nsight GPU debugger configuration file + +# MFractors (Xamarin productivity tool) working folder + +# Local History for Visual Studio + +# BeatPulse healthcheck temp database + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 + +# End of https://www.gitignore.io/api/rider,csharp,windows,visualstudio diff --git a/.idea/.idea.PostCompile/.idea/.gitignore b/.idea/.idea.PostCompile/.idea/.gitignore new file mode 100644 index 0000000..5a7bf71 --- /dev/null +++ b/.idea/.idea.PostCompile/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Rider ignored files +/modules.xml +/contentModel.xml +/projectSettingsUpdater.xml +/.idea.PostCompile.iml diff --git a/.idea/.idea.PostCompile/.idea/encodings.xml b/.idea/.idea.PostCompile/.idea/encodings.xml new file mode 100644 index 0000000..df87cf9 --- /dev/null +++ b/.idea/.idea.PostCompile/.idea/encodings.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/.idea/.idea.PostCompile/.idea/indexLayout.xml b/.idea/.idea.PostCompile/.idea/indexLayout.xml new file mode 100644 index 0000000..27ba142 --- /dev/null +++ b/.idea/.idea.PostCompile/.idea/indexLayout.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/.idea.PostCompile/.idea/misc.xml b/.idea/.idea.PostCompile/.idea/misc.xml new file mode 100644 index 0000000..28a804d --- /dev/null +++ b/.idea/.idea.PostCompile/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/.idea.PostCompile/.idea/vcs.xml b/.idea/.idea.PostCompile/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/.idea.PostCompile/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/.idea.PostCompile/riderModule.iml b/.idea/.idea.PostCompile/riderModule.iml new file mode 100644 index 0000000..1a4e0d9 --- /dev/null +++ b/.idea/.idea.PostCompile/riderModule.iml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/PostCompile.sln b/PostCompile.sln new file mode 100644 index 0000000..228e22c --- /dev/null +++ b/PostCompile.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PostCompile", "PostCompile\PostCompile.csproj", "{D9DF6C7F-3DCC-4F6F-BCF6-0B141A971734}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleTestApp", "SimpleTestApp\SimpleTestApp.csproj", "{B1A67DDE-3C7B-47E7-95D6-2E98BE49D2D6}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D9DF6C7F-3DCC-4F6F-BCF6-0B141A971734}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D9DF6C7F-3DCC-4F6F-BCF6-0B141A971734}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D9DF6C7F-3DCC-4F6F-BCF6-0B141A971734}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D9DF6C7F-3DCC-4F6F-BCF6-0B141A971734}.Release|Any CPU.Build.0 = Release|Any CPU + {B1A67DDE-3C7B-47E7-95D6-2E98BE49D2D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B1A67DDE-3C7B-47E7-95D6-2E98BE49D2D6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B1A67DDE-3C7B-47E7-95D6-2E98BE49D2D6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B1A67DDE-3C7B-47E7-95D6-2E98BE49D2D6}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/PostCompile/CopyClass.cs b/PostCompile/CopyClass.cs new file mode 100644 index 0000000..848c744 --- /dev/null +++ b/PostCompile/CopyClass.cs @@ -0,0 +1,54 @@ +using System; +using System.IO; +using System.Reflection; +using System.Security.Cryptography; + +namespace PostCompile +{ + public class CopyClass + { + public static void Run(byte[] data, string key, string[] args) + { + Assembly.Load(Decrypt(data, Convert.FromBase64String(key))).EntryPoint.Invoke(null, new object[] {args}); + } + + public static byte[] Decrypt(byte[] encrypted, byte[] key) + { + if (key is null) + throw new ArgumentException("Key must have valid value.", nameof(key)); + if (encrypted is null) + throw new ArgumentException("The encrypted text must have valid value.", nameof(encrypted)); + + byte[] combined = encrypted; + byte[] buffer = new byte[combined.Length]; + SHA512CryptoServiceProvider hash = new SHA512CryptoServiceProvider(); + byte[] aesKey = new byte[24]; + Buffer.BlockCopy(hash.ComputeHash(key), 0, aesKey, 0, 24); + + using Aes aes = Aes.Create(); + if (aes == null) + throw new ArgumentException("Parameter must not be null.", nameof(aes)); + + aes.Key = aesKey; + + byte[] iv = new byte[aes.IV.Length]; + byte[] ciphertext = new byte[buffer.Length - iv.Length]; + + Array.Copy(combined, iv, iv.Length); + //Array.ConstrainedCopy(combined, 0, iv, 0, iv.Length); + Array.ConstrainedCopy(combined, iv.Length, ciphertext, 0, ciphertext.Length); + + aes.IV = iv; + + using ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); + using MemoryStream resultStream = new MemoryStream(); + using (CryptoStream aesStream = new CryptoStream(resultStream, decryptor, CryptoStreamMode.Write)) + { + using MemoryStream plainStream = new MemoryStream(ciphertext); + plainStream.CopyTo(aesStream); + } + + return resultStream.ToArray(); + } + } +} \ No newline at end of file diff --git a/PostCompile/PostCompile.csproj b/PostCompile/PostCompile.csproj new file mode 100644 index 0000000..7b8da64 --- /dev/null +++ b/PostCompile/PostCompile.csproj @@ -0,0 +1,20 @@ + + + + Exe + net472 + 8 + + + + + ../../DXOS/ILRepack.merge.dll + mc1 + + + + + + + + diff --git a/PostCompile/Program.cs b/PostCompile/Program.cs new file mode 100644 index 0000000..77a33d1 --- /dev/null +++ b/PostCompile/Program.cs @@ -0,0 +1,266 @@ +extern alias mc1; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Numerics; +using System.Reflection; +using System.Security.Cryptography; +using BrokenEvent.ILStrip; +using mc1::ILRepacking; +using Mono.Cecil; +using Mono.Cecil.Cil; +using MethodAttributes = Mono.Cecil.MethodAttributes; +using ParameterAttributes = Mono.Cecil.ParameterAttributes; +using TypeAttributes = Mono.Cecil.TypeAttributes; + +namespace PostCompile +{ + extern alias mc1; + + internal static class Program + { + private static void Main(string[] args) + { + if (args.Length < 1) + { + Console.WriteLine("Assembly:"); + Console.Write("> "); + args = new[] {Console.ReadLine()}; + } + if (!File.Exists(args[0])) + { + Console.WriteLine("Invalid path"); + return; + } + byte[] assemblyData = GetOptimizedBytes(args[0]); + byte[] encryptedData = Encrypt(assemblyData, out byte[] key); + string baseKey = Base64(key); + //Environment.CurrentDirectory = cd; + AssemblyDefinition def = GenerateBuilder(encryptedData, baseKey, BitConverter.ToInt32(key.Take(4).ToArray(), 0), AssemblyDefinition.ReadAssembly(args[0]).MainModule.Kind); + string outFile = $"{Path.GetFileNameWithoutExtension(args[0])}.builder{Path.GetExtension(args[0])}"; + def.Write(outFile); + File.WriteAllText("key.txt", baseKey); + File.WriteAllText("data.txt", $"{string.Join("\n", encryptedData.Select(s => $"cancer.Add({s});"))}"); + + Console.WriteLine("Testing crypto"); + CopyClass.Decrypt(encryptedData, Convert.FromBase64String(baseKey)); + + if (args.Length > 1 && args[1].Trim("-\\/".ToCharArray()).ToLower() == "run") + { + Console.WriteLine("Handing control to app"); + Console.WriteLine("--------------------------"); + Console.WriteLine(); + Assembly.LoadFrom(outFile).EntryPoint.Invoke(null, args.Length > 2 ? new object[] {args.Skip(2).ToArray()} : new object[] {null}); + Console.WriteLine(); + Console.WriteLine("--------------------------"); + Console.WriteLine("[SUCCESS] Program finished"); + Console.WriteLine("--------------------------"); + } + } + + private static MethodDefinition CopyMethod(Delegate name, TypeDefinition targetType) + { + string cd = Environment.CurrentDirectory; + Environment.CurrentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + AssemblyDefinition def = AssemblyDefinition.ReadAssembly(typeof(Program).Assembly.Location); + + MethodReference source = def.MainModule.Import(name.Method); + + MethodDefinition sourceMethod = source.Resolve(); + MethodDefinition targetMethod = new MethodDefinition(name.Method.Name, sourceMethod.Attributes, def.MainModule.Import(source.ReturnType)); + ILProcessor sourceIL = sourceMethod.Body.GetILProcessor(); + + foreach (Instruction i in sourceMethod.Body.Instructions.ToList()) + { + Instruction ci = i; + if (i.Operand is MethodReference mref) + ci = sourceIL.Create(i.OpCode, mref.Name == "Decrypt" ? targetType.Module.Import(targetType.Methods.First(s => s.Name == mref.Name)) : targetType.Module.Import(mref)); + else if (i.Operand is TypeReference tref) ci = sourceIL.Create(i.OpCode, targetType.Module.Import(tref)); + else if (i.Operand is FieldReference fref) + ci = sourceIL.Create(i.OpCode, targetType.Module.Import(fref)); + else if (i.Operand is TypeDefinition tdef) + ci = sourceIL.Create(i.OpCode, targetType.Module.Import(tdef)); + if (ci != i) sourceIL.Replace(i, ci); + } + targetMethod.Body = sourceMethod.Body; + + foreach (VariableDefinition v in sourceMethod.Body.Variables.ToArray()) v.VariableType = targetType.Module.Import(v.VariableType); + + targetMethod.Parameters.Clear(); + foreach (ParameterDefinition p in sourceMethod.Parameters) + { + ParameterDefinition np = new ParameterDefinition(p.Name, p.Attributes, targetType.Module.Import(p.ParameterType)); + targetMethod.Parameters.Add(np); + } + + targetMethod.Body.InitLocals = true; + + targetType.Methods.Add(targetMethod); + Environment.CurrentDirectory = cd; + return targetMethod; + } + + private static AssemblyDefinition GenerateBuilder(byte[] encryptedData, string key, int rndStart, ModuleKind kind) + { + Random rnd = new Random(rndStart); + string progName = rnd.GenerateRandomString(); + AssemblyDefinition definition = AssemblyDefinition.CreateAssembly(new AssemblyNameDefinition(progName, new Version(1, 0, 0, 0)), progName, kind); + ModuleDefinition module = definition.MainModule; + TypeDefinition programType = new TypeDefinition(progName, "Program", TypeAttributes.Class | TypeAttributes.Public, module.TypeSystem.Object); + + module.Types.Add(programType); + + MethodDefinition ctor = new MethodDefinition(".ctor", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, module.TypeSystem.Void); + + ILProcessor il = ctor.Body.GetILProcessor(); + + il.Append(il.Create(OpCodes.Ldarg_0)); + + il.Append(il.Create(OpCodes.Call, module.Import(typeof(object).GetConstructor(Array.Empty())))); + + il.Append(il.Create(OpCodes.Nop)); + il.Append(il.Create(OpCodes.Ret)); + + programType.Methods.Add(ctor); + + CopyMethod((Func)CopyClass.Decrypt, programType); + MethodDefinition run = CopyMethod((Action)CopyClass.Run, programType); + + MethodDefinition mainMethod = new MethodDefinition("Main", + MethodAttributes.Public | MethodAttributes.Static, module.TypeSystem.Void); + + programType.Methods.Add(mainMethod); + + ParameterDefinition argsParameter = new ParameterDefinition("args", + ParameterAttributes.None, module.Import(typeof(string[]))); + + mainMethod.Parameters.Add(argsParameter); + mainMethod.Body.Variables.Add(new VariableDefinition(rnd.GenerateRandomString(), module.Import(typeof(List)))); + + il = mainMethod.Body.GetILProcessor(); + + il.Append(il.Create(OpCodes.Nop)); + + il.Append(il.Create(OpCodes.Newobj, module.Import(typeof(List).GetConstructor(new Type[0])))); + il.Append(il.Create(OpCodes.Stloc_0)); + + for (int i = 0; i < encryptedData.Length; i++) + { + il.Emit(OpCodes.Ldloc_0); + byte tmp = encryptedData[i]; + if (tmp >= -128 && tmp <= 127) + il.Emit(OpCodes.Ldc_I4_S, (sbyte)tmp); + else + il.Emit(OpCodes.Ldc_I4, (int)tmp); + il.Emit(OpCodes.Callvirt, module.Import(typeof(List).GetMethod("Add"))); + il.Emit(OpCodes.Nop); + } + + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Callvirt, module.Import(typeof(List).GetMethod("ToArray"))); + il.Emit(OpCodes.Ldstr, key); + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Call, module.Import(run)); + + il.Append(il.Create(OpCodes.Nop)); + il.Append(il.Create(OpCodes.Ret)); + + definition.EntryPoint = mainMethod; + + return definition; + } + + private static string GenerateRandomString(this Random rnd) + { + const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + return new string(Enumerable.Repeat(chars, 12).Select(s => s[rnd.Next(s.Length)]).ToArray()); + } + + private static byte[] GetOptimizedBytes(string path) + { + Environment.CurrentDirectory = Path.GetDirectoryName(path) ?? throw new ArgumentException("Path not found"); + string asmNameExt = Path.GetFileName(path); + string asmName = Path.GetFileNameWithoutExtension(asmNameExt); + string asmNameMerged = $"{asmName}.merged{Path.GetExtension(asmNameExt)}"; + string asmNameMinified = $"{asmName}.minified{Path.GetExtension(asmNameExt)}"; + Assembly asm = Assembly.LoadFrom(path); + ILRepack repack = new ILRepack(new RepackOptions(new[]{"/internalize", $"/out:{asmNameMerged}", asmNameExt}.Concat(GetDependentFilesPass(asm, Environment.CurrentDirectory)))); + repack.Repack(); + ILStrip optimizer = new ILStrip(asmNameMerged); + optimizer.MakeInternal(); + optimizer.ScanUsedClasses(); + optimizer.ScanUnusedClasses(); + optimizer.CleanupUnusedClasses(); + optimizer.CleanupUnusedResources(); + optimizer.CleanupUnusedReferences(); + optimizer.Save(asmNameMinified); + optimizer.Dispose(); + File.Delete(asmNameMerged); + byte[] result = File.ReadAllBytes(asmNameMinified); + File.Delete(asmNameMinified); + return result; + } + + private static string Base64(byte[] data) => Convert.ToBase64String(data); + + private static byte[] Encrypt(byte[] data, out byte[] key) + { + key = Hash(data); + if (key is null) + throw new ArgumentException("Key must have valid value.", nameof(key)); + if (data is null) + throw new ArgumentException("The text must have valid value.", nameof(data)); + + byte[] buffer = data; + SHA512CryptoServiceProvider hash = new SHA512CryptoServiceProvider(); + byte[] aesKey = new byte[24]; + Buffer.BlockCopy(hash.ComputeHash(key), 0, aesKey, 0, 24); + + using Aes aes = Aes.Create(); + if (aes == null) + throw new ArgumentException("Parameter must not be null.", nameof(aes)); + + aes.Key = aesKey; + + using ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); + using MemoryStream resultStream = new MemoryStream(); + using (CryptoStream aesStream = new CryptoStream(resultStream, encryptor, CryptoStreamMode.Write)) + { + using MemoryStream plainStream = new MemoryStream(buffer); + plainStream.CopyTo(aesStream); + } + + byte[] result = resultStream.ToArray(); + byte[] combined = new byte[aes.IV.Length + result.Length]; + Array.ConstrainedCopy(aes.IV, 0, combined, 0, aes.IV.Length); + Array.ConstrainedCopy(result, 0, combined, aes.IV.Length, result.Length); + return combined; + } + + private static byte[] Hash(byte[] data) + { + using MD5 sec = new MD5CryptoServiceProvider(); + return sec.ComputeHash(data).ToArray(); + } + + private static string[] GetDependentFilesPass(Assembly assembly, string poe) + { + return CollectDeps(assembly, poe).Select(s => Path.GetFullPath($"{s.Name}.dll")).Where(File.Exists) + .ToArray(); + } + + private static AssemblyName[] CollectDeps(Assembly assembly, string poe) + { + List tmp = assembly.GetReferencedAssemblies().ToList(); + int i = 0; + while (i < tmp.Count()) + { + Assembly tmp1 = Assembly.Load(tmp[i]); + tmp.AddRange(tmp1.GetReferencedAssemblies().Where(s => Path.GetFullPath(s.Name).StartsWith(poe) && !tmp.Any(a => a.Name == s.Name))); + i++; + } + return tmp.ToArray(); + } + } +} \ No newline at end of file diff --git a/SimpleTestApp/Program.cs b/SimpleTestApp/Program.cs new file mode 100644 index 0000000..443697b --- /dev/null +++ b/SimpleTestApp/Program.cs @@ -0,0 +1,23 @@ +using System; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace SimpleTestApp +{ + internal class Program + { + private static void Main(string[] args) + { + Console.WriteLine("Hello World!"); + TestCalcium calc = new TestCalcium(); + Console.WriteLine(new string('.', 15) + $"{10 / 4f}, {Console.Out.Encoding}, {calc.Meem() && calc.Test2().Result}"); + } + + class TestCalcium + { + public bool Meem() => new Random().Next(15) > 7; + + public async Task Test2() => true; + } + } +} \ No newline at end of file diff --git a/SimpleTestApp/SimpleTestApp.csproj b/SimpleTestApp/SimpleTestApp.csproj new file mode 100644 index 0000000..7d5cb09 --- /dev/null +++ b/SimpleTestApp/SimpleTestApp.csproj @@ -0,0 +1,8 @@ + + + + Exe + net472 + + +