public RuleResult CheckType(TypeDefinition type)
        {
            if (type.IsAbstract || type.IsSealed || type.IsVisible() || type.IsGeneratedCode())
            {
                return(RuleResult.Success);
            }

            ModuleDefinition module = type.Module;
            string           name   = type.Name;
            string           nspace = type.Namespace;

            foreach (TypeDefinition type_definition in module.GetAllTypes())
            {
                // skip ourself
                if (type_definition.IsNamed(nspace, name))
                {
                    continue;
                }
                if (type_definition.Inherits(nspace, name))
                {
                    return(RuleResult.Success);
                }
            }

            Confidence c = module.Assembly.HasAttribute("System.Runtime.CompilerServices", "InternalsVisibleToAttribute") ?
                           Confidence.High : Confidence.Total;

            Runner.Report(type, Severity.Medium, c);
            return(RuleResult.Failure);
        }
Esempio n. 2
0
        private static IDictionary <uint, IMetadataTokenProvider> InitializeTokenProviderCache(ModuleDefinition module)
        {
            var dict     = new Dictionary <uint, IMetadataTokenProvider>();
            var allTypes = module.GetAllTypes();

            foreach (var type in allTypes)
            {
                foreach (var prop in type.Properties)
                {
                    dict[prop.MetadataToken.ToUInt32()] = prop;
                }
                foreach (var vent in type.Events)
                {
                    dict[vent.MetadataToken.ToUInt32()] = vent;
                }
            }
            foreach (var expType in module.ExportedTypes)
            {
                dict[expType.MetadataToken.ToUInt32()] = expType;
            }
            foreach (var modRef in module.ModuleReferences)
            {
                dict[modRef.MetadataToken.ToUInt32()] = modRef;
            }
            foreach (var assRef in module.AssemblyReferences)
            {
                dict[assRef.MetadataToken.ToUInt32()] = assRef;
            }
            return(dict);
        }
Esempio n. 3
0
        private void DoWeave(ModuleDefinition module)
        {
            var type   = module.GetAllTypes().FirstOrDefault(it => it.Name.Equals("Program"));
            var method = type.GetMethods().FirstOrDefault(it => it.Name.Equals("Main"));

            method.Body.SimplifyMacros();

            PrintInfo(method);

            var instrs = CreateInstructionsToInject(module, method.Body);

            int idx   = 0;
            var calls = method.Body.Instructions.Where(it => it.OpCode.Equals(OpCodes.Call)).ToArray();

            idx = method.Body.Instructions.IndexOf(calls[1]) + 1;

            //After the injection point all debugs are messed up. The lines before the injection point are OK.

            foreach (var instr in instrs.AsEnumerable().Reverse())
            {
                method.Body.Instructions.Insert(idx, instr);
            }

            PrintInfo(method);

            method.Body.InitLocals = true;

            method.Body.OptimizeMacros();

            PrintInfo(method);
        }
