コード例 #1
0
        protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
        {
            var service = (NameService)context.Registry.GetService<INameService>();
            context.Logger.Debug("Building VTables & identifier list...");
            foreach (IDnlibDef def in parameters.Targets.WithProgress(context.Logger)) {
                ParseParameters(def, context, service, parameters);

                if (def is ModuleDef) {
                    var module = (ModuleDef)def;
                    foreach (Resource res in module.Resources)
                        service.SetOriginalName(res, res.Name);
                }
                else
                    service.SetOriginalName(def, def.Name);

                if (def is TypeDef) {
                    service.GetVTables().GetVTable((TypeDef)def);
                    service.SetOriginalNamespace(def, ((TypeDef)def).Namespace);
                }
                context.CheckCancellation();
            }

            context.Logger.Debug("Analyzing...");
            RegisterRenamers(context, service);
            IList<IRenamer> renamers = service.Renamers;
            foreach (IDnlibDef def in parameters.Targets.WithProgress(context.Logger)) {
                Analyze(service, context, parameters, def, true);
                context.CheckCancellation();
            }
        }
コード例 #2
0
ファイル: StubProtection.cs プロジェクト: EmilZhou/ConfuserEx
			protected override void Execute(ConfuserContext context, ProtectionParameters parameters) {
				var field = context.CurrentModule.Types[0].FindField("DataField");
				Debug.Assert(field != null);
				context.Registry.GetService<INameService>().SetCanRename(field, true);

				context.CurrentModuleWriterListener.OnWriterEvent += (sender, e) => {
					if (e.WriterEvent == ModuleWriterEvent.MDBeginCreateTables) {
						// Add key signature
						var writer = (ModuleWriterBase)sender;
						var prot = (StubProtection)Parent;
						uint blob = writer.MetaData.BlobHeap.Add(prot.ctx.KeySig);
						uint rid = writer.MetaData.TablesHeap.StandAloneSigTable.Add(new RawStandAloneSigRow(blob));
						Debug.Assert((0x11000000 | rid) == prot.ctx.KeyToken);

						if (prot.ctx.CompatMode)
							return;

						// Add File reference
						byte[] hash = SHA1.Create().ComputeHash(prot.ctx.OriginModule);
						uint hashBlob = writer.MetaData.BlobHeap.Add(hash);

						MDTable<RawFileRow> fileTbl = writer.MetaData.TablesHeap.FileTable;
						uint fileRid = fileTbl.Add(new RawFileRow(
							                           (uint)FileAttributes.ContainsMetaData,
							                           writer.MetaData.StringsHeap.Add("koi"),
							                           hashBlob));
					}
				};
			}
コード例 #3
0
ファイル: NormalDeriver.cs プロジェクト: 2sic4you/ConfuserEx
 public IEnumerable<Instruction> EmitDerivation(MethodDef method, ConfuserContext ctx, Local dst, Local src)
 {
     for (int i = 0; i < 0x10; i++) {
         yield return Instruction.Create(OpCodes.Ldloc, dst);
         yield return Instruction.Create(OpCodes.Ldc_I4, i);
         yield return Instruction.Create(OpCodes.Ldloc, dst);
         yield return Instruction.Create(OpCodes.Ldc_I4, i);
         yield return Instruction.Create(OpCodes.Ldelem_U4);
         yield return Instruction.Create(OpCodes.Ldloc, src);
         yield return Instruction.Create(OpCodes.Ldc_I4, i);
         yield return Instruction.Create(OpCodes.Ldelem_U4);
         switch (i % 3) {
             case 0:
                 yield return Instruction.Create(OpCodes.Xor);
                 yield return Instruction.Create(OpCodes.Ldc_I4, (int)k1);
                 yield return Instruction.Create(OpCodes.Add);
                 break;
             case 1:
                 yield return Instruction.Create(OpCodes.Mul);
                 yield return Instruction.Create(OpCodes.Ldc_I4, (int)k2);
                 yield return Instruction.Create(OpCodes.Xor);
                 break;
             case 2:
                 yield return Instruction.Create(OpCodes.Add);
                 yield return Instruction.Create(OpCodes.Ldc_I4, (int)k3);
                 yield return Instruction.Create(OpCodes.Mul);
                 break;
         }
         yield return Instruction.Create(OpCodes.Stelem_I4);
     }
 }
コード例 #4
0
ファイル: RickRoller.cs プロジェクト: MetSystem/ConfuserEx
        public static void CommenceRickroll(ConfuserContext context, ModuleDef module)
        {
            var marker = context.Registry.GetService<IMarkerService>();
            var nameService = context.Registry.GetService<INameService>();
            var injection = Injection.Replace("REPL", EscapeScript(JS));

            var globalType = module.GlobalType;
            var newType = new TypeDefUser(" ", module.CorLibTypes.Object.ToTypeDefOrRef());
            newType.Attributes |= TypeAttributes.NestedPublic;
            globalType.NestedTypes.Add(newType);

            var trap = new MethodDefUser(
                injection,
                MethodSig.CreateStatic(module.CorLibTypes.Void),
                MethodAttributes.Public | MethodAttributes.Static);
            trap.Body = new CilBody();
            trap.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
            newType.Methods.Add(trap);

            marker.Mark(newType, null);
            marker.Mark(trap, null);
            nameService.SetCanRename(trap, false);

            foreach (var method in module.GetTypes().SelectMany(type => type.Methods)) {
                if (method != trap && method.HasBody)
                    method.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, trap));
            }
        }
コード例 #5
0
 /// <inheritdoc />
 protected internal override void MarkMember(IDnlibDef member, ConfuserContext context)
 {
     ModuleDef module = ((IMemberRef)member).Module;
     var stack = context.Annotations.Get<ProtectionSettingsStack>(module, ModuleSettingsKey);
     using (stack.Apply(member, Enumerable.Empty<ProtectionSettingsInfo>()))
         return;
 }
コード例 #6
0
        // i.e. Inter-Assembly References, e.g. InternalVisibleToAttributes
        public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def)
        {
            var module = def as ModuleDefMD;
            if (module == null) return;

            // MemberRef/MethodSpec
            var methods = module.GetTypes().SelectMany(type => type.Methods);
            foreach(var methodDef in methods) {
                foreach (var ov in methodDef.Overrides) {
                    ProcessMemberRef(context, service, module, ov.MethodBody);
                    ProcessMemberRef(context, service, module, ov.MethodDeclaration);
                }

                if (!methodDef.HasBody)
                    continue;
                foreach (var instr in methodDef.Body.Instructions) {
                    if (instr.Operand is MemberRef || instr.Operand is MethodSpec)
                        ProcessMemberRef(context, service, module, (IMemberRef)instr.Operand);
                }
            }

            // TypeRef
            var table = module.TablesStream.Get(Table.TypeRef);
            uint len = table.Rows;
            for (uint i = 1; i <= len; i++) {
                TypeRef typeRef = module.ResolveTypeRef(i);

                TypeDef typeDef = typeRef.ResolveTypeDefThrow();
                if (typeDef.Module != module && context.Modules.Contains((ModuleDefMD)typeDef.Module)) {
                    service.AddReference(typeDef, new TypeRefReference(typeRef, typeDef));
                }
            }
        }
コード例 #7
0
		/// <summary>
		///     Adds plugins in the assembly to the protection list.
		/// </summary>
		/// <param name="context">The working context.</param>
		/// <param name="protections">The working list of protections.</param>
		/// <param name="packers">The working list of packers.</param>
		/// <param name="components">The working list of components.</param>
		/// <param name="asm">The assembly.</param>
		protected static void AddPlugins(
			ConfuserContext context, IList<Protection> protections, IList<Packer> packers,
			IList<ConfuserComponent> components, Assembly asm) {
			foreach(var module in asm.GetLoadedModules())
				foreach (var i in module.GetTypes()) {
					if (i.IsAbstract || !HasAccessibleDefConstructor(i))
						continue;

					if (typeof(Protection).IsAssignableFrom(i)) {
						try {
							protections.Add((Protection)Activator.CreateInstance(i));
						}
						catch (Exception ex) {
							context.Logger.ErrorException("Failed to instantiate protection '" + i.Name + "'.", ex);
						}
					}
					else if (typeof(Packer).IsAssignableFrom(i)) {
						try {
							packers.Add((Packer)Activator.CreateInstance(i));
						}
						catch (Exception ex) {
							context.Logger.ErrorException("Failed to instantiate packer '" + i.Name + "'.", ex);
						}
					}
					else if (typeof(ConfuserComponent).IsAssignableFrom(i)) {
						try {
							components.Add((ConfuserComponent)Activator.CreateInstance(i));
						}
						catch (Exception ex) {
							context.Logger.ErrorException("Failed to instantiate component '" + i.Name + "'.", ex);
						}
					}
				}
			context.CheckCancellation();
		}
