예제 #1
0
 private void EditParameterForm_Load(object sender, EventArgs e)
 {
     ItemName.Text = SelectedParameter.Name;
     TypeSpecificationEditor.SelectedTypeReference = SelectedParameter.ParameterType;
     Attributes.Bind(CecilHelper.CloneParameterDefinition(SelectedParameter, MethodDefinition));
     ConstantEditor.ReadStateFrom(SelectedParameter);
 }
예제 #2
0
 private void ProcessStrongNames(AssemblyDefinition[] assemblies)
 {
     foreach (AssemblyDefinition asmdef in assemblies)
     {
         CecilHelper.RemoveStrongName(asmdef);
     }
 }
예제 #3
0
 private static void ProcessStrongNames(IEnumerable <AssemblyDefinition> assemblies)
 {
     foreach (var asmdef in assemblies)
     {
         CecilHelper.RemoveStrongName(asmdef);
     }
 }
        /// <summary>
        /// Load the assembly object only
        /// </summary>
        /// <param name="assemblyPath"></param>
        /// <returns></returns>
        public NetAssembly LoadAssembly(string assemblyPath)
        {
            // get the cecil assembly
            AssemblyDefinition AsmToProfile = CecilHelper.GetAssembly(assemblyPath);

            if (AsmToProfile == null)
            {
                return(null);
            }

            return(new NetAssembly(AsmToProfile)
            {
                Name = AsmToProfile.Name.Name,
                FilePath = assemblyPath,
                Version = AsmToProfile.Name.Version.ToString(),
                Culture = AsmToProfile.Name.Culture,
                PublicKey = ByteHelper.ByteToHexString(AsmToProfile.Name.PublicKey),
                PublicKeyToken = ByteHelper.ByteToHexString(AsmToProfile.Name.PublicKeyToken),
                Hash = ByteHelper.ByteToHexString(AsmToProfile.Name.Hash),
                HashAlgorithm = AsmToProfile.Name.HashAlgorithm.ToString(),
                EntryPoint = AsmToProfile.EntryPoint != null?AsmToProfile.EntryPoint.ToString() : string.Empty,
                                 Kind = AsmToProfile.Kind != null?AsmToProfile.Kind.ToString() : string.Empty
                                            //IsProgram = (AsmToProfile.EntryPoint.ToString() != string.Empty && AsmToProfile.Kind.ToString() != string.Empty)
            });
        }
예제 #5
0
        public static RequireFeatureConditional Create(BasicBlockScanner scanner, ref BasicBlock bb, ref int index)
        {
            if (bb.Instructions.Count == 1)
            {
                throw new OptimizerAssertionException();
            }
            if (index + 1 >= scanner.Body.Instructions.Count)
            {
                throw new OptimizerAssertionException();
            }

            /*
             * `void MonoLinkerSupport.RequireFeature (MonoLinkerFeature feature)`
             *
             */

            if (bb.Instructions.Count > 2)
            {
                scanner.BlockList.SplitBlockAt(ref bb, bb.Instructions.Count - 2);
            }

            var feature  = (MonoLinkerFeature)CecilHelper.GetFeatureArgument(bb.FirstInstruction);
            var instance = new RequireFeatureConditional(scanner, feature);

            bb.LinkerConditional = instance;
            bb = null;

            return(instance);
        }
예제 #6
0
파일: CodeForm.cs 프로젝트: xul8tr/Reflexil
        private MethodDefinition FindMatchingMethod()
        {
            MethodDefinition result = null;

            var asmdef = PluginFactory.GetInstance().LoadAssembly(_compiler.AssemblyLocation, false);

            // Fix for inner types, remove namespace and owner.
            var typename = (_mdefsource.DeclaringType.IsNested)
                                ? _mdefsource.DeclaringType.Name
                                : _mdefsource.DeclaringType.FullName;

            // Generic hierarchy will push all generic parameters to the final type, so fix type name
            var tag = typename.LastIndexOf(BaseLanguageHelper.GenericTypeTag, StringComparison.Ordinal);

            if (tag >= 0)
            {
                typename = string.Concat(typename.Substring(0, tag + 1), _mdefsource.DeclaringType.GenericParameters.Count);
            }

            var tdef = CecilHelper.FindMatchingType(asmdef.MainModule, typename);

            if (tdef != null)
            {
                result = CecilHelper.FindMatchingMethod(tdef, _mdefsource);
            }

            return(result);
        }
