From 97a3acec39a5ebaa8d335ec02133b49fa55bdb84 Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Mon, 27 Feb 2023 11:05:30 +0200 Subject: [PATCH 01/24] Fix grammar in CHANGELOG --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 307b0451..174a0a92 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,8 +25,8 @@ ### v0.11.0-alpha.20: 2023-02-016 #### Added: -* BitMono ASCII Art in CLI -* Hiding of the pathes (file path, directory path, etc) +* BitMono ASCII Art in CLI. +* Hiding of the pathes (file path, directory path, etc). * Documentation. #### Fixed: From 046833bb31cb721ea0874d9deadf5c3bd1f66f35 Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Mon, 27 Feb 2023 14:03:30 +0200 Subject: [PATCH 02/24] Implement feature for costura fody resources as references Includes a bit of code refactoring --- .../Modules/CLIObfuscationNeedsFactory.cs | 2 +- .../CLIOptionsObfuscationNeedsFactory.cs | 4 +- src/BitMono.CLI/Program.cs | 2 +- .../Resolvers/AssemblyResolver.cs | 7 +-- .../Pages/Obfuscation/Protect.razor.cs | 6 +-- .../AutomaticReferencesDataResolver.cs | 23 +++++++++ .../CosturaReferencesDataResolver.cs | 47 ++++++++++++++++++ .../Abstractions/DependenciesDataResolver.cs | 21 -------- .../Abstractions/ObfuscationNeeds.cs | 2 +- .../Abstractions/ReferencesDataResolver.cs | 21 ++++++++ src/BitMono.Obfuscation/BitMonoEngine.cs | 49 +++++++++---------- src/BitMono.Obfuscation/BitMonoObfuscator.cs | 3 +- .../Factories/BitMonoContextFactory.cs | 17 ++++--- .../Factories/ProtectionContextFactory.cs | 30 ++++++------ src/BitMono.Obfuscation/GlobalUsings.cs | 1 + .../Interfaces/IDependenciesDataResolver.cs | 6 --- .../Interfaces/IReferencesDataResolver.cs | 6 +++ 17 files changed, 161 insertions(+), 86 deletions(-) create mode 100644 src/BitMono.Obfuscation/Abstractions/AutomaticReferencesDataResolver.cs create mode 100644 src/BitMono.Obfuscation/Abstractions/CosturaReferencesDataResolver.cs delete mode 100644 src/BitMono.Obfuscation/Abstractions/DependenciesDataResolver.cs create mode 100644 src/BitMono.Obfuscation/Abstractions/ReferencesDataResolver.cs delete mode 100644 src/BitMono.Obfuscation/Interfaces/IDependenciesDataResolver.cs create mode 100644 src/BitMono.Obfuscation/Interfaces/IReferencesDataResolver.cs diff --git a/src/BitMono.CLI/Modules/CLIObfuscationNeedsFactory.cs b/src/BitMono.CLI/Modules/CLIObfuscationNeedsFactory.cs index d5fa59f7..f3613f15 100644 --- a/src/BitMono.CLI/Modules/CLIObfuscationNeedsFactory.cs +++ b/src/BitMono.CLI/Modules/CLIObfuscationNeedsFactory.cs @@ -99,7 +99,7 @@ public ObfuscationNeeds Create() { FileName = fileName, FileBaseDirectory = fileBaseDirectory, - DependenciesDirectoryName = dependenciesDirectoryName, + ReferencesDirectoryName = dependenciesDirectoryName, OutputDirectoryName = outputDirectoryName }; } diff --git a/src/BitMono.CLI/Modules/CLIOptionsObfuscationNeedsFactory.cs b/src/BitMono.CLI/Modules/CLIOptionsObfuscationNeedsFactory.cs index eb9dc336..80250e71 100644 --- a/src/BitMono.CLI/Modules/CLIOptionsObfuscationNeedsFactory.cs +++ b/src/BitMono.CLI/Modules/CLIOptionsObfuscationNeedsFactory.cs @@ -37,7 +37,7 @@ public CLIOptionsObfuscationNeedsFactory(string[] args, ILogger logger) { FileName = options.File, FileBaseDirectory = fileBaseDirectory, - DependenciesDirectoryName = options.Libraries.IsNullOrEmpty() == false + ReferencesDirectoryName = options.Libraries.IsNullOrEmpty() == false ? options.Libraries : Path.Combine(fileBaseDirectory, "libs"), OutputDirectoryName = options.Output.IsNullOrEmpty() == false @@ -46,7 +46,7 @@ public CLIOptionsObfuscationNeedsFactory(string[] args, ILogger logger) }; Directory.CreateDirectory(needs.OutputDirectoryName); - Directory.CreateDirectory(needs.DependenciesDirectoryName); + Directory.CreateDirectory(needs.ReferencesDirectoryName); return needs; } } \ No newline at end of file diff --git a/src/BitMono.CLI/Program.cs b/src/BitMono.CLI/Program.cs index f46839e8..8979b426 100644 --- a/src/BitMono.CLI/Program.cs +++ b/src/BitMono.CLI/Program.cs @@ -42,7 +42,7 @@ private static async Task Main(string[] args) Console.Clear(); logger.Information("File: {0}", needs.FileName); - logger.Information("Dependencies (libs): {0}", needs.DependenciesDirectoryName); + logger.Information("Dependencies (libs): {0}", needs.ReferencesDirectoryName); logger.Information("Everything is seems to be ok, starting obfuscation.."); logger.Information(AsciiArt); diff --git a/src/BitMono.Core/Resolvers/AssemblyResolver.cs b/src/BitMono.Core/Resolvers/AssemblyResolver.cs index 58220c56..ae26db72 100644 --- a/src/BitMono.Core/Resolvers/AssemblyResolver.cs +++ b/src/BitMono.Core/Resolvers/AssemblyResolver.cs @@ -1,9 +1,9 @@ #pragma warning disable CS8602 namespace BitMono.Core.Resolvers; -public class AssemblyResolver +public static class AssemblyResolver { - public AssemblyResolve Resolve(IEnumerable dependenciesData, ProtectionContext context) + public static AssemblyResolve Resolve(IEnumerable dependenciesData, ProtectionContext context) { context.ThrowIfCancellationRequested(); @@ -28,8 +28,9 @@ public AssemblyResolve Resolve(IEnumerable dependenciesData, ProtectionC context.AssemblyResolver.AddToCache(originalReference, definition); } } - catch (BadImageFormatException) + catch (BadImageFormatException ex) { + Console.WriteLine("originalRef: " + originalReference.Name + ", " + ex.ToString()); badImageReferences.Add(originalReference); } } diff --git a/src/BitMono.GUI/Pages/Obfuscation/Protect.razor.cs b/src/BitMono.GUI/Pages/Obfuscation/Protect.razor.cs index 3fb3e714..0bf3b4ca 100644 --- a/src/BitMono.GUI/Pages/Obfuscation/Protect.razor.cs +++ b/src/BitMono.GUI/Pages/Obfuscation/Protect.razor.cs @@ -48,9 +48,9 @@ public async Task ObfuscateAsync() dependeciesData.Add(File.ReadAllBytes(dependencies[i])); } - var dataResolver = new DependenciesDataResolver(_dependenciesDirectoryName); - var bitMonoContextFactory = new BitMonoContextFactory(dataResolver, obfuscation); - var bitMonoContext = bitMonoContextFactory.Create(_outputDirectoryName, _obfuscationFile.Name); + var dataResolver = new ReferencesDataResolver(_dependenciesDirectoryName); + //var bitMonoContextFactory = new BitMonoContextFactory(dataResolver, obfuscation); + //var bitMonoContext = bitMonoContextFactory.Create(_outputDirectoryName, _obfuscationFile.Name); //var engine = new BitMonoEngine(obfuscationAttributeResolver, obfuscation, StoringProtections.Protections, MemberResolvers.ToList(), Protections.ToList(), Logger); //await engine.StartAsync(); } diff --git a/src/BitMono.Obfuscation/Abstractions/AutomaticReferencesDataResolver.cs b/src/BitMono.Obfuscation/Abstractions/AutomaticReferencesDataResolver.cs new file mode 100644 index 00000000..b7498ce7 --- /dev/null +++ b/src/BitMono.Obfuscation/Abstractions/AutomaticReferencesDataResolver.cs @@ -0,0 +1,23 @@ +namespace BitMono.Obfuscation.Abstractions; + +public class AutomaticReferencesDataResolver : IReferencesDataResolver +{ + private readonly string _referencesDirectoryName; + + public AutomaticReferencesDataResolver(string referencesDirectoryName) + { + _referencesDirectoryName = referencesDirectoryName; + } + + [SuppressMessage("ReSharper", "ConvertIfStatementToReturnStatement")] + public IEnumerable Resolve(ModuleDefinition module) + { + var referencesData = new ReferencesDataResolver(_referencesDirectoryName).Resolve(module); + var costuraReferencesData = new CosturaReferencesDataResolver().Resolve(module); + if (costuraReferencesData.IsEmpty() == false) + { + return referencesData.Concat(costuraReferencesData); + } + return referencesData; + } +} \ No newline at end of file diff --git a/src/BitMono.Obfuscation/Abstractions/CosturaReferencesDataResolver.cs b/src/BitMono.Obfuscation/Abstractions/CosturaReferencesDataResolver.cs new file mode 100644 index 00000000..130374b4 --- /dev/null +++ b/src/BitMono.Obfuscation/Abstractions/CosturaReferencesDataResolver.cs @@ -0,0 +1,47 @@ +namespace BitMono.Obfuscation.Abstractions; + +public class CosturaReferencesDataResolver : IReferencesDataResolver +{ + private const string CosturaResourceNameStart = "costura."; + private const string CosturaResourceNameEnd = ".dll.compressed"; + private const int MinCosturaResourceNameCharactersLenght = 19; + + [SuppressMessage("ReSharper", "ForCanBeConvertedToForeach")] + [SuppressMessage("ReSharper", "LoopCanBeConvertedToQuery")] + [SuppressMessage("ReSharper", "InvertIf")] + public IEnumerable Resolve(ModuleDefinition module) + { + for (var i = 0; i < module.Resources.Count; i++) + { + var resource = module.Resources[i]; + if (resource.IsEmbedded) + { + if (Utf8String.IsNullOrEmpty(resource.Name) == false) + { + var name = resource.Name.Value; + if (name.Length > MinCosturaResourceNameCharactersLenght) + { + if (name.StartsWith(CosturaResourceNameStart) && name.EndsWith(CosturaResourceNameEnd)) + { + var data = resource.GetData(); + if (data != null) + { + data = Decompress(data); + yield return data; + } + } + } + } + } + } + } + + private static byte[] Decompress(byte[] data) + { + using var input = new MemoryStream(data); + using var output = new MemoryStream(); + using var deflateStream = new DeflateStream(input, CompressionMode.Decompress); + deflateStream.CopyTo(output); + return output.ToArray(); + } +} \ No newline at end of file diff --git a/src/BitMono.Obfuscation/Abstractions/DependenciesDataResolver.cs b/src/BitMono.Obfuscation/Abstractions/DependenciesDataResolver.cs deleted file mode 100644 index ce0e408f..00000000 --- a/src/BitMono.Obfuscation/Abstractions/DependenciesDataResolver.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace BitMono.Obfuscation.Abstractions; - -public class DependenciesDataResolver : IDependenciesDataResolver -{ - private readonly string m_DependenciesDirectoryName; - - public DependenciesDataResolver(string dependenciesDirectoryName) - { - m_DependenciesDirectoryName = dependenciesDirectoryName; - } - - [SuppressMessage("ReSharper", "ForCanBeConvertedToForeach")] - public IEnumerable Resolve() - { - var dependencies = Directory.GetFiles(m_DependenciesDirectoryName); - for (var i = 0; i < dependencies.Length; i++) - { - yield return File.ReadAllBytes(dependencies[i]); - } - } -} \ No newline at end of file diff --git a/src/BitMono.Obfuscation/Abstractions/ObfuscationNeeds.cs b/src/BitMono.Obfuscation/Abstractions/ObfuscationNeeds.cs index e1cf1fd8..60db1531 100644 --- a/src/BitMono.Obfuscation/Abstractions/ObfuscationNeeds.cs +++ b/src/BitMono.Obfuscation/Abstractions/ObfuscationNeeds.cs @@ -4,6 +4,6 @@ public class ObfuscationNeeds { public string? FileName { get; set; } public string? FileBaseDirectory { get; set; } - public string? DependenciesDirectoryName { get; set; } + public string? ReferencesDirectoryName { get; set; } public string? OutputDirectoryName { get; set; } } \ No newline at end of file diff --git a/src/BitMono.Obfuscation/Abstractions/ReferencesDataResolver.cs b/src/BitMono.Obfuscation/Abstractions/ReferencesDataResolver.cs new file mode 100644 index 00000000..765551cc --- /dev/null +++ b/src/BitMono.Obfuscation/Abstractions/ReferencesDataResolver.cs @@ -0,0 +1,21 @@ +namespace BitMono.Obfuscation.Abstractions; + +public class ReferencesDataResolver : IReferencesDataResolver +{ + private readonly string _referencesDirectoryName; + + public ReferencesDataResolver(string referencesDirectoryName) + { + _referencesDirectoryName = referencesDirectoryName; + } + + [SuppressMessage("ReSharper", "ForCanBeConvertedToForeach")] + public IEnumerable Resolve(ModuleDefinition module) + { + var dependencies = Directory.GetFiles(_referencesDirectoryName); + for (var i = 0; i < dependencies.Length; i++) + { + yield return File.ReadAllBytes(dependencies[i]); + } + } +} \ No newline at end of file diff --git a/src/BitMono.Obfuscation/BitMonoEngine.cs b/src/BitMono.Obfuscation/BitMonoEngine.cs index 6d380feb..c65770b2 100644 --- a/src/BitMono.Obfuscation/BitMonoEngine.cs +++ b/src/BitMono.Obfuscation/BitMonoEngine.cs @@ -7,25 +7,25 @@ namespace BitMono.Obfuscation; [SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] public class BitMonoEngine { - private readonly ILifetimeScope m_LifetimeScope; - private readonly ObfuscationAttributeResolver m_ObfuscationAttributeResolver; - private readonly ObfuscateAssemblyAttributeResolver m_ObfuscateAssemblyAttributeResolver; - private readonly Shared.Models.Obfuscation m_Obfuscation; - private readonly List m_ProtectionSettings; - private readonly List m_MemberResolvers; - private readonly ILogger m_Logger; + private readonly ILifetimeScope _lifetimeScope; + private readonly ObfuscationAttributeResolver _obfuscationAttributeResolver; + private readonly ObfuscateAssemblyAttributeResolver _obfuscateAssemblyAttributeResolver; + private readonly Shared.Models.Obfuscation _obfuscation; + private readonly List _protectionSettings; + private readonly List _memberResolvers; + private readonly ILogger _logger; public BitMonoEngine(ILifetimeScope lifetimeScope) { - m_LifetimeScope = lifetimeScope; - m_ObfuscationAttributeResolver = m_LifetimeScope.Resolve(); - m_ObfuscateAssemblyAttributeResolver = m_LifetimeScope.Resolve(); - m_Obfuscation = m_LifetimeScope.Resolve>().Value; - m_ProtectionSettings = m_LifetimeScope.Resolve>().Value.Protections; - m_MemberResolvers = m_LifetimeScope + _lifetimeScope = lifetimeScope; + _obfuscationAttributeResolver = _lifetimeScope.Resolve(); + _obfuscateAssemblyAttributeResolver = _lifetimeScope.Resolve(); + _obfuscation = _lifetimeScope.Resolve>().Value; + _protectionSettings = _lifetimeScope.Resolve>().Value.Protections; + _memberResolvers = _lifetimeScope .Resolve>() .ToList();; - m_Logger = m_LifetimeScope + _logger = _lifetimeScope .Resolve() .ForContext(); } @@ -34,30 +34,29 @@ internal async Task StartAsync(ProtectionContext context, IDataWriter data { context.ThrowIfCancellationRequested(); - m_Logger.Information("Loaded Module {0}", context.Module.Name.Value); + _logger.Information("Loaded Module {0}", context.Module.Name.Value); - var protections = m_LifetimeScope + var protections = _lifetimeScope .Resolve>(new TypedParameter(typeof(ProtectionContext), context)) .ToList(); - var protectionsSorter = new ProtectionsSorter(m_ObfuscationAttributeResolver, context.Module.Assembly); - var protectionsSort = protectionsSorter.Sort(protections, m_ProtectionSettings); + var protectionsSorter = new ProtectionsSorter(_obfuscationAttributeResolver, context.Module.Assembly); + var protectionsSort = protectionsSorter.Sort(protections, _protectionSettings); if (protectionsSort.HasProtections == false) { - m_Logger.Fatal("No one protection were detected, please specify or enable them in protections.json!"); + _logger.Fatal("No one protection were detected, please specify or enable them in protections.json!"); return false; } - var obfuscator = new BitMonoObfuscator(context, m_MemberResolvers, protectionsSort, dataWriter, m_ObfuscationAttributeResolver, m_ObfuscateAssemblyAttributeResolver, m_Obfuscation, m_Logger); + var obfuscator = new BitMonoObfuscator(context, _memberResolvers, protectionsSort, dataWriter, _obfuscationAttributeResolver, _obfuscateAssemblyAttributeResolver, _obfuscation, _logger); await obfuscator.ProtectAsync(); return true; } - public async Task StartAsync(ObfuscationNeeds needs, IModuleFactory moduleFactory, IDataWriter dataWriter, IDependenciesDataResolver dependenciesDataResolver, CancellationToken cancellationToken) + public async Task StartAsync(ObfuscationNeeds needs, IModuleFactory moduleFactory, IDataWriter dataWriter, IReferencesDataResolver referencesDataResolver, CancellationToken cancellationToken) { - var bitMonoContextFactory = new BitMonoContextFactory(dependenciesDataResolver, m_Obfuscation); - var bitMonoContext = bitMonoContextFactory.Create(needs.OutputDirectoryName, needs.FileName); - var runtimeModule = ModuleDefinition.FromFile(typeof(BitMono.Runtime.Data).Assembly.Location); var moduleFactoryResult = moduleFactory.Create(); + var bitMonoContextFactory = new BitMonoContextFactory(moduleFactoryResult.Module, referencesDataResolver, _obfuscation); + var bitMonoContext = bitMonoContextFactory.Create(needs.OutputDirectoryName, needs.FileName); var protectionContextFactory = new ProtectionContextFactory(moduleFactoryResult, runtimeModule, bitMonoContext, cancellationToken); var protectionContext = protectionContextFactory.Create(); bitMonoContext.OutputFile = OutputFilePathFactory.Create(bitMonoContext); @@ -65,6 +64,6 @@ public async Task StartAsync(ObfuscationNeeds needs, IModuleFactory module } public async Task StartAsync(ObfuscationNeeds needs, CancellationToken cancellationToken) { - return await StartAsync(needs, new ModuleFactory(File.ReadAllBytes(needs.FileName), new LogErrorListener(m_Logger)), new FileDataWriter(), new DependenciesDataResolver(needs.DependenciesDirectoryName), cancellationToken); + return await StartAsync(needs, new ModuleFactory(File.ReadAllBytes(needs.FileName), new LogErrorListener(_logger)), new FileDataWriter(), new AutomaticReferencesDataResolver(needs.ReferencesDirectoryName), cancellationToken); } } \ No newline at end of file diff --git a/src/BitMono.Obfuscation/BitMonoObfuscator.cs b/src/BitMono.Obfuscation/BitMonoObfuscator.cs index a45390e7..a406de92 100644 --- a/src/BitMono.Obfuscation/BitMonoObfuscator.cs +++ b/src/BitMono.Obfuscation/BitMonoObfuscator.cs @@ -88,7 +88,8 @@ private Task OutputFrameworkInformationAsync() } private Task ResolveDependenciesAsync() { - var assemblyResolve = new AssemblyResolver().Resolve(_context.BitMonoContext.ReferencesData, _context); + _logger.Information("Starting resolving dependencies..."); + var assemblyResolve = AssemblyResolver.Resolve(_context.BitMonoContext.ReferencesData, _context); foreach (var reference in assemblyResolve.ResolvedReferences) { _logger.Information("Successfully resolved dependency: {0}", reference.FullName); diff --git a/src/BitMono.Obfuscation/Factories/BitMonoContextFactory.cs b/src/BitMono.Obfuscation/Factories/BitMonoContextFactory.cs index 2c95a0db..512538ae 100644 --- a/src/BitMono.Obfuscation/Factories/BitMonoContextFactory.cs +++ b/src/BitMono.Obfuscation/Factories/BitMonoContextFactory.cs @@ -2,22 +2,25 @@ public class BitMonoContextFactory { - private readonly IDependenciesDataResolver m_DependenciesDataResolver; - private readonly Shared.Models.Obfuscation m_Obfuscation; + private readonly ModuleDefinition _module; + private readonly IReferencesDataResolver _referencesDataResolver; + private readonly Shared.Models.Obfuscation _obfuscation; - public BitMonoContextFactory(IDependenciesDataResolver dependenciesDataResolver, Shared.Models.Obfuscation obfuscation) + public BitMonoContextFactory(ModuleDefinition module, IReferencesDataResolver referencesDataResolver, Shared.Models.Obfuscation obfuscation) { - m_DependenciesDataResolver = dependenciesDataResolver; - m_Obfuscation = obfuscation; + _module = module; + _referencesDataResolver = referencesDataResolver; + _obfuscation = obfuscation; } public BitMonoContext Create(string outputDirectoryName, string fileName) { + var referencesData = _referencesDataResolver.Resolve(_module); return new BitMonoContext { OutputDirectoryName = outputDirectoryName, - ReferencesData = m_DependenciesDataResolver.Resolve(), - Watermark = m_Obfuscation.Watermark, + ReferencesData = referencesData, + Watermark = _obfuscation.Watermark, FileName = fileName }; } diff --git a/src/BitMono.Obfuscation/Factories/ProtectionContextFactory.cs b/src/BitMono.Obfuscation/Factories/ProtectionContextFactory.cs index bdb4c0e1..d0978c1a 100644 --- a/src/BitMono.Obfuscation/Factories/ProtectionContextFactory.cs +++ b/src/BitMono.Obfuscation/Factories/ProtectionContextFactory.cs @@ -2,30 +2,30 @@ public class ProtectionContextFactory { - private readonly ModuleFactoryResult m_ModuleFactoryResult; - private readonly ModuleDefinition m_RuntimeModule; - private readonly BitMonoContext m_Context; - private readonly CancellationToken m_CancellationToken; + private readonly ModuleFactoryResult _moduleFactoryResult; + private readonly ModuleDefinition _runtimeModule; + private readonly BitMonoContext _context; + private readonly CancellationToken _cancellationToken; public ProtectionContextFactory(ModuleFactoryResult moduleFactoryResult, ModuleDefinition runtimeModule, BitMonoContext context, CancellationToken cancellationToken) { - m_ModuleFactoryResult = moduleFactoryResult; - m_RuntimeModule = runtimeModule; - m_Context = context; - m_CancellationToken = cancellationToken; + _moduleFactoryResult = moduleFactoryResult; + _runtimeModule = runtimeModule; + _context = context; + _cancellationToken = cancellationToken; } public ProtectionContext Create() { return new ProtectionContext { - Module = m_ModuleFactoryResult.Module, - RuntimeModule = m_RuntimeModule, - ModuleReaderParameters = m_ModuleFactoryResult.ModuleReaderParameters, - PEImageBuilder = m_ModuleFactoryResult.PEImageBuilder, - RuntimeImporter = new ReferenceImporter(m_RuntimeModule), - BitMonoContext = m_Context, - CancellationToken = m_CancellationToken, + Module = _moduleFactoryResult.Module, + RuntimeModule = _runtimeModule, + ModuleReaderParameters = _moduleFactoryResult.ModuleReaderParameters, + PEImageBuilder = _moduleFactoryResult.PEImageBuilder, + RuntimeImporter = _runtimeModule.DefaultImporter, + BitMonoContext = _context, + CancellationToken = _cancellationToken, }; } } \ No newline at end of file diff --git a/src/BitMono.Obfuscation/GlobalUsings.cs b/src/BitMono.Obfuscation/GlobalUsings.cs index 5732605f..6e6a86b8 100644 --- a/src/BitMono.Obfuscation/GlobalUsings.cs +++ b/src/BitMono.Obfuscation/GlobalUsings.cs @@ -12,6 +12,7 @@ global using System.Diagnostics; global using System.Diagnostics.CodeAnalysis; global using System.IO; +global using System.IO.Compression; global using System.Linq; global using System.Text; global using System.Threading; diff --git a/src/BitMono.Obfuscation/Interfaces/IDependenciesDataResolver.cs b/src/BitMono.Obfuscation/Interfaces/IDependenciesDataResolver.cs deleted file mode 100644 index 9f7622cc..00000000 --- a/src/BitMono.Obfuscation/Interfaces/IDependenciesDataResolver.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace BitMono.Obfuscation.Interfaces; - -public interface IDependenciesDataResolver -{ - IEnumerable Resolve(); -} \ No newline at end of file diff --git a/src/BitMono.Obfuscation/Interfaces/IReferencesDataResolver.cs b/src/BitMono.Obfuscation/Interfaces/IReferencesDataResolver.cs new file mode 100644 index 00000000..497b5f58 --- /dev/null +++ b/src/BitMono.Obfuscation/Interfaces/IReferencesDataResolver.cs @@ -0,0 +1,6 @@ +namespace BitMono.Obfuscation.Interfaces; + +public interface IReferencesDataResolver +{ + IEnumerable Resolve(ModuleDefinition module); +} \ No newline at end of file From f6d95dabbbc9b4d546ff9bedd0389b046f039b5a Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Mon, 27 Feb 2023 16:35:38 +0200 Subject: [PATCH 03/24] Add new credits to drakonia for the costura decompressor --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index a19f9d4a..65669462 100644 --- a/README.md +++ b/README.md @@ -140,6 +140,8 @@ Credits **[Kao and his blogs][author_kao_blog]** thanks a lot of these blogs. +**[drakonia][author_drakonia]** for her [costura decompressor](simple_costura_decompressor_source). + [test]: https://ci.appveyor.com/project/sunnamed434/bitmono/branch/main/tests [codefactor]: https://www.codefactor.io/repository/github/sunnamed434/bitmono/overview/main [deepsource]: https://deepsource.io/gh/sunnamed434/BitMono/?ref=repository-badge @@ -154,11 +156,13 @@ Credits [bitmethoddotnet_source]: https://github.com/sunnamed434/BitMethodDotnet [dotnethook_source]: https://github.com/Elliesaur/DotNetHook [confuserex_source]: https://github.com/yck1509/ConfuserEx +[simple_costura_decompressor_source]: https://github.com/dr4k0nia/Simple-Costura-Decompressor [author_0x59r11]: https://github.com/0x59R11 [author_gazzi]: https://github.com/GazziFX [author_ellisaur]: https://github.com/Elliesaur [author_naweka]: https://github.com/naweka [author_kao_blog]: https://lifeinhex.com/ +[author_drakonia]: https://github.com/dr4k0nia [author_sunnamed434]: https://github.com/sunnamed434 [appveyor_main_build]: https://ci.appveyor.com/project/sunnamed434/bitmono/branch/main [appveyor_dev_build]: https://ci.appveyor.com/project/sunnamed434/bitmono/branch/dev From 94a1308025431130aac54b25f3f95a0525d8bed5 Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Mon, 27 Feb 2023 16:36:02 +0200 Subject: [PATCH 04/24] Add FAQ for the Costura-Fody support in docs --- docs/faq/costura-support.rst | 4 ++++ docs/index.rst | 10 +++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 docs/faq/costura-support.rst diff --git a/docs/faq/costura-support.rst b/docs/faq/costura-support.rst new file mode 100644 index 00000000..0cee6694 --- /dev/null +++ b/docs/faq/costura-support.rst @@ -0,0 +1,4 @@ +Does BitMono provides Costura-Fody Support? +=========================================== + +Indeed, by default BitMono provides support for the Costura-Fody, resources will be resolved automatically, in this case, you don't need to have copies of your .DLLs or even set ``DisableCleanup`` to ``true`` in ``FodyWeavers.xml``. \ No newline at end of file diff --git a/docs/index.rst b/docs/index.rst index 01a5c1e7..e6dec98b 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -42,4 +42,12 @@ Table of Contents: configuration/exclude-obfuscation configuration/third-party-issues - configuration/protections \ No newline at end of file + configuration/protections + + +.. toctree:: + :maxdepth: 1 + :caption: Frequently Asked Questions + :name: sec-faq + + faq/costura-support \ No newline at end of file From f127f6d1bb2933f34fc0f1a176d902eb9432f163 Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Mon, 27 Feb 2023 16:41:01 +0200 Subject: [PATCH 05/24] Fix readme link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 65669462..c4cd747a 100644 --- a/README.md +++ b/README.md @@ -140,7 +140,7 @@ Credits **[Kao and his blogs][author_kao_blog]** thanks a lot of these blogs. -**[drakonia][author_drakonia]** for her [costura decompressor](simple_costura_decompressor_source). +**[drakonia][author_drakonia]** for her **[costura decompressor][simple_costura_decompressor_source]**. [test]: https://ci.appveyor.com/project/sunnamed434/bitmono/branch/main/tests [codefactor]: https://www.codefactor.io/repository/github/sunnamed434/bitmono/overview/main From 90cd6eeb89985789e39e4974fa4265f1a8c63752 Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Mon, 27 Feb 2023 16:44:01 +0200 Subject: [PATCH 06/24] Fix grammar in docs of costura support faq --- docs/faq/costura-support.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/faq/costura-support.rst b/docs/faq/costura-support.rst index 0cee6694..4f559361 100644 --- a/docs/faq/costura-support.rst +++ b/docs/faq/costura-support.rst @@ -1,4 +1,4 @@ -Does BitMono provides Costura-Fody Support? -=========================================== +Does BitMono provide Costura-Fody Support by default? +===================================================== Indeed, by default BitMono provides support for the Costura-Fody, resources will be resolved automatically, in this case, you don't need to have copies of your .DLLs or even set ``DisableCleanup`` to ``true`` in ``FodyWeavers.xml``. \ No newline at end of file From dd243d3c5c9a3c5d7a31f23d3d92e79e2bb4e07c Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Tue, 28 Feb 2023 12:28:19 +0200 Subject: [PATCH 07/24] Improve path masking pattern --- src/BitMono.Host/Extensions/PathMaskingOperator.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/BitMono.Host/Extensions/PathMaskingOperator.cs b/src/BitMono.Host/Extensions/PathMaskingOperator.cs index 4360f20d..f422e77a 100644 --- a/src/BitMono.Host/Extensions/PathMaskingOperator.cs +++ b/src/BitMono.Host/Extensions/PathMaskingOperator.cs @@ -2,7 +2,7 @@ namespace BitMono.Host.Extensions; public class PathMaskingOperator : RegexMaskingOperator { - private const string PathPattern = @"^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$"; + private const string PathPattern = @"^(?:[a-zA-Z]\:|\\\\[\w-]+\\[\w-]+\$?|[\/][^\/\0]+)+(\\[^\\/:*?""<>|]*)*(\\?)?$"; public PathMaskingOperator() : base(PathPattern) { From 19abf210e16784b700effc575dc23ab9cbbe4b66 Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Tue, 28 Feb 2023 12:31:08 +0200 Subject: [PATCH 08/24] Code refactoring --- src/BitMono.Core/GlobalUsings.cs | 2 +- src/BitMono.Core/Injection/CustomInjector.cs | 4 +- .../Injection/MscrolibInjector.cs | 18 ++++----- src/BitMono.Core/Renaming/Renamer.cs | 34 ++++++++--------- src/BitMono.Core/RuntimeImplementations.cs | 15 -------- src/BitMono.Core/Services/RandomNext.cs | 3 ++ src/BitMono.Core/Services/RandomService.cs | 11 ++++++ src/BitMono.GUI/GlobalUsings.cs | 1 - src/BitMono.Host/GlobalUsings.cs | 3 +- src/BitMono.Host/Modules/BitMonoModule.cs | 15 +------- src/BitMono.Obfuscation/BitMonoObfuscator.cs | 4 +- src/BitMono.Obfuscation/GlobalUsings.cs | 1 - src/BitMono.Protections/AntiDe4dot.cs | 37 +++++++++---------- src/BitMono.Protections/AntiILdasm.cs | 7 +--- src/BitMono.Protections/BitMethodDotnet.cs | 12 +++--- src/BitMono.Protections/DotNetHook.cs | 8 ++-- src/BitMono.Protections/GlobalUsings.cs | 1 + src/BitMono.Protections/StringsEncryption.cs | 12 +++--- src/BitMono.Utilities/GlobalUsings.cs | 3 +- .../{ => Paths}/StringPathExtensions.cs | 2 +- .../EnvironmentRuntimeInformation.cs | 2 +- .../{Time => Runtime}/KnownMonoRuntimes.cs | 2 +- .../{ => Runtime}/RuntimeUtilities.cs | 2 +- test/BitMono.Benchmarks/GlobalUsings.cs | 2 +- 24 files changed, 91 insertions(+), 110 deletions(-) delete mode 100644 src/BitMono.Core/RuntimeImplementations.cs create mode 100644 src/BitMono.Core/Services/RandomNext.cs create mode 100644 src/BitMono.Core/Services/RandomService.cs rename src/BitMono.Utilities/{ => Paths}/StringPathExtensions.cs (91%) rename src/BitMono.Utilities/{ => Runtime}/EnvironmentRuntimeInformation.cs (93%) rename src/BitMono.Utilities/{Time => Runtime}/KnownMonoRuntimes.cs (79%) rename src/BitMono.Utilities/{ => Runtime}/RuntimeUtilities.cs (97%) diff --git a/src/BitMono.Core/GlobalUsings.cs b/src/BitMono.Core/GlobalUsings.cs index 2892da71..77d2cfb0 100644 --- a/src/BitMono.Core/GlobalUsings.cs +++ b/src/BitMono.Core/GlobalUsings.cs @@ -23,8 +23,8 @@ global using BitMono.API.Pipeline; global using BitMono.Core.Analyzing; global using BitMono.Core.Contexts; -global using BitMono.Core.Injection; global using BitMono.Core.Renaming; +global using BitMono.Core.Services; global using BitMono.Utilities.AsmResolver; global using Echo.DataFlow.Analysis; global using Echo.Platforms.AsmResolver; diff --git a/src/BitMono.Core/Injection/CustomInjector.cs b/src/BitMono.Core/Injection/CustomInjector.cs index 5c7da9c6..c1afe893 100644 --- a/src/BitMono.Core/Injection/CustomInjector.cs +++ b/src/BitMono.Core/Injection/CustomInjector.cs @@ -2,7 +2,7 @@ public class CustomInjector { - public CustomAttribute InjectAttribute(ModuleDefinition module, string @namespace, string name) + public static CustomAttribute InjectAttribute(ModuleDefinition module, string @namespace, string name) { var factory = module.CorLibTypeFactory; var attributeReference = new TypeReference(module, module, @namespace, name); @@ -12,7 +12,7 @@ public CustomAttribute InjectAttribute(ModuleDefinition module, string @namespac module.CustomAttributes.Add(attribute); return attribute; } - public CustomAttribute InjectAttribute(ModuleDefinition module, string @namespace, string name, string content) + public static CustomAttribute InjectAttribute(ModuleDefinition module, string @namespace, string name, string content) { var factory = module.CorLibTypeFactory; var attributeReference = new TypeReference(module, module, @namespace, name); diff --git a/src/BitMono.Core/Injection/MscrolibInjector.cs b/src/BitMono.Core/Injection/MscrolibInjector.cs index dc97e039..46bea1da 100644 --- a/src/BitMono.Core/Injection/MscrolibInjector.cs +++ b/src/BitMono.Core/Injection/MscrolibInjector.cs @@ -3,7 +3,7 @@ namespace BitMono.Core.Injection; public class MscorlibInjector { - public FieldDefinition InjectCompilerGeneratedArray(ModuleDefinition module, TypeDefinition type, byte[] data, string name) + public static FieldDefinition InjectCompilerGeneratedArray(ModuleDefinition module, TypeDefinition type, byte[] data, string name) { var importer = module.DefaultImporter; var valueType = importer.ImportType(typeof(ValueType)); @@ -41,44 +41,44 @@ public FieldDefinition InjectCompilerGeneratedArray(ModuleDefinition module, Typ }); return fieldInjectedArray; } - public TypeDefinition InjectCompilerGeneratedValueType(ModuleDefinition module, TypeDefinition type, string? name = null) + public static TypeDefinition InjectCompilerGeneratedValueType(ModuleDefinition module, TypeDefinition type, string? name = null) { var result = CreateCompilerGeneratedValueType(module, name); type.NestedTypes.Add(result); return result; } - public CustomAttribute InjectCompilerGeneratedAttribute(ModuleDefinition module, IHasCustomAttribute @in) + public static CustomAttribute InjectCompilerGeneratedAttribute(ModuleDefinition module, IHasCustomAttribute @in) { var attribute = CreateCompilerGeneratedAttribute(module); @in.CustomAttributes.Add(attribute); return attribute; } - public CustomAttribute InjectAttribute(ModuleDefinition module, string @namespace, string name, IHasCustomAttribute @in) + public static CustomAttribute InjectAttribute(ModuleDefinition module, string @namespace, string name, IHasCustomAttribute @in) { var attribute = CreateAttribute(module, @namespace, name); @in.CustomAttributes.Add(attribute); return attribute; } - public TypeDefinition CreateCompilerGeneratedType(ModuleDefinition module, string? name = null) + public static TypeDefinition CreateCompilerGeneratedType(ModuleDefinition module, string? name = null) { var @object = module.CorLibTypeFactory.Object.ToTypeDefOrRef(); var invisibleType = new TypeDefinition(null, name ?? "", TypeAttributes.Public, @object); InjectCompilerGeneratedAttribute(module, invisibleType); return invisibleType; } - public TypeDefinition CreateCompilerGeneratedValueType(ModuleDefinition module, string? name = null) + public static TypeDefinition CreateCompilerGeneratedValueType(ModuleDefinition module, string? name = null) { var valueType = module.DefaultImporter.ImportType(typeof(ValueType)); var invisibleValueType = new TypeDefinition(null, name ?? "", TypeAttributes.NestedPublic, valueType); InjectCompilerGeneratedAttribute(module, invisibleValueType); return invisibleValueType; } - public CustomAttribute CreateCompilerGeneratedAttribute(ModuleDefinition module) + public static CustomAttribute CreateCompilerGeneratedAttribute(ModuleDefinition module) { var attribute = CreateAttribute(module, typeof(CompilerGeneratedAttribute).Namespace, nameof(CompilerGeneratedAttribute)); return attribute; } - public CustomAttribute CreateAttributeWithContent(ModuleDefinition module, string @namespace, string name, string content) + public static CustomAttribute CreateAttributeWithContent(ModuleDefinition module, string @namespace, string name, string content) { var factory = module.CorLibTypeFactory; var ctor = factory.CorLibScope @@ -90,7 +90,7 @@ public CustomAttribute CreateAttributeWithContent(ModuleDefinition module, strin attribute.Signature.FixedArguments.Add(new CustomAttributeArgument(factory.String, content)); return attribute; } - public CustomAttribute CreateAttribute(ModuleDefinition module, string @namespace, string name) + public static CustomAttribute CreateAttribute(ModuleDefinition module, string @namespace, string name) { var factory = module.CorLibTypeFactory; var ctor = factory.CorLibScope diff --git a/src/BitMono.Core/Renaming/Renamer.cs b/src/BitMono.Core/Renaming/Renamer.cs index ed3b2da3..728f0048 100644 --- a/src/BitMono.Core/Renaming/Renamer.cs +++ b/src/BitMono.Core/Renaming/Renamer.cs @@ -3,43 +3,43 @@ namespace BitMono.Core.Renaming; public class Renamer { - private readonly NameCriticalAnalyzer m_NameCriticalAnalyzer; - private readonly SpecificNamespaceCriticalAnalyzer m_SpecificNamespaceCriticalAnalyzer; - private readonly Obfuscation m_Obfuscation; - private readonly Random m_Random; + private readonly NameCriticalAnalyzer _nameCriticalAnalyzer; + private readonly SpecificNamespaceCriticalAnalyzer _specificNamespaceCriticalAnalyzer; + private readonly Obfuscation _obfuscation; + private readonly RandomNext _randomNext; public Renamer( NameCriticalAnalyzer nameCriticalAnalyzer, SpecificNamespaceCriticalAnalyzer specificNamespaceCriticalAnalyzer, IOptions configuration, - RuntimeImplementations runtime) + RandomNext randomNext) { - m_NameCriticalAnalyzer = nameCriticalAnalyzer; - m_SpecificNamespaceCriticalAnalyzer = specificNamespaceCriticalAnalyzer; - m_Obfuscation = configuration.Value; - m_Random = runtime.Random; + _nameCriticalAnalyzer = nameCriticalAnalyzer; + _specificNamespaceCriticalAnalyzer = specificNamespaceCriticalAnalyzer; + _obfuscation = configuration.Value; + _randomNext = randomNext; } public string RenameUnsafely() { - var strings = m_Obfuscation.RandomStrings; - var randomStringOne = strings[m_Random.Next(0, strings.Length - 1)] + " " + strings[m_Random.Next(0, strings.Length - 1)]; - var randomStringTwo = strings[m_Random.Next(0, strings.Length - 1)]; - var randomStringThree = strings[m_Random.Next(0, strings.Length - 1)]; + var strings = _obfuscation.RandomStrings; + var randomStringOne = strings[_randomNext(0, strings.Length - 1)] + " " + strings[_randomNext(0, strings.Length - 1)]; + var randomStringTwo = strings[_randomNext(0, strings.Length - 1)]; + var randomStringThree = strings[_randomNext(0, strings.Length - 1)]; return $"{randomStringTwo} {randomStringOne}.{randomStringThree}"; } public void Rename(IMetadataMember member) { if (member is TypeDefinition type) { - if (m_NameCriticalAnalyzer.NotCriticalToMakeChanges(type)) + if (_nameCriticalAnalyzer.NotCriticalToMakeChanges(type)) { type.Name = RenameUnsafely(); } } if (member is MethodDefinition method) { - if (m_NameCriticalAnalyzer.NotCriticalToMakeChanges(method)) + if (_nameCriticalAnalyzer.NotCriticalToMakeChanges(method)) { method.Name = RenameUnsafely(); } @@ -64,14 +64,14 @@ public void RemoveNamespace(IMetadataMember member) { if (member is TypeDefinition type) { - if (m_SpecificNamespaceCriticalAnalyzer.NotCriticalToMakeChanges(type)) + if (_specificNamespaceCriticalAnalyzer.NotCriticalToMakeChanges(type)) { type.Namespace = string.Empty; } } if (member is MethodDefinition method) { - if (m_NameCriticalAnalyzer.NotCriticalToMakeChanges(method)) + if (_nameCriticalAnalyzer.NotCriticalToMakeChanges(method)) { method.DeclaringType.Namespace = string.Empty; } diff --git a/src/BitMono.Core/RuntimeImplementations.cs b/src/BitMono.Core/RuntimeImplementations.cs deleted file mode 100644 index c43ffa37..00000000 --- a/src/BitMono.Core/RuntimeImplementations.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace BitMono.Core; - -public class RuntimeImplementations -{ - public RuntimeImplementations(MscorlibInjector mscorlibInjector, CustomInjector customInjector) - { - MscorlibInjector = mscorlibInjector; - CustomInjector = customInjector; - Random = new Random(); - } - - public MscorlibInjector MscorlibInjector { get; } - public CustomInjector CustomInjector { get; } - public Random Random { get; } -} \ No newline at end of file diff --git a/src/BitMono.Core/Services/RandomNext.cs b/src/BitMono.Core/Services/RandomNext.cs new file mode 100644 index 00000000..be2bc995 --- /dev/null +++ b/src/BitMono.Core/Services/RandomNext.cs @@ -0,0 +1,3 @@ +namespace BitMono.Core.Services; + +public delegate int RandomNext(int minValue, int maxValue); \ No newline at end of file diff --git a/src/BitMono.Core/Services/RandomService.cs b/src/BitMono.Core/Services/RandomService.cs new file mode 100644 index 00000000..45a56a75 --- /dev/null +++ b/src/BitMono.Core/Services/RandomService.cs @@ -0,0 +1,11 @@ +namespace BitMono.Core.Services; + +public static class RandomService +{ + private static readonly Random Random = new Random(); + + public static int RandomNext(int minValue, int maxValue) + { + return Random.Next(minValue, maxValue); + } +} \ No newline at end of file diff --git a/src/BitMono.GUI/GlobalUsings.cs b/src/BitMono.GUI/GlobalUsings.cs index cd67da68..52089558 100644 --- a/src/BitMono.GUI/GlobalUsings.cs +++ b/src/BitMono.GUI/GlobalUsings.cs @@ -5,7 +5,6 @@ global using BitMono.GUI.Shared.Alerting; global using BitMono.GUI.Shared.Inputs; global using BitMono.Host.Modules; -global using BitMono.Obfuscation; global using BitMono.Shared.Models; global using Microsoft.AspNetCore.Components; global using Microsoft.AspNetCore.Components.Forms; diff --git a/src/BitMono.Host/GlobalUsings.cs b/src/BitMono.Host/GlobalUsings.cs index a389214d..88bef5ec 100644 --- a/src/BitMono.Host/GlobalUsings.cs +++ b/src/BitMono.Host/GlobalUsings.cs @@ -17,11 +17,10 @@ global using BitMono.API.Analyzing; global using BitMono.API.Pipeline; global using BitMono.API.Resolvers; -global using BitMono.Core; global using BitMono.Core.Configuration; -global using BitMono.Core.Injection; global using BitMono.Core.Renaming; global using BitMono.Core.Resolvers; +global using BitMono.Core.Services; global using BitMono.Shared.Models; global using Serilog.Enrichers.Sensitive; global using Module = Autofac.Module; \ No newline at end of file diff --git a/src/BitMono.Host/Modules/BitMonoModule.cs b/src/BitMono.Host/Modules/BitMonoModule.cs index 35f57ea0..cbf0670d 100644 --- a/src/BitMono.Host/Modules/BitMonoModule.cs +++ b/src/BitMono.Host/Modules/BitMonoModule.cs @@ -49,22 +49,11 @@ protected override void Load(ContainerBuilder containerBuilder) var serviceCollection = new ServiceCollection(); m_ConfigureServices?.Invoke(serviceCollection); - containerBuilder.RegisterType() - .OwnedByLifetimeScope() - .SingleInstance(); - - containerBuilder.RegisterType() - .AsSelf() + containerBuilder.Register(_ => RandomService.RandomNext) .OwnedByLifetimeScope() .SingleInstance(); - containerBuilder.RegisterType() - .AsSelf() - .OwnedByLifetimeScope() - .SingleInstance(); - - containerBuilder.RegisterType() - .AsSelf() + containerBuilder.RegisterType() .OwnedByLifetimeScope() .SingleInstance(); diff --git a/src/BitMono.Obfuscation/BitMonoObfuscator.cs b/src/BitMono.Obfuscation/BitMonoObfuscator.cs index a406de92..c8a11b62 100644 --- a/src/BitMono.Obfuscation/BitMonoObfuscator.cs +++ b/src/BitMono.Obfuscation/BitMonoObfuscator.cs @@ -1,4 +1,6 @@ -#pragma warning disable CS8604 +using BitMono.Utilities.Runtime; + +#pragma warning disable CS8604 #pragma warning disable CS8602 namespace BitMono.Obfuscation; diff --git a/src/BitMono.Obfuscation/GlobalUsings.cs b/src/BitMono.Obfuscation/GlobalUsings.cs index 6e6a86b8..61b1df7e 100644 --- a/src/BitMono.Obfuscation/GlobalUsings.cs +++ b/src/BitMono.Obfuscation/GlobalUsings.cs @@ -29,7 +29,6 @@ global using BitMono.Obfuscation.Factories; global using BitMono.Obfuscation.Interfaces; global using BitMono.Obfuscation.Notifiers; -global using BitMono.Utilities; global using BitMono.Utilities.AsmResolver; global using BitMono.Utilities.Time; global using Microsoft.Extensions.Options; diff --git a/src/BitMono.Protections/AntiDe4dot.cs b/src/BitMono.Protections/AntiDe4dot.cs index 3f072079..27b84283 100644 --- a/src/BitMono.Protections/AntiDe4dot.cs +++ b/src/BitMono.Protections/AntiDe4dot.cs @@ -2,31 +2,28 @@ public class AntiDe4dot : Protection { - private readonly CustomInjector m_Injector; - - public AntiDe4dot(CustomInjector injector, ProtectionContext context) : base(context) + public AntiDe4dot(ProtectionContext context) : base(context) { - m_Injector = injector; } public override Task ExecuteAsync(ProtectionParameters parameters) { - m_Injector.InjectAttribute(Context.Module, "SmartAssembly.Attributes", "PoweredBy", string.Empty); - m_Injector.InjectAttribute(Context.Module, "Xenocode.Client.Attributes.AssemblyAttributes", "PoweredBy", string.Empty); - m_Injector.InjectAttribute(Context.Module, string.Empty, "ObfuscatedByGoliath", string.Empty); - m_Injector.InjectAttribute(Context.Module, "SecureTeam.Attributes", "ObfuscatedByAgileDotNet", string.Empty); - m_Injector.InjectAttribute(Context.Module, string.Empty, "TrinityObfuscator", string.Empty); - m_Injector.InjectAttribute(Context.Module, "SecureTeam.Attributes", "ObfuscatedByCliSecure", string.Empty); - m_Injector.InjectAttribute(Context.Module, string.Empty, "ZYXDNGuarder", string.Empty); - m_Injector.InjectAttribute(Context.Module, string.Empty, "BabelObfuscator", string.Empty); - m_Injector.InjectAttribute(Context.Module, string.Empty, "BabelObfuscator", string.Empty); - m_Injector.InjectAttribute(Context.Module, string.Empty, "Dotfuscator", string.Empty); - m_Injector.InjectAttribute(Context.Module, string.Empty, "Centos", string.Empty); - m_Injector.InjectAttribute(Context.Module, string.Empty, "ConfusedBy", string.Empty); - m_Injector.InjectAttribute(Context.Module, "NineRays.Obfuscator", "Evaluation", string.Empty); - m_Injector.InjectAttribute(Context.Module, "CryptoObfuscator", "ProtectedWithCryptoObfuscator", string.Empty); - m_Injector.InjectAttribute(Context.Module, string.Empty, "();\u0009", string.Empty); - m_Injector.InjectAttribute(Context.Module, string.Empty, "EMyPID_8234_", string.Empty); + CustomInjector.InjectAttribute(Context.Module, "SmartAssembly.Attributes", "PoweredBy", string.Empty); + CustomInjector.InjectAttribute(Context.Module, "Xenocode.Client.Attributes.AssemblyAttributes", "PoweredBy", string.Empty); + CustomInjector.InjectAttribute(Context.Module, string.Empty, "ObfuscatedByGoliath", string.Empty); + CustomInjector.InjectAttribute(Context.Module, "SecureTeam.Attributes", "ObfuscatedByAgileDotNet", string.Empty); + CustomInjector.InjectAttribute(Context.Module, string.Empty, "TrinityObfuscator", string.Empty); + CustomInjector.InjectAttribute(Context.Module, "SecureTeam.Attributes", "ObfuscatedByCliSecure", string.Empty); + CustomInjector.InjectAttribute(Context.Module, string.Empty, "ZYXDNGuarder", string.Empty); + CustomInjector.InjectAttribute(Context.Module, string.Empty, "BabelObfuscator", string.Empty); + CustomInjector.InjectAttribute(Context.Module, string.Empty, "BabelObfuscator", string.Empty); + CustomInjector.InjectAttribute(Context.Module, string.Empty, "Dotfuscator", string.Empty); + CustomInjector.InjectAttribute(Context.Module, string.Empty, "Centos", string.Empty); + CustomInjector.InjectAttribute(Context.Module, string.Empty, "ConfusedBy", string.Empty); + CustomInjector.InjectAttribute(Context.Module, "NineRays.Obfuscator", "Evaluation", string.Empty); + CustomInjector.InjectAttribute(Context.Module, "CryptoObfuscator", "ProtectedWithCryptoObfuscator", string.Empty); + CustomInjector.InjectAttribute(Context.Module, string.Empty, "();\u0009", string.Empty); + CustomInjector.InjectAttribute(Context.Module, string.Empty, "EMyPID_8234_", string.Empty); return Task.CompletedTask; } } \ No newline at end of file diff --git a/src/BitMono.Protections/AntiILdasm.cs b/src/BitMono.Protections/AntiILdasm.cs index 032fb59b..aa9f4708 100644 --- a/src/BitMono.Protections/AntiILdasm.cs +++ b/src/BitMono.Protections/AntiILdasm.cs @@ -2,16 +2,13 @@ public class AntiILdasm : Protection { - private readonly MscorlibInjector _injector; - - public AntiILdasm(MscorlibInjector injector, ProtectionContext context) : base(context) + public AntiILdasm(ProtectionContext context) : base(context) { - _injector = injector; } public override Task ExecuteAsync(ProtectionParameters parameters) { - _injector.InjectAttribute(Context.Module, typeof(SuppressIldasmAttribute).Namespace, nameof(SuppressIldasmAttribute), Context.Module); + MscorlibInjector.InjectAttribute(Context.Module, typeof(SuppressIldasmAttribute).Namespace, nameof(SuppressIldasmAttribute), Context.Module); return Task.CompletedTask; } } \ No newline at end of file diff --git a/src/BitMono.Protections/BitMethodDotnet.cs b/src/BitMono.Protections/BitMethodDotnet.cs index ff5227bc..dabca246 100644 --- a/src/BitMono.Protections/BitMethodDotnet.cs +++ b/src/BitMono.Protections/BitMethodDotnet.cs @@ -3,13 +3,15 @@ [DoNotResolve(MemberInclusionFlags.SpecialRuntime)] public class BitMethodDotnet : Protection { - private readonly Random _random; + private readonly RandomNext _randomNext; - public BitMethodDotnet(RuntimeImplementations runtime, ProtectionContext context) : base(context) + public BitMethodDotnet(RandomNext randomNext, ProtectionContext context) : base(context) { - _random = runtime.Random; + _randomNext = randomNext; } + [SuppressMessage("ReSharper", "InvertIf")] + [SuppressMessage("ReSharper", "ConvertIfStatementToConditionalTernaryExpression")] public override Task ExecuteAsync(ProtectionParameters parameters) { foreach (var method in parameters.Members.OfType()) @@ -19,10 +21,10 @@ public override Task ExecuteAsync(ProtectionParameters parameters) var randomMethodBodyIndex = 0; if (body.Instructions.Count >= 3) { - randomMethodBodyIndex = _random.Next(0, body.Instructions.Count); + randomMethodBodyIndex = _randomNext(0, body.Instructions.Count); } - var randomValue = _random.Next(0, 3); + var randomValue = _randomNext(0, 3); var randomOpCode = randomValue switch { 0 => CilOpCodes.Readonly, diff --git a/src/BitMono.Protections/DotNetHook.cs b/src/BitMono.Protections/DotNetHook.cs index 3c72030e..a95b4975 100644 --- a/src/BitMono.Protections/DotNetHook.cs +++ b/src/BitMono.Protections/DotNetHook.cs @@ -3,12 +3,12 @@ public class DotNetHook : Protection { private readonly Renamer _renamer; - private readonly Random _random; + private readonly RandomNext _randomNext; - public DotNetHook(Renamer renamer, RuntimeImplementations runtime, ProtectionContext context) : base(context) + public DotNetHook(Renamer renamer, RandomNext randomNext, ProtectionContext context) : base(context) { _renamer = renamer; - _random = runtime.Random; + _randomNext = randomNext; } [SuppressMessage("ReSharper", "ForCanBeConvertedToForeach")] @@ -79,7 +79,7 @@ public override Task ExecuteAsync(ProtectionParameters parameters) moduleType.Methods.Add(initializationMethod); instruction.Operand = dummyMethod; - var randomIndex = _random.Next(0, moduleCctor.CilMethodBody.Instructions.CountWithoutRet()); + var randomIndex = _randomNext(0, moduleCctor.CilMethodBody.Instructions.CountWithoutRet()); moduleCctor.CilMethodBody.Instructions.Insert(randomIndex, new CilInstruction(CilOpCodes.Call, initializationMethod)); } } diff --git a/src/BitMono.Protections/GlobalUsings.cs b/src/BitMono.Protections/GlobalUsings.cs index 02e282d3..eac0462e 100644 --- a/src/BitMono.Protections/GlobalUsings.cs +++ b/src/BitMono.Protections/GlobalUsings.cs @@ -19,6 +19,7 @@ global using BitMono.Core.Contexts; global using BitMono.Core.Injection; global using BitMono.Core.Renaming; +global using BitMono.Core.Services; global using BitMono.Utilities.AsmResolver; global using MethodAttributes = AsmResolver.PE.DotNet.Metadata.Tables.Rows.MethodAttributes; global using TypeAttributes = AsmResolver.PE.DotNet.Metadata.Tables.Rows.TypeAttributes; \ No newline at end of file diff --git a/src/BitMono.Protections/StringsEncryption.cs b/src/BitMono.Protections/StringsEncryption.cs index 05f6ca5d..986bbf30 100644 --- a/src/BitMono.Protections/StringsEncryption.cs +++ b/src/BitMono.Protections/StringsEncryption.cs @@ -3,21 +3,19 @@ [DoNotResolve(MemberInclusionFlags.SpecialRuntime)] public class StringsEncryption : Protection { - private readonly MscorlibInjector _injector; private readonly Renamer _renamer; - public StringsEncryption(RuntimeImplementations runtime, Renamer renamer, ProtectionContext context) : base(context) + public StringsEncryption(Renamer renamer, ProtectionContext context) : base(context) { - _injector = runtime.MscorlibInjector; _renamer = renamer; } public override Task ExecuteAsync(ProtectionParameters parameters) { var globalModuleType = Context.Module.GetOrCreateModuleType(); - _injector.InjectCompilerGeneratedValueType(Context.Module, globalModuleType, _renamer.RenameUnsafely()); - var cryptKeyField = _injector.InjectCompilerGeneratedArray(Context.Module, globalModuleType, Data.CryptKeyBytes, _renamer.RenameUnsafely()); - var saltBytesField = _injector.InjectCompilerGeneratedArray(Context.Module, globalModuleType, Data.SaltBytes, _renamer.RenameUnsafely()); + MscorlibInjector.InjectCompilerGeneratedValueType(Context.Module, globalModuleType, _renamer.RenameUnsafely()); + var cryptKeyField = MscorlibInjector.InjectCompilerGeneratedArray(Context.Module, globalModuleType, Data.CryptKeyBytes, _renamer.RenameUnsafely()); + var saltBytesField = MscorlibInjector.InjectCompilerGeneratedArray(Context.Module, globalModuleType, Data.SaltBytes, _renamer.RenameUnsafely()); var runtimeDecryptorType = Context.RuntimeModule.ResolveOrThrow(typeof(Decryptor)); var runtimeDecryptMethod = runtimeDecryptorType.Methods.Single(c => c.Name.Equals(nameof(Decryptor.Decrypt))); @@ -38,7 +36,7 @@ public override Task ExecuteAsync(ProtectionParameters parameters) { var data = Encryptor.EncryptContent(content, Data.SaltBytes, Data.CryptKeyBytes); var arrayName = _renamer.RenameUnsafely(); - var encryptedDataFieldDef = _injector.InjectCompilerGeneratedArray(Context.Module, globalModuleType, data, arrayName); + var encryptedDataFieldDef = MscorlibInjector.InjectCompilerGeneratedArray(Context.Module, globalModuleType, data, arrayName); body.Instructions[i].ReplaceWith(CilOpCodes.Ldsfld, encryptedDataFieldDef); body.Instructions.InsertRange(i + 1, new CilInstruction[] diff --git a/src/BitMono.Utilities/GlobalUsings.cs b/src/BitMono.Utilities/GlobalUsings.cs index 7b319f48..e55c320c 100644 --- a/src/BitMono.Utilities/GlobalUsings.cs +++ b/src/BitMono.Utilities/GlobalUsings.cs @@ -14,5 +14,4 @@ global using System.Reflection; global using System.Runtime.CompilerServices; global using AsmResolver.DotNet.Signatures; -global using AsmResolver.DotNet.Signatures.Types; -global using BitMono.Utilities.Time; \ No newline at end of file +global using AsmResolver.DotNet.Signatures.Types; \ No newline at end of file diff --git a/src/BitMono.Utilities/StringPathExtensions.cs b/src/BitMono.Utilities/Paths/StringPathExtensions.cs similarity index 91% rename from src/BitMono.Utilities/StringPathExtensions.cs rename to src/BitMono.Utilities/Paths/StringPathExtensions.cs index c26fb630..78f6facc 100644 --- a/src/BitMono.Utilities/StringPathExtensions.cs +++ b/src/BitMono.Utilities/Paths/StringPathExtensions.cs @@ -1,4 +1,4 @@ -namespace BitMono.Utilities; +namespace BitMono.Utilities.Paths; public static class StringPathExtensions { diff --git a/src/BitMono.Utilities/EnvironmentRuntimeInformation.cs b/src/BitMono.Utilities/Runtime/EnvironmentRuntimeInformation.cs similarity index 93% rename from src/BitMono.Utilities/EnvironmentRuntimeInformation.cs rename to src/BitMono.Utilities/Runtime/EnvironmentRuntimeInformation.cs index 33d21f5d..770208d5 100644 --- a/src/BitMono.Utilities/EnvironmentRuntimeInformation.cs +++ b/src/BitMono.Utilities/Runtime/EnvironmentRuntimeInformation.cs @@ -1,4 +1,4 @@ -namespace BitMono.Utilities; +namespace BitMono.Utilities.Runtime; public class EnvironmentRuntimeInformation { diff --git a/src/BitMono.Utilities/Time/KnownMonoRuntimes.cs b/src/BitMono.Utilities/Runtime/KnownMonoRuntimes.cs similarity index 79% rename from src/BitMono.Utilities/Time/KnownMonoRuntimes.cs rename to src/BitMono.Utilities/Runtime/KnownMonoRuntimes.cs index 7682d07c..51a40cad 100644 --- a/src/BitMono.Utilities/Time/KnownMonoRuntimes.cs +++ b/src/BitMono.Utilities/Runtime/KnownMonoRuntimes.cs @@ -1,4 +1,4 @@ -namespace BitMono.Utilities.Time; +namespace BitMono.Utilities.Runtime; public static class KnownMonoRuntimes { diff --git a/src/BitMono.Utilities/RuntimeUtilities.cs b/src/BitMono.Utilities/Runtime/RuntimeUtilities.cs similarity index 97% rename from src/BitMono.Utilities/RuntimeUtilities.cs rename to src/BitMono.Utilities/Runtime/RuntimeUtilities.cs index 338a414b..e8250bf5 100644 --- a/src/BitMono.Utilities/RuntimeUtilities.cs +++ b/src/BitMono.Utilities/Runtime/RuntimeUtilities.cs @@ -1,4 +1,4 @@ -namespace BitMono.Utilities; +namespace BitMono.Utilities.Runtime; public static class RuntimeUtilities { diff --git a/test/BitMono.Benchmarks/GlobalUsings.cs b/test/BitMono.Benchmarks/GlobalUsings.cs index 718bb5ae..93153fb8 100644 --- a/test/BitMono.Benchmarks/GlobalUsings.cs +++ b/test/BitMono.Benchmarks/GlobalUsings.cs @@ -1,3 +1,3 @@ global using BenchmarkDotNet.Attributes; global using BenchmarkDotNet.Running; -global using BitMono.Utilities; \ No newline at end of file +global using BitMono.Utilities.Runtime; \ No newline at end of file From da3da29b3b28db7b71bd0a04a420ae142f56a369 Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Tue, 28 Feb 2023 12:33:37 +0200 Subject: [PATCH 09/24] Make static readonly field const --- src/BitMono.Host/Extensions/AutofacServiceProviderExtensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/BitMono.Host/Extensions/AutofacServiceProviderExtensions.cs b/src/BitMono.Host/Extensions/AutofacServiceProviderExtensions.cs index a0d3b906..3d2cb607 100644 --- a/src/BitMono.Host/Extensions/AutofacServiceProviderExtensions.cs +++ b/src/BitMono.Host/Extensions/AutofacServiceProviderExtensions.cs @@ -5,7 +5,7 @@ namespace BitMono.Host.Extensions; [SuppressMessage("ReSharper", "IdentifierTypo")] public static class AutofacServiceProviderExtensions { - private static readonly string ProtectionsFileName = "BitMono.Protections.dll"; + private const string ProtectionsFileName = "BitMono.Protections.dll"; public static ContainerBuilder AddProtections(this ContainerBuilder source, string? file = null) { var rawData = File.ReadAllBytes(file ?? ProtectionsFileName); From ef0ab886e1edb1d3026d9034e82ed13b880e7e30 Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Tue, 28 Feb 2023 13:07:09 +0200 Subject: [PATCH 10/24] Code refactoring --- .../Injection/MscrolibInjector.cs | 12 ++--- .../AntiDebugBreakpoints.cs | 50 ++++++++++--------- src/BitMono.Protections/AntiDecompiler.cs | 4 +- src/BitMono.Protections/CallToCalli.cs | 22 ++++---- src/BitMono.Protections/FullRenamer.cs | 5 +- src/BitMono.Protections/GlobalUsings.cs | 1 + src/BitMono.Protections/ObjectReturnType.cs | 5 +- src/BitMono.Protections/StringsEncryption.cs | 7 +-- 8 files changed, 55 insertions(+), 51 deletions(-) diff --git a/src/BitMono.Core/Injection/MscrolibInjector.cs b/src/BitMono.Core/Injection/MscrolibInjector.cs index 46bea1da..ba0b64a5 100644 --- a/src/BitMono.Core/Injection/MscrolibInjector.cs +++ b/src/BitMono.Core/Injection/MscrolibInjector.cs @@ -32,12 +32,12 @@ public static FieldDefinition InjectCompilerGeneratedArray(ModuleDefinition modu var instructions = cctor.CilMethodBody.Instructions; instructions.InsertRange(0, new CilInstruction[] { - new CilInstruction(CilOpCodes.Ldc_I4, data.Length), - new CilInstruction(CilOpCodes.Newarr, systemByte), - new CilInstruction(CilOpCodes.Dup), - new CilInstruction(CilOpCodes.Ldtoken, fieldWithRVA), - new CilInstruction(CilOpCodes.Call, initializeArrayMethod), - new CilInstruction(CilOpCodes.Stsfld, fieldInjectedArray), + new(CilOpCodes.Ldc_I4, data.Length), + new(CilOpCodes.Newarr, systemByte), + new(CilOpCodes.Dup), + new(CilOpCodes.Ldtoken, fieldWithRVA), + new(CilOpCodes.Call, initializeArrayMethod), + new(CilOpCodes.Stsfld, fieldInjectedArray), }); return fieldInjectedArray; } diff --git a/src/BitMono.Protections/AntiDebugBreakpoints.cs b/src/BitMono.Protections/AntiDebugBreakpoints.cs index e3255a4f..c15bbbaf 100644 --- a/src/BitMono.Protections/AntiDebugBreakpoints.cs +++ b/src/BitMono.Protections/AntiDebugBreakpoints.cs @@ -7,45 +7,47 @@ public AntiDebugBreakpoints(ProtectionContext context) : base(context) { } + [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] + [SuppressMessage("ReSharper", "InvertIf")] public override Task ExecuteAsync(ProtectionParameters parameters) { var threadSleepMethods = new List { - Context.Importer.ImportMethod(typeof(Thread).GetMethod(nameof(Thread.Sleep), new Type[] + Context.Importer.ImportMethod(typeof(Thread).GetMethod(nameof(Thread.Sleep), new[] { typeof(int) })), - Context.Importer.ImportMethod(typeof(Thread).GetMethod(nameof(Thread.Sleep), new Type[] + Context.Importer.ImportMethod(typeof(Thread).GetMethod(nameof(Thread.Sleep), new[] { typeof(TimeSpan) })), - Context.Importer.ImportMethod(typeof(Task).GetMethod(nameof(Task.Delay), new Type[] + Context.Importer.ImportMethod(typeof(Task).GetMethod(nameof(Task.Delay), new[] { typeof(int) })), - Context.Importer.ImportMethod(typeof(Task).GetMethod(nameof(Task.Delay), new Type[] + Context.Importer.ImportMethod(typeof(Task).GetMethod(nameof(Task.Delay), new[] { typeof(TimeSpan) })), - Context.Importer.ImportMethod(typeof(Task).GetMethod(nameof(Task.Delay), new Type[] + Context.Importer.ImportMethod(typeof(Task).GetMethod(nameof(Task.Delay), new[] { typeof(int), typeof(CancellationToken), })), - Context.Importer.ImportMethod(typeof(Task).GetMethod(nameof(Task.Delay), new Type[] + Context.Importer.ImportMethod(typeof(Task).GetMethod(nameof(Task.Delay), new[] { typeof(TimeSpan), typeof(CancellationToken), })), }; var dateTimeUtcNowMethod = Context.Importer.ImportMethod(typeof(DateTime).GetProperty(nameof(DateTime.UtcNow)).GetMethod); - var dateTimeSubtractionMethod = Context.Importer.ImportMethod(typeof(DateTime).GetMethod("op_Subtraction", new Type[] + var dateTimeSubtractionMethod = Context.Importer.ImportMethod(typeof(DateTime).GetMethod("op_Subtraction", new[] { typeof(DateTime), typeof(DateTime) })); var timeSpanTotalMillisecondsMethod = Context.Importer.ImportMethod(typeof(TimeSpan).GetProperty(nameof(TimeSpan.TotalMilliseconds)).GetMethod); - var environmentFailFast = Context.Importer.ImportMethod(typeof(Environment).GetMethod(nameof(Environment.FailFast), new Type[] + var environmentFailFast = Context.Importer.ImportMethod(typeof(Environment).GetMethod(nameof(Environment.FailFast), new[] { typeof(string) })); @@ -90,7 +92,7 @@ public override Task ExecuteAsync(ProtectionParameters parameters) body.LocalVariables.Add(timeSpanLocal); body.LocalVariables.Add(intLocal); - body.Instructions.InsertRange(startIndex, new CilInstruction[] + body.Instructions.InsertRange(startIndex, new[] { new CilInstruction(CilOpCodes.Call, dateTimeUtcNowMethod), new CilInstruction(CilOpCodes.Stloc_S, dateTimeLocal) @@ -98,22 +100,22 @@ public override Task ExecuteAsync(ProtectionParameters parameters) var nopInstruction = new CilInstruction(CilOpCodes.Nop); var nopLabel = nopInstruction.CreateLabel(); - body.Instructions.InsertRange(endIndex, new CilInstruction[] + body.Instructions.InsertRange(endIndex, new[] { - new CilInstruction(CilOpCodes.Call, dateTimeUtcNowMethod), - new CilInstruction(CilOpCodes.Ldloc_S, dateTimeLocal), - new CilInstruction(CilOpCodes.Call, dateTimeSubtractionMethod), - new CilInstruction(CilOpCodes.Stloc_S, timeSpanLocal), - new CilInstruction(CilOpCodes.Ldloca_S, timeSpanLocal), - new CilInstruction(CilOpCodes.Call, timeSpanTotalMillisecondsMethod), - new CilInstruction(CilOpCodes.Ldc_R8, 5000.0), - new CilInstruction(CilOpCodes.Ble_Un_S, nopLabel), - new CilInstruction(CilOpCodes.Ldc_I4_1), - new CilInstruction(CilOpCodes.Ldc_I4_0), - new CilInstruction(CilOpCodes.Stloc_S, intLocal), - new CilInstruction(CilOpCodes.Ldloc_S, intLocal), - new CilInstruction(CilOpCodes.Div), - new CilInstruction(CilOpCodes.Pop), + new(CilOpCodes.Call, dateTimeUtcNowMethod), + new(CilOpCodes.Ldloc_S, dateTimeLocal), + new(CilOpCodes.Call, dateTimeSubtractionMethod), + new(CilOpCodes.Stloc_S, timeSpanLocal), + new(CilOpCodes.Ldloca_S, timeSpanLocal), + new(CilOpCodes.Call, timeSpanTotalMillisecondsMethod), + new(CilOpCodes.Ldc_R8, 5000.0), + new(CilOpCodes.Ble_Un_S, nopLabel), + new(CilOpCodes.Ldc_I4_1), + new(CilOpCodes.Ldc_I4_0), + new(CilOpCodes.Stloc_S, intLocal), + new(CilOpCodes.Ldloc_S, intLocal), + new(CilOpCodes.Div), + new(CilOpCodes.Pop), nopInstruction }); } diff --git a/src/BitMono.Protections/AntiDecompiler.cs b/src/BitMono.Protections/AntiDecompiler.cs index af7b305e..441f2376 100644 --- a/src/BitMono.Protections/AntiDecompiler.cs +++ b/src/BitMono.Protections/AntiDecompiler.cs @@ -1,6 +1,4 @@ -using BitMono.API.Pipeline; - -namespace BitMono.Protections; +namespace BitMono.Protections; [RuntimeMonikerMono] public class AntiDecompiler : PipelineProtection diff --git a/src/BitMono.Protections/CallToCalli.cs b/src/BitMono.Protections/CallToCalli.cs index c784b2e4..402d8d98 100644 --- a/src/BitMono.Protections/CallToCalli.cs +++ b/src/BitMono.Protections/CallToCalli.cs @@ -13,12 +13,12 @@ public CallToCalli(ProtectionContext context) : base(context) public override Task ExecuteAsync(ProtectionParameters parameters) { var runtimeMethodHandle = Context.Importer.ImportType(typeof(RuntimeMethodHandle)).ToTypeSignature(isValueType: true); - var getTypeFromHandleMethod = Context.Importer.ImportMethod(typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle), new Type[] + var getTypeFromHandleMethod = Context.Importer.ImportMethod(typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle), new[] { typeof(RuntimeTypeHandle) })); var getModuleMethod = Context.Importer.ImportMethod(typeof(Type).GetProperty(nameof(Type.Module)).GetMethod); - var resolveMethodMethod = Context.Importer.ImportMethod(typeof(Module).GetMethod(nameof(Module.ResolveMethod), new Type[] + var resolveMethodMethod = Context.Importer.ImportMethod(typeof(Module).GetMethod(nameof(Module.ResolveMethod), new[] { typeof(int) })); @@ -45,15 +45,15 @@ public override Task ExecuteAsync(ProtectionParameters parameters) instruction.ReplaceWith(CilOpCodes.Ldtoken, moduleType); body.Instructions.InsertRange(i + 1, new CilInstruction[] { - new CilInstruction(CilOpCodes.Call, getTypeFromHandleMethod), - new CilInstruction(CilOpCodes.Callvirt, getModuleMethod), - new CilInstruction(CilOpCodes.Ldc_I4, callingMethodMetadata.MetadataToken.ToInt32()), - new CilInstruction(CilOpCodes.Call, resolveMethodMethod), - new CilInstruction(CilOpCodes.Callvirt, getMethodHandleMethod), - new CilInstruction(CilOpCodes.Stloc, runtimeMethodHandleLocal), - new CilInstruction(CilOpCodes.Ldloca, runtimeMethodHandleLocal), - new CilInstruction(CilOpCodes.Call, getFunctionPointerMethod), - new CilInstruction(CilOpCodes.Calli, callingMethod.Signature.MakeStandAloneSignature()) + new(CilOpCodes.Call, getTypeFromHandleMethod), + new(CilOpCodes.Callvirt, getModuleMethod), + new(CilOpCodes.Ldc_I4, callingMethodMetadata.MetadataToken.ToInt32()), + new(CilOpCodes.Call, resolveMethodMethod), + new(CilOpCodes.Callvirt, getMethodHandleMethod), + new(CilOpCodes.Stloc, runtimeMethodHandleLocal), + new(CilOpCodes.Ldloca, runtimeMethodHandleLocal), + new(CilOpCodes.Call, getFunctionPointerMethod), + new(CilOpCodes.Calli, callingMethod.Signature.MakeStandAloneSignature()) }); } } diff --git a/src/BitMono.Protections/FullRenamer.cs b/src/BitMono.Protections/FullRenamer.cs index cfd4344c..2b390239 100644 --- a/src/BitMono.Protections/FullRenamer.cs +++ b/src/BitMono.Protections/FullRenamer.cs @@ -10,11 +10,12 @@ public FullRenamer(Renamer renamer, ProtectionContext context) : base(context) _renamer = renamer; } + [SuppressMessage("ReSharper", "InvertIf")] public override Task ExecuteAsync(ProtectionParameters parameters) { foreach (var method in parameters.Members.OfType()) { - if (method.DeclaringType.IsModuleType == false && method.IsConstructor == false && method.IsVirtual == false) + if (method.DeclaringType?.IsModuleType == false && method is { IsConstructor: false, IsVirtual: false }) { _renamer.Rename(method); if (method.HasParameters()) @@ -35,7 +36,7 @@ public override Task ExecuteAsync(ProtectionParameters parameters) } foreach (var field in parameters.Members.OfType()) { - if (field.DeclaringType.IsModuleType == false) + if (field.DeclaringType?.IsModuleType == false) { _renamer.Rename(field); } diff --git a/src/BitMono.Protections/GlobalUsings.cs b/src/BitMono.Protections/GlobalUsings.cs index eac0462e..c3bcd53c 100644 --- a/src/BitMono.Protections/GlobalUsings.cs +++ b/src/BitMono.Protections/GlobalUsings.cs @@ -14,6 +14,7 @@ global using System.Threading; global using System.Threading.Tasks; global using BitMono.API.Contexts; +global using BitMono.API.Pipeline; global using BitMono.Core; global using BitMono.Core.Attributes; global using BitMono.Core.Contexts; diff --git a/src/BitMono.Protections/ObjectReturnType.cs b/src/BitMono.Protections/ObjectReturnType.cs index e62416a2..13cb82e3 100644 --- a/src/BitMono.Protections/ObjectReturnType.cs +++ b/src/BitMono.Protections/ObjectReturnType.cs @@ -7,6 +7,7 @@ public ObjectReturnType(ProtectionContext context) : base(context) { } + [SuppressMessage("ReSharper", "InvertIf")] public override Task ExecuteAsync(ProtectionParameters parameters) { var factory = Context.Module.CorLibTypeFactory; @@ -16,8 +17,8 @@ public override Task ExecuteAsync(ProtectionParameters parameters) { if (method.Signature.ReturnsValue(systemBoolean)) { - if (method.IsConstructor == false && method.IsVirtual == false && method.NotAsync() - && method.IsSetMethod == false && method.IsGetMethod == false) + if (method is { IsConstructor: false, IsVirtual: false, IsSetMethod: false, IsGetMethod: false } + && method.NotAsync()) { if (method.ParameterDefinitions.Any(p => p.IsOut || p.IsIn) == false) { diff --git a/src/BitMono.Protections/StringsEncryption.cs b/src/BitMono.Protections/StringsEncryption.cs index 986bbf30..7dcb6fc3 100644 --- a/src/BitMono.Protections/StringsEncryption.cs +++ b/src/BitMono.Protections/StringsEncryption.cs @@ -10,6 +10,7 @@ public StringsEncryption(Renamer renamer, ProtectionContext context) : base(cont _renamer = renamer; } + [SuppressMessage("ReSharper", "InvertIf")] public override Task ExecuteAsync(ProtectionParameters parameters) { var globalModuleType = Context.Module.GetOrCreateModuleType(); @@ -41,9 +42,9 @@ public override Task ExecuteAsync(ProtectionParameters parameters) body.Instructions[i].ReplaceWith(CilOpCodes.Ldsfld, encryptedDataFieldDef); body.Instructions.InsertRange(i + 1, new CilInstruction[] { - new CilInstruction(CilOpCodes.Ldsfld, saltBytesField), - new CilInstruction(CilOpCodes.Ldsfld, cryptKeyField), - new CilInstruction(CilOpCodes.Call, decryptMethod), + new(CilOpCodes.Ldsfld, saltBytesField), + new(CilOpCodes.Ldsfld, cryptKeyField), + new(CilOpCodes.Call, decryptMethod), }); } } From d657b02eddfd65ebd968a3c36ace7a91e0dd6e53 Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Tue, 28 Feb 2023 13:09:05 +0200 Subject: [PATCH 11/24] ProtectionParameters to file scoped namespace --- src/BitMono.API/Contexts/ProtectionParameters.cs | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/BitMono.API/Contexts/ProtectionParameters.cs b/src/BitMono.API/Contexts/ProtectionParameters.cs index b50af740..dd857ad5 100644 --- a/src/BitMono.API/Contexts/ProtectionParameters.cs +++ b/src/BitMono.API/Contexts/ProtectionParameters.cs @@ -1,12 +1,11 @@ -namespace BitMono.API.Contexts +namespace BitMono.API.Contexts; + +public class ProtectionParameters { - public class ProtectionParameters + public ProtectionParameters(List members) { - public ProtectionParameters(List members) - { - Members = members; - } - - public List Members { get; } + Members = members; } + + public List Members { get; } } \ No newline at end of file From 1601e0007457996f18cfcf8c63c03d3d418a6d91 Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Tue, 28 Feb 2023 13:19:38 +0200 Subject: [PATCH 12/24] Update BitMonoApplication.cs --- src/BitMono.Host/BitMonoApplication.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/BitMono.Host/BitMonoApplication.cs b/src/BitMono.Host/BitMonoApplication.cs index ceac0913..f9225270 100644 --- a/src/BitMono.Host/BitMonoApplication.cs +++ b/src/BitMono.Host/BitMonoApplication.cs @@ -24,9 +24,10 @@ public IApplication RegisterModule(IModule module) [SuppressMessage("ReSharper", "ForCanBeConvertedToForeach")] public AutofacServiceProvider Build() { - for (var i = 0; i < m_Modules.Count; i++) + var modules = m_Modules; + for (var i = 0; i < modules.Count; i++) { - m_ContainerBuilder.RegisterModule(m_Modules[i]); + m_ContainerBuilder.RegisterModule(modules[i]); } var container = m_ContainerBuilder.Build(); return new AutofacServiceProvider(container.Resolve()); From cdab9e23173c33c438373a04d92d46e133514d25 Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Tue, 28 Feb 2023 13:28:55 +0200 Subject: [PATCH 13/24] Improved path making --- src/BitMono.Host/Extensions/IPathWrapper.cs | 8 +++++ .../Extensions/PathMaskingOperator.cs | 29 ++++++++++++++----- src/BitMono.Host/Extensions/PathWrapper.cs | 17 +++++++++++ 3 files changed, 47 insertions(+), 7 deletions(-) create mode 100644 src/BitMono.Host/Extensions/IPathWrapper.cs create mode 100644 src/BitMono.Host/Extensions/PathWrapper.cs diff --git a/src/BitMono.Host/Extensions/IPathWrapper.cs b/src/BitMono.Host/Extensions/IPathWrapper.cs new file mode 100644 index 00000000..c09b4ae5 --- /dev/null +++ b/src/BitMono.Host/Extensions/IPathWrapper.cs @@ -0,0 +1,8 @@ +namespace BitMono.Host.Extensions; + +public interface IPathWrapper +{ + bool IsDirectory(string path); + string GetFileName(string path); + string GetDirectoryName(string path); +} \ No newline at end of file diff --git a/src/BitMono.Host/Extensions/PathMaskingOperator.cs b/src/BitMono.Host/Extensions/PathMaskingOperator.cs index f422e77a..f67482b4 100644 --- a/src/BitMono.Host/Extensions/PathMaskingOperator.cs +++ b/src/BitMono.Host/Extensions/PathMaskingOperator.cs @@ -2,18 +2,33 @@ namespace BitMono.Host.Extensions; public class PathMaskingOperator : RegexMaskingOperator { - private const string PathPattern = @"^(?:[a-zA-Z]\:|\\\\[\w-]+\\[\w-]+\$?|[\/][^\/\0]+)+(\\[^\\/:*?""<>|]*)*(\\?)?$"; + private readonly IPathWrapper _pathWrapper; + private readonly bool _combineMaskWithPath; + private const string PathPattern = + @"^(?:[a-zA-Z]\:|\\\\[\w-]+\\[\w-]+\$?|[\/][^\/\0]+)+(\\[^\\/:*?""<>|]*)*(\\?)?$"; - public PathMaskingOperator() : base(PathPattern) + public PathMaskingOperator(IPathWrapper pathWrapper, bool combineMaskWithPath = true) : base(PathPattern) + { + _pathWrapper = pathWrapper; + _combineMaskWithPath = combineMaskWithPath; + } + public PathMaskingOperator(bool combineMaskWithPath = true) : this(new PathWrapper(), combineMaskWithPath) + { + } + public PathMaskingOperator() : this(combineMaskWithPath: true) { } + [SuppressMessage("ReSharper", "InvertIf")] protected override string PreprocessMask(string mask, Match match) { - var value = match.Value; - var attributes = File.GetAttributes(value); - return attributes.HasFlag(FileAttributes.Directory) - ? mask + Path.GetFileName(Path.GetDirectoryName(value)) - : mask + Path.GetFileName(value); + if (_combineMaskWithPath) + { + var value = match.Value; + return _pathWrapper.IsDirectory(value) + ? mask + _pathWrapper.GetDirectoryName(value) + : mask + _pathWrapper.GetFileName(value); + } + return mask; } } \ No newline at end of file diff --git a/src/BitMono.Host/Extensions/PathWrapper.cs b/src/BitMono.Host/Extensions/PathWrapper.cs new file mode 100644 index 00000000..53f5ffe5 --- /dev/null +++ b/src/BitMono.Host/Extensions/PathWrapper.cs @@ -0,0 +1,17 @@ +namespace BitMono.Host.Extensions; + +public class PathWrapper : IPathWrapper +{ + public bool IsDirectory(string path) + { + return Path.GetExtension(path) == string.Empty; + } + public string GetFileName(string path) + { + return Path.GetFileName(path); + } + public string GetDirectoryName(string path) + { + return new DirectoryInfo(path).Name; + } +} \ No newline at end of file From c532b83a601e1ab0b8afd66cd2f2c63537b35ceb Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Tue, 28 Feb 2023 13:42:33 +0200 Subject: [PATCH 14/24] Remove extra comma from logging.json --- src/BitMono.Host/logging.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/BitMono.Host/logging.json b/src/BitMono.Host/logging.json index 63109267..503cf98f 100644 --- a/src/BitMono.Host/logging.json +++ b/src/BitMono.Host/logging.json @@ -32,7 +32,7 @@ "MaskProperties": [ "path", "directory", "file" ], "MaskingOperators": [ "BitMono.Host.Extensions.PathMaskingOperator, BitMono.Host" ] } - }, + } }, "FromLogContext" From f6bf480814c0e1eebc3f8c5d241edce8c23c4e96 Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Tue, 28 Feb 2023 13:44:37 +0200 Subject: [PATCH 15/24] Add in docs how to disable path masking --- docs/faq/disable-path-masking.rst | 55 +++++++++++++++++++++++++++++++ docs/index.rst | 3 +- 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 docs/faq/disable-path-masking.rst diff --git a/docs/faq/disable-path-masking.rst b/docs/faq/disable-path-masking.rst new file mode 100644 index 00000000..28465475 --- /dev/null +++ b/docs/faq/disable-path-masking.rst @@ -0,0 +1,55 @@ +How to disable path masking? +============================ + +Open-up ``logging.json`` in the root of the downloaded BitMono, edit this file, and remove this: +.. code-block:: json + + "Enrich": [ + { + "Name": "WithSensitiveDataMasking", + "Args": { + "options": { + "MaskValue": "***\\", + "MaskProperties": [ "path", "directory", "file" ], + "MaskingOperators": [ "BitMono.Host.Extensions.PathMaskingOperator, BitMono.Host" ] + } + } + }, + ], + + +So, after edit ``logging.json`` looks like this: +.. code-block:: json + + + { + "Serilog": { + "Using": [ + "Serilog", + "Serilog.Sinks.Console", + "Serilog.Sinks.File", + "Serilog.Sinks.Async", + "Serilog.Enrichers.Sensitive" + ], + "WriteTo": [ + { + "Name": "Async", + "Args": { + "configure": [ + { + "Name": "File", + "Args": { + "path": "logs/bitmono-{{date}}.log", + "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}][{SourceContext}] {Message:lj}{NewLine}{Exception}" + } + } + ] + } + } + ], + "Enrich": [ + "FromLogContext" + ], + "MinimumLevel": "Debug" + } + } \ No newline at end of file diff --git a/docs/index.rst b/docs/index.rst index e6dec98b..067cfeab 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -50,4 +50,5 @@ Table of Contents: :caption: Frequently Asked Questions :name: sec-faq - faq/costura-support \ No newline at end of file + faq/costura-support + faq/disable-path-masking \ No newline at end of file From aea6cdf1d4589dfef9434a3138a24231aea0d309 Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Tue, 28 Feb 2023 13:47:35 +0200 Subject: [PATCH 16/24] Fix disable-path-masking faq in docs --- docs/faq/disable-path-masking.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/faq/disable-path-masking.rst b/docs/faq/disable-path-masking.rst index 28465475..9a6813b7 100644 --- a/docs/faq/disable-path-masking.rst +++ b/docs/faq/disable-path-masking.rst @@ -2,6 +2,7 @@ How to disable path masking? ============================ Open-up ``logging.json`` in the root of the downloaded BitMono, edit this file, and remove this: + .. code-block:: json "Enrich": [ @@ -19,8 +20,8 @@ Open-up ``logging.json`` in the root of the downloaded BitMono, edit this file, So, after edit ``logging.json`` looks like this: -.. code-block:: json +.. code-block:: json { "Serilog": { From 1c181256aa540f56a3bcc74bf727df3cc4592fb3 Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Tue, 28 Feb 2023 13:53:25 +0200 Subject: [PATCH 17/24] Add more info in disable-path-masking faq in docs --- docs/faq/disable-path-masking.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/faq/disable-path-masking.rst b/docs/faq/disable-path-masking.rst index 9a6813b7..1b109809 100644 --- a/docs/faq/disable-path-masking.rst +++ b/docs/faq/disable-path-masking.rst @@ -1,6 +1,8 @@ How to disable path masking? ============================ +You're probably getting a message with the file/directory or just a path ``(***\things)``, and you might have the same folder twice somewhere, and you need to see the full path without masking if this is what you're looking for, all instructions how to do that are provided here. + Open-up ``logging.json`` in the root of the downloaded BitMono, edit this file, and remove this: .. code-block:: json From 94852547220ca061a29ff749fb0e65b4cd360923 Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Tue, 28 Feb 2023 14:03:04 +0200 Subject: [PATCH 18/24] Update CLIOptions.cs --- src/BitMono.CLI/Modules/CLIOptions.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/BitMono.CLI/Modules/CLIOptions.cs b/src/BitMono.CLI/Modules/CLIOptions.cs index 7739ec50..99ffb43c 100644 --- a/src/BitMono.CLI/Modules/CLIOptions.cs +++ b/src/BitMono.CLI/Modules/CLIOptions.cs @@ -2,6 +2,7 @@ namespace BitMono.CLI.Modules; [SuppressMessage("ReSharper", "InconsistentNaming")] [SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")] +[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global")] public class CLIOptions { [Option('f', "file", Required = true, HelpText = "Set file path.")] From 14df13532d2e20ae236a8103af50627e6ccf527c Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Tue, 28 Feb 2023 14:26:19 +0200 Subject: [PATCH 19/24] Fixed issue when path contains quotes ("path...") --- src/BitMono.CLI/GlobalUsings.cs | 1 + .../Modules/CLIBitMonoModuleFileResolver.cs | 2 +- src/BitMono.CLI/Modules/CLIObfuscationNeedsFactory.cs | 4 ++-- src/BitMono.Utilities/Paths/PathFormatterUtility.cs | 11 +++++++++++ 4 files changed, 15 insertions(+), 3 deletions(-) create mode 100644 src/BitMono.Utilities/Paths/PathFormatterUtility.cs diff --git a/src/BitMono.CLI/GlobalUsings.cs b/src/BitMono.CLI/GlobalUsings.cs index f4c65d71..f09533de 100644 --- a/src/BitMono.CLI/GlobalUsings.cs +++ b/src/BitMono.CLI/GlobalUsings.cs @@ -12,6 +12,7 @@ global using BitMono.Host.Extensions; global using BitMono.Obfuscation.Abstractions; global using BitMono.Obfuscation.Interfaces; +global using BitMono.Utilities.Paths; global using CommandLine; global using Microsoft.Extensions.Options; global using Pocket.Extensions; diff --git a/src/BitMono.CLI/Modules/CLIBitMonoModuleFileResolver.cs b/src/BitMono.CLI/Modules/CLIBitMonoModuleFileResolver.cs index 669299d1..a4cbe0aa 100644 --- a/src/BitMono.CLI/Modules/CLIBitMonoModuleFileResolver.cs +++ b/src/BitMono.CLI/Modules/CLIBitMonoModuleFileResolver.cs @@ -7,7 +7,7 @@ internal class CLIBitMonoModuleFileResolver string? file = null; if (args.IsEmpty() == false) { - file = args[0]; + file = PathFormatterUtility.Format(args[0]); } return file; } diff --git a/src/BitMono.CLI/Modules/CLIObfuscationNeedsFactory.cs b/src/BitMono.CLI/Modules/CLIObfuscationNeedsFactory.cs index f3613f15..208ba733 100644 --- a/src/BitMono.CLI/Modules/CLIObfuscationNeedsFactory.cs +++ b/src/BitMono.CLI/Modules/CLIObfuscationNeedsFactory.cs @@ -21,7 +21,7 @@ public ObfuscationNeeds Create() try { m_Logger.Information("Please, specify file or drag-and-drop in BitMono CLI"); - fileName = Console.ReadLine(); + fileName = PathFormatterUtility.Format(Console.ReadLine()); if (string.IsNullOrWhiteSpace(fileName) == false) { if (File.Exists(fileName)) @@ -62,7 +62,7 @@ public ObfuscationNeeds Create() } m_Logger.Information("Please, specify dependencies (libs) path: "); - var newDependenciesDirectoryName = Console.ReadLine(); + var newDependenciesDirectoryName = PathFormatterUtility.Format(Console.ReadLine()); if (string.IsNullOrWhiteSpace(newDependenciesDirectoryName) == false) { if (Directory.Exists(newDependenciesDirectoryName)) diff --git a/src/BitMono.Utilities/Paths/PathFormatterUtility.cs b/src/BitMono.Utilities/Paths/PathFormatterUtility.cs new file mode 100644 index 00000000..b2720247 --- /dev/null +++ b/src/BitMono.Utilities/Paths/PathFormatterUtility.cs @@ -0,0 +1,11 @@ +namespace BitMono.Utilities.Paths; + +public static class PathFormatterUtility +{ + private const string QuotesValue = "\""; + + public static string Format(string path) + { + return path.Replace(QuotesValue,string.Empty); + } +} \ No newline at end of file From cf4a7701df8430d0d7527ad27063ea0d58c215c1 Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Wed, 1 Mar 2023 19:09:08 +0200 Subject: [PATCH 20/24] Update ObjectReturnType.cs --- src/BitMono.Protections/ObjectReturnType.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/BitMono.Protections/ObjectReturnType.cs b/src/BitMono.Protections/ObjectReturnType.cs index 13cb82e3..effbe7ee 100644 --- a/src/BitMono.Protections/ObjectReturnType.cs +++ b/src/BitMono.Protections/ObjectReturnType.cs @@ -15,7 +15,7 @@ public override Task ExecuteAsync(ProtectionParameters parameters) var systemObject = factory.Object; foreach (var method in parameters.Members.OfType()) { - if (method.Signature.ReturnsValue(systemBoolean)) + if (method.Signature != null && method.Signature.ReturnsValue(systemBoolean)) { if (method is { IsConstructor: false, IsVirtual: false, IsSetMethod: false, IsGetMethod: false } && method.NotAsync()) From 183799e3befc44289e35c59743eba9da4d7ec6a4 Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Wed, 1 Mar 2023 19:09:09 +0200 Subject: [PATCH 21/24] Update MethodDefinitionExtensions.cs --- src/BitMono.Utilities/AsmResolver/MethodDefinitionExtensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/BitMono.Utilities/AsmResolver/MethodDefinitionExtensions.cs b/src/BitMono.Utilities/AsmResolver/MethodDefinitionExtensions.cs index 3beee2db..d66b2a11 100644 --- a/src/BitMono.Utilities/AsmResolver/MethodDefinitionExtensions.cs +++ b/src/BitMono.Utilities/AsmResolver/MethodDefinitionExtensions.cs @@ -39,6 +39,6 @@ public static bool HasParameters(this MethodDefinition source) } public static bool ReturnsValue(this MethodSignature source, TypeSignature typeSignature) { - return source.ReturnsValue && source.ReturnType.Equals(typeSignature); + return source.ReturnType.Equals(typeSignature); } } \ No newline at end of file From c8f72c0360d73f209945d200bbd295b911a0949f Mon Sep 17 00:00:00 2001 From: sunnamed434 <65300126+sunnamed434@users.noreply.github.com> Date: Wed, 1 Mar 2023 19:09:11 +0200 Subject: [PATCH 22/24] Update README.md --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index c4cd747a..694784c7 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ [![Gitter Chat][image_gitter]][gitter] [![MIT License][image_license]][license] -BitMono is an free open-source C# obfuscator that in most cases works **only** with Mono - well known as a fork of .NET framework but for Unity, you can still use this for a whole .NET, but be careful that something working not as intentional, etc. Which uses **[AsmResolver][asmresolver]** for assembly manipulation. If you have any questions/issues please let me know **[there][bitmono_issues]**. You can install the latest version of BitMono **[here][bitmono_releases]**. +BitMono is a free open-source C# obfuscator that in most cases works **only** with Mono - well known as a fork of .NET framework (which runs popular platforms such as Unity, etc), you can still use this for a whole .NET, but be careful that something working not as intentional, etc. Which uses **[AsmResolver][asmresolver]** for assembly manipulation. If you have any questions/issues please let me know **[there][bitmono_issues]**. You can install the latest version of BitMono **[here][bitmono_releases]**.