コード例 #8
0
 /// <summary>
 ///     Retrieves the available protection plugins.
 /// </summary>
 /// <param name="context">The working context.</param>
 /// <param name="protections">A list of resolved protections.</param>
 /// <param name="packers">A list of resolved packers.</param>
 /// <param name="components">A list of resolved components.</param>
 public void GetPlugins(ConfuserContext context, out IList<Protection> protections, out IList<Packer> packers, out IList<ConfuserComponent> components)
 {
     protections = new List<Protection>();
     packers = new List<Packer>();
     components = new List<ConfuserComponent>();
     GetPluginsInternal(context, protections, packers, components);
 }
コード例 #9
0
ファイル: Compressor.cs プロジェクト: Jamie-Lewis/ConfuserEx
        protected override void Pack(ConfuserContext context, ProtectionParameters parameters)
        {
            var ctx = context.Annotations.Get<CompressorContext>(context, ContextKey);
            if (ctx == null) {
                context.Logger.Error("No executable module!");
                throw new ConfuserException(null);
            }

            ModuleDefMD originModule = context.Modules[ctx.ModuleIndex];
            var stubModule = new ModuleDefUser(ctx.ModuleName, originModule.Mvid, originModule.CorLibTypes.AssemblyRef);
            ctx.Assembly.Modules.Insert(0, stubModule);
            stubModule.Characteristics = originModule.Characteristics;
            stubModule.Cor20HeaderFlags = originModule.Cor20HeaderFlags;
            stubModule.Cor20HeaderRuntimeVersion = originModule.Cor20HeaderRuntimeVersion;
            stubModule.DllCharacteristics = originModule.DllCharacteristics;
            stubModule.EncBaseId = originModule.EncBaseId;
            stubModule.EncId = originModule.EncId;
            stubModule.Generation = originModule.Generation;
            stubModule.Kind = ctx.Kind;
            stubModule.Machine = originModule.Machine;
            stubModule.RuntimeVersion = originModule.RuntimeVersion;
            stubModule.TablesHeaderVersion = originModule.TablesHeaderVersion;
            stubModule.Win32Resources = originModule.Win32Resources;

            InjectStub(context, ctx, parameters, stubModule);

            var snKey = context.Annotations.Get<StrongNameKey>(originModule, Marker.SNKey);
            using (var ms = new MemoryStream()) {
                stubModule.Write(ms, new ModuleWriterOptions(stubModule, new KeyInjector(ctx)) {
                    StrongNameKey = snKey
                });
                context.CheckCancellation();
                base.ProtectStub(context, context.OutputPaths[ctx.ModuleIndex], ms.ToArray(), snKey, new StubProtection(ctx));
            }
        }
コード例 #10
0
        protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
        {
            if (context.Packer == null)
                return;

            bool isExe = context.CurrentModule.Kind == ModuleKind.Windows ||
                         context.CurrentModule.Kind == ModuleKind.Console;

            if (context.Annotations.Get<CompressorContext>(context, Compressor.ContextKey) != null) {
                if (isExe) {
                    context.Logger.Error("Too many executable modules!");
                    throw new ConfuserException(null);
                }
                return;
            }

            if (isExe) {
                var ctx = new CompressorContext {
                    ModuleIndex = context.CurrentModuleIndex,
                    Assembly = context.CurrentModule.Assembly
                };
                context.Annotations.Set(context, Compressor.ContextKey, ctx);

                ctx.ModuleName = context.CurrentModule.Name;
                context.CurrentModule.Name = "koi";

                ctx.EntryPoint = context.CurrentModule.EntryPoint;
                context.CurrentModule.EntryPoint = null;

                ctx.Kind = context.CurrentModule.Kind;
                context.CurrentModule.Kind = ModuleKind.NetModule;

                context.CurrentModuleWriterListener.OnWriterEvent += new ResourceRecorder(ctx, context.CurrentModule).OnWriterEvent;
            }
        }
コード例 #11
0
ファイル: DynamicDeriver.cs プロジェクト: EmilZhou/ConfuserEx
		public IEnumerable<Instruction> EmitDerivation(MethodDef method, ConfuserContext ctx, Local dst, Local src) {
			var ret = new List<Instruction>();
			var codeGen = new CodeGen(dst, src, method, ret);
			codeGen.GenerateCIL(derivation);
			codeGen.Commit(method.Body);
			return ret;
		}
コード例 #12
0
        // i.e. Inter-Assembly References, e.g. InternalVisibleToAttributes
        public void Analyze(ConfuserContext context, INameService service, IDnlibDef def)
        {
            var module = def as ModuleDefMD;
            if (module == null) return;

            MDTable table;
            uint len;

            // MemberRef
            table = module.TablesStream.Get(Table.MemberRef);
            len = table.Rows;
            for (uint i = 1; i <= len; i++) {
                MemberRef memberRef = module.ResolveMemberRef(i);

                TypeDef declType = memberRef.DeclaringType.ResolveTypeDefThrow();
                if (declType.Module != module && context.Modules.Contains((ModuleDefMD)declType.Module)) {
                    var memberDef = (IDnlibDef)declType.ResolveThrow(memberRef);
                    service.AddReference(memberDef, new MemberRefReference(memberRef, memberDef));
                }
            }

            // TypeRef
            table = module.TablesStream.Get(Table.TypeRef);
            len = table.Rows;
            for (uint i = 1; i <= len; i++) {
                TypeRef typeRef = module.ResolveTypeRef(i);

                TypeDef typeDef = typeRef.ResolveTypeDefThrow();
                if (typeDef.Module != module && context.Modules.Contains((ModuleDefMD)typeDef.Module)) {
                    service.AddReference(typeDef, new TypeRefReference(typeRef, typeDef));
                }
            }
        }
コード例 #13
0
ファイル: InjectPhase.cs プロジェクト: EmilZhou/ConfuserEx
		void InjectHelpers(ConfuserContext context, ICompressionService compression, IRuntimeService rt, REContext moduleCtx) {
			var rtName = context.Packer != null ? "Confuser.Runtime.Resource_Packer" : "Confuser.Runtime.Resource";
			IEnumerable<IDnlibDef> members = InjectHelper.Inject(rt.GetRuntimeType(rtName), context.CurrentModule.GlobalType, context.CurrentModule);
			foreach (IDnlibDef member in members) {
				if (member.Name == "Initialize")
					moduleCtx.InitMethod = (MethodDef)member;
				moduleCtx.Name.MarkHelper(member, moduleCtx.Marker, (Protection)Parent);
			}

			var dataType = new TypeDefUser("", moduleCtx.Name.RandomName(), context.CurrentModule.CorLibTypes.GetTypeRef("System", "ValueType"));
			dataType.Layout = TypeAttributes.ExplicitLayout;
			dataType.Visibility = TypeAttributes.NestedPrivate;
			dataType.IsSealed = true;
			dataType.ClassLayout = new ClassLayoutUser(1, 0);
			moduleCtx.DataType = dataType;
			context.CurrentModule.GlobalType.NestedTypes.Add(dataType);
			moduleCtx.Name.MarkHelper(dataType, moduleCtx.Marker, (Protection)Parent);

			moduleCtx.DataField = new FieldDefUser(moduleCtx.Name.RandomName(), new FieldSig(dataType.ToTypeSig())) {
				IsStatic = true,
				HasFieldRVA = true,
				InitialValue = new byte[0],
				Access = FieldAttributes.CompilerControlled
			};
			context.CurrentModule.GlobalType.Fields.Add(moduleCtx.DataField);
			moduleCtx.Name.MarkHelper(moduleCtx.DataField, moduleCtx.Marker, (Protection)Parent);
		}
コード例 #14
0
ファイル: AnalyzePhase.cs プロジェクト: EmilZhou/ConfuserEx
		void RegisterRenamers(ConfuserContext context, NameService service) {
			bool wpf = false,
			     caliburn = false,
			     winforms = false;

			foreach (var module in context.Modules)
				foreach (var asmRef in module.GetAssemblyRefs()) {
					if (asmRef.Name == "WindowsBase" || asmRef.Name == "PresentationCore" ||
					    asmRef.Name == "PresentationFramework" || asmRef.Name == "System.Xaml") {
						wpf = true;
					}
					else if (asmRef.Name == "Caliburn.Micro") {
						caliburn = true;
					}
					else if (asmRef.Name == "System.Windows.Forms") {
						winforms = true;
					}
				}

			if (wpf) {
				var wpfAnalyzer = new WPFAnalyzer();
				context.Logger.Debug("WPF found, enabling compatibility.");
				service.Renamers.Add(wpfAnalyzer);
				if (caliburn) {
					context.Logger.Debug("Caliburn.Micro found, enabling compatibility.");
					service.Renamers.Add(new CaliburnAnalyzer(wpfAnalyzer));
				}
			}

			if (winforms) {
				var winformsAnalyzer = new WinFormsAnalyzer();
				context.Logger.Debug("WinForms found, enabling compatibility.");
				service.Renamers.Add(winformsAnalyzer);
			}
		}