예제 #7
0
        private void Compile()
        {
            TextEditor.Document.MarkerStrategy.RemoveAll(marker => true);
            var profile = (CompilerProfile)SelVersion.SelectedItem;
            var isUnitySilverLightProfile = profile == Compiler.UnitySilverLightProfile;

            _compiler.Compile(TextEditor.Text, GetReferences(true, profile), Settings.Default.Language, profile);

            if (!_compiler.Errors.HasErrors)
            {
                MethodDefinition = FindMatchingMethod();

                if (isUnitySilverLightProfile && MethodDefinition != null)
                {
                    CecilHelper.PatchAssemblyNames(MethodDefinition.Module, Compiler.MicrosoftPublicKeyToken, Compiler.MicrosoftVersion, Compiler.UnitySilverLightPublicKeyToken, Compiler.UnitySilverLightVersion);
                }

                ButOk.Enabled = MethodDefinition != null;
                VerticalSplitContainer.Panel2Collapsed = true;
            }
            else
            {
                MethodDefinition = null;
                ButOk.Enabled    = false;
                CompilerErrorBindingSource.DataSource  = _compiler.Errors;
                VerticalSplitContainer.Panel2Collapsed = false;

                //Add error markers to the TextEditor
                foreach (CompilerError error in _compiler.Errors)
                {
                    if (error.Line <= 0)
                    {
                        continue;
                    }

                    var offset = TextEditor.Document.PositionToOffset(new TextLocation(error.Column, error.Line - 1));
                    var length = TextEditor.Document.LineSegmentCollection[error.Line - 1].Length - error.Column + 1;

                    if (length <= 0)
                    {
                        length = 1;
                    }
                    else
                    {
                        offset--;
                    }

                    var color  = (error.IsWarning) ? Color.Orange : Color.Red;
                    var marker = new TextMarker(offset, length, TextMarkerType.WaveLine, color)
                    {
                        ToolTip = error.ErrorText
                    };
                    TextEditor.Document.MarkerStrategy.AddMarker(marker);
                }
            }

            TextEditor.Refresh();

            MethodHandler.HandleItem(MethodDefinition);
        }
예제 #8
0
        /// <summary>
        ///     Redirects a constructor.
        /// </summary>
        /// <param name="cecilContext">
        ///     The <see cref="CecilContext" />.
        /// </param>
        /// <param name="asmType">
        ///     The type whose constructor to redirect
        /// </param>
        protected override void RedirectConstructorInMethod(CecilContext cecilContext, Type asmType)
        {
            var attributes =
                asmType.GetCustomAttributes(typeof(HookRedirectConstructorFromBaseAttribute), false)
                .ToList()
                .Cast <HookRedirectConstructorFromBaseAttribute>();

            foreach (var attribute in attributes)
            {
                if (attribute.GenericArguments != null && attribute.GenericArguments.Any())
                {
                    CecilHelper.RedirectConstructorFromBase(
                        cecilContext,
                        asmType,
                        attribute.GenericArguments,
                        attribute.Type,
                        attribute.Method,
                        attribute.Parameters);
                }
                else
                {
                    CecilHelper.RedirectConstructorFromBase(
                        cecilContext,
                        asmType,
                        attribute.Type,
                        attribute.Method,
                        attribute.Parameters);
                }
            }
        }