Date: Sun, 5 Mar 2023 21:47:57 +0200 Subject: [PATCH 23/24] Update CHANGELOG.md --- CHANGELOG.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 174a0a92..0cf7bcc4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ | Versions: | | - | +| [v0.12.0-alpha](#v0120-alpha21) | | [v0.11.0-alpha](#v0110-alpha20) | | [v0.10.0-alpha](#v0100-alpha19) | | [v0.9.0-alpha](#v090-alpha18) | @@ -22,6 +23,16 @@ | [v0.1.0](#v010) | --- +### v0.12.0-alpha.21: +2023-03-05 +#### Added: +* [Costura-Fody](https://github.com/Fody/Costura) support, now references are resolved automatically, [#102](https://github.com/sunnamed434/BitMono/issues/102) +* Support when path contains quotes (for example: "path..."), [#104](https://github.com/sunnamed434/BitMono/issues/104) + +#### Fixed: +* Hiding of the paths (before paths with .exe may cause an ignore) +* Now output directory path message shows normally (before ***\folder_before_output, now ***\output) + ### v0.11.0-alpha.20: 2023-02-016 #### Added: From bb9b70b5fc661e5ff7dd9eba8bf57080249fa697 Mon Sep 17 00:00:00 2001 From: sunnamed434 Date: Sun, 5 Mar 2023 22:03:55 +0200 Subject: [PATCH 24/24] Bump new version 0.12.0-alpha.21 --- README.md | 8 +------- props/SharedProjectProps.props | 6 +++--- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 694784c7..bbb39dd4 100644 --- a/README.md +++ b/README.md @@ -80,12 +80,6 @@ specially_created_folder_for_obfuscation/ Copy all libraries (.dll) from the building application folder and paste them into the `libs` directory (if it doesn't exist yet create it), or even create the libs directory yourself with a custom name for example - `myLibs`, and then specify it in BitMono, however, if you will use `libs` then by default BitMono looking for a `libs` directory, so it will save your time. ### Using CLI Commands -Outputs available commands -```console -$ BitMono.CLI --help -``` - -Upper command output: ```console -f, --file Required. Set file path. @@ -98,7 +92,7 @@ Upper command output: --version Display version information. ``` -Basic examples +Basic example ```console $ BitMono.CLI -f C:\specially_created_folder_for_obfuscation/your_app.exe -l specially_created_folder_for_obfuscation/libs ``` diff --git a/props/SharedProjectProps.props b/props/SharedProjectProps.props index 50e496d2..5295190b 100644 --- a/props/SharedProjectProps.props +++ b/props/SharedProjectProps.props @@ -6,12 +6,12 @@ MIT https://github.com/sunnamed434/BitMono sunnamed434 - 0.11.0-alpha.20 + 0.12.0-alpha.21 https://github.com/sunnamed434/BitMono git sunnamed434 - 0.11.0-alpha.20 - 0.11.0-alpha.20 + 0.12.0-alpha.21 + 0.12.0-alpha.21 BitMono sunnamed434 10