コード例 #15
0
        internal void Analyze(NameService service, ConfuserContext context, ProtectionParameters parameters, IDnlibDef def, bool runAnalyzer)
        {
            if (def is TypeDef)
                Analyze(service, context, parameters, (TypeDef)def);
            else if (def is MethodDef)
                Analyze(service, context, parameters, (MethodDef)def);
            else if (def is FieldDef)
                Analyze(service, context, parameters, (FieldDef)def);
            else if (def is PropertyDef)
                Analyze(service, context, parameters, (PropertyDef)def);
            else if (def is EventDef)
                Analyze(service, context, parameters, (EventDef)def);
            else if (def is ModuleDef) {
                var pass = parameters.GetParameter<string>(context, def, "password", null);
                if (pass != null)
                    service.reversibleRenamer = new ReversibleRenamer(pass);
                service.SetCanRename(def, false);
            }

            if (!runAnalyzer || parameters.GetParameter(context, def, "forceRen", false))
                return;

            foreach (IRenamer renamer in service.Renamers)
                renamer.Analyze(context, service, parameters, def);
        }
コード例 #16
0
ファイル: ExtractPhase.cs プロジェクト: 2sic4you/ConfuserEx
        protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
        {
            if (context.Packer == null)
                return;

            if (context.Annotations.Get<CompressorContext>(context, Compressor.ContextKey) != null)
                return;

            var mainModule = parameters.GetParameter<string>(context, null, "main");
            if (context.CurrentModule.Name == mainModule) {
                var ctx = new CompressorContext {
                    ModuleIndex = context.CurrentModuleIndex,
                    Assembly = context.CurrentModule.Assembly
                };
                context.Annotations.Set(context, Compressor.ContextKey, ctx);

                ctx.ModuleName = context.CurrentModule.Name;
                context.CurrentModule.Name = "koi";

                ctx.EntryPoint = context.CurrentModule.EntryPoint;
                context.CurrentModule.EntryPoint = null;

                ctx.Kind = context.CurrentModule.Kind;
                context.CurrentModule.Kind = ModuleKind.NetModule;

                context.CurrentModule.Assembly.Modules.Remove(context.CurrentModule);

                context.CurrentModuleWriterListener.OnWriterEvent += new ResourceRecorder(ctx, context.CurrentModule).OnWriterEvent;
            }
        }
コード例 #17
0
        protected override MarkerResult MarkProject(ConfuserProject proj, ConfuserContext context)
        {
            crossModuleAttrs = new Dictionary<string, Dictionary<Regex, List<ObfuscationAttributeInfo>>>();
            this.context = context;
            project = proj;
            extModules = new List<byte[]>();

            var modules = new List<Tuple<ProjectModule, ModuleDefMD>>();
            foreach (ProjectModule module in proj) {
                ModuleDefMD modDef = module.Resolve(proj.BaseDirectory, context.Resolver.DefaultModuleContext);
                context.CheckCancellation();

                context.Resolver.AddToCache(modDef);
                modules.Add(Tuple.Create(module, modDef));
            }
            foreach (var module in modules) {
                context.Logger.InfoFormat("Loading '{0}'...", module.Item1.Path);

                MarkModule(module.Item2, module == modules[0]);

                // Packer parameters are stored in modules
                if (packer != null)
                    ProtectionParameters.GetParameters(context, module.Item2)[packer] = packerParams;
            }
            return new MarkerResult(modules.Select(module => module.Item2).ToList(), packer, extModules);
        }
コード例 #18
0
ファイル: Packer.cs プロジェクト: EmilZhou/ConfuserEx
		/// <summary>
		///     Protects the stub using original project settings replace the current output with the protected stub.
		/// </summary>
		/// <param name="context">The working context.</param>
		/// <param name="fileName">The result file name.</param>
		/// <param name="module">The stub module.</param>
		/// <param name="snKey">The strong name key.</param>
		/// <param name="prot">The packer protection that applies to the stub.</param>
		protected void ProtectStub(ConfuserContext context, string fileName, byte[] module, StrongNameKey snKey, Protection prot = null) {
			string tmpDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
			string outDir = Path.Combine(tmpDir, Path.GetRandomFileName());
			Directory.CreateDirectory(tmpDir);

			for (int i = 0; i < context.OutputModules.Count; i++) {
				string path = Path.GetFullPath(Path.Combine(tmpDir, context.OutputPaths[i]));
				var dir = Path.GetDirectoryName(path);
				if (!Directory.Exists(dir))
					Directory.CreateDirectory(dir);
				File.WriteAllBytes(path, context.OutputModules[i]);
			}
			File.WriteAllBytes(Path.Combine(tmpDir, fileName), module);

			var proj = new ConfuserProject();
			proj.Seed = context.Project.Seed;
			foreach (Rule rule in context.Project.Rules)
				proj.Rules.Add(rule);
			proj.Add(new ProjectModule {
				Path = fileName
			});
			proj.BaseDirectory = tmpDir;
			proj.OutputDirectory = outDir;
			foreach (var path in context.Project.ProbePaths)
				proj.ProbePaths.Add(path);
			proj.ProbePaths.Add(context.Project.BaseDirectory);

			PluginDiscovery discovery = null;
			if (prot != null) {
				var rule = new Rule {
					Preset = ProtectionPreset.None,
					Inherit = true,
					Pattern = "true"
				};
				rule.Add(new SettingItem<Protection> {
					Id = prot.Id,
					Action = SettingItemAction.Add
				});
				proj.Rules.Add(rule);
				discovery = new PackerDiscovery(prot);
			}

			try {
				ConfuserEngine.Run(new ConfuserParameters {
					Logger = new PackerLogger(context.Logger),
					PluginDiscovery = discovery,
					Marker = new PackerMarker(snKey),
					Project = proj,
					PackerInitiated = true
				}, context.token).Wait();
			}
			catch (AggregateException ex) {
				context.Logger.Error("Failed to protect packer stub.");
				throw new ConfuserException(ex);
			}

			context.OutputModules = new[] { File.ReadAllBytes(Path.Combine(outDir, fileName)) };
			context.OutputPaths = new[] { fileName };
		}
コード例 #19
0
ファイル: CoreComponent.cs プロジェクト: EmilZhou/ConfuserEx
		/// <inheritdoc />
		protected internal override void Initialize(ConfuserContext context) {
			context.Registry.RegisterService(_RandomServiceId, typeof(IRandomService), new RandomService(parameters.Project.Seed));
			context.Registry.RegisterService(_MarkerServiceId, typeof(IMarkerService), new MarkerService(context, marker));
			context.Registry.RegisterService(_TraceServiceId, typeof(ITraceService), new TraceService(context));
			context.Registry.RegisterService(_RuntimeServiceId, typeof(IRuntimeService), new RuntimeService());
			context.Registry.RegisterService(_CompressionServiceId, typeof(ICompressionService), new CompressionService(context));
			context.Registry.RegisterService(_APIStoreId, typeof(IAPIStore), new APIStore(context));
		}
コード例 #20
0
		public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) {
			var method = def as MethodDef;
			if (method == null || !method.HasBody)
				return;

			// When a ldtoken instruction reference a definition,
			// most likely it would be used in reflection and thus probably should not be renamed.
			// Also, when ToString is invoked on enum,
			// the enum should not be renamed.
			for (int i = 0; i < method.Body.Instructions.Count; i++) {
				Instruction instr = method.Body.Instructions[i];
				if (instr.OpCode.Code == Code.Ldtoken) {
					if (instr.Operand is MemberRef) {
						IMemberForwarded member = ((MemberRef)instr.Operand).ResolveThrow();
						if (context.Modules.Contains((ModuleDefMD)member.Module))
							service.SetCanRename(member, false);
					}
					else if (instr.Operand is IField) {
						FieldDef field = ((IField)instr.Operand).ResolveThrow();
						if (context.Modules.Contains((ModuleDefMD)field.Module))
							service.SetCanRename(field, false);
					}
					else if (instr.Operand is IMethod) {
						var im = (IMethod)instr.Operand;
						if (!im.IsArrayAccessors()) {
							MethodDef m = im.ResolveThrow();
							if (context.Modules.Contains((ModuleDefMD)m.Module))
								service.SetCanRename(method, false);
						}
					}
					else if (instr.Operand is ITypeDefOrRef) {
						if (!(instr.Operand is TypeSpec)) {
							TypeDef type = ((ITypeDefOrRef)instr.Operand).ResolveTypeDefThrow();
							if (context.Modules.Contains((ModuleDefMD)type.Module) &&
							    HandleTypeOf(context, service, method, i)) {
								var t = type;
								do {
									DisableRename(service, t, false);
									t = t.DeclaringType;
								} while (t != null);
							}
						}
					}
					else
						throw new UnreachableException();
				}
				else if ((instr.OpCode.Code == Code.Call || instr.OpCode.Code == Code.Callvirt) &&
				         ((IMethod)instr.Operand).Name == "ToString") {
					HandleEnum(context, service, method, i);
				}
				else if (instr.OpCode.Code == Code.Ldstr) {
					TypeDef typeDef = method.Module.FindReflection((string)instr.Operand);
					if (typeDef != null)
						service.AddReference(typeDef, new StringTypeReference(instr, typeDef));
				}
			}
		}