예제 #9
0
        protected void HookApiVirtualAlterations <T>(CecilContext cecilContext)
        {
            try
            {
                var types = FarmhandAssemblies.SelectMany(a => a.GetTypesWithCustomAttribute(typeof(T).FullName)).ToArray();

                foreach (var asmType in types)
                {
                    try
                    {
                        if (asmType.BaseType != null)
                        {
                            CecilHelper.SetVirtualOnBaseMethods(cecilContext, asmType.BaseType.FullName ?? asmType.BaseType.Namespace + "." + asmType.BaseType.Name);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Error setting protections for {asmType.FullName}: \n\t{ex.Message}");
                    }
                }
            }
            catch (System.Reflection.ReflectionTypeLoadException ex)
            {
                Console.WriteLine($"Error setting method/field protections: \n\t{ex.Message}\n\t\t{ex.LoaderExceptions[0].Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error setting method/field protections: \n\t{ex.Message}");
            }
        }
예제 #10
0
 private static void ProcessReferences(AssemblyDefinition current, AssemblyDefinition other)
 {
     foreach (var anref in from moddef in current.Modules from anref in moddef.AssemblyReferences where CecilHelper.ReferenceMatches(anref, other.Name) select anref)
     {
         CecilHelper.RemoveStrongNameReference(anref);
     }
 }
예제 #11
0
        // Functionality methods

        private void TestMet1()
        {
            if (structureViever.SelectedNode == null)
            {
                return;
            }
            TypeDefinition TypDef = structureViever.SelectedNode.Tag as TypeDefinition;

            if (TypDef == null)
            {
                return;
            }

            string     test = @"using System.Windows.Forms;
							namespace DefNamSp
							{
							  public class DefClass
							  {
								public void DefFunc()
								{
									MessageBox.Show(""Message Successfuly Injected"");
								}
							  }
							}"                            ;
            CSCompiler csc  = new CSCompiler(dataStruct.AssemblyDefinition);

            csc.Code = test;
            MethodDefinition md = csc.GetMethodDefinition(string.Empty, string.Empty);

            if (md == null)
            {
                return;
            }
            TypeDefinition tdret = (TypeDefinition)dataStruct.ILNodeManager.FindMemberByPath("-.System.Void");

            if (tdret == null)
            {
                return;
            }
            MethodDefinition md2 = new MethodDefinition("blub", MethodAttributes.Public, tdret);

            TypDef.Methods.Add(md2);

            CecilHelper.CloneMethodBody(md, md2);

            using (SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Title = "Save to :",
                Filter = "Executables | *.exe;*.dll"
            })
            {
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    dataStruct.AssemblyDefinition.MainModule.Runtime = TargetRuntime.Net_4_0;
                    dataStruct.AssemblyDefinition.Write(saveFileDialog.FileName);
                    MessageBox.Show("Message Successfuly Injected");
                }
            }
        }
        //public override bool IsMatchedAssembly(string path, object assembly)
        //{
        //    Reflector.CodeModel.IAssembly a = (Reflector.CodeModel.IAssembly)assembly;
        //    return a.Location.Equals(path, StringComparison.OrdinalIgnoreCase);
        //}

        public override void btnLoad_Clicked(AssemblyDefinition currentAssembly, string loadedFile)
        {
            if (currentAssembly != null)
            {
                CecilHelper.RemoveAssemblyCache(currentAssembly);
            }
            _form.ReflectorLoadedFile.Text = loadedFile;
        }
 private NetMethod AddMethod(MethodType typ, MethodDefinition constructorType)
 {
     return(new NetMethod(typ, constructorType)
     {
         Name = constructorType.Name,
         NameSpace = CecilHelper.GetMethodParamSignature(constructorType)
     });
 }