Esempio n. 4
0
 /// <summary>
 /// Do Proxy Progress.
 /// </summary>
 private static void DoProxies()
 {
     // Get All Types In Module (Note That GetAllTypes() Includes Nested Types).
     foreach (TypeDefinition TypeDef in _module.GetAllTypes().Where(Type => Type.Methods.Count > 0 && !Type.IsCompilerGenerated()).ToArray()) /* Purify Types Has No Methods & Not Compiler Gen. Using Linq. */
     {
         foreach (MethodDefinition MethodDef in TypeDef.Methods.Where(Method => Method.HasMethodBody && !Method.IsNative).ToArray())          /* Purify Methods Has No CilBody & Not x86 Method Using Linq. */
         {
             // Expanding Method Instructions (Some Times Branches MayBreak so Expaning Is Required).
             MethodDef.CilMethodBody.Instructions.ExpandMacros();
             // Get IL_Codes from MethodDef CilBody.
             var ILCode = MethodDef.CilMethodBody.Instructions;
             // Loop in ILCodes to Manage Process
             for (int x = 0; x < ILCode.Count; x++)
             {
                 // Check If Current Instruction is Vaild Call Instruction.
                 if (!(ILCode[x].OpCode == CilOpCodes.Call || ILCode[x].OpCode == CilOpCodes.Callvirt || ILCode[x].OpCode == CilOpCodes.Newobj))
                 {
                     continue;
                 }
                 // No Generic-Methods (You Can Do It But That Simple-Tutorial You Must Release you Ideas After Learning :D).
                 if (!(ILCode[x].Operand is not MethodSpecification))
                 {
                     continue;
                 }
                 // Assign Method In Variable.
                 var _calledmethod = (IMethodDescriptor)ILCode[x].Operand;
                 // Assign If That Instruction is Newobj.
                 bool IsNewObj = ILCode[x].OpCode == CilOpCodes.Newobj;
                 // Check Cache.
                 if (!Cache.ContainsKey(_calledmethod))
                 {
                     // Make New Method (Proxy-Method).
                     var _proxymethod = new MethodDefinition(Guid.NewGuid().GetHashCode().ToString("x"),
                                                             MethodAttributes.Static | MethodAttributes.Public | MethodAttributes.ReuseSlot,
                                                             GetSignature(IsNewObj, _calledmethod));
                     // Valided Proxy CilBody.
                     _proxymethod.ProcessProxyBody(ILCode[x]);
                     // Add Proxy-Meth to Current TypeDef.
                     TypeDef.Methods.Add(_proxymethod);
                     // Change OpCode to Call.
                     ILCode[x].OpCode = CilOpCodes.Call;
                     // Change Operand To Imported ProxyMethod.
                     ILCode[x].Operand = _importer.ImportMethod(_proxymethod);
                     // Add to cache.
                     Cache.Add(_calledmethod, _proxymethod);
                 }
                 else
                 {
                     // Change OpCode to Call.
                     ILCode[x].OpCode = CilOpCodes.Call;
                     // Change Operand To Stored Method.
                     ILCode[x].Operand = Cache[_calledmethod];
                 }
             }
             // Serializing Instructions After Processing.
             MethodDef.CilMethodBody.Instructions.OptimizeMacros();
         }
     }
 }
        public void Compile(Mappings result, ModuleDefinition module)
        {
            foreach (var typeDefinition in module.GetAllTypes())
            {
                var type = new MappedType(typeDefinition.FullName, GetOrDefault(typeDefinition.Name));

                foreach (var methodDefinition in typeDefinition.Methods)
                {
                    if (methodDefinition.Name.IsObfuscated() && !Names.ContainsKey(methodDefinition.Name))
                    {
                        continue; // dead method
                    }
                    var method = new MappedMethod(methodDefinition, GetOrDefault(methodDefinition.Name));

                    foreach (var parameterDefinition in methodDefinition.Parameters)
                    {
                        method.Parameters.Add(GetOrDefault(parameterDefinition.Name) ?? parameterDefinition.Name);
                    }

                    if (!methodDefinition.Name.IsObfuscated() && !method.Parameters.Any())
                    {
                        continue;
                    }

                    type.Methods.Add(method);
                }

                foreach (var fieldDefinition in typeDefinition.Fields)
                {
                    var field = new MappedMember(fieldDefinition.Name, GetOrDefault(fieldDefinition.Name) ?? fieldDefinition.Name.Clean());

                    if (!fieldDefinition.Name.IsObfuscated() && fieldDefinition.Name == field.Mapped)
                    {
                        continue;
                    }

                    type.Fields.Add(field);
                }

                foreach (var propertyDefinition in typeDefinition.Properties)
                {
                    var field = new MappedMember(propertyDefinition.Name, GetOrDefault(propertyDefinition.Name));

                    if (!propertyDefinition.Name.IsObfuscated())
                    {
                        continue;
                    }

                    type.Properties.Add(field);
                }

                if (!typeDefinition.Name.IsObfuscated() && !type.Fields.Any() && !type.Methods.Any() && !type.Properties.Any() && !type.Nested.Any())
                {
                    continue;
                }

                result.Types.Add(type);
            }
        }