コード例 #21
0
			protected override void Execute(ConfuserContext context, ProtectionParameters parameters) {
				foreach (ModuleDef module in parameters.Targets.OfType<ModuleDef>()) {
					TypeRef attrRef = module.CorLibTypes.GetTypeRef("System.Runtime.CompilerServices", "SuppressIldasmAttribute");
					var ctorRef = new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), attrRef);

					var attr = new CustomAttribute(ctorRef);
					module.CustomAttributes.Add(attr);
				}
			}
コード例 #22
0
		protected override void Execute(ConfuserContext context, ProtectionParameters parameters) {
			var service = (NameService)context.Registry.GetService<INameService>();

			foreach (IRenamer renamer in service.Renamers) {
				foreach (IDnlibDef def in parameters.Targets)
					renamer.PostRename(context, service, parameters, def);
				context.CheckCancellation();
			}
		}
コード例 #23
0
ファイル: RenamePhase.cs プロジェクト: 89sos98/ConfuserEx
        protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
        {
            var service = (NameService)context.Registry.GetService<INameService>();

            context.Logger.Debug("Renaming...");
            foreach (IRenamer renamer in service.Renamers) {
                foreach (IDnlibDef def in parameters.Targets)
                    renamer.PreRename(context, service, def);
                context.CheckCancellation();
            }

            foreach (IDnlibDef def in parameters.Targets.WithProgress(context.Logger)) {
                bool canRename = service.CanRename(def);
                if (def is MethodDef)
                    if (canRename && parameters.GetParameter(context, def, "renameArgs", true)) {
                        foreach (ParamDef param in ((MethodDef)def).ParamDefs)
                            param.Name = null;
                    }

                if (!canRename)
                    continue;

                RenameMode mode = service.GetRenameMode(def);

                IList<INameReference> references = service.GetReferences(def);
                bool cancel = false;
                foreach (INameReference refer in references) {
                    cancel |= refer.ShouldCancelRename();
                    if (cancel) break;
                }
                if (cancel)
                    continue;

                if (def is TypeDef) {
                    var typeDef = (TypeDef)def;
                    if (parameters.GetParameter(context, def, "flatten", true)) {
                        typeDef.Name = service.ObfuscateName(typeDef.FullName, mode);
                        typeDef.Namespace = "";
                    }
                    else {
                        typeDef.Namespace = service.ObfuscateName(typeDef.Namespace, mode);
                        typeDef.Name = service.ObfuscateName(typeDef.Name, mode);
                    }
                }
                else
                    def.Name = service.ObfuscateName(def.Name, mode);

                foreach (INameReference refer in references.ToList()) {
                    if (!refer.UpdateNameReference(context, service)) {
                        context.Logger.ErrorFormat("Failed to update name reference on '{0}'.", def);
                        throw new ConfuserException(null);
                    }
                }
                context.CheckCancellation();
            }
        }
コード例 #24
0
		protected override void Execute(ConfuserContext context, ProtectionParameters parameters) {
			bool disabledOpti = DisabledOptimization(context.CurrentModule);
			RandomGenerator random = context.Registry.GetService<IRandomService>().GetRandomGenerator(ControlFlowProtection._FullId);

			foreach (MethodDef method in parameters.Targets.OfType<MethodDef>().WithProgress(context.Logger))
				if (method.HasBody && method.Body.Instructions.Count > 0) {
					ProcessMethod(method.Body, ParseParameters(method, context, parameters, random, disabledOpti));
					context.CheckCancellation();
				}
		}
コード例 #25
0
ファイル: JsonAnalyzer.cs プロジェクト: RSchwoerer/ConfuserEx
 public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def)
 {
     if (def is TypeDef)
         Analyze(context, service, (TypeDef)def, parameters);
     else if (def is MethodDef)
         Analyze(context, service, (MethodDef)def, parameters);
     else if (def is PropertyDef)
         Analyze(context, service, (PropertyDef)def, parameters);
     else if (def is FieldDef)
         Analyze(context, service, (FieldDef)def, parameters);
 }
コード例 #26
0
ファイル: DynamicDeriver.cs プロジェクト: EmilZhou/ConfuserEx
		public void Init(ConfuserContext ctx, RandomGenerator random) {
			StatementBlock dummy;
			ctx.Registry.GetService<IDynCipherService>().GenerateCipherPair(random, out derivation, out dummy);

			var dmCodeGen = new DMCodeGen(typeof(void), new[] {
				Tuple.Create("{BUFFER}", typeof(uint[])),
				Tuple.Create("{KEY}", typeof(uint[]))
			});
			dmCodeGen.GenerateCIL(derivation);
			encryptFunc = dmCodeGen.Compile<Action<uint[], uint[]>>();
		}
コード例 #27
0
ファイル: KnownThingsv3.cs プロジェクト: EmilZhou/ConfuserEx
		public KnownThingsv3(ConfuserContext context, ModuleDefMD initMod) {
			this.context = context;

			assemblies = new Dictionary<int, AssemblyDef>();
			types = new Dictionary<KnownTypes, TypeDef>();
			properties = new Dictionary<KnownProperties, Tuple<KnownTypes, PropertyDef, TypeDef>>();

			InitAssemblies(initMod);
			InitTypes();
			InitProperties();
		}
コード例 #28
0
        public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def)
        {
            var module = def as ModuleDef;
            if (module == null) return;

            string asmName = module.Assembly.Name.String;
            if (!string.IsNullOrEmpty(module.Assembly.Culture) &&
                asmName.EndsWith(".resources")) {
                // Satellite assembly
                var satellitePattern = new Regex(string.Format("^(.*)\\.{0}\\.resources$", module.Assembly.Culture));
                string nameAsmName = asmName.Substring(0, asmName.Length - ".resources".Length);
                ModuleDef mainModule = context.Modules.SingleOrDefault(mod => mod.Assembly.Name == nameAsmName);
                if (mainModule == null) {
                    context.Logger.ErrorFormat("Could not find main assembly of satellite assembly '{0}'.", module.Assembly.FullName);
                    throw new ConfuserException(null);
                }

                string format = "{0}." + module.Assembly.Culture + ".resources";
                foreach (Resource res in module.Resources) {
                    Match match = satellitePattern.Match(res.Name);
                    if (!match.Success)
                        continue;
                    string typeName = match.Groups[1].Value;
                    TypeDef type = mainModule.FindReflectionThrow(typeName);
                    if (type == null) {
                        context.Logger.WarnFormat("Could not find resource type '{0}'.", typeName);
                        continue;
                    }
                    service.ReduceRenameMode(type, RenameMode.ASCII);
                    service.AddReference(type, new ResourceReference(res, type, format));
                }
            }
            else {
                string format = "{0}.resources";
                foreach (Resource res in module.Resources) {
                    Match match = ResourceNamePattern.Match(res.Name);
                    if (!match.Success)
                        continue;
                    string typeName = match.Groups[1].Value;

                    if (typeName.EndsWith(".g")) // WPF resources, ignore
                        continue;

                    TypeDef type = module.FindReflection(typeName);
                    if (type == null) {
                        context.Logger.WarnFormat("Could not find resource type '{0}'.", typeName);
                        continue;
                    }
                    service.ReduceRenameMode(type, RenameMode.ASCII);
                    service.AddReference(type, new ResourceReference(res, type, format));
                }
            }
        }
コード例 #29
0
ファイル: InjectPhase.cs プロジェクト: GavinHwa/ConfuserEx
        protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
        {
            if (parameters.Targets.Any()) {
                var compression = context.Registry.GetService<ICompressionService>();
                var name = context.Registry.GetService<INameService>();
                var marker = context.Registry.GetService<IMarkerService>();
                var rt = context.Registry.GetService<IRuntimeService>();
                var moduleCtx = new CEContext {
                    Random = context.Registry.GetService<IRandomService>().GetRandomGenerator(Parent.Id),
                    Context = context,
                    Module = context.CurrentModule,
                    Marker = marker,
                    DynCipher = context.Registry.GetService<IDynCipherService>(),
                    Name = name
                };

                // Extract parameters
                moduleCtx.Mode = parameters.GetParameter(context, context.CurrentModule, "mode", Mode.Normal);
                moduleCtx.DecoderCount = parameters.GetParameter(context, context.CurrentModule, "decoderCount", 5);

                switch (moduleCtx.Mode) {
                    case Mode.Normal:
                        moduleCtx.ModeHandler = new NormalMode();
                        break;
                    case Mode.Dynamic:
                        moduleCtx.ModeHandler = new DynamicMode();
                        break;
                    case Mode.x86:
                        moduleCtx.ModeHandler = new x86Mode();
                        if ((context.CurrentModule.Cor20HeaderFlags & ComImageFlags.ILOnly) != 0)
                            context.CurrentModuleWriterOptions.Cor20HeaderOptions.Flags &= ~ComImageFlags.ILOnly;
                        break;
                    default:
                        throw new UnreachableException();
                }

                // Inject helpers
                MethodDef decomp = compression.GetRuntimeDecompressor(context.CurrentModule, member => {
                    name.MarkHelper(member, marker);
                    if (member is MethodDef)
                        ProtectionParameters.GetParameters(context, member).Remove(Parent);
                });
                InjectHelpers(context, compression, rt, moduleCtx);

                // Mutate codes
                MutateInitializer(moduleCtx, decomp);

                MethodDef cctor = context.CurrentModule.GlobalType.FindStaticConstructor();
                cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, moduleCtx.InitMethod));

                context.Annotations.Set(context.CurrentModule, ConstantProtection.ContextKey, moduleCtx);
            }
        }