예제 #14
0
        public override void Process(ConfusionParameter parameter)
        {
            IMemberDefinition mem = parameter.Target as IMemberDefinition;

            if (GetCancel(mem))
            {
                return;
            }

            if (mem is TypeDefinition)
            {
                TypeDefinition type = mem as TypeDefinition;
                if (GetRenOk(type))
                {
                    string originalName  = type.Name;
                    string originalFName = TypeParser.ToParseable(type);
                    var    mode          = (NameMode)(mem.Module as IAnnotationProvider).Annotations[NameAnalyzer.RenMode];
                    type.Name = ObfuscationHelper.GetNewName(originalFName, mode);
                    switch (mode)
                    {
                    case NameMode.Unreadable:
                        type.Namespace = ""; break;

                    case NameMode.ASCII:
                        type.Namespace = " "; break;

                    case NameMode.Letters:
                        type.Namespace = "BANANA"; break;
                    }
                    Identifier id = (Identifier)(type as IAnnotationProvider).Annotations[NameAnalyzer.RenId];
                    Identifier n  = id;
                    n.name  = CecilHelper.GetName(type);
                    n.scope = CecilHelper.GetNamespace(type);
                    foreach (IReference refer in (type as IAnnotationProvider).Annotations[NameAnalyzer.RenRef] as List <IReference> )
                    {
                        refer.UpdateReference(id, n);
                    }
                    Database.AddEntry("Rename", originalName, type.Name);
                }
            }
            else if (mem is MethodDefinition)
            {
                MethodDefinition mtd = mem as MethodDefinition;
                PerformMethod(mtd);
            }
            else if (GetRenOk(mem as IAnnotationProvider))
            {
                mem.Name = ObfuscationHelper.GetNewName(mem.Name, (NameMode)(mem.Module as IAnnotationProvider).Annotations[NameAnalyzer.RenMode]);
                Identifier id = (Identifier)(mem as IAnnotationProvider).Annotations[NameAnalyzer.RenId];
                Identifier n  = id;
                n.scope = mem.DeclaringType.FullName;
                n.name  = mem.Name;
                foreach (IReference refer in (mem as IAnnotationProvider).Annotations[NameAnalyzer.RenRef] as List <IReference> )
                {
                    refer.UpdateReference(id, n);
                }
            }
        }
예제 #15
0
            public override void DeInitialize()
            {
                _Context txt = cc.txts[mod];

                TypeDefinition     modType = mod.GetType("<Module>");
                AssemblyDefinition i       = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location);

                i.MainModule.ReadSymbols();
                txt.proxy = i.MainModule.GetType("Proxies").Methods.FirstOrDefault(mtd => mtd.Name == "CtorProxy");
                txt.proxy = CecilHelper.Inject(mod, txt.proxy);
                modType.Methods.Add(txt.proxy);
                txt.proxy.IsAssembly = true;
                txt.proxy.Name       = ObfuscationHelper.GetRandomName();
                AddHelper(txt.proxy, 0);
                Database.AddEntry("CtorProxy", "Proxy", txt.proxy.FullName);

                Instruction placeholder = null;

                txt.key = (uint)Random.Next();
                Database.AddEntry("CtorProxy", "Key", txt.key);
                Mutator mutator = new Mutator();

                mutator.Mutate(Random, txt.proxy.Body);
                placeholder = mutator.Placeholder;
                if (txt.isNative)
                {
                    txt.nativeDecr = new MethodDefinition(
                        ObfuscationHelper.GetRandomName(),
                        MethodAttributes.Abstract | MethodAttributes.CompilerControlled |
                        MethodAttributes.ReuseSlot | MethodAttributes.Static,
                        mod.TypeSystem.Int32);
                    txt.nativeDecr.ImplAttributes = MethodImplAttributes.Native;
                    txt.nativeDecr.Parameters.Add(new ParameterDefinition(mod.TypeSystem.Int32));
                    modType.Methods.Add(txt.nativeDecr);
                    Database.AddEntry("CtorProxy", "NativeDecr", txt.nativeDecr.FullName);
                    do
                    {
                        txt.exp    = new ExpressionGenerator(Random.Next()).Generate(6);
                        txt.invExp = ExpressionInverser.InverseExpression(txt.exp);
                    } while ((txt.visitor = new x86Visitor(txt.invExp, null)).RegisterOverflowed);

                    Database.AddEntry("CtorProxy", "Exp", txt.exp);
                    Database.AddEntry("CtorProxy", "InvExp", txt.invExp);

                    CecilHelper.Replace(txt.proxy.Body, placeholder, new Instruction[]
                    {
                        Instruction.Create(OpCodes.Call, txt.nativeDecr)
                    });
                }
                else
                {
                    CecilHelper.Replace(txt.proxy.Body, placeholder, new Instruction[]
                    {
                        Instruction.Create(OpCodes.Ldc_I4, (int)txt.key),
                        Instruction.Create(OpCodes.Xor)
                    });
                }
            }