Esempio n. 6
0
 private static void AnnotateModule(SuppressibleLoggingHelper?log, ModuleDefinition moduleDefinition, ModuleDefinition annotatedModuleDefinition, Dictionary <string, TypeDefinition> attributesOfInterest)
 {
     Annotate(moduleDefinition, annotatedModuleDefinition, attributesOfInterest);
     foreach (var type in moduleDefinition.GetAllTypes())
     {
         AnnotateType(log, type, annotatedModuleDefinition, attributesOfInterest);
     }
 }
Esempio n. 7
0
 private static void AnnotateModule(ModuleDefinition moduleDefinition, ModuleDefinition annotatedModuleDefinition, Dictionary <string, TypeDefinition> attributesOfInterest)
 {
     Annotate(moduleDefinition, annotatedModuleDefinition, attributesOfInterest);
     foreach (var type in moduleDefinition.GetAllTypes())
     {
         AnnotateType(type, annotatedModuleDefinition, attributesOfInterest);
     }
 }
        public GenerationContext(ModuleDefinition cleanModule, ModuleDefinition obfuscatedModule)
        {
            CleanModule      = cleanModule;
            ObfuscatedModule = obfuscatedModule;

            AllCleanTypes      = CleanModule.GetAllTypes();
            AllObfuscatedTypes = ObfuscatedModule.GetAllTypes();
        }
        internal static void Inject(this ModuleDefinition @this)
        {
            @this.RunInjectors();

            foreach (var type in @this.GetAllTypes())
            {
                type.Inject();
            }
        }
Esempio n. 10
0
        private Task LoadDll(string file)
        {
            ModuleDefinition moduleDef = ModuleDefinition.FromFile(file);

            TypeDefinition[] typeDefs = moduleDef.GetAllTypes().Where(m => m.FullName.Contains(".Entities.")).ToArray();
            _assemblyTypesDict[file] = typeDefs;

            return(Task.FromResult(0));
        }
Esempio n. 11
0
        public IEnumerable <MethodDefinition> FindMethodsUsingArraySlices(TypeDefinition typeToFind)
        {
            var methods = from type in ModuleDefinition.GetAllTypes()
                          from method in type.Methods
                          where IsMethodUsingTypeIndexers(method, typeToFind)
                          select method;

            return(methods);
        }
Esempio n. 12
0
    public static TypeDefinition GetTypeDefinition <T>(this ModuleDefinition moduleDefinition)
    {
        var replace = typeof(T).FullName.Replace("+", "/")
                      //trim trailing generic info
                      .Split('[')
                      .First();

        return(moduleDefinition.GetAllTypes()
               .First(x => x.FullName == replace));
    }
Esempio n. 13
0
        protected MethodDefinition GetMethodDefinition(string source, string methodName)
        {
            Uri    testDllLocation = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            string assemblyPath    = Compile(source, "testasm", new[] { testDllLocation.AbsolutePath });

            using (ModuleDefinition moduleDef = ModuleDefinition.ReadModule(assemblyPath))
            {
                return(moduleDef.GetAllTypes().SelectMany(typeDef => typeDef.Methods)
                       .FirstOrDefault(methodDef => methodDef.Name.Equals(methodName, StringComparison.OrdinalIgnoreCase)));
            }
        }
Esempio n. 14
0
        /// <summary>Changes types referencing mscorlib so they appear to be defined in System.Runtime.dll</summary>
        /// <param name="mainModule">module which assembly references will be added to/removed from</param>
        public static void FixReferences(ModuleDefinition mainModule)
        {
            foreach (var t in mainModule.GetAllTypes())
            {
                FixType(t, mainModule);
            }

            foreach (var tbr in mainModule.AssemblyReferences.Where(a => a.Name == "mscorlib" || a.Name == "System.Private.CoreLib").ToArray())
            {
                mainModule.AssemblyReferences.Remove(tbr);
            }
        }
Esempio n. 15
0
        private void InternalExecute()
        {
            var typeReferenceProvider   = new TypeReferenceProvider(_configuration, this, _moduleDefinition);
            var methodReferenceProvider = new MethodReferenceProvider(typeReferenceProvider, _moduleDefinition);

            var factory = new TypeWeaverFactory(_configuration.Filter, typeReferenceProvider, methodReferenceProvider);

            foreach (var type in _moduleDefinition.GetAllTypes())
            {
                var weaver = factory.Create(type);
                weaver.Execute();
            }
        }
		public void GetAllTypesTest (ModuleDefinition module)
		{
			var sequence = new [] {
				module.GetType ("<Module>"),
				module.GetType ("Foo"),
				module.GetType ("Foo/Bar"),
				module.GetType ("Foo/Gazonk"),
				module.GetType ("Foo/Gazonk/Baz"),
				module.GetType ("Pan"),
			};

			Assert.IsTrue (sequence.SequenceEqual (module.GetAllTypes ()));
		}