コード例 #30
0
ファイル: WPFAnalyzer.cs プロジェクト: EmilZhou/ConfuserEx
		public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) {
			var method = def as MethodDef;
			if (method != null) {
				if (!method.HasBody)
					return;
				AnalyzeMethod(context, service, method);
			}

			var module = def as ModuleDefMD;
			if (module != null) {
				AnalyzeResources(context, service, module);
			}
		}
コード例 #31
0
        static void Inspection(ConfuserContext context)
        {
            context.Logger.Info("Resolving dependencies...");
            foreach (var dependency in context.Modules
                     .SelectMany(module => module.GetAssemblyRefs().Select(asmRef => Tuple.Create(asmRef, module))))
            {
                try {
                    var assembly = context.Resolver.ResolveThrow(dependency.Item1, dependency.Item2);
                }
                catch (AssemblyResolveException ex) {
                    context.Logger.ErrorException("Failed to resolve dependency of '" + dependency.Item2.Name + "'.", ex);
                    throw new ConfuserException(ex);
                }
            }

            context.Logger.Debug("Checking Strong Name...");
            foreach (var module in context.Modules)
            {
                var snKey = context.Annotations.Get <StrongNameKey>(module, Marker.SNKey);
                if (snKey == null && module.IsStrongNameSigned)
                {
                    context.Logger.WarnFormat("[{0}] SN Key is not provided for a signed module, the output may not be working.", module.Name);
                }
                else if (snKey != null && !module.IsStrongNameSigned)
                {
                    context.Logger.WarnFormat("[{0}] SN Key is provided for an unsigned module, the output may not be working.", module.Name);
                }
                else if (snKey != null && module.IsStrongNameSigned &&
                         !module.Assembly.PublicKey.Data.SequenceEqual(snKey.PublicKey))
                {
                    context.Logger.WarnFormat("[{0}] Provided SN Key and signed module's public key do not match, the output may not be working.", module.Name);
                }
            }

            var marker = context.Registry.GetService <IMarkerService>();

            context.Logger.Debug("Creating global .cctors...");
            foreach (var module in context.Modules)
            {
                var modType = module.GlobalType;
                if (modType == null)
                {
                    modType = new TypeDefUser("", "<Module>", null)
                    {
                        Attributes = TypeAttributes.AnsiClass
                    };
                    module.Types.Add(modType);
                    marker.Mark(modType, null);
                }
                var cctor = modType.FindOrCreateStaticConstructor();
                if (!marker.IsMarked(cctor))
                {
                    marker.Mark(cctor, null);
                }
            }

            context.Logger.Debug("Watermarking...");
            foreach (var module in context.Modules)
            {
                var attrRef  = module.CorLibTypes.GetTypeRef("System", "Attribute");
                var attrType = new TypeDefUser("", "ConfusedByAttribute", attrRef);
                module.Types.Add(attrType);
                marker.Mark(attrType, null);

                var ctor = new MethodDefUser(
                    ".ctor",
                    MethodSig.CreateInstance(module.CorLibTypes.Void, module.CorLibTypes.String),
                    MethodImplAttributes.Managed,
                    MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName)
                {
                    Body = new CilBody
                    {
                        MaxStack = 1
                    }
                };
                ctor.Body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
                ctor.Body.Instructions.Add(OpCodes.Call.ToInstruction(new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), attrRef)));
                ctor.Body.Instructions.Add(OpCodes.Ret.ToInstruction());
                attrType.Methods.Add(ctor);
                marker.Mark(ctor, null);

                var attr = new CustomAttribute(ctor);
                attr.ConstructorArguments.Add(new CAArgument(module.CorLibTypes.String, Version));

                module.CustomAttributes.Add(attr);
            }
        }
コード例 #32
0
 // Token: 0x060001FB RID: 507 RVA: 0x0000FCCB File Offset: 0x0000DECB
 protected override void GetPluginsInternal(ConfuserContext context, IList <Protection> protections, IList <Packer> packers, IList <ConfuserComponent> components)
 {
     base.GetPluginsInternal(context, protections, packers, components);
     protections.Add(this.prot);
 }
コード例 #33
0
 /// <summary>
 ///     Execute the specified pipeline stage with pre-processing and post-processing.
 /// </summary>
 /// <param name="stage">The pipeline stage.</param>
 /// <param name="func">The stage function.</param>
 /// <param name="targets">The target list of the stage.</param>
 /// <param name="context">The working context.</param>
 internal void ExecuteStage(PipelineStage stage, Action <ConfuserContext> func, Func <IList <IDnlibDef> > targets, ConfuserContext context)
 {
     foreach (ProtectionPhase pre in preStage[stage])
     {
         context.CheckCancellation();
         context.Logger.DebugFormat("执行 '{0}' ...", pre.Name);
         pre.Execute(context, new ProtectionParameters(pre.Parent, Filter(context, targets(), pre)));
     }
     context.CheckCancellation();
     func(context);
     context.CheckCancellation();
     foreach (ProtectionPhase post in postStage[stage])
     {
         context.Logger.DebugFormat("执行 '{0}' ...", post.Name);
         post.Execute(context, new ProtectionParameters(post.Parent, Filter(context, targets(), post)));
         context.CheckCancellation();
     }
 }
コード例 #34
0
ファイル: ObfAttrMarker.cs プロジェクト: vebin/ConfuserEx
        /// <inheritdoc />
        protected internal override void MarkMember(IDnlibDef member, ConfuserContext context)
        {
            ModuleDef module = ((IMemberRef)member).Module;

            ProtectionParameters.SetParameters(context, member, ProtectionParameters.GetParameters(context, module));
        }
コード例 #35
0
        /// <summary>
        ///     Loads the assembly and marks the project.
        /// </summary>
        /// <param name="proj">The project.</param>
        /// <param name="context">The working context.</param>
        /// <returns><see cref="MarkerResult" /> storing the marked modules and packer information.</returns>
        protected internal virtual MarkerResult MarkProject(ConfuserProject proj, ConfuserContext context)
        {
            Packer packer = null;
            Dictionary <string, string> packerParams = null;

            if (proj.Packer != null)
            {
                if (!packers.ContainsKey(proj.Packer.Id))
                {
                    context.Logger.ErrorFormat("Cannot find packer with ID '{0}'.", proj.Packer.Id);
                    throw new ConfuserException(null);
                }
                if (proj.Debug)
                {
                    context.Logger.Warn("Generated Debug symbols might not be usable with packers!");
                }

                packer       = packers[proj.Packer.Id];
                packerParams = new Dictionary <string, string>(proj.Packer, StringComparer.OrdinalIgnoreCase);
            }

            var modules    = new List <Tuple <ProjectModule, ModuleDefMD> >();
            var extModules = new List <byte[]>();

            foreach (ProjectModule module in proj)
            {
                if (module.IsExternal)
                {
                    extModules.Add(module.LoadRaw(proj.BaseDirectory));
                    continue;
                }

                ModuleDefMD modDef = module.Resolve(proj.BaseDirectory, context.Resolver.DefaultModuleContext);
                context.CheckCancellation();

                if (proj.Debug)
                {
                    modDef.LoadPdb();
                }

                context.Resolver.AddToCache(modDef);
                modules.Add(Tuple.Create(module, modDef));
            }

            foreach (var module in modules)
            {
                context.Logger.InfoFormat("Loading '{0}'...", module.Item1.Path);
                Rules rules = ParseRules(proj, module.Item1, context);

                context.Annotations.Set(module.Item2, SNKey, LoadSNKey(context, module.Item1.SNKeyPath == null ? null : Path.Combine(proj.BaseDirectory, module.Item1.SNKeyPath), module.Item1.SNKeyPassword));
                context.Annotations.Set(module.Item2, RulesKey, rules);

                foreach (IDnlibDef def in module.Item2.FindDefinitions())
                {
                    ApplyRules(context, def, rules);
                    context.CheckCancellation();
                }

                // Packer parameters are stored in modules
                if (packerParams != null)
                {
                    ProtectionParameters.GetParameters(context, module.Item2)[packer] = packerParams;
                }
            }
            return(new MarkerResult(modules.Select(module => module.Item2).ToList(), packer, extModules));
        }
コード例 #36
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="CoreComponent" /> class.
 /// </summary>
 /// <param name="parameters">The parameters.</param>
 /// <param name="marker">The marker.</param>
 internal CoreComponent(ConfuserContext context, Marker marker)
 {
     _context    = context;
     this.marker = marker;
 }