예제 #16
0
        public static IsWeakInstanceOfConditional Create(BasicBlockScanner scanner, ref BasicBlock bb, ref int index, TypeDefinition type)
        {
            if (bb.Instructions.Count == 1)
            {
                throw new OptimizerAssertionException();
            }
            if (index + 1 >= scanner.Body.Instructions.Count)
            {
                throw new OptimizerAssertionException();
            }

            /*
             * `bool MonoLinkerSupport.IsWeakInstance<T> (object instance)`
             *
             * If the function argument is a simple load (like for instance `Ldarg_0`),
             * then we can simply remove that load.  Otherwise, we need to insert a
             * `Pop` to discard the value on the stack.
             *
             * In either case, we always start a new basic block for the conditional.
             * Its first instruction will either be the simple load or the call itself.
             */

            var argument = scanner.Body.Instructions [index - 1];

            scanner.LogDebug(1, $"WEAK INSTANCE OF: {bb} {index} {type} - {argument}");

            bool           hasLoad;
            TypeDefinition instanceType;

            if (CecilHelper.IsSimpleLoad(argument))
            {
                if (bb.Instructions.Count > 2)
                {
                    scanner.BlockList.SplitBlockAt(ref bb, bb.Instructions.Count - 2);
                }
                instanceType = CecilHelper.GetWeakInstanceArgument(bb.Instructions [1]);
                hasLoad      = true;
            }
            else
            {
                scanner.BlockList.SplitBlockAt(ref bb, bb.Instructions.Count - 1);
                instanceType = CecilHelper.GetWeakInstanceArgument(bb.Instructions [0]);
                hasLoad      = false;
            }

            var instance = new IsWeakInstanceOfConditional(scanner, instanceType, hasLoad);

            bb.LinkerConditional = instance;

            /*
             * Once we get here, the current block only contains the (optional) simple load
             * and the conditional call itself.
             */

            LookAheadAfterConditional(scanner.BlockList, ref bb, ref index);

            return(instance);
        }
예제 #17
0
        protected override void RedirectConstructorInMethod(CecilContext cecilContext, Type asmType)
        {
            var attributes = asmType.GetCustomAttributes(typeof(HookRedirectConstructorFromBaseAttribute), false).ToList().Cast <HookRedirectConstructorFromBaseAttribute>();

            foreach (var attribute in attributes)
            {
                CecilHelper.RedirectConstructorFromBase(cecilContext, asmType, attribute.Type, attribute.Method);
            }
        }
예제 #18
0
        public override void Initialize()
        {
            _stubAssembly = StubWorker.GenerateStub();

            _decompressor = CecilHelper.Inject(_stubAssembly.MainModule, Globals.Context.Injections["Decompressor"] as TypeDefinition);
            _loader       = CecilHelper.Inject(_stubAssembly.MainModule, Globals.Context.Injections["Loader"] as TypeDefinition);

            base.Initialize();
        }