Esempio n. 17
0
        public void GetAllTypesTest(ModuleDefinition module)
        {
            var sequence = new [] {
                module.GetType("<Module>"),
                module.GetType("Foo"),
                module.GetType("Foo/Bar"),
                module.GetType("Foo/Gazonk"),
                module.GetType("Foo/Gazonk/Baz"),
                module.GetType("Pan"),
            };

            Assert.IsTrue(sequence.SequenceEqual(module.GetAllTypes()));
        }
Esempio n. 18
0
        protected TypeDefinition GetTypeDef <T> ()
        {
            var type = typeof(T);

            if (module == null)
            {
                module = ModuleDefinition.ReadModule(type.Module.FullyQualifiedName);
            }

            var typeref = module.GetAllTypes().Single(t => t.Name == type.Name);

            return(typeref);
        }
Esempio n. 19
0
    public void Execute()
    {
        if (!string.IsNullOrEmpty(AddinDirectoryPath)) //it is not empty when triggered from MS Build (Fody)
        {
            List <string> localRefDirs = new List <string>();
            foreach (var refCopyLocalPath in ReferenceCopyLocalPaths)
            {
                localRefDirs.Add(Directory.GetParent(refCopyLocalPath).FullName);
            }

            var defAssemblyResolver = new DefaultAssemblyResolver();

            defAssemblyResolver.AddSearchDirectory(AddinDirectoryPath);

            localRefDirs.ForEach(refDir => defAssemblyResolver.AddSearchDirectory(refDir));

            AssemblyResolver = defAssemblyResolver;
        }
        else //for testing
        {
            AssemblyResolver = ModuleDefinition.AssemblyResolver;
        }

        ReferencedModules = new List <ModuleDefinition>();
        foreach (var assemblyRef in ModuleDefinition.AssemblyReferences)
        {
            var refModuleDefinition = AssemblyResolver.Resolve(assemblyRef).MainModule;
            ReferencedModules.Add(refModuleDefinition);
        }

        TestFlaskAspectsModule = ResolveTestFlaskAspectsModuleDefinition();

        typeSystem = ModuleDefinition.TypeSystem;

        var playableMethods = ModuleDefinition.GetAllTypes().SelectMany(
            t => t.Methods.Where(
                md => md.CustomAttributes.Any(ca => ca.AttributeType.Name.Equals("PlaybackAttribute")))
            ).ToList();

        foreach (var playableMethod in playableMethods)
        {
            var playbackAttr = playableMethod.CustomAttributes.Single(ca => ca.AttributeType.Name.Equals("PlaybackAttribute"));

            TypeDefinition requestIdentifierTypeDef  = playbackAttr.ConstructorArguments[0].Value as TypeDefinition;
            TypeDefinition responseIdentifierTypeDef = playbackAttr.ConstructorArguments[1].Value as TypeDefinition;

            var clonePlayableMethod = CloneOriginalMethod(playableMethod);

            DecorateMethod(playableMethod, clonePlayableMethod, requestIdentifierTypeDef, responseIdentifierTypeDef);
        }
    }
Esempio n. 20
0
        private void InternalExecute()
        {
            TypeReferenceProvider   typeReferenceProvider   = new TypeReferenceProvider(_configuration, this, _moduleDefinition);
            MethodReferenceProvider methodReferenceProvider = new MethodReferenceProvider(typeReferenceProvider, _moduleDefinition);

            TypeWeaverFactory factory = new TypeWeaverFactory(_configuration.Filter, typeReferenceProvider, methodReferenceProvider, _configuration.ShouldTraceConstructors,
                                                              _configuration.ShouldTraceProperties);

            foreach (TypeDefinition type in _moduleDefinition.GetAllTypes())
            {
                TypeWeaver weaver = factory.Create(type);
                weaver.Execute();
            }
        }