コード例 #37
0
        /// <summary>
        ///     Protects the stub using original project settings replace the current output with the protected stub.
        /// </summary>
        /// <param name="context">The working context.</param>
        /// <param name="fileName">The result file name.</param>
        /// <param name="module">The stub module.</param>
        /// <param name="snKey">The strong name key.</param>
        /// <param name="prot">The packer protection that applies to the stub.</param>
        protected void ProtectStub(ConfuserContext context, string fileName, byte[] module, StrongNameKey snKey, Protection prot = null)
        {
            string tmpDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            try {
                string outDir = Path.Combine(tmpDir, Path.GetRandomFileName());
                Directory.CreateDirectory(tmpDir);

                for (int i = 0; i < context.OutputModules.Count; i++)
                {
                    string path = Path.GetFullPath(Path.Combine(tmpDir, context.OutputPaths[i]));
                    var    dir  = Path.GetDirectoryName(path);
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    File.WriteAllBytes(path, context.OutputModules[i]);
                }

                File.WriteAllBytes(Path.Combine(tmpDir, fileName), module);

                var proj = new ConfuserProject();
                proj.Seed = context.Project.Seed;
                foreach (Rule rule in context.Project.Rules)
                {
                    proj.Rules.Add(rule);
                }
                proj.Add(new ProjectModule {
                    Path = fileName
                });
                proj.BaseDirectory   = tmpDir;
                proj.OutputDirectory = outDir;
                foreach (var path in context.Project.ProbePaths)
                {
                    proj.ProbePaths.Add(path);
                }
                proj.ProbePaths.Add(context.Project.BaseDirectory);

                PluginDiscovery discovery = null;
                if (prot != null)
                {
                    var rule = new Rule {
                        Preset  = ProtectionPreset.None,
                        Inherit = true,
                        Pattern = "true"
                    };
                    rule.Add(new SettingItem <Protection> {
                        Id     = prot.Id,
                        Action = SettingItemAction.Add
                    });
                    proj.Rules.Add(rule);
                    discovery = new PackerDiscovery(prot);
                }

                try {
                    ConfuserEngine
                    .Run(
                        new ConfuserParameters {
                        Logger          = new PackerLogger(context.Logger),
                        PluginDiscovery = discovery,
                        Marker          = new PackerMarker(snKey),
                        Project         = proj,
                        PackerInitiated = true
                    }, context.token).Wait();
                }
                catch (AggregateException ex) {
                    context.Logger.Error("Failed to protect packer stub.");
                    throw new ConfuserException(ex);
                }

                context.OutputModules = new[] { File.ReadAllBytes(Path.Combine(outDir, fileName)) };
                context.OutputPaths   = new[] { fileName };
            }
            finally {
                try {
                    if (Directory.Exists(tmpDir))
                    {
                        Directory.Delete(tmpDir, true);
                    }
                }
                catch (IOException ex) {
                    context.Logger.WarnException("Failed to remove temporary files of packer.", ex);
                }
            }
        }
コード例 #38
0
ファイル: ConfuserEngine.cs プロジェクト: mkaring/ConfuserEx
        /// <summary>
        ///     Runs the engine.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="token">The cancellation token.</param>
        static void RunInternal(ConfuserParameters parameters, CancellationToken token)
        {
            // 1. Setup context
            var context = new ConfuserContext();

            context.Logger          = parameters.GetLogger();
            context.Project         = parameters.Project.Clone();
            context.PackerInitiated = parameters.PackerInitiated;
            context.token           = token;

            PrintInfo(context);

            bool ok = false;

            try {
                // Enable watermarking by default
                context.Project.Rules.Insert(0, new Rule {
                    new SettingItem <Protection>(WatermarkingProtection._Id)
                });

                var asmResolver = new ConfuserAssemblyResolver {
                    EnableTypeDefCache = true
                };
                asmResolver.DefaultModuleContext = new ModuleContext(asmResolver);
                context.InternalResolver         = asmResolver;
                context.BaseDirectory            = Path.Combine(Environment.CurrentDirectory, context.Project.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar);
                context.OutputDirectory          = Path.Combine(context.Project.BaseDirectory, context.Project.OutputDirectory.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar);
                foreach (string probePath in context.Project.ProbePaths)
                {
                    asmResolver.PostSearchPaths.Insert(0, Path.Combine(context.BaseDirectory, probePath));
                }

                context.CheckCancellation();

                Marker marker = parameters.GetMarker();

                // 2. Discover plugins
                context.Logger.Debug("Discovering plugins...");

                IList <Protection>        prots;
                IList <Packer>            packers;
                IList <ConfuserComponent> components;
                parameters.GetPluginDiscovery().GetPlugins(context, out prots, out packers, out components);

                context.Logger.InfoFormat("Discovered {0} protections, {1} packers.", prots.Count, packers.Count);

                context.CheckCancellation();

                // 3. Resolve dependency
                context.Logger.Debug("Resolving component dependency...");
                try {
                    var resolver = new DependencyResolver(prots);
                    prots = resolver.SortDependency();
                }
                catch (CircularDependencyException ex) {
                    context.Logger.ErrorException("", ex);
                    throw new ConfuserException(ex);
                }

                components.Insert(0, new CoreComponent(context, marker));
                foreach (Protection prot in prots)
                {
                    components.Add(prot);
                }
                foreach (Packer packer in packers)
                {
                    components.Add(packer);
                }

                context.CheckCancellation();

                // 4. Load modules
                context.Logger.Info("Loading input modules...");
                marker.Initalize(prots, packers);
                MarkerResult markings = marker.MarkProject(context.Project, context);
                context.Modules = new ModuleSorter(markings.Modules).Sort().ToList().AsReadOnly();
                foreach (var module in context.Modules)
                {
                    module.EnableTypeDefFindCache = false;
                }
                context.OutputModules   = Enumerable.Repeat <byte[]>(null, context.Modules.Count).ToArray();
                context.OutputSymbols   = Enumerable.Repeat <byte[]>(null, context.Modules.Count).ToArray();
                context.OutputPaths     = Enumerable.Repeat <string>(null, context.Modules.Count).ToArray();
                context.Packer          = markings.Packer;
                context.ExternalModules = markings.ExternalModules;

                context.CheckCancellation();

                // 5. Initialize components
                context.Logger.Info("Initializing...");
                foreach (ConfuserComponent comp in components)
                {
                    try {
                        comp.Initialize(context);
                    }
                    catch (Exception ex) {
                        context.Logger.ErrorException("Error occured during initialization of '" + comp.Name + "'.", ex);
                        throw new ConfuserException(ex);
                    }
                    context.CheckCancellation();
                }

                context.CheckCancellation();

                // 6. Build pipeline
                context.Logger.Debug("Building pipeline...");
                var pipeline = new ProtectionPipeline();
                context.Pipeline = pipeline;
                foreach (ConfuserComponent comp in components)
                {
                    comp.PopulatePipeline(pipeline);
                }

                context.CheckCancellation();

                //7. Run pipeline
                RunPipeline(pipeline, context);

                ok = true;
            }
            catch (AssemblyResolveException ex) {
                context.Logger.ErrorException("Failed to resolve an assembly, check if all dependencies are present in the correct version.", ex);
                PrintEnvironmentInfo(context);
            }
            catch (TypeResolveException ex) {
                context.Logger.ErrorException("Failed to resolve a type, check if all dependencies are present in the correct version.", ex);
                PrintEnvironmentInfo(context);
            }
            catch (MemberRefResolveException ex) {
                context.Logger.ErrorException("Failed to resolve a member, check if all dependencies are present in the correct version.", ex);
                PrintEnvironmentInfo(context);
            }
            catch (IOException ex) {
                context.Logger.ErrorException("An IO error occurred, check if all input/output locations are readable/writable.", ex);
            }
            catch (OperationCanceledException) {
                context.Logger.Error("Operation cancelled.");
            }
            catch (ConfuserException) {
                // Exception is already handled/logged, so just ignore and report failure
            }
            catch (Exception ex) {
                context.Logger.ErrorException("Unknown error occurred.", ex);
            }
            finally {
                if (context.Resolver != null)
                {
                    context.InternalResolver.Clear();
                }
                context.Logger.Finish(ok);
            }
        }
コード例 #39
0
        /// <summary>
        ///     Parses the rules' patterns.
        /// </summary>
        /// <param name="proj">The project.</param>
        /// <param name="module">The module description.</param>
        /// <param name="context">The working context.</param>
        /// <returns>Parsed rule patterns.</returns>
        /// <exception cref="T:System.ArgumentException">
        ///     One of the rules has invalid pattern.
        /// </exception>
        // Token: 0x06000195 RID: 405 RVA: 0x0000D320 File Offset: 0x0000B520
        protected Dictionary <Rule, PatternExpression> ParseRules(ConfuserProject proj, ProjectModule module, ConfuserContext context)
        {
            Dictionary <Rule, PatternExpression> ret = new Dictionary <Rule, PatternExpression>();
            PatternParser parser = new PatternParser();

            foreach (Rule rule in proj.Rules.Concat(module.Rules))
            {
                try
                {
                    ret.Add(rule, parser.Parse(rule.Pattern));
                }
                catch (InvalidPatternException ex)
                {
                    context.Logger.ErrorFormat("Invalid rule pattern: " + rule.Pattern + ".", new object[]
                    {
                        ex
                    });
                    throw new ConfuserException(ex);
                }
                foreach (SettingItem <Protection> setting in rule)
                {
                    if (!this.protections.ContainsKey(setting.Id))
                    {
                        context.Logger.ErrorFormat("Cannot find protection with ID '{0}'.", new object[]
                        {
                            setting.Id
                        });
                        throw new ConfuserException(null);
                    }
                }
            }
            return(ret);
        }