예제 #19
0
        protected override void AlterTypeProtections(CecilContext context, Type type)
        {
            var attributeValue = type.GetCustomAttributes(typeof(HookAlterProtectionAttribute), false).First() as HookAlterProtectionAttribute;

            if (type.BaseType != null)
            {
                CecilHelper.AlterProtectionOnType(context, attributeValue != null && attributeValue.Protection == LowestProtection.Public, attributeValue.ClassName);
            }
        }
 private void Instructions_GridUpdated(object sender, EventArgs e)
 {
     if (m_mdef.Body != null)
     {
         CecilHelper.UpdateInstructionsOffsets(m_mdef.Body);
     }
     Instructions.Rehash();
     ExceptionHandlers.Rehash();
 }
        protected override void HookConstructionToMethodRedirectors(CecilContext cecilContext)
        {
            var methods = FarmhandAssemblies.SelectMany(a => a.GetTypes())
                          .SelectMany(t => t.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static))
                          .Where(m => m.GetCustomAttributes(typeof(HookRedirectConstructorToMethodAttribute), false).Any())
                          .ToArray();

            foreach (var method in methods)
            {
                // Check if this method has any properties that would immediately disqualify it from using this hook
                if (method.ReturnType == typeof(void))
                {
                    Logging.Log.Warning($"{method.Name} in {method.DeclaringType.FullName} cannot be used in a hook because it does not return a value!");
                    continue;
                }
                if (!method.IsStatic)
                {
                    Logging.Log.Warning($"{method.Name} in {method.DeclaringType.FullName} cannot be used in a hook because it is not static!");
                    continue;
                }

                // Get the type that the method returns
                var typeName = method.ReturnType.FullName;
                // Get the name of the method
                var methodName = method.Name;
                // Get the type name of the method
                var methodDeclaringType = method.DeclaringType.FullName;
                // Get an array of parameters that the method returns
                var    methodParameterInfo = method.GetParameters();
                Type[] methodParamters     = new Type[methodParameterInfo.Length];
                for (int i = 0; i < methodParamters.Length; i++)
                {
                    methodParamters[i] = methodParameterInfo[i].ParameterType;
                }

                // Get all the hooks for this method
                var hookAttributes = method.GetCustomAttributes(typeof(HookRedirectConstructorToMethodAttribute), false).Cast <HookRedirectConstructorToMethodAttribute>();

                foreach (var hook in hookAttributes)
                {
                    // Get the type name that contains the method we're hooking in
                    var hookTypeName = hook.Type;
                    // Get the name of the method we're hooking in
                    var hookMethodName = hook.Method;
                    try
                    {
                        CecilHelper.RedirectConstructorToMethod(cecilContext, method.ReturnType, hookTypeName, hookMethodName, methodDeclaringType, methodName, methodParamters);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Failed to Inject {typeName}.{methodName} into {hookTypeName}.{hookMethodName}\n\t{ex.Message}");
                        throw ex;
                    }
                }
            }
        }
예제 #22
0
        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;

            if (worker == null)
            {
                return;
            }

            var asmdef = e.Argument as AssemblyDefinition;

            if (asmdef == null)
            {
                return;
            }

            var result = new List <AssemblyDefinition>();

            e.Result = result;

            var files         = new List <FileInfo>();
            var fileName      = asmdef.MainModule.Image.FileName;
            var directoryName = Path.GetDirectoryName(fileName);

            if (directoryName != null)
            {
                var directory = new DirectoryInfo(directoryName);
                files.AddRange(directory.GetFiles("*.exe"));
                files.AddRange(directory.GetFiles("*.dll"));
            }

            foreach (var file in files)
            {
                if (worker.CancellationPending)
                {
                    result.Clear();
                    return;
                }

                string msg;
                try
                {
                    var refasm = PluginFactory.GetInstance().LoadAssembly(file.FullName, false);
                    result.AddRange(
                        refasm.MainModule.AssemblyReferences.Where(name => CecilHelper.ReferenceMatches(asmdef.Name, name))
                        .Select(name => refasm));
                    msg = string.Format("{0} ({1}/{2})", refasm, files.IndexOf(file), files.Count);
                }
                catch
                {
                    msg = file.FullName;
                }

                worker.ReportProgress((files.IndexOf(file) + 1) * 100 / files.Count, msg);
            }
        }