Esempio n. 21
0
        private static void Process(ModuleDefinition module)
        {
            foreach (var type in module.GetAllTypes())
            {
                foreach (var feature in Features)
                {
                    feature.Process(type);
                }
            }

            foreach (var feature in Features)
            {
                feature.PostProcess(module);
            }
        }
Esempio n. 22
0
        private MethodDefinition FindOpCodeMethod(ModuleDefinition Module)
        {
            foreach (var type in Module.GetAllTypes())
            {
                var method = type.Methods.FirstOrDefault(q =>
                                                         q.IsIL && q.CilMethodBody != null && q.CilMethodBody.Instructions != null &&
                                                         q.CilMethodBody.Instructions.Count >= 3200 &&
                                                         q.CilMethodBody.Instructions.Count(d => d.OpCode == CilOpCodes.Switch) == 1);
                if (method != null)
                {
                    return(method);
                }
            }

            return(null);
        }
    public override void Execute()
    {
        IEnumerable <TypeDefinition> inpcClasses = ModuleDefinition
                                                   .GetAllTypes()
                                                   .Where(t => Implements(t, "INotifyPropertyChanged"));

        foreach (var inpcClass in inpcClasses)
        {
            var dependencies = FindPropertyDependencies(inpcClass);

            foreach (var property in dependencies.Keys)
            {
                AddPropertyChangedInvokations(property, dependencies[property]);
            }
        }
    }
Esempio n. 24
0
        static MethodDefinition GetProgramMethod(string name)
        {
            ModuleDefinition module = GetProgramAssembly().MainModule;

            foreach (TypeDefinition type in module.GetAllTypes())
            {
                if (type.FullName == "Cecil.Decompiler.Debug.Program")
                {
                    foreach (MethodDefinition method in type.Methods)
                    {
                        if (method.Name == name)
                        {
                            return(method);
                        }
                    }
                }
            }
            return(null);
        }
        private static void Main(string[] args)
        {
            string file = args[0];

            Module           reflectedModule  = Assembly.LoadFrom(file).Modules.First();
            ModuleDefinition moduleDefinition = ModuleDefinition.FromFile(file);

            IEnumerable <TypeDefinition> types = moduleDefinition.GetAllTypes();

            int decryptorTypeToken = types.First(type => type.FullName.Contains("PrivateImplementation")).MetadataToken.ToInt32();

            foreach (TypeDefinition type in types)
            {
                foreach (MethodDefinition method in type.Methods)
                {
                    if (method.CilMethodBody == null)
                    {
                        continue;
                    }

                    foreach (CilInstruction instruction in method.CilMethodBody.Instructions)
                    {
                        if (instruction.OpCode.Code != CilCode.Call || instruction.Operand is not MethodDefinition methodDefinition || methodDefinition.Parameters.Count != 0)
                        {
                            continue;
                        }

                        int methodToken = methodDefinition.DeclaringType.MetadataToken.ToInt32();

                        if (methodToken != decryptorTypeToken)
                        {
                            continue;
                        }

                        MethodBase reflectedMethod = reflectedModule.ResolveMethod(methodDefinition.MetadataToken.ToInt32());
                        instruction.OpCode = CilOpCodes.Ldstr;
                        Console.WriteLine(instruction.Operand = reflectedMethod.Invoke(null, Array.Empty <object>()));
                    }
                }
            }
            moduleDefinition.Write("SRXDLadder-decrypted.dll");
        }
Esempio n. 26
0
        private void CheckUsage(FieldDefinition field, ModuleDefinition module)
        {
            int match = 0;

            foreach (var type in module.GetAllTypes())
            {
                foreach (var method in type.Methods.Where(m => m.CilMethodBody != null))
                {
                    if (method.CilMethodBody.Instructions.Any(i =>
                                                              i.Operand is FieldDefinition matchedField && matchedField == field))
                    {
                        match++;
                    }
                }
            }
            if (match == 1)
            {
                FieldsInModule.Add(field);
            }
        }
