backup
walon 2025-05-17 12:11:36 +08:00
parent 76d4b5d5af
commit 419c5f34f7
28 changed files with 202 additions and 216 deletions

View File

@ -8,6 +8,6 @@ namespace Obfuz.Editor
{ {
public static class ConstValues public static class ConstValues
{ {
public const string ObfuzMetadataNamePrefix = "$Obfuz$"; public const string ObfuzInternalSymbolNamePrefix = "$Obfuz$";
} }
} }

View File

@ -103,13 +103,13 @@ namespace Obfuz.Data
{ {
_module.EnableTypeDefFindCache = false; _module.EnableTypeDefFindCache = false;
ITypeDefOrRef objectTypeRef = _module.Import(typeof(object)); ITypeDefOrRef objectTypeRef = _module.Import(typeof(object));
_holderTypeDef = new TypeDefUser($"{ConstValues.ObfuzMetadataNamePrefix}ConstFieldHolder${_holderTypeDefs.Count}", objectTypeRef); _holderTypeDef = new TypeDefUser($"{ConstValues.ObfuzInternalSymbolNamePrefix}ConstFieldHolder${_holderTypeDefs.Count}", objectTypeRef);
_module.Types.Add(_holderTypeDef); _module.Types.Add(_holderTypeDef);
_holderTypeDefs.Add(_holderTypeDef); _holderTypeDefs.Add(_holderTypeDef);
_module.EnableTypeDefFindCache = true; _module.EnableTypeDefFindCache = true;
} }
var field = new FieldDefUser($"{ConstValues.ObfuzMetadataNamePrefix}RVA_Value{_holderTypeDef.Fields.Count}", new FieldSig(GetTypeSigOfValue(value)), FieldAttributes.Static | FieldAttributes.Private | FieldAttributes.InitOnly); var field = new FieldDefUser($"{ConstValues.ObfuzInternalSymbolNamePrefix}RVA_Value{_holderTypeDef.Fields.Count}", new FieldSig(GetTypeSigOfValue(value)), FieldAttributes.Static | FieldAttributes.Private | FieldAttributes.InitOnly);
field.DeclaringType = _holderTypeDef; field.DeclaringType = _holderTypeDef;
return new ConstFieldInfo return new ConstFieldInfo
{ {

View File

@ -9,11 +9,6 @@ using System.Threading.Tasks;
namespace Obfuz.Emit namespace Obfuz.Emit
{ {
public static class LoopDetector
{
}
public class BasicBlock public class BasicBlock
{ {
public readonly List<Instruction> instructions = new List<Instruction>(); public readonly List<Instruction> instructions = new List<Instruction>();

View File

@ -13,9 +13,9 @@ namespace Obfuz.ObfusPasses
public override void Process() public override void Process()
{ {
var ctx = ObfuscationPassContext.Current; var ctx = ObfuscationPassContext.Current;
NotObfuscatedMethodWhiteList whiteList = ctx.whiteList; ObfuscationMethodWhitelist whiteList = ctx.whiteList;
ConfigurablePassPolicy passPolicy = ctx.passPolicy; ConfigurablePassPolicy passPolicy = ctx.passPolicy;
foreach (ModuleDef mod in ctx.toObfuscatedModules) foreach (ModuleDef mod in ctx.modulesToObfuscate)
{ {
if (whiteList.IsInWhiteList(mod) || !Support(passPolicy.GetAssemblyObfuscationPasses(mod))) if (whiteList.IsInWhiteList(mod) || !Support(passPolicy.GetAssemblyObfuscationPasses(mod)))
{ {

View File

@ -22,10 +22,10 @@ namespace Obfuz.ObfusPasses.CallObfus
public override ObfuscationPassType Type => ObfuscationPassType.CallObfus; public override ObfuscationPassType Type => ObfuscationPassType.CallObfus;
public CallObfusPass(CallObfusSettings settings) public CallObfusPass(CallObfuscationSettings settings)
{ {
_configFiles = settings.configFiles.ToList(); _configFiles = settings.ruleFiles.ToList();
_obfuscationLevel = settings.callObfuscationLevel; _obfuscationLevel = settings.obfuscationLevel;
} }
public override void Stop() public override void Stop()
@ -37,7 +37,7 @@ namespace Obfuz.ObfusPasses.CallObfus
{ {
var ctx = ObfuscationPassContext.Current; var ctx = ObfuscationPassContext.Current;
_dynamicProxyObfuscator = new DefaultCallProxyObfuscator(ctx.encryptionScopeProvider, ctx.constFieldAllocator, ctx.moduleEntityManager, _obfuscationLevel); _dynamicProxyObfuscator = new DefaultCallProxyObfuscator(ctx.encryptionScopeProvider, ctx.constFieldAllocator, ctx.moduleEntityManager, _obfuscationLevel);
_dynamicProxyPolicy = new ConfigurableObfuscationPolicy(ctx.toObfuscatedAssemblyNames, _configFiles); _dynamicProxyPolicy = new ConfigurableObfuscationPolicy(ctx.assembliesToObfuscate, _configFiles);
} }
protected override bool NeedObfuscateMethod(MethodDef method) protected override bool NeedObfuscateMethod(MethodDef method)

View File

@ -110,7 +110,7 @@ namespace Obfuz.ObfusPasses.CallObfus
private TypeDef CreateProxyTypeDef() private TypeDef CreateProxyTypeDef()
{ {
var typeDef = new TypeDefUser($"{ConstValues.ObfuzMetadataNamePrefix}ProxyCall", _module.CorLibTypes.Object.ToTypeDefOrRef()); var typeDef = new TypeDefUser($"{ConstValues.ObfuzInternalSymbolNamePrefix}ProxyCall", _module.CorLibTypes.Object.ToTypeDefOrRef());
typeDef.Attributes = TypeAttributes.NotPublic | TypeAttributes.Sealed; typeDef.Attributes = TypeAttributes.NotPublic | TypeAttributes.Sealed;
_module.EnableTypeDefFindCache = false; _module.EnableTypeDefFindCache = false;
_module.Types.Add(typeDef); _module.Types.Add(typeDef);
@ -124,7 +124,7 @@ namespace Obfuz.ObfusPasses.CallObfus
{ {
_proxyTypeDef = CreateProxyTypeDef(); _proxyTypeDef = CreateProxyTypeDef();
} }
MethodDef methodDef = new MethodDefUser($"{ConstValues.ObfuzMetadataNamePrefix}ProxyCall$Dispatch${_proxyTypeDef.Methods.Count}", methodSig, MethodDef methodDef = new MethodDefUser($"{ConstValues.ObfuzInternalSymbolNamePrefix}ProxyCall$Dispatch${_proxyTypeDef.Methods.Count}", methodSig,
MethodImplAttributes.IL | MethodImplAttributes.Managed, MethodImplAttributes.IL | MethodImplAttributes.Managed,
MethodAttributes.Static | MethodAttributes.Private); MethodAttributes.Static | MethodAttributes.Private);
methodDef.DeclaringType = _proxyTypeDef; methodDef.DeclaringType = _proxyTypeDef;

View File

@ -24,7 +24,7 @@ namespace Obfuz.ObfusPasses.CleanUp
public override void Process() public override void Process()
{ {
var ctx = ObfuscationPassContext.Current; var ctx = ObfuscationPassContext.Current;
foreach (ModuleDef mod in ctx.toObfuscatedModules) foreach (ModuleDef mod in ctx.modulesToObfuscate)
{ {
foreach (TypeDef type in mod.GetTypes()) foreach (TypeDef type in mod.GetTypes())
{ {

View File

@ -34,7 +34,7 @@ namespace Obfuz.ObfusPasses.CleanUp
public override void Process() public override void Process()
{ {
var ctx = ObfuscationPassContext.Current; var ctx = ObfuscationPassContext.Current;
foreach (ModuleDef mod in ctx.toObfuscatedModules) foreach (ModuleDef mod in ctx.modulesToObfuscate)
{ {
RemoveObfuzAttributes(mod); RemoveObfuzAttributes(mod);
foreach (TypeDef type in mod.GetTypes()) foreach (TypeDef type in mod.GetTypes())

View File

@ -21,16 +21,16 @@ namespace Obfuz.ObfusPasses.ConstEncrypt
private IConstEncryptor _dataObfuscator; private IConstEncryptor _dataObfuscator;
public override ObfuscationPassType Type => ObfuscationPassType.ConstEncrypt; public override ObfuscationPassType Type => ObfuscationPassType.ConstEncrypt;
public ConstEncryptPass(ConstEncryptSettings settings) public ConstEncryptPass(ConstEncryptionSettings settings)
{ {
_configFiles = settings.configFiles.ToList(); _configFiles = settings.ruleFiles.ToList();
_encryptionLevel = settings.encryptionLevel; _encryptionLevel = settings.encryptionLevel;
} }
public override void Start() public override void Start()
{ {
var ctx = ObfuscationPassContext.Current; var ctx = ObfuscationPassContext.Current;
_dataObfuscatorPolicy = new ConfigurableEncryptPolicy(ctx.toObfuscatedAssemblyNames, _configFiles); _dataObfuscatorPolicy = new ConfigurableEncryptPolicy(ctx.assembliesToObfuscate, _configFiles);
_dataObfuscator = new DefaultConstEncryptor(ctx.encryptionScopeProvider, ctx.rvaDataAllocator, ctx.constFieldAllocator, ctx.moduleEntityManager, _encryptionLevel); _dataObfuscator = new DefaultConstEncryptor(ctx.encryptionScopeProvider, ctx.rvaDataAllocator, ctx.constFieldAllocator, ctx.moduleEntityManager, _encryptionLevel);
} }

View File

@ -19,9 +19,9 @@ namespace Obfuz.ObfusPasses.FieldEncrypt
public override ObfuscationPassType Type => ObfuscationPassType.FieldEncrypt; public override ObfuscationPassType Type => ObfuscationPassType.FieldEncrypt;
public FieldEncryptPass(FieldEncryptSettings settings) public FieldEncryptPass(FieldEncryptionSettings settings)
{ {
_configFiles = settings.configFiles.ToList(); _configFiles = settings.ruleFiles.ToList();
_encryptionLevel = settings.encryptionLevel; _encryptionLevel = settings.encryptionLevel;
} }
@ -31,7 +31,7 @@ namespace Obfuz.ObfusPasses.FieldEncrypt
{ {
var ctx = ObfuscationPassContext.Current; var ctx = ObfuscationPassContext.Current;
_memoryEncryptor = new DefaultFieldEncryptor(ctx.encryptionScopeProvider, ctx.moduleEntityManager, _encryptionLevel); _memoryEncryptor = new DefaultFieldEncryptor(ctx.encryptionScopeProvider, ctx.moduleEntityManager, _encryptionLevel);
_encryptionPolicy = new ConfigurableEncryptPolicy(ctx.toObfuscatedAssemblyNames, _configFiles); _encryptionPolicy = new ConfigurableEncryptPolicy(ctx.assembliesToObfuscate, _configFiles);
} }
public override void Stop() public override void Stop()

View File

@ -14,8 +14,8 @@ namespace Obfuz.ObfusPasses
public override void Process() public override void Process()
{ {
var ctx = ObfuscationPassContext.Current; var ctx = ObfuscationPassContext.Current;
var modules = ForceProcessAllAssembliesAndIgnoreAllPolicy ? ctx.obfuscatedAndNotObfuscatedModules : ctx.toObfuscatedModules; var modules = ForceProcessAllAssembliesAndIgnoreAllPolicy ? ctx.allObfuscationRelativeModules : ctx.modulesToObfuscate;
NotObfuscatedMethodWhiteList whiteList = ctx.whiteList; ObfuscationMethodWhitelist whiteList = ctx.whiteList;
ConfigurablePassPolicy passPolicy = ctx.passPolicy; ConfigurablePassPolicy passPolicy = ctx.passPolicy;
foreach (ModuleDef mod in modules) foreach (ModuleDef mod in modules)
{ {

View File

@ -13,7 +13,7 @@ namespace Obfuz.ObfusPasses.SymbolObfus
public override ObfuscationPassType Type => ObfuscationPassType.SymbolObfus; public override ObfuscationPassType Type => ObfuscationPassType.SymbolObfus;
public SymbolObfusPass(SymbolObfusSettings settings) public SymbolObfusPass(SymbolObfuscationSettings settings)
{ {
_symbolRename = new SymbolRename(settings); _symbolRename = new SymbolRename(settings);
} }

View File

@ -53,12 +53,12 @@ namespace Obfuz.ObfusPasses.SymbolObfus
public List<CANamedArgument> namedArguments; public List<CANamedArgument> namedArguments;
} }
public SymbolRename(SymbolObfusSettings settings) public SymbolRename(SymbolObfuscationSettings settings)
{ {
_useConsistentNamespaceObfuscation = settings.useConsistentNamespaceObfuscation; _useConsistentNamespaceObfuscation = settings.useConsistentNamespaceObfuscation;
_mappingXmlPath = settings.mappingFile; _mappingXmlPath = settings.symbolMappingFile;
_obfuscationRuleFiles = settings.ruleFiles.ToList(); _obfuscationRuleFiles = settings.ruleFiles.ToList();
_renameRecordMap = new RenameRecordMap(settings.debug ? null : settings.mappingFile); _renameRecordMap = new RenameRecordMap(settings.debug ? null : settings.symbolMappingFile);
_virtualMethodGroupCalculator = new VirtualMethodGroupCalculator(); _virtualMethodGroupCalculator = new VirtualMethodGroupCalculator();
_nameMaker = settings.debug ? NameMakerFactory.CreateDebugNameMaker() : NameMakerFactory.CreateNameMakerBaseASCIICharSet(settings.obfuscatedNamePrefix); _nameMaker = settings.debug ? NameMakerFactory.CreateDebugNameMaker() : NameMakerFactory.CreateNameMakerBaseASCIICharSet(settings.obfuscatedNamePrefix);
} }
@ -67,10 +67,10 @@ namespace Obfuz.ObfusPasses.SymbolObfus
{ {
var ctx = ObfuscationPassContext.Current; var ctx = ObfuscationPassContext.Current;
_assemblyCache = ctx.assemblyCache; _assemblyCache = ctx.assemblyCache;
_toObfuscatedModules = ctx.toObfuscatedModules; _toObfuscatedModules = ctx.modulesToObfuscate;
_obfuscatedAndNotObfuscatedModules = ctx.obfuscatedAndNotObfuscatedModules; _obfuscatedAndNotObfuscatedModules = ctx.allObfuscationRelativeModules;
_toObfuscatedModuleSet = new HashSet<ModuleDef>(ctx.toObfuscatedModules); _toObfuscatedModuleSet = new HashSet<ModuleDef>(ctx.modulesToObfuscate);
var obfuscateRuleConfig = new ConfigurableRenamePolicy(ctx.toObfuscatedAssemblyNames, _obfuscationRuleFiles); var obfuscateRuleConfig = new ConfigurableRenamePolicy(ctx.assembliesToObfuscate, _obfuscationRuleFiles);
_renamePolicy = new CacheRenamePolicy(new CombineRenamePolicy(new SupportPassPolicy(ctx.passPolicy), new SystemRenamePolicy(), new UnityRenamePolicy(), obfuscateRuleConfig)); _renamePolicy = new CacheRenamePolicy(new CombineRenamePolicy(new SupportPassPolicy(ctx.passPolicy), new SystemRenamePolicy(), new UnityRenamePolicy(), obfuscateRuleConfig));
BuildCustomAttributeArguments(); BuildCustomAttributeArguments();
} }

View File

@ -9,7 +9,7 @@ using System.Threading.Tasks;
namespace Obfuz namespace Obfuz
{ {
public class NotObfuscatedMethodWhiteList public class ObfuscationMethodWhitelist
{ {
private bool ShouldBeIgnoredByCustomAttribute(IHasCustomAttribute obj) private bool ShouldBeIgnoredByCustomAttribute(IHasCustomAttribute obj)
{ {
@ -36,7 +36,7 @@ namespace Obfuz
{ {
return true; return true;
} }
if (method.Name.StartsWith(ConstValues.ObfuzMetadataNamePrefix)) if (method.Name.StartsWith(ConstValues.ObfuzInternalSymbolNamePrefix))
{ {
return true; return true;
} }
@ -49,7 +49,7 @@ namespace Obfuz
public bool IsInWhiteList(TypeDef type) public bool IsInWhiteList(TypeDef type)
{ {
if (type.Name.StartsWith(ConstValues.ObfuzMetadataNamePrefix)) if (type.Name.StartsWith(ConstValues.ObfuzInternalSymbolNamePrefix))
{ {
return true; return true;
} }

View File

@ -16,15 +16,11 @@ namespace Obfuz
public class EncryptionScopeInfo public class EncryptionScopeInfo
{ {
public readonly byte[] byteSecret;
public readonly int[] intSecret;
public readonly IEncryptor encryptor; public readonly IEncryptor encryptor;
public readonly RandomCreator localRandomCreator; public readonly RandomCreator localRandomCreator;
public EncryptionScopeInfo(byte[] byteSecret, int[] intSecret, IEncryptor encryptor, RandomCreator localRandomCreator) public EncryptionScopeInfo(IEncryptor encryptor, RandomCreator localRandomCreator)
{ {
this.byteSecret = byteSecret;
this.intSecret = intSecret;
this.encryptor = encryptor; this.encryptor = encryptor;
this.localRandomCreator = localRandomCreator; this.localRandomCreator = localRandomCreator;
} }
@ -70,18 +66,18 @@ namespace Obfuz
public AssemblyCache assemblyCache; public AssemblyCache assemblyCache;
public List<ModuleDef> toObfuscatedModules; public List<ModuleDef> modulesToObfuscate;
public List<ModuleDef> obfuscatedAndNotObfuscatedModules; public List<ModuleDef> allObfuscationRelativeModules;
public List<string> toObfuscatedAssemblyNames; public List<string> assembliesToObfuscate;
public List<string> notObfuscatedAssemblyNamesReferencingObfuscated; public List<string> nonObfuscatedButReferencingObfuscatedAssemblies;
public string obfuscatedAssemblyOutputDir; public string obfuscatedAssemblyOutputPath;
public EncryptionScopeProvider encryptionScopeProvider; public EncryptionScopeProvider encryptionScopeProvider;
public ConstFieldAllocator constFieldAllocator; public ConstFieldAllocator constFieldAllocator;
public RvaDataAllocator rvaDataAllocator; public RvaDataAllocator rvaDataAllocator;
public NotObfuscatedMethodWhiteList whiteList; public ObfuscationMethodWhitelist whiteList;
public ConfigurablePassPolicy passPolicy; public ConfigurablePassPolicy passPolicy;
} }
} }

View File

@ -19,25 +19,23 @@ namespace Obfuz
public class Obfuscator public class Obfuscator
{ {
private readonly string _obfuscatedAssemblyOutputDir; private readonly string _obfuscatedAssemblyOutputPath;
private readonly List<string> _toObfuscatedAssemblyNames; private readonly List<string> _assembliesToObfuscate;
private readonly List<string> _notObfuscatedAssemblyNamesReferencingObfuscated; private readonly List<string> _nonObfuscatedButReferencingObfuscatedAssemblies;
private readonly List<string> _assemblySearchDirs; private readonly List<string> _assemblySearchPaths;
private readonly ConfigurablePassPolicy _passPolicy; private readonly ConfigurablePassPolicy _passPolicy;
private readonly Pipeline _pipeline1 = new Pipeline(); private readonly Pipeline _pipeline1 = new Pipeline();
private readonly Pipeline _pipeline2 = new Pipeline(); private readonly Pipeline _pipeline2 = new Pipeline();
private readonly byte[] _defaultStaticByteSecret; private readonly byte[] _defaultStaticByteSecretKey;
private readonly int[] _defaultStaticIntSecret;
private readonly byte[] _defaultDynamicByteSecret; private readonly byte[] _defaultDynamicByteSecret;
private readonly int[] _defaultDynamicIntSecret; private readonly HashSet<string> _assembliesUsingDynamicSecretKeys;
private readonly HashSet<string> _dynamicSecretAssemblyNames;
private readonly int _randomSeed; private readonly int _randomSeed;
private readonly string _encryptionVmGenerationSecret; private readonly string _encryptionVmGenerationSecretKey;
private readonly int _encryptionVmOpCodeCount; private readonly int _encryptionVmOpCodeCount;
private readonly string _encryptionVmCodeFile; private readonly string _encryptionVmCodeFile;
@ -45,24 +43,22 @@ namespace Obfuz
public Obfuscator(ObfuscatorBuilder builder) public Obfuscator(ObfuscatorBuilder builder)
{ {
_defaultStaticByteSecret = KeyGenerator.GenerateKey(builder.DefaultStaticSecret, VirtualMachine.SecretKeyLength); _defaultStaticByteSecretKey = KeyGenerator.GenerateKey(builder.DefaultStaticSecretKey, VirtualMachine.SecretKeyLength);
_defaultStaticIntSecret = KeyGenerator.ConvertToIntKey(_defaultStaticByteSecret); _defaultDynamicByteSecret = KeyGenerator.GenerateKey(builder.DefaultDynamicSecretKey, VirtualMachine.SecretKeyLength);
_defaultDynamicByteSecret = KeyGenerator.GenerateKey(builder.DefaultDynamicSecret, VirtualMachine.SecretKeyLength); _assembliesUsingDynamicSecretKeys = new HashSet<string>(builder.AssembliesUsingDynamicSecretKeys);
_defaultDynamicIntSecret = KeyGenerator.ConvertToIntKey(_defaultDynamicByteSecret);
_dynamicSecretAssemblyNames = new HashSet<string>(builder.DynamicSecretAssemblyNames);
_randomSeed = builder.RandomSeed; _randomSeed = builder.RandomSeed;
_encryptionVmGenerationSecret = builder.EncryptionVmGenerationSecretKey; _encryptionVmGenerationSecretKey = builder.EncryptionVmGenerationSecretKey;
_encryptionVmOpCodeCount = builder.EncryptionVmOpCodeCount; _encryptionVmOpCodeCount = builder.EncryptionVmOpCodeCount;
_encryptionVmCodeFile = builder.EncryptionVmCodeFile; _encryptionVmCodeFile = builder.EncryptionVmCodeFile;
_toObfuscatedAssemblyNames = builder.ToObfuscatedAssemblyNames; _assembliesToObfuscate = builder.AssembliesToObfuscate;
_notObfuscatedAssemblyNamesReferencingObfuscated = builder.NotObfuscatedAssemblyNamesReferencingObfuscated; _nonObfuscatedButReferencingObfuscatedAssemblies = builder.NonObfuscatedButReferencingObfuscatedAssemblies;
_obfuscatedAssemblyOutputDir = builder.ObfuscatedAssemblyOutputDir; _obfuscatedAssemblyOutputPath = builder.ObfuscatedAssemblyOutputPath;
_assemblySearchDirs = builder.AssemblySearchDirs; _assemblySearchPaths = builder.AssemblySearchPaths;
_passPolicy = new ConfigurablePassPolicy(_toObfuscatedAssemblyNames, builder.EnableObfuscationPasses, builder.ObfuscationPassConfigFiles); _passPolicy = new ConfigurablePassPolicy(_assembliesToObfuscate, builder.EnableObfuscationPasses, builder.ObfuscationPassRuleConfigFiles);
foreach (var pass in builder.ObfuscationPasses) foreach (var pass in builder.ObfuscationPasses)
{ {
@ -81,9 +77,9 @@ namespace Obfuz
public void Run() public void Run()
{ {
FileUtil.RecreateDir(_obfuscatedAssemblyOutputDir); FileUtil.RecreateDir(_obfuscatedAssemblyOutputPath);
RunPipeline(_pipeline1); RunPipeline(_pipeline1);
_assemblySearchDirs.Insert(0, _obfuscatedAssemblyOutputDir); _assemblySearchPaths.Insert(0, _obfuscatedAssemblyOutputPath);
RunPipeline(_pipeline2); RunPipeline(_pipeline2);
} }
@ -98,9 +94,9 @@ namespace Obfuz
OnPostObfuscation(pipeline); OnPostObfuscation(pipeline);
} }
private IEncryptor CreateEncryptionVirtualMachine(byte[] secret) private IEncryptor CreateEncryptionVirtualMachine(byte[] secretKey)
{ {
var vmCreator = new VirtualMachineCreator(_encryptionVmGenerationSecret); var vmCreator = new VirtualMachineCreator(_encryptionVmGenerationSecretKey);
var vm = vmCreator.CreateVirtualMachine(_encryptionVmOpCodeCount); var vm = vmCreator.CreateVirtualMachine(_encryptionVmOpCodeCount);
var vmGenerator = new VirtualMachineCodeGenerator(vm); var vmGenerator = new VirtualMachineCodeGenerator(vm);
@ -112,7 +108,7 @@ namespace Obfuz
{ {
throw new Exception($"EncryptionVm CodeFile:`{_encryptionVmCodeFile}` not match with encryptionVM settings! Please run `Obfuz/GenerateVm` to update it!"); throw new Exception($"EncryptionVm CodeFile:`{_encryptionVmCodeFile}` not match with encryptionVM settings! Please run `Obfuz/GenerateVm` to update it!");
} }
var vms = new VirtualMachineSimulator(vm, secret); var vms = new VirtualMachineSimulator(vm, secretKey);
var generatedVmTypes = AppDomain.CurrentDomain.GetAssemblies() var generatedVmTypes = AppDomain.CurrentDomain.GetAssemblies()
.Select(assembly => assembly.GetType("Obfuz.EncryptionVM.GeneratedEncryptionVirtualMachine")) .Select(assembly => assembly.GetType("Obfuz.EncryptionVM.GeneratedEncryptionVirtualMachine"))
@ -127,14 +123,14 @@ namespace Obfuz
throw new Exception($"class Obfuz.EncryptionVM.GeneratedEncryptionVirtualMachine found in multiple assemblies! Please retain only one!"); throw new Exception($"class Obfuz.EncryptionVM.GeneratedEncryptionVirtualMachine found in multiple assemblies! Please retain only one!");
} }
var gvmInstance = (IEncryptor)Activator.CreateInstance(generatedVmTypes[0], new object[] { secret } ); var gvmInstance = (IEncryptor)Activator.CreateInstance(generatedVmTypes[0], new object[] { secretKey } );
VerifyVm(vm, vms, gvmInstance); VerifyVm(vm, vms, gvmInstance);
return vms; return vms;
} }
private void VerifyVm(VirtualMachine vm, VirtualMachineSimulator vms, IEncryptor gvmInstance) private void VerifyVm(VirtualMachine vm, VirtualMachineSimulator vms, IEncryptor gvm)
{ {
int testInt = 11223344; int testInt = 11223344;
long testLong = 1122334455667788L; long testLong = 1122334455667788L;
@ -154,8 +150,8 @@ namespace Obfuz
{ {
throw new Exception($"VirtualMachineSimulator decrypt failed! opCode:{i}, originalValue:{testInt} decryptedValue:{decryptedIntOfVms}"); throw new Exception($"VirtualMachineSimulator decrypt failed! opCode:{i}, originalValue:{testInt} decryptedValue:{decryptedIntOfVms}");
} }
int encryptedValueOfGvm = gvmInstance.Encrypt(testInt, ops, salt); int encryptedValueOfGvm = gvm.Encrypt(testInt, ops, salt);
int decryptedValueOfGvm = gvmInstance.Decrypt(encryptedValueOfGvm, ops, salt); int decryptedValueOfGvm = gvm.Decrypt(encryptedValueOfGvm, ops, salt);
if (encryptedValueOfGvm != encryptedIntOfVms) if (encryptedValueOfGvm != encryptedIntOfVms)
{ {
throw new Exception($"encryptedValue not match! opCode:{i}, originalValue:{testInt} encryptedValue VirtualMachineSimulator:{encryptedIntOfVms} GeneratedEncryptionVirtualMachine:{encryptedValueOfGvm}"); throw new Exception($"encryptedValue not match! opCode:{i}, originalValue:{testInt} encryptedValue VirtualMachineSimulator:{encryptedIntOfVms} GeneratedEncryptionVirtualMachine:{encryptedValueOfGvm}");
@ -172,8 +168,8 @@ namespace Obfuz
{ {
throw new Exception($"VirtualMachineSimulator decrypt long failed! opCode:{i}, originalValue:{testLong} decryptedValue:{decryptedLongOfVms}"); throw new Exception($"VirtualMachineSimulator decrypt long failed! opCode:{i}, originalValue:{testLong} decryptedValue:{decryptedLongOfVms}");
} }
long encryptedValueOfGvm = gvmInstance.Encrypt(testLong, ops, salt); long encryptedValueOfGvm = gvm.Encrypt(testLong, ops, salt);
long decryptedValueOfGvm = gvmInstance.Decrypt(encryptedValueOfGvm, ops, salt); long decryptedValueOfGvm = gvm.Decrypt(encryptedValueOfGvm, ops, salt);
if (encryptedValueOfGvm != encryptedLongOfVms) if (encryptedValueOfGvm != encryptedLongOfVms)
{ {
throw new Exception($"encryptedValue not match! opCode:{i}, originalValue:{testLong} encryptedValue VirtualMachineSimulator:{encryptedLongOfVms} GeneratedEncryptionVirtualMachine:{encryptedValueOfGvm}"); throw new Exception($"encryptedValue not match! opCode:{i}, originalValue:{testLong} encryptedValue VirtualMachineSimulator:{encryptedLongOfVms} GeneratedEncryptionVirtualMachine:{encryptedValueOfGvm}");
@ -190,8 +186,8 @@ namespace Obfuz
{ {
throw new Exception("encryptedFloat not match"); throw new Exception("encryptedFloat not match");
} }
float encryptedValueOfGvm = gvmInstance.Encrypt(testFloat, ops, salt); float encryptedValueOfGvm = gvm.Encrypt(testFloat, ops, salt);
float decryptedValueOfGvm = gvmInstance.Decrypt(encryptedFloatOfVms, ops, salt); float decryptedValueOfGvm = gvm.Decrypt(encryptedFloatOfVms, ops, salt);
if (encryptedFloatOfVms != encryptedValueOfGvm) if (encryptedFloatOfVms != encryptedValueOfGvm)
{ {
throw new Exception($"encryptedValue not match! opCode:{i}, originalValue:{testFloat} encryptedValue"); throw new Exception($"encryptedValue not match! opCode:{i}, originalValue:{testFloat} encryptedValue");
@ -208,8 +204,8 @@ namespace Obfuz
{ {
throw new Exception("encryptedFloat not match"); throw new Exception("encryptedFloat not match");
} }
double encryptedValueOfGvm = gvmInstance.Encrypt(testDouble, ops, salt); double encryptedValueOfGvm = gvm.Encrypt(testDouble, ops, salt);
double decryptedValueOfGvm = gvmInstance.Decrypt(encryptedFloatOfVms, ops, salt); double decryptedValueOfGvm = gvm.Decrypt(encryptedFloatOfVms, ops, salt);
if (encryptedFloatOfVms != encryptedValueOfGvm) if (encryptedFloatOfVms != encryptedValueOfGvm)
{ {
throw new Exception($"encryptedValue not match! opCode:{i}, originalValue:{testDouble} encryptedValue"); throw new Exception($"encryptedValue not match! opCode:{i}, originalValue:{testDouble} encryptedValue");
@ -222,52 +218,53 @@ namespace Obfuz
{ {
byte[] encryptedStrOfVms = vms.Encrypt(testString, ops, salt); byte[] encryptedStrOfVms = vms.Encrypt(testString, ops, salt);
string descryptedStrOfVms = vms.DecryptString(encryptedStrOfVms, 0, encryptedStrOfVms.Length, ops, salt); string decryptedStrOfVms = vms.DecryptString(encryptedStrOfVms, 0, encryptedStrOfVms.Length, ops, salt);
if (descryptedStrOfVms != testString) if (decryptedStrOfVms != testString)
{ {
throw new Exception($"VirtualMachineSimulator decrypt string failed! opCode:{i}, originalValue:{testString} decryptedValue:{descryptedStrOfVms}"); throw new Exception($"VirtualMachineSimulator decrypt string failed! opCode:{i}, originalValue:{testString} decryptedValue:{decryptedStrOfVms}");
} }
byte[] encryptedStrOfGvm = gvmInstance.Encrypt(testString, ops, salt); byte[] encryptedStrOfGvm = gvm.Encrypt(testString, ops, salt);
string descryptedStrOfGvm = gvmInstance.DecryptString(encryptedStrOfGvm, 0, encryptedStrOfGvm.Length, ops, salt); string decryptedStrOfGvm = gvm.DecryptString(encryptedStrOfGvm, 0, encryptedStrOfGvm.Length, ops, salt);
if (!encryptedStrOfGvm.SequenceEqual(encryptedStrOfVms)) if (!encryptedStrOfGvm.SequenceEqual(encryptedStrOfVms))
{ {
throw new Exception($"encryptedValue not match! opCode:{i}, originalValue:{testString} encryptedValue VirtualMachineSimulator:{encryptedStrOfVms} GeneratedEncryptionVirtualMachine:{encryptedStrOfGvm}"); throw new Exception($"encryptedValue not match! opCode:{i}, originalValue:{testString} encryptedValue VirtualMachineSimulator:{encryptedStrOfVms} GeneratedEncryptionVirtualMachine:{encryptedStrOfGvm}");
} }
if (descryptedStrOfGvm != testString) if (decryptedStrOfGvm != testString)
{ {
throw new Exception($"GeneratedEncryptionVirtualMachine decrypt string failed! opCode:{i}, originalValue:{testString} decryptedValue:{descryptedStrOfGvm}"); throw new Exception($"GeneratedEncryptionVirtualMachine decrypt string failed! opCode:{i}, originalValue:{testString} decryptedValue:{decryptedStrOfGvm}");
} }
} }
} }
} }
private EncryptionScopeInfo CreateEncryptionScope(byte[] byteSecret, int[] intSecret) private EncryptionScopeInfo CreateEncryptionScope(byte[] byteSecret)
{ {
int[] intSecretKey = KeyGenerator.ConvertToIntKey(byteSecret);
IEncryptor encryption = CreateEncryptionVirtualMachine(byteSecret); IEncryptor encryption = CreateEncryptionVirtualMachine(byteSecret);
RandomCreator localRandomCreator = (seed) => new RandomWithKey(intSecret, _randomSeed ^ seed); RandomCreator localRandomCreator = (seed) => new RandomWithKey(intSecretKey, _randomSeed ^ seed);
return new EncryptionScopeInfo(byteSecret, intSecret, encryption, localRandomCreator); return new EncryptionScopeInfo(encryption, localRandomCreator);
} }
private EncryptionScopeProvider CreateEncryptionScopeProvider() private EncryptionScopeProvider CreateEncryptionScopeProvider()
{ {
var defaultStaticScope = CreateEncryptionScope(_defaultStaticByteSecret, _defaultStaticIntSecret); var defaultStaticScope = CreateEncryptionScope(_defaultStaticByteSecretKey);
var defaultDynamicScope = CreateEncryptionScope(_defaultDynamicByteSecret, _defaultDynamicIntSecret); var defaultDynamicScope = CreateEncryptionScope(_defaultDynamicByteSecret);
foreach (string dynamicAssName in _dynamicSecretAssemblyNames) foreach (string dynamicAssName in _assembliesUsingDynamicSecretKeys)
{ {
if (!_toObfuscatedAssemblyNames.Contains(dynamicAssName)) if (!_assembliesToObfuscate.Contains(dynamicAssName))
{ {
throw new Exception($"Dynamic secret assembly `{dynamicAssName}` should be in the toObfuscatedAssemblyNames list!"); throw new Exception($"Dynamic secret assembly `{dynamicAssName}` should be in the toObfuscatedAssemblyNames list!");
} }
} }
return new EncryptionScopeProvider(defaultStaticScope, defaultDynamicScope, _dynamicSecretAssemblyNames); return new EncryptionScopeProvider(defaultStaticScope, defaultDynamicScope, _assembliesUsingDynamicSecretKeys);
} }
private void OnPreObfuscation(Pipeline pipeline) private void OnPreObfuscation(Pipeline pipeline)
{ {
AssemblyCache assemblyCache = new AssemblyCache(new PathAssemblyResolver(_assemblySearchDirs.ToArray())); AssemblyCache assemblyCache = new AssemblyCache(new PathAssemblyResolver(_assemblySearchPaths.ToArray()));
List<ModuleDef> toObfuscatedModules = new List<ModuleDef>(); List<ModuleDef> modulesToObfuscate = new List<ModuleDef>();
List<ModuleDef> obfuscatedAndNotObfuscatedModules = new List<ModuleDef>(); List<ModuleDef> allObfuscationRelativeModules = new List<ModuleDef>();
LoadAssemblies(assemblyCache, toObfuscatedModules, obfuscatedAndNotObfuscatedModules); LoadAssemblies(assemblyCache, modulesToObfuscate, allObfuscationRelativeModules);
EncryptionScopeProvider encryptionScopeProvider = CreateEncryptionScopeProvider(); EncryptionScopeProvider encryptionScopeProvider = CreateEncryptionScopeProvider();
var moduleEntityManager = new GroupByModuleEntityManager(); var moduleEntityManager = new GroupByModuleEntityManager();
@ -276,27 +273,27 @@ namespace Obfuz
_ctx = new ObfuscationPassContext _ctx = new ObfuscationPassContext
{ {
assemblyCache = assemblyCache, assemblyCache = assemblyCache,
toObfuscatedModules = toObfuscatedModules, modulesToObfuscate = modulesToObfuscate,
obfuscatedAndNotObfuscatedModules = obfuscatedAndNotObfuscatedModules, allObfuscationRelativeModules = allObfuscationRelativeModules,
toObfuscatedAssemblyNames = _toObfuscatedAssemblyNames, assembliesToObfuscate = _assembliesToObfuscate,
notObfuscatedAssemblyNamesReferencingObfuscated = _notObfuscatedAssemblyNamesReferencingObfuscated, nonObfuscatedButReferencingObfuscatedAssemblies = _nonObfuscatedButReferencingObfuscatedAssemblies,
obfuscatedAssemblyOutputDir = _obfuscatedAssemblyOutputDir, obfuscatedAssemblyOutputPath = _obfuscatedAssemblyOutputPath,
moduleEntityManager = moduleEntityManager, moduleEntityManager = moduleEntityManager,
encryptionScopeProvider = encryptionScopeProvider, encryptionScopeProvider = encryptionScopeProvider,
rvaDataAllocator = rvaDataAllocator, rvaDataAllocator = rvaDataAllocator,
constFieldAllocator = constFieldAllocator, constFieldAllocator = constFieldAllocator,
whiteList = new NotObfuscatedMethodWhiteList(), whiteList = new ObfuscationMethodWhitelist(),
passPolicy = _passPolicy, passPolicy = _passPolicy,
}; };
ObfuscationPassContext.Current = _ctx; ObfuscationPassContext.Current = _ctx;
pipeline.Start(); pipeline.Start();
} }
private void LoadAssemblies(AssemblyCache assemblyCache, List<ModuleDef> toObfuscatedModules, List<ModuleDef> obfuscatedAndNotObfuscatedModules) private void LoadAssemblies(AssemblyCache assemblyCache, List<ModuleDef> modulesToObfuscate, List<ModuleDef> allObfuscationRelativeModules)
{ {
foreach (string assName in _toObfuscatedAssemblyNames.Concat(_notObfuscatedAssemblyNamesReferencingObfuscated)) foreach (string assName in _assembliesToObfuscate.Concat(_nonObfuscatedButReferencingObfuscatedAssemblies))
{ {
ModuleDefMD mod = assemblyCache.TryLoadModule(assName); ModuleDefMD mod = assemblyCache.TryLoadModule(assName);
if (mod == null) if (mod == null)
@ -304,20 +301,20 @@ namespace Obfuz
Debug.Log($"assembly: {assName} not found! ignore."); Debug.Log($"assembly: {assName} not found! ignore.");
continue; continue;
} }
if (_toObfuscatedAssemblyNames.Contains(assName)) if (_assembliesToObfuscate.Contains(assName))
{ {
toObfuscatedModules.Add(mod); modulesToObfuscate.Add(mod);
} }
obfuscatedAndNotObfuscatedModules.Add(mod); allObfuscationRelativeModules.Add(mod);
} }
} }
private void WriteAssemblies() private void WriteAssemblies()
{ {
foreach (ModuleDef mod in _ctx.obfuscatedAndNotObfuscatedModules) foreach (ModuleDef mod in _ctx.allObfuscationRelativeModules)
{ {
string assNameWithExt = mod.Name; string assNameWithExt = mod.Name;
string outputFile = $"{_obfuscatedAssemblyOutputDir}/{assNameWithExt}"; string outputFile = $"{_obfuscatedAssemblyOutputPath}/{assNameWithExt}";
mod.Write(outputFile); mod.Write(outputFile);
Debug.Log($"save module. name:{mod.Assembly.Name} output:{outputFile}"); Debug.Log($"save module. name:{mod.Assembly.Name} output:{outputFile}");
} }

View File

@ -15,55 +15,55 @@ namespace Obfuz
{ {
public class ObfuscatorBuilder public class ObfuscatorBuilder
{ {
private string _defaultStaticSecret; private string _defaultStaticSecretKey;
private string _defaultStaticSecretOutputPath; private string _defaultStaticSecretKeyOutputPath;
private string _defaultDynamicSecret; private string _defaultDynamicSecretKey;
private string _defaultDynamicSecretOutputPath; private string _defaultDynamicSecretKeyOutputPath;
private List<string> _dynamicSecretAssemblyNames = new List<string>(); private List<string> _assembliesUsingDynamicSecretKeys = new List<string>();
private int _randomSeed; private int _randomSeed;
private string _encryptionVmGenerationSecretKey; private string _encryptionVmGenerationSecretKey;
private int _encryptionVmOpCodeCount; private int _encryptionVmOpCodeCount;
private string _encryptionVmCodeFile; private string _encryptionVmCodeFile;
private List<string> _toObfuscatedAssemblyNames = new List<string>(); private List<string> _assembliesToObfuscate = new List<string>();
private List<string> _notObfuscatedAssemblyNamesReferencingObfuscated = new List<string>(); private List<string> _nonObfuscatedButReferencingObfuscatedAssemblies = new List<string>();
private List<string> _assemblySearchDirs = new List<string>(); private List<string> _assemblySearchPaths = new List<string>();
private string _obfuscatedAssemblyOutputDir; private string _obfuscatedAssemblyOutputPath;
private List<string> _obfuscationPassConfigFiles; private List<string> _obfuscationPassRuleConfigFiles;
private ObfuscationPassType _enabledObfuscationPasses; private ObfuscationPassType _enabledObfuscationPasses;
private List<IObfuscationPass> _obfuscationPasses = new List<IObfuscationPass>(); private List<IObfuscationPass> _obfuscationPasses = new List<IObfuscationPass>();
public string DefaultStaticSecret public string DefaultStaticSecretKey
{ {
get => _defaultStaticSecret; get => _defaultStaticSecretKey;
set => _defaultStaticSecret = value; set => _defaultStaticSecretKey = value;
} }
public string DefaultStaticSecretOutputPath public string DefaultStaticSecretKeyOutputPath
{ {
get => _defaultStaticSecretOutputPath; get => _defaultStaticSecretKeyOutputPath;
set => _defaultStaticSecretOutputPath = value; set => _defaultStaticSecretKeyOutputPath = value;
} }
public string DefaultDynamicSecret public string DefaultDynamicSecretKey
{ {
get => _defaultDynamicSecret; get => _defaultDynamicSecretKey;
set => _defaultDynamicSecret = value; set => _defaultDynamicSecretKey = value;
} }
public string DefaultDynamicSecretOutputPath public string DefaultDynamicSecretKeyOutputPath
{ {
get => _defaultDynamicSecretOutputPath; get => _defaultDynamicSecretKeyOutputPath;
set => _defaultDynamicSecretOutputPath = value; set => _defaultDynamicSecretKeyOutputPath = value;
} }
public List<string> DynamicSecretAssemblyNames public List<string> AssembliesUsingDynamicSecretKeys
{ {
get => _dynamicSecretAssemblyNames; get => _assembliesUsingDynamicSecretKeys;
set => _dynamicSecretAssemblyNames = value; set => _assembliesUsingDynamicSecretKeys = value;
} }
public int RandomSeed public int RandomSeed
@ -90,28 +90,28 @@ namespace Obfuz
set => _encryptionVmCodeFile = value; set => _encryptionVmCodeFile = value;
} }
public List<string> ToObfuscatedAssemblyNames public List<string> AssembliesToObfuscate
{ {
get => _toObfuscatedAssemblyNames; get => _assembliesToObfuscate;
set => _toObfuscatedAssemblyNames = value; set => _assembliesToObfuscate = value;
} }
public List<string> NotObfuscatedAssemblyNamesReferencingObfuscated public List<string> NonObfuscatedButReferencingObfuscatedAssemblies
{ {
get => _notObfuscatedAssemblyNamesReferencingObfuscated; get => _nonObfuscatedButReferencingObfuscatedAssemblies;
set => _notObfuscatedAssemblyNamesReferencingObfuscated = value; set => _nonObfuscatedButReferencingObfuscatedAssemblies = value;
} }
public List<string> AssemblySearchDirs public List<string> AssemblySearchPaths
{ {
get => _assemblySearchDirs; get => _assemblySearchPaths;
set => _assemblySearchDirs = value; set => _assemblySearchPaths = value;
} }
public string ObfuscatedAssemblyOutputDir public string ObfuscatedAssemblyOutputPath
{ {
get => _obfuscatedAssemblyOutputDir; get => _obfuscatedAssemblyOutputPath;
set => _obfuscatedAssemblyOutputDir = value; set => _obfuscatedAssemblyOutputPath = value;
} }
public ObfuscationPassType EnableObfuscationPasses public ObfuscationPassType EnableObfuscationPasses
@ -120,10 +120,10 @@ namespace Obfuz
set => _enabledObfuscationPasses = value; set => _enabledObfuscationPasses = value;
} }
public List<string> ObfuscationPassConfigFiles public List<string> ObfuscationPassRuleConfigFiles
{ {
get => _obfuscationPassConfigFiles; get => _obfuscationPassRuleConfigFiles;
set => _obfuscationPassConfigFiles = value; set => _obfuscationPassRuleConfigFiles = value;
} }
public List<IObfuscationPass> ObfuscationPasses public List<IObfuscationPass> ObfuscationPasses
@ -132,9 +132,9 @@ namespace Obfuz
set => _obfuscationPasses = value; set => _obfuscationPasses = value;
} }
public void InsertTopPriorityAssemblySearchDirs(List<string> assemblySearchDirs) public void InsertTopPriorityAssemblySearchPaths(List<string> assemblySearchPaths)
{ {
_assemblySearchDirs.InsertRange(0, assemblySearchDirs); _assemblySearchPaths.InsertRange(0, assemblySearchPaths);
} }
public ObfuscatorBuilder AddPass(IObfuscationPass pass) public ObfuscatorBuilder AddPass(IObfuscationPass pass)
@ -169,25 +169,25 @@ namespace Obfuz
public static ObfuscatorBuilder FromObfuzSettings(ObfuzSettings settings, BuildTarget target, bool searchPathIncludeUnityEditorInstallLocation) public static ObfuscatorBuilder FromObfuzSettings(ObfuzSettings settings, BuildTarget target, bool searchPathIncludeUnityEditorInstallLocation)
{ {
List<string> searchPaths = searchPathIncludeUnityEditorInstallLocation ? List<string> searchPaths = searchPathIncludeUnityEditorInstallLocation ?
BuildUnityAssemblySearchPaths().Concat(settings.assemblySettings.extraAssemblySearchDirs).ToList() BuildUnityAssemblySearchPaths().Concat(settings.assemblySettings.additionalAssemblySearchPaths).ToList()
: settings.assemblySettings.extraAssemblySearchDirs.ToList(); : settings.assemblySettings.additionalAssemblySearchPaths.ToList();
var builder = new ObfuscatorBuilder var builder = new ObfuscatorBuilder
{ {
_defaultStaticSecret = settings.secretSettings.defaultStaticSecret, _defaultStaticSecretKey = settings.secretSettings.defaultStaticSecretKey,
_defaultStaticSecretOutputPath = settings.secretSettings.DefaultStaticSecretKeyOutputPath, _defaultStaticSecretKeyOutputPath = settings.secretSettings.DefaultStaticSecretKeyOutputPath,
_defaultDynamicSecret = settings.secretSettings.defaultDynamicSecret, _defaultDynamicSecretKey = settings.secretSettings.defaultDynamicSecretKey,
_defaultDynamicSecretOutputPath = settings.secretSettings.DefaultDynamicSecretKeyOutputPath, _defaultDynamicSecretKeyOutputPath = settings.secretSettings.DefaultDynamicSecretKeyOutputPath,
_dynamicSecretAssemblyNames = settings.secretSettings.dynamicSecretAssemblyNames.ToList(), _assembliesUsingDynamicSecretKeys = settings.secretSettings.assembliesUsingDynamicSecretKeys.ToList(),
_randomSeed = settings.secretSettings.randomSeed, _randomSeed = settings.secretSettings.randomSeed,
_encryptionVmGenerationSecretKey = settings.encryptionVMSettings.codeGenerationSecret, _encryptionVmGenerationSecretKey = settings.encryptionVMSettings.codeGenerationSecretKey,
_encryptionVmOpCodeCount = settings.encryptionVMSettings.encryptionOpCodeCount, _encryptionVmOpCodeCount = settings.encryptionVMSettings.encryptionOpCodeCount,
_encryptionVmCodeFile = settings.encryptionVMSettings.codeOutputPath, _encryptionVmCodeFile = settings.encryptionVMSettings.codeOutputPath,
_toObfuscatedAssemblyNames = settings.assemblySettings.toObfuscatedAssemblyNames.ToList(), _assembliesToObfuscate = settings.assemblySettings.assembliesToObfuscate.ToList(),
_notObfuscatedAssemblyNamesReferencingObfuscated = settings.assemblySettings.notObfuscatedAssemblyNamesReferencingObfuscated.ToList(), _nonObfuscatedButReferencingObfuscatedAssemblies = settings.assemblySettings.nonObfuscatedButReferencingObfuscatedAssemblies.ToList(),
_assemblySearchDirs = searchPaths, _assemblySearchPaths = searchPaths,
_obfuscatedAssemblyOutputDir = settings.GetObfuscatedAssemblyOutputDir(target), _obfuscatedAssemblyOutputPath = settings.GetObfuscatedAssemblyOutputPath(target),
_enabledObfuscationPasses = settings.obfuscationPassSettings.enabledPasses, _enabledObfuscationPasses = settings.obfuscationPassSettings.enabledPasses,
_obfuscationPassConfigFiles = settings.obfuscationPassSettings.configFiles.ToList(), _obfuscationPassRuleConfigFiles = settings.obfuscationPassSettings.ruleFiles.ToList(),
}; };
ObfuscationPassType obfuscationPasses = settings.obfuscationPassSettings.enabledPasses; ObfuscationPassType obfuscationPasses = settings.obfuscationPassSettings.enabledPasses;
if (obfuscationPasses.HasFlag(ObfuscationPassType.ConstEncrypt)) if (obfuscationPasses.HasFlag(ObfuscationPassType.ConstEncrypt))

View File

@ -8,19 +8,19 @@ namespace Obfuz.Settings
public class AssemblySettings public class AssemblySettings
{ {
[Tooltip("name of assemblies to obfuscated")] [Tooltip("name of assemblies to obfuscate")]
public string[] toObfuscatedAssemblyNames; public string[] assembliesToObfuscate;
[Tooltip("name of assemblies not obfuscated but reference assemblies to obfuscated ")] [Tooltip("name of assemblies not obfuscated but reference assemblies to obfuscated ")]
public string[] notObfuscatedAssemblyNamesReferencingObfuscated; public string[] nonObfuscatedButReferencingObfuscatedAssemblies;
[Tooltip("extra assembly search dirs")] [Tooltip("additional assembly search paths")]
public string[] extraAssemblySearchDirs; public string[] additionalAssemblySearchPaths;
public string[] GetObfuscationRelativeAssemblyNames() public string[] GetObfuscationRelativeAssemblyNames()
{ {
return toObfuscatedAssemblyNames return assembliesToObfuscate
.Concat(notObfuscatedAssemblyNamesReferencingObfuscated) .Concat(nonObfuscatedButReferencingObfuscatedAssemblies)
.ToArray(); .ToArray();
} }
} }

View File

@ -8,13 +8,13 @@ using UnityEngine;
namespace Obfuz.Settings namespace Obfuz.Settings
{ {
[Serializable] [Serializable]
public class CallObfusSettings public class CallObfuscationSettings
{ {
[Tooltip("The obfuscation level for the obfuscation. Higher levels provide more security but may impact performance.")] [Tooltip("The obfuscation level for the obfuscation. Higher levels provide more security but may impact performance.")]
[Range(1, 4)] [Range(1, 4)]
public int callObfuscationLevel = 1; public int obfuscationLevel = 1;
[Tooltip("config xml files")] [Tooltip("rule config xml files")]
public string[] configFiles; public string[] ruleFiles;
} }
} }

View File

@ -8,13 +8,13 @@ using UnityEngine;
namespace Obfuz.Settings namespace Obfuz.Settings
{ {
[Serializable] [Serializable]
public class ConstEncryptSettings public class ConstEncryptionSettings
{ {
[Tooltip("The encryption level for the obfuscation. Higher levels provide more security but may impact performance.")] [Tooltip("The encryption level for the obfuscation. Higher levels provide more security but may impact performance.")]
[Range(1, 4)] [Range(1, 4)]
public int encryptionLevel = 1; public int encryptionLevel = 1;
[Tooltip("config xml files")] [Tooltip("config xml files")]
public string[] configFiles; public string[] ruleFiles;
} }
} }

View File

@ -12,7 +12,7 @@ namespace Obfuz.Settings
public class EncryptionVMSettings public class EncryptionVMSettings
{ {
[Tooltip("secret key for generating encryption virtual machine source code")] [Tooltip("secret key for generating encryption virtual machine source code")]
public string codeGenerationSecret = "Obfuz"; public string codeGenerationSecretKey = "Obfuz";
[Tooltip("encryption OpCode count, should be power of 2 and >= 64")] [Tooltip("encryption OpCode count, should be power of 2 and >= 64")]
public int encryptionOpCodeCount = 256; public int encryptionOpCodeCount = 256;

View File

@ -8,13 +8,13 @@ using UnityEngine;
namespace Obfuz.Settings namespace Obfuz.Settings
{ {
[Serializable] [Serializable]
public class FieldEncryptSettings public class FieldEncryptionSettings
{ {
[Tooltip("The encryption level for the obfuscation. Higher levels provide more security but may impact performance.")] [Tooltip("The encryption level for the obfuscation. Higher levels provide more security but may impact performance.")]
[Range(1, 4)] [Range(1, 4)]
public int encryptionLevel = 1; public int encryptionLevel = 1;
[Tooltip("config xml files")] [Tooltip("rule config xml files")]
public string[] configFiles; public string[] ruleFiles;
} }
} }

View File

@ -10,7 +10,7 @@ namespace Obfuz.Settings
[Tooltip("enable obfuscation pass")] [Tooltip("enable obfuscation pass")]
public ObfuscationPassType enabledPasses = ObfuscationPassType.All; public ObfuscationPassType enabledPasses = ObfuscationPassType.All;
[Tooltip("config xml files")] [Tooltip("rule config xml files")]
public string[] configFiles; public string[] ruleFiles;
} }
} }

View File

@ -27,20 +27,20 @@ namespace Obfuz.Settings
public EncryptionVMSettings encryptionVMSettings; public EncryptionVMSettings encryptionVMSettings;
[Tooltip("symbol obfuscation settings")] [Tooltip("symbol obfuscation settings")]
public SymbolObfusSettings symbolObfusSettings; public SymbolObfuscationSettings symbolObfusSettings;
[Tooltip("const encryption settings")] [Tooltip("const encryption settings")]
public ConstEncryptSettings constEncryptSettings; public ConstEncryptionSettings constEncryptSettings;
[Tooltip("field encryption settings")] [Tooltip("field encryption settings")]
public FieldEncryptSettings fieldEncryptSettings; public FieldEncryptionSettings fieldEncryptSettings;
[Tooltip("call obfuscation settings")] [Tooltip("call obfuscation settings")]
public CallObfusSettings callObfusSettings; public CallObfuscationSettings callObfusSettings;
public string ObfuzRootDir => $"Library/Obfuz"; public string ObfuzRootDir => $"Library/Obfuz";
public string GetObfuscatedAssemblyOutputDir(BuildTarget target) public string GetObfuscatedAssemblyOutputPath(BuildTarget target)
{ {
return $"{ObfuzRootDir}/{target}/ObfuscatedAssemblies"; return $"{ObfuzRootDir}/{target}/ObfuscatedAssemblies";
} }
@ -72,7 +72,7 @@ namespace Obfuz.Settings
var arr = InternalEditorUtility.LoadSerializedFileAndForget(filePath); var arr = InternalEditorUtility.LoadSerializedFileAndForget(filePath);
//Debug.Log($"typeof arr:{arr?.GetType()} arr[0]:{(arr != null && arr.Length > 0 ? arr[0].GetType(): null)}"); //Debug.Log($"typeof arr:{arr?.GetType()} arr[0]:{(arr != null && arr.Length > 0 ? arr[0].GetType(): null)}");
s_Instance = arr != null && arr.Length > 0 ? (ObfuzSettings)arr[0] : CreateInstance<ObfuzSettings>(); s_Instance = arr != null && arr.Length > 0 ? (ObfuzSettings)arr[0] : (s_Instance ?? CreateInstance<ObfuzSettings>());
return s_Instance; return s_Instance;
} }

View File

@ -9,21 +9,22 @@ namespace Obfuz.Settings
{ {
[Tooltip("default static secret key")] [Tooltip("default static secret key")]
public string defaultStaticSecret = "Code Philosophy-Static"; public string defaultStaticSecretKey = "Code Philosophy-Static";
public string defaultDynamicSecret = "Code Philosophy-Dynamic"; [Tooltip("default dynamic secret key")]
public string defaultDynamicSecretKey = "Code Philosophy-Dynamic";
[Tooltip("secret key output directory")] [Tooltip("secret key output path")]
public string secretOutputDir = $"Assets/Resources/Obfuz"; public string secretKeyOutputPath = $"Assets/Resources/Obfuz";
[Tooltip("random seed")] [Tooltip("random seed")]
public int randomSeed = 0; public int randomSeed = 0;
[Tooltip("name of assemblies those use dynamic secret")] [Tooltip("name of assemblies those use dynamic secret key")]
public string[] dynamicSecretAssemblyNames; public string[] assembliesUsingDynamicSecretKeys;
public string DefaultStaticSecretKeyOutputPath => Path.Combine(secretOutputDir, "defaultStaticSecret.bytes"); public string DefaultStaticSecretKeyOutputPath => Path.Combine(secretKeyOutputPath, "defaultStaticSecret.bytes");
public string DefaultDynamicSecretKeyOutputPath => Path.Combine(secretOutputDir, "defaultDynamicSecret.bytes"); public string DefaultDynamicSecretKeyOutputPath => Path.Combine(secretKeyOutputPath, "defaultDynamicSecret.bytes");
} }
} }

View File

@ -8,7 +8,7 @@ using UnityEngine;
namespace Obfuz.Settings namespace Obfuz.Settings
{ {
[Serializable] [Serializable]
public class SymbolObfusSettings public class SymbolObfuscationSettings
{ {
public bool debug; public bool debug;
@ -18,10 +18,10 @@ namespace Obfuz.Settings
[Tooltip("obfuscate same namespace to one name")] [Tooltip("obfuscate same namespace to one name")]
public bool useConsistentNamespaceObfuscation = true; public bool useConsistentNamespaceObfuscation = true;
[Tooltip("path of mapping.xml")] [Tooltip("symbol mapping file path")]
public string mappingFile = "Assets/Obfuz/SymbolObfus/mapping.xml"; public string symbolMappingFile = "Assets/Obfuz/SymbolObfus/symbol-mapping.xml";
[Tooltip("obfuscation rule files for assemblies")] [Tooltip("rule files")]
public string[] ruleFiles; public string[] ruleFiles;
} }
} }

View File

@ -74,13 +74,13 @@ namespace Obfuz.Unity
{ {
stagingAreaTempManagedDllDir, stagingAreaTempManagedDllDir,
}; };
obfuscatorBuilder.InsertTopPriorityAssemblySearchDirs(assemblySearchDirs); obfuscatorBuilder.InsertTopPriorityAssemblySearchPaths(assemblySearchDirs);
OnObfuscationBegin?.Invoke(new ObfuscationBeginEventArgs OnObfuscationBegin?.Invoke(new ObfuscationBeginEventArgs
{ {
scriptAssembliesPath = stagingAreaTempManagedDllDir, scriptAssembliesPath = stagingAreaTempManagedDllDir,
obfuscatedScriptAssembliesPath = obfuscatorBuilder.ObfuscatedAssemblyOutputDir, obfuscatedScriptAssembliesPath = obfuscatorBuilder.ObfuscatedAssemblyOutputPath,
}); });
bool succ = false; bool succ = false;
@ -91,7 +91,7 @@ namespace Obfuz.Unity
foreach (var dllName in obfuscationRelativeAssemblyNames) foreach (var dllName in obfuscationRelativeAssemblyNames)
{ {
string src = $"{obfuscatorBuilder.ObfuscatedAssemblyOutputDir}/{dllName}.dll"; string src = $"{obfuscatorBuilder.ObfuscatedAssemblyOutputPath}/{dllName}.dll";
string dst = $"{stagingAreaTempManagedDllDir}/{dllName}.dll"; string dst = $"{stagingAreaTempManagedDllDir}/{dllName}.dll";
if (!File.Exists(src)) if (!File.Exists(src))

View File

@ -18,7 +18,7 @@ namespace Obfuz.Unity
public static void GenerateEncryptionVM() public static void GenerateEncryptionVM()
{ {
EncryptionVMSettings settings = ObfuzSettings.Instance.encryptionVMSettings; EncryptionVMSettings settings = ObfuzSettings.Instance.encryptionVMSettings;
var generator = new VirtualMachineCodeGenerator(settings.codeGenerationSecret, settings.encryptionOpCodeCount); var generator = new VirtualMachineCodeGenerator(settings.codeGenerationSecretKey, settings.encryptionOpCodeCount);
generator.Generate(settings.codeOutputPath); generator.Generate(settings.codeOutputPath);
} }
@ -27,10 +27,10 @@ namespace Obfuz.Unity
{ {
SecretSettings settings = ObfuzSettings.Instance.secretSettings; SecretSettings settings = ObfuzSettings.Instance.secretSettings;
var staticSecretBytes = KeyGenerator.GenerateKey(settings.defaultStaticSecret, VirtualMachine.SecretKeyLength); var staticSecretBytes = KeyGenerator.GenerateKey(settings.defaultStaticSecretKey, VirtualMachine.SecretKeyLength);
SaveKey(staticSecretBytes, settings.DefaultStaticSecretKeyOutputPath); SaveKey(staticSecretBytes, settings.DefaultStaticSecretKeyOutputPath);
Debug.Log($"Save static secret key to {settings.DefaultStaticSecretKeyOutputPath}"); Debug.Log($"Save static secret key to {settings.DefaultStaticSecretKeyOutputPath}");
var dynamicSecretBytes = KeyGenerator.GenerateKey(settings.defaultDynamicSecret, VirtualMachine.SecretKeyLength); var dynamicSecretBytes = KeyGenerator.GenerateKey(settings.defaultDynamicSecretKey, VirtualMachine.SecretKeyLength);
SaveKey(dynamicSecretBytes, settings.DefaultDynamicSecretKeyOutputPath); SaveKey(dynamicSecretBytes, settings.DefaultDynamicSecretKeyOutputPath);
Debug.Log($"Save dynamic secret key to {settings.DefaultDynamicSecretKeyOutputPath}"); Debug.Log($"Save dynamic secret key to {settings.DefaultDynamicSecretKeyOutputPath}");
} }
@ -56,9 +56,6 @@ namespace Obfuz.Unity
[MenuItem("Obfuz/Documents/GitHub")] [MenuItem("Obfuz/Documents/GitHub")]
public static void OpenGitHub() => Application.OpenURL("https://github.com/focus-creative-games/obfuz"); public static void OpenGitHub() => Application.OpenURL("https://github.com/focus-creative-games/obfuz");
[MenuItem("Obfuz/Documents/Gitee")]
public static void OpenGitee() => Application.OpenURL("https://gitee.com/focus-creative-games/obfuz");
[MenuItem("Obfuz/Documents/About")] [MenuItem("Obfuz/Documents/About")]
public static void OpenAbout() => Application.OpenURL("https://obfuz.doc.code-philosophy.com/docs/intro"); public static void OpenAbout() => Application.OpenURL("https://obfuz.doc.code-philosophy.com/docs/intro");
} }