예제 #23
0
        protected void FixAndUpdateWorkingAttribute()
        {
            var module = CecilHelper.GetModuleFromCustomAttributeProvider(SelectedProvider);

            WorkingAttribute.Constructor = module.Import(Constructor.SelectedOperand);

            FixCustomAttributeArguments(module, WorkingAttribute.ConstructorArguments);
            FixCustomAttributeNamedArguments(module, WorkingAttribute.Fields);
            FixCustomAttributeNamedArguments(module, WorkingAttribute.Properties);
        }
        private TypeDefinition GetTypeDefinition(TypeReference item)
        {
            ModuleDefinition moddef = null;

            if ((item.Scope) is ModuleDefinition)
            {
                moddef = (ModuleDefinition)item.Scope;

                // Force node lazy load for all candidates, we already have the module
                // ReSharper disable once ReturnValueOfPureMethodIsNotUsed
                GetAssemblyDefinitionsByNodeName(moddef.Assembly.Name.Name).ToList();
            }
            else if ((item.Scope) is AssemblyNameReference)
            {
                var anr    = (AssemblyNameReference)item.Scope;
                var asmdef = GetAssemblyDefinitionsByNodeName(anr.Name).FirstOrDefault();

                if (asmdef != null)
                {
                    moddef = asmdef.MainModule;
                }
            }

            if (moddef == null)
            {
                return(null);
            }

            var typedef = CecilHelper.FindMatchingType(moddef.Types, StripGenerics(item, item.FullName));

            if (typedef == null)
            {
                return(null);
            }

            if (typedef.DeclaringType != null)
            {
                GetTypeDefinition(typedef.DeclaringType);
            }

            TreeNode moduleNode;
            TreeNode typeNode;

            if (_nodes.TryGetValue(moddef, out moduleNode))
            {
                LoadNodeOnDemand(moduleNode);
            }

            if (_nodes.TryGetValue(typedef, out typeNode))
            {
                LoadNodeOnDemand(typeNode);
            }

            return(typedef);
        }
예제 #25
0
            public override void Process(ConfusionParameter parameter)
            {
                AssemblyDefinition i = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location);

                cion.root = CecilHelper.Inject(mod, i.MainModule.GetType("AntiTamper"));
                mod.Types.Add(cion.root);
                MethodDefinition cctor = mod.GetType("<Module>").GetStaticConstructor();

                cctor.Body.GetILProcessor().InsertBefore(0, Instruction.Create(OpCodes.Call, cion.root.Methods.FirstOrDefault(mtd => mtd.Name == "Initalize")));

                MethodDefinition init = cion.root.Methods.FirstOrDefault(mtd => mtd.Name == "Initalize");

                foreach (Instruction inst in init.Body.Instructions)
                {
                    if (inst.Operand is int)
                    {
                        switch ((int)inst.Operand)
                        {
                        case 0x11111111:
                            inst.Operand = cion.key0; break;

                        case 0x33333333:
                            inst.Operand = cion.key2; break;

                        case 0x44444444:
                            inst.Operand = cion.key3; break;

                        case 0x55555555:
                            inst.Operand = cion.key4; break;
                        }
                    }
                    else if (inst.Operand is long && (long)inst.Operand == 0x2222222222222222)
                    {
                        inst.Operand = cion.key1;
                    }
                }
                MethodDefinition dec = cion.root.Methods.FirstOrDefault(mtd => mtd.Name == "Decrypt");

                foreach (Instruction inst in dec.Body.Instructions)
                {
                    if (inst.Operand is int && (int)inst.Operand == 0x11111111)
                    {
                        inst.Operand = (int)cion.key5;
                    }
                }

                cion.root.Name      = ObfuscationHelper.GetNewName("AntiTamperModule" + Guid.NewGuid().ToString());
                cion.root.Namespace = "";
                AddHelper(cion.root, HelperAttribute.NoInjection);
                foreach (MethodDefinition mtdDef in cion.root.Methods)
                {
                    mtdDef.Name = ObfuscationHelper.GetNewName(mtdDef.Name + Guid.NewGuid().ToString());
                    AddHelper(mtdDef, HelperAttribute.NoInjection);
                }
            }