Esempio n. 27
0
    public void Execute()
    {
        LoadSystemTypes();
        var allTypes = ModuleDefinition.GetAllTypes();

        foreach (var type in allTypes)
        {
            var allMethods = type.GetMethods();
            foreach (var method in allMethods)
            {
                CustomAttribute unSwallowAttribute;
                if (!TryGetCustomAttribute(method, "UnSwallowExceptions.Fody.UnSwallowExceptionsAttribute", out unSwallowAttribute))
                {
                    continue;
                }

                ProcessMethodDefinition(method);
            }
        }
    }
Esempio n. 28
0
        protected override void ProcessAssembly(AssemblyDefinition assembly)
        {
            if (Annotations.GetAction(assembly) != AssemblyAction.Link)
            {
                return;
            }

            module = assembly.MainModule;

            foreach (TypeDefinition type in module.GetAllTypes())
            {
                if (!type.IsNSObject())
                {
                    continue;
                }

                ProcessNSObject(type);
            }

            imported = false;
        }
Esempio n. 29
0
        private void AddModule(ModuleDefinition module)
        {
            var moduleTable = (ModuleDefinitionTable)_tableStream.GetTable(MetadataTokenType.Module);

            // Create and add module row.
            var moduleRow = new MetadataRow <ushort, uint, uint, uint, uint>
            {
                Column1 = module.Generation,
                Column2 = _parentBuffer.StringStreamBuffer.GetStringOffset(module.Name),
                Column3 = _parentBuffer.GuidStreamBuffer.GetGuidOffset(module.Mvid),
                Column4 = _parentBuffer.GuidStreamBuffer.GetGuidOffset(module.EncId),
                Column5 = _parentBuffer.GuidStreamBuffer.GetGuidOffset(module.EncBaseId)
            };

            moduleTable.Add(moduleRow);
            _members.Add(module, moduleRow.MetadataToken);

            // Add children.
            AddTypes(module.GetAllTypes().ToArray());
            AddCustomAttributes(module);
        }
Esempio n. 30
0
        public override void Execute()
        {
            var valueType = ModuleDefinition.ImportReference(typeof(ValueType));

            int replacedType = 0, replacedMethod = 0;

            foreach (var t in ModuleDefinition.GetAllTypes())
            {
                if (t.HasGenericParameters && t.GenericParameters[0].HasConstraints)
                {
                    var g = t.GenericParameters[0];
                    if (g.Constraints[0].FullName.Contains("Unmanaged"))
                    {
                        g.Constraints[0] = valueType;
                        g.CustomAttributes.RemoveAt(0);
                        replacedType++;
                    }
                }
            }
            foreach (var m in ModuleDefinition.GetAllTypes().SelectMany(t => t.Methods))
            {
                var t = m;
                if (t.HasGenericParameters && t.GenericParameters[0].HasConstraints)
                {
                    var g = t.GenericParameters[0];
                    if (g.Constraints[0].FullName.Contains("Unmanaged"))
                    {
                        g.Constraints[0] = valueType;
                        g.CustomAttributes.RemoveAt(0);
                        replacedMethod++;
                    }
                }
            }

            LogMessage($"LightDx unmanaged constrain weaver finished, replacing {replacedType} types " +
                       $"and {replacedMethod} methods.", MessageImportance.High);
        }
 private MethodDefinition FindSetupMethod()
 {
     foreach (var method in ModuleDefinition.GetAllTypes().SelectMany(t => t.GetMethods())
              .Where(m => m.CustomAttributes.Any(a => a.AttributeType.IsType <SetupMethodAttribute>())))
     {
         if (!method.IsStatic)
         {
             LogWarning($"Setup method '{method.FullName}' must be static");
             return(null);
         }
         if (!method.IsPublic && !method.IsAssembly)
         {
             LogWarning($"Setup method '{method.FullName}' must be public or internal");
             return(null);
         }
         if (method.Parameters.Count != 1 || !method.Parameters[0].ParameterType.IsType <IApplicationBuilder>())
         {
             LogWarning($"Setup method '{method.FullName}' must take a single parameter of type '{typeof(IApplicationBuilder).FullName}'");
             return(null);
         }
         return(method);
     }
     return(null);
 }