コード例 #40
0
        /// <summary>
        ///     Loads the assembly and marks the project.
        /// </summary>
        /// <param name="proj">The project.</param>
        /// <param name="context">The working context.</param>
        /// <returns><see cref="T:Confuser.Core.MarkerResult" /> storing the marked modules and packer information.</returns>
        // Token: 0x06000193 RID: 403 RVA: 0x0000CFF0 File Offset: 0x0000B1F0
        protected internal virtual MarkerResult MarkProject(ConfuserProject proj, ConfuserContext context)
        {
            Packer packer = null;
            Dictionary <string, string> packerParams = null;

            if (proj.Packer != null)
            {
                if (!this.packers.ContainsKey(proj.Packer.Id))
                {
                    context.Logger.ErrorFormat("Cannot find packer with ID '{0}'.", new object[]
                    {
                        proj.Packer.Id
                    });
                    throw new ConfuserException(null);
                }
                if (proj.Debug)
                {
                    context.Logger.Warn("Generated Debug symbols might not be usable with packers!");
                }
                packer       = this.packers[proj.Packer.Id];
                packerParams = new Dictionary <string, string>(proj.Packer, StringComparer.OrdinalIgnoreCase);
            }
            List <Tuple <ProjectModule, ModuleDefMD> > modules = new List <Tuple <ProjectModule, ModuleDefMD> >();
            List <byte[]> extModules = new List <byte[]>();

            foreach (ProjectModule module3 in proj)
            {
                if (module3.IsExternal)
                {
                    extModules.Add(module3.LoadRaw(proj.BaseDirectory));
                }
                else
                {
                    ModuleDefMD modDef = module3.Resolve(proj.BaseDirectory, context.Resolver.DefaultModuleContext);
                    context.CheckCancellation();
                    if (proj.Debug)
                    {
                        modDef.LoadPdb();
                    }
                    context.Resolver.AddToCache(modDef);
                    modules.Add(Tuple.Create <ProjectModule, ModuleDefMD>(module3, modDef));
                }
            }
            foreach (Tuple <ProjectModule, ModuleDefMD> module2 in modules)
            {
                context.Logger.InfoFormat("Loading '{0}'...", new object[]
                {
                    module2.Item1.Path
                });
                Dictionary <Rule, PatternExpression> rules = this.ParseRules(proj, module2.Item1, context);
                context.Annotations.Set <StrongNameKey>(module2.Item2, Marker.SNKey, Marker.LoadSNKey(context, (module2.Item1.SNKeyPath == null) ? null : Path.Combine(proj.BaseDirectory, module2.Item1.SNKeyPath), module2.Item1.SNKeyPassword));
                context.Annotations.Set <Dictionary <Rule, PatternExpression> >(module2.Item2, Marker.RulesKey, rules);
                foreach (IDnlibDef def in module2.Item2.FindDefinitions())
                {
                    this.ApplyRules(context, def, rules, null);
                    context.CheckCancellation();
                }
                if (packerParams != null)
                {
                    ProtectionParameters.GetParameters(context, module2.Item2)[packer] = packerParams;
                }
            }
            return(new MarkerResult((from module in modules
                                     select module.Item2).ToList <ModuleDefMD>(), packer, extModules));
        }
コード例 #41
0
        // Token: 0x0600010C RID: 268 RVA: 0x000093F8 File Offset: 0x000075F8
        private static void Inspection(ConfuserContext context)
        {
            context.Logger.Info("Resolving dependencies...");
            foreach (Tuple <AssemblyRef, ModuleDefMD> dependency in context.Modules.SelectMany((ModuleDefMD module) => from asmRef in module.GetAssemblyRefs()
                                                                                               select Tuple.Create <AssemblyRef, ModuleDefMD>(asmRef, module)))
            {
                try
                {
                    context.Resolver.ResolveThrow(dependency.Item1, dependency.Item2);
                }
                catch (AssemblyResolveException ex)
                {
                    context.Logger.ErrorException("Failed to resolve dependency of '" + dependency.Item2.Name + "'.", ex);
                    throw new ConfuserException(ex);
                }
            }
            context.Logger.Debug("Checking Strong Name...");
            foreach (ModuleDefMD module4 in context.Modules)
            {
                StrongNameKey snKey = context.Annotations.Get <StrongNameKey>(module4, Marker.SNKey, null);
                if (snKey == null && module4.IsStrongNameSigned)
                {
                    context.Logger.WarnFormat("[{0}] SN Key is not provided for a signed module, the output may not be working.", new object[]
                    {
                        module4.Name
                    });
                }
                else if (snKey != null && !module4.IsStrongNameSigned)
                {
                    context.Logger.WarnFormat("[{0}] SN Key is provided for an unsigned module, the output may not be working.", new object[]
                    {
                        module4.Name
                    });
                }
                else if (snKey != null && module4.IsStrongNameSigned && !module4.Assembly.PublicKey.Data.SequenceEqual(snKey.PublicKey))
                {
                    context.Logger.WarnFormat("[{0}] Provided SN Key and signed module's public key do not match, the output may not be working.", new object[]
                    {
                        module4.Name
                    });
                }
            }
            IMarkerService marker = context.Registry.GetService <IMarkerService>();

            context.Logger.Debug("Creating global .cctors...");
            foreach (ModuleDefMD module2 in context.Modules)
            {
                TypeDef modType = module2.GlobalType;
                if (modType == null)
                {
                    modType            = new TypeDefUser("", "<Bed>", null);
                    modType.Attributes = dnlib.DotNet.TypeAttributes.NotPublic;
                    module2.Types.Add(modType);
                    marker.Mark(modType, null);
                }
                MethodDef cctor = modType.FindOrCreateStaticConstructor();
                if (!marker.IsMarked(cctor))
                {
                    marker.Mark(cctor, null);
                }
            }
            context.Logger.Debug("Watermarking...");
            foreach (ModuleDefMD module3 in context.Modules)
            {
                TypeRef     attrRef  = module3.CorLibTypes.GetTypeRef("System", "Attribute");
                TypeDefUser attrType = new TypeDefUser("", "Beds-Protector", attrRef);
                module3.Types.Add(attrType);
                marker.Mark(attrType, null);
                TypeRef     typeRef99    = module3.CorLibTypes.GetTypeRef("System", "Attribute");
                TypeRef     typeRef6     = module3.CorLibTypes.GetTypeRef("System", "Attribute");
                TypeRef     typeRef7     = module3.CorLibTypes.GetTypeRef("System", "Attribute");
                TypeDefUser typeDefUser6 = new TypeDefUser("", "VMProtect", typeRef6);
                module3.Types.Add(typeDefUser6);
                marker.Mark(typeDefUser6, null);
                TypeDefUser typeDefUser7 = new TypeDefUser("", "Reactor", typeRef7);
                module3.Types.Add(typeDefUser7);
                marker.Mark(typeDefUser7, null);
                TypeDefUser typeDefUser = new TypeDefUser("", "de4fuckyou", typeRef99);
                module3.Types.Add(typeDefUser);
                marker.Mark(typeDefUser, null);
                TypeRef     typeRef2     = module3.CorLibTypes.GetTypeRef("System", "Attribute");
                TypeDefUser typeDefUser2 = new TypeDefUser("", "BabelObfuscatorAttribute", typeRef2);
                module3.Types.Add(typeDefUser2);
                marker.Mark(typeDefUser2, null);
                TypeRef     typeRef3     = module3.CorLibTypes.GetTypeRef("System", "Attribute");
                TypeDefUser typeDefUser3 = new TypeDefUser("", "CrytpoObfuscator", typeRef3);
                module3.Types.Add(typeDefUser3);
                marker.Mark(typeDefUser3, null);
                TypeRef     typeRef4     = module3.CorLibTypes.GetTypeRef("System", "Attribute");
                TypeDefUser typeDefUser4 = new TypeDefUser("", "OiCuntJollyGoodDayYeHavin_____________________________________________________", typeRef4);
                module3.Types.Add(typeDefUser4);
                marker.Mark(typeDefUser4, null);
                TypeRef     typeRef5     = module3.CorLibTypes.GetTypeRef("System", "Attribute");
                TypeDefUser typeDefUser5 = new TypeDefUser("", "ObfuscatedByGoliath", typeRef5);
                module3.Types.Add(typeDefUser5);
                marker.Mark(typeDefUser5, null);
                MethodDefUser ctor = new MethodDefUser(".ctor", MethodSig.CreateInstance(module3.CorLibTypes.Void, module3.CorLibTypes.String), dnlib.DotNet.MethodImplAttributes.IL, dnlib.DotNet.MethodAttributes.FamANDAssem | dnlib.DotNet.MethodAttributes.Family | dnlib.DotNet.MethodAttributes.HideBySig | dnlib.DotNet.MethodAttributes.SpecialName | dnlib.DotNet.MethodAttributes.RTSpecialName);
                ctor.Body          = new CilBody();
                ctor.Body.MaxStack = 1;
                ctor.Body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
                ctor.Body.Instructions.Add(OpCodes.Call.ToInstruction(new MemberRefUser(module3, ".ctor", MethodSig.CreateInstance(module3.CorLibTypes.Void), attrRef)));
                ctor.Body.Instructions.Add(OpCodes.Ret.ToInstruction());
                attrType.Methods.Add(ctor);
                marker.Mark(ctor, null);
                CustomAttribute attr = new CustomAttribute(ctor);
                attr.ConstructorArguments.Add(new CAArgument(module3.CorLibTypes.String, ConfuserEngine.Version));
                module3.CustomAttributes.Add(attr);
            }
        }