예제 #26
0
 private void HookGlobalRouting(CecilContext cecilContext)
 {
     if (!this.Options.DisableGrm)
     {
         CecilHelper.HookAllGlobalRouteMethods(cecilContext);
     }
     else
     {
         Console.WriteLine("Skipping GRM injection");
     }
 }
예제 #27
0
        private void HookOutputableApiEvents(CecilContext cecilContext)
        {
            try
            {
                var methods = FarmhandAssemblies.SelectMany(a => a.GetTypes())
                              .SelectMany(t => t.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static))
                              .Where(m => m.GetCustomAttributes(typeof(HookReturnableAttribute), false).Any())
                              .ToArray();

                foreach (var method in methods)
                {
                    if (method.DeclaringType == null)
                    {
                        continue;
                    }

                    var typeName       = method.DeclaringType.FullName;
                    var methodName     = method.Name;
                    var hookAttributes = method.GetCustomAttributes(typeof(HookReturnableAttribute), false).Cast <HookReturnableAttribute>();

                    foreach (var hook in hookAttributes)
                    {
                        var hookTypeName   = hook.Type;
                        var hookMethodName = hook.Method;
                        try
                        {
                            switch (hook.HookType)
                            {
                            case HookType.Entry:
                                CecilHelper.InjectReturnableEntryMethod <ParameterBindAttribute, ThisBindAttribute, InputBindAttribute, LocalBindAttribute,
                                                                         UseOutputBindAttribute, MethodOutputBindAttribute>
                                    (cecilContext, hookTypeName, hookMethodName, typeName, methodName); break;

                            case HookType.Exit:
                                CecilHelper.InjectReturnableExitMethod <ParameterBindAttribute, ThisBindAttribute, InputBindAttribute, LocalBindAttribute,
                                                                        UseOutputBindAttribute, MethodOutputBindAttribute>
                                    (cecilContext, hookTypeName, hookMethodName, typeName, methodName); break;

                            default:
                                throw new Exception("Unknown HookType");
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"Failed to Inject {typeName}.{methodName} into {hookTypeName}.{hookMethodName}\n\t{ex.Message}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
예제 #28
0
        protected override void SetVirtualCallOnMethod(CecilContext cecilContext, MethodInfo asmMethod)
        {
            var attributes = asmMethod.GetCustomAttributes(typeof(HookMakeBaseVirtualCallAttribute), false).ToList().Cast <HookMakeBaseVirtualCallAttribute>();

            foreach (var attribute in attributes.Where(attribute => asmMethod.DeclaringType?.BaseType != null))
            {
                if (asmMethod.DeclaringType?.BaseType != null)
                {
                    CecilHelper.SetVirtualCallOnMethod(cecilContext, asmMethod.DeclaringType.BaseType.FullName, asmMethod.Name, attribute.Type, attribute.Method);
                }
            }
        }
        public override void UnloadAssembly(object assembly)
        {
            Reflector.CodeModel.IAssembly a = (Reflector.CodeModel.IAssembly)assembly;

            string             path = a.Location;
            AssemblyDefinition ad   = FindAssemblyDefinition(path);

            if (ad != null)
            {
                CecilHelper.RemoveAssemblyCache(ad);
            }
            _reflector.AssemblyManager.Unload(a);
        }
예제 #30
0
 private void ProcessReferences(AssemblyDefinition current, AssemblyDefinition other)
 {
     foreach (ModuleDefinition moddef in current.Modules)
     {
         foreach (AssemblyNameReference anref in moddef.AssemblyReferences)
         {
             if (CecilHelper.ReferenceMatches(anref, other.Name))
             {
                 CecilHelper.RemoveStrongNameReference(anref);
             }
         }
     }
 }