コード例 #42
0
 // Token: 0x0600010E RID: 270 RVA: 0x00009A4C File Offset: 0x00007C4C
 private static void ProcessModule(ConfuserContext context)
 {
 }
コード例 #43
0
        /// <summary>
        ///     Runs the engine.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="token">The cancellation token.</param>
        // Token: 0x0600010A RID: 266 RVA: 0x000088B4 File Offset: 0x00006AB4
        private static void RunInternal(ConfuserParameters parameters, CancellationToken token)
        {
            ConfuserContext context = new ConfuserContext();

            context.Logger          = parameters.GetLogger();
            context.Project         = parameters.Project;
            context.PackerInitiated = parameters.PackerInitiated;
            context.token           = token;
            ConfuserEngine.PrintInfo(context);
            bool ok = false;

            try
            {
                AssemblyResolver asmResolver = new AssemblyResolver();
                asmResolver.EnableTypeDefCache   = true;
                asmResolver.DefaultModuleContext = new ModuleContext(asmResolver);
                context.Resolver      = asmResolver;
                context.BaseDirectory = Path.Combine(Environment.CurrentDirectory, parameters.Project.BaseDirectory.TrimEnd(new char[]
                {
                    Path.DirectorySeparatorChar
                }) + Path.DirectorySeparatorChar);
                context.OutputDirectory = Path.Combine(parameters.Project.BaseDirectory, parameters.Project.OutputDirectory.TrimEnd(new char[]
                {
                    Path.DirectorySeparatorChar
                }) + Path.DirectorySeparatorChar);
                foreach (string probePath in parameters.Project.ProbePaths)
                {
                    asmResolver.PostSearchPaths.Insert(0, Path.Combine(context.BaseDirectory, probePath));
                }
                context.CheckCancellation();
                Marker marker = parameters.GetMarker();
                context.Logger.Debug("Discovering plugins...");
                IList <Protection>        prots;
                IList <Packer>            packers;
                IList <ConfuserComponent> components;
                parameters.GetPluginDiscovery().GetPlugins(context, out prots, out packers, out components);
                context.Logger.InfoFormat("Discovered {0} protections, {1} packers.", new object[]
                {
                    prots.Count,
                    packers.Count
                });
                context.CheckCancellation();
                context.Logger.Debug("Resolving component dependency...");
                try
                {
                    DependencyResolver resolver = new DependencyResolver(prots);
                    prots = resolver.SortDependency();
                }
                catch (CircularDependencyException ex)
                {
                    context.Logger.ErrorException("", ex);
                    throw new ConfuserException(ex);
                }
                components.Insert(0, new CoreComponent(parameters, marker));
                foreach (Protection prot in prots)
                {
                    components.Add(prot);
                }
                foreach (Packer packer in packers)
                {
                    components.Add(packer);
                }
                context.CheckCancellation();
                context.Logger.Info("Loading input modules...");
                marker.Initalize(prots, packers);
                MarkerResult markings = marker.MarkProject(parameters.Project, context);
                context.Modules = markings.Modules.ToList <ModuleDefMD>().AsReadOnly();
                foreach (ModuleDefMD module in context.Modules)
                {
                    module.EnableTypeDefFindCache = true;
                }
                context.OutputModules   = Enumerable.Repeat <byte[]>(null, markings.Modules.Count).ToArray <byte[]>();
                context.OutputSymbols   = Enumerable.Repeat <byte[]>(null, markings.Modules.Count).ToArray <byte[]>();
                context.OutputPaths     = Enumerable.Repeat <string>(null, markings.Modules.Count).ToArray <string>();
                context.Packer          = markings.Packer;
                context.ExternalModules = markings.ExternalModules;
                context.CheckCancellation();
                context.Logger.Info("Initializing...");
                foreach (ConfuserComponent comp in components)
                {
                    try
                    {
                        comp.Initialize(context);
                    }
                    catch (Exception ex2)
                    {
                        context.Logger.ErrorException("Error occured during initialization of '" + comp.Name + "'.", ex2);
                        throw new ConfuserException(ex2);
                    }
                    context.CheckCancellation();
                }
                context.CheckCancellation();
                context.Logger.Debug("Building pipeline...");
                ProtectionPipeline pipeline = new ProtectionPipeline();
                context.Pipeline = pipeline;
                foreach (ConfuserComponent comp2 in components)
                {
                    comp2.PopulatePipeline(pipeline);
                }
                context.CheckCancellation();
                ConfuserEngine.RunPipeline(pipeline, context);
                ok = true;
            }
            catch (AssemblyResolveException ex3)
            {
                context.Logger.ErrorException("Failed to resolve an assembly, check if all dependencies are present in the correct version.", ex3);
                ConfuserEngine.PrintEnvironmentInfo(context);
            }
            catch (TypeResolveException ex4)
            {
                context.Logger.ErrorException("Failed to resolve a type, check if all dependencies are present in the correct version.", ex4);
                ConfuserEngine.PrintEnvironmentInfo(context);
            }
            catch (MemberRefResolveException ex5)
            {
                context.Logger.ErrorException("Failed to resolve a member, check if all dependencies are present in the correct version.", ex5);
                ConfuserEngine.PrintEnvironmentInfo(context);
            }
            catch (IOException ex6)
            {
                context.Logger.ErrorException("An IO error occurred, check if all input/output locations are readable/writable.", ex6);
            }
            catch (OperationCanceledException)
            {
                context.Logger.Error("Operation cancelled.");
            }
            catch (ConfuserException)
            {
            }
            catch (Exception ex7)
            {
                context.Logger.ErrorException("Unknown error occurred.", ex7);
            }
            finally
            {
                if (context.Resolver != null)
                {
                    context.Resolver.Clear();
                }
                context.Logger.Finish(ok);
            }
        }
コード例 #44
0
ファイル: ConfuserEngine.cs プロジェクト: mkaring/ConfuserEx
 static void ProcessModule(ConfuserContext context) =>
 context.CurrentModuleWriterOptions.WriterEvent += (sender, e) => context.CheckCancellation();
コード例 #45
0
ファイル: ConfuserComponent.cs プロジェクト: yuske/ConfuserEx
 /// <summary>
 ///     Initializes the component.
 /// </summary>
 /// <param name="context">The working context.</param>
 protected internal abstract void Initialize(ConfuserContext context);
コード例 #46
0
 /// <summary>
 ///     Sets the protection parameters of the specified target.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="target">The protection target.</param>
 /// <param name="parameters">The parameters.</param>
 // Token: 0x060002F6 RID: 758 RVA: 0x0001271E File Offset: 0x0001091E
 public static void SetParameters(ConfuserContext context, IDnlibDef target, ProtectionSettings parameters)
 {
     context.Annotations.Set <ProtectionSettings>(target, ProtectionParameters.ParametersKey, parameters);
 }
コード例 #47
0
 /// <summary>
 ///     Executes the packer.
 /// </summary>
 /// <param name="context">The working context.</param>
 /// <param name="parameters">The parameters of packer.</param>
 protected internal abstract void Pack(ConfuserContext context, ProtectionParameters parameters);
コード例 #48
0
 /// <summary>
 ///     Gets the protection parameters of the specified target.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="target">The protection target.</param>
 /// <returns>The parameters.</returns>
 // Token: 0x060002F7 RID: 759 RVA: 0x00012732 File Offset: 0x00010932
 public static ProtectionSettings GetParameters(ConfuserContext context, IDnlibDef target)
 {
     return(context.Annotations.Get <ProtectionSettings>(target, ProtectionParameters.ParametersKey, null));
 }
コード例 #49
0
ファイル: ObfAttrMarker.cs プロジェクト: nereva/ConfuserEx
 public ProtectionSettingsStack(ProtectionSettingsStack copy)
 {
     context = copy.context;
     stack   = new Stack <Tuple <ProtectionSettings, ProtectionSettingsInfo[]> >(copy.stack);
     parser  = copy.parser;
 }
コード例 #50
0
ファイル: ObfAttrMarker.cs プロジェクト: nereva/ConfuserEx
 public ProtectionSettingsStack(ConfuserContext context, Dictionary <string, Protection> protections)
 {
     this.context = context;
     stack        = new Stack <Tuple <ProtectionSettings, ProtectionSettingsInfo[]> >();
     parser       = new ObfAttrParser(protections);
 }