Example #1
0
		public void Find() {
			var requiredFields = new string[] {
				"System.Threading.ReaderWriterLock",
				"System.Collections.Hashtable",
			};
			foreach (var type in module.GetTypes()) {
				var fieldTypes = new FieldTypes(type);
				if (!fieldTypes.All(requiredFields))
					continue;
				if (type.FindMethod("Finalize") == null)
					continue;
				var executeMethod = DotNetUtils.GetMethod(type, "System.Object", "(System.String,System.Object[])");
				if (executeMethod == null || !executeMethod.IsStatic || executeMethod.Body == null)
					continue;

				var decrypterType = FindMethodsDecrypterType(type);
				if (decrypterType == null)
					continue;

				resourceDecrypter.DecryptMethod = FindDecryptMethod(decrypterType);

				methodsDecrypterCreator = type;
				methodsDecrypter = decrypterType;
				decryptExecuteMethod = executeMethod;
				return;
			}
		}
		bool InlineMethod(MethodDef methodToInline, int instrIndex, int const1, int const2) {
			this.methodToInline = methodToInline = cflowDeobfuscator.Deobfuscate(methodToInline);

			parameters = methodToInline.Parameters;
			arg1 = parameters[parameters.Count - 2];
			arg2 = parameters[parameters.Count - 1];
			returnValue = null;

			instructionEmulator.Initialize(methodToInline);
			foreach (var arg in parameters) {
				if (!arg.IsNormalMethodParameter)
					continue;
				if (arg.Type.ElementType >= ElementType.Boolean && arg.Type.ElementType <= ElementType.U4)
					instructionEmulator.SetArg(arg, new Int32Value(0));
			}
			instructionEmulator.SetArg(arg1, new Int32Value(const1));
			instructionEmulator.SetArg(arg2, new Int32Value(const2));

			int index = 0;
			if (!EmulateInstructions(ref index, false))
				return false;
			var patcher = TryInlineOtherMethod(instrIndex, methodToInline, methodToInline.Body.Instructions[index], index + 1, 2);
			if (patcher == null)
				return false;
			if (!EmulateToReturn(patcher.afterIndex, patcher.lastInstr))
				return false;
			patcher.Patch(block);
			block.Insert(instrIndex, OpCodes.Pop.ToInstruction());
			block.Insert(instrIndex, OpCodes.Pop.ToInstruction());
			return true;
		}
		protected override List<Instruction> ReadInstructions(MethodDef cilMethod, CsvmMethodData csvmMethod) {
			var reader = new BinaryReader(new MemoryStream(csvmMethod.Instructions));
			var instrs = new List<Instruction>();
			var handlerInfoReader = new OpCodeHandlerInfoReader(module);

			int numVmInstrs = reader.ReadInt32();
			var vmInstrs = new ushort[numVmInstrs];
			for (int i = 0; i < numVmInstrs; i++)
				vmInstrs[i] = reader.ReadUInt16();

			uint offset = 0;
			for (int vmInstrIndex = 0; vmInstrIndex < numVmInstrs; vmInstrIndex++) {
				var composite = opCodeDetector.Handlers[vmInstrs[vmInstrIndex]];
				var handlerInfos = composite.OpCodeHandlerInfos;
				if (handlerInfos.Count == 0)
					handlerInfos = new List<OpCodeHandlerInfo>() { new OpCodeHandlerInfo(HandlerTypeCode.Nop, null) };
				for (int hi = 0; hi < handlerInfos.Count; hi++) {
					var instr = handlerInfoReader.Read(handlerInfos[hi].TypeCode, reader);
					instr.Offset = offset;
					offset += (uint)GetInstructionSize(instr);
					SetCilToVmIndex(instr, vmInstrIndex);
					if (hi == 0)
						SetVmIndexToCil(instr, vmInstrIndex);
					instrs.Add(instr);
				}
			}
			return instrs;
		}
Example #4
0
		bool Find(MethodDef methodToCheck) {
			if (methodToCheck == null)
				return false;
			foreach (var method in DotNetUtils.GetCalledMethods(module, methodToCheck)) {
				var type = method.DeclaringType;

				if (!method.IsStatic || !DotNetUtils.IsMethod(method, "System.Void", "()"))
					continue;
				if (DotNetUtils.GetPInvokeMethod(type, "kernel32", "LoadLibrary") == null)
					continue;
				if (DotNetUtils.GetPInvokeMethod(type, "kernel32", "GetProcAddress") == null)
					continue;
				Deobfuscate(method);
				if (!ContainsString(method, "debugger is activ") &&
					!ContainsString(method, "debugger is running") &&
					!ContainsString(method, "Debugger detected") &&
					!ContainsString(method, "Debugger was detected") &&
					!ContainsString(method, "{0} was detected") &&
					!ContainsString(method, "run under") &&
					!ContainsString(method, "run with") &&
					!ContainsString(method, "started under") &&
					!ContainsString(method, "{0} detected") &&
					!ContainsString(method, "{0} found"))
					continue;

				antiDebuggerType = type;
				antiDebuggerMethod = method;
				return true;
			}

			return false;
		}
		protected override Instruction OnAfterLoadArg(MethodDef methodToInline, Instruction instr, ref int instrIndex) {
			if (instr.OpCode.Code != Code.Box)
				return instr;
			if (methodToInline.MethodSig.GetGenParamCount() == 0)
				return instr;
			return DotNetUtils.GetInstruction(methodToInline.Body.Instructions, ref instrIndex);
		}
Example #6
0
		bool IsEmptyClass(MethodDef emptyMethod) {
			if (!DotNetUtils.IsEmptyObfuscated(emptyMethod))
				return false;

			var type = emptyMethod.DeclaringType;
			if (type.HasEvents || type.HasProperties)
				return false;
			if (type.Fields.Count != 1)
				return false;
			if (type.Fields[0].FieldType.FullName != "System.Boolean")
				return false;
			if (type.IsPublic)
				return false;

			int otherMethods = 0;
			foreach (var method in type.Methods) {
				if (method.Name == ".ctor" || method.Name == ".cctor")
					continue;
				if (method == emptyMethod)
					continue;
				otherMethods++;
				if (method.Body == null)
					return false;
				if (method.Body.Instructions.Count > 20)
					return false;
			}
			if (otherMethods > 8)
				return false;

			return true;
		}
Example #7
0
		bool CheckMethod(ISimpleDeobfuscator simpleDeobfuscator, MethodDef method) {
			if (method == null || method.Body == null)
				return false;

			foreach (var instr in method.Body.Instructions) {
				if (instr.OpCode.Code != Code.Call)
					continue;
				var calledMethod = instr.Operand as MethodDef;
				if (calledMethod == null)
					continue;
				if (calledMethod == null || !calledMethod.IsStatic)
					continue;
				if (!DotNetUtils.IsMethod(calledMethod, "System.Void", "()"))
					continue;
				var type = calledMethod.DeclaringType;
				if (type.NestedTypes.Count > 0)
					continue;

				simpleDeobfuscator.Deobfuscate(calledMethod, SimpleDeobfuscatorFlags.Force | SimpleDeobfuscatorFlags.DisableConstantsFolderExtraInstrs);
				if (CheckType(type, calledMethod)) {
					initMethod = calledMethod;
					return true;
				}
			}
			return false;
		}
Example #8
0
		static bool JumpToStatement(MethodDef method, uint ilOffset, DecompilerTextView textView) {
			if (method == null)
				return false;
			var serMod = method.Module.ToSerializedDnSpyModule();
			var key = new SerializedDnSpyToken(serMod, method.MDToken);
			if (textView == null)
				textView = MainWindow.Instance.SafeActiveTextView;

			bool found = MainWindow.Instance.DnSpyFileListTreeNode.FindModuleNode(method.Module) != null;
			if (found) {
				return MainWindow.Instance.JumpToReference(textView, method, (success, hasMovedCaret) => {
					if (success)
						return MoveCaretTo(textView, key, ilOffset);
					return false;
				});
			}

			MainWindow.Instance.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => {
				MainWindow.Instance.JumpToReference(textView, method, (success, hasMovedCaret) => {
					if (success)
						return MoveCaretTo(textView, key, ilOffset);
					return false;
				});
			}));
			return true;
		}
Example #9
0
		void Initialize() {
			var callCounter = new CallCounter();
			int count = 0;
			foreach (var type in module.GetTypes()) {
				if (count >= 40)
					break;
				foreach (var method in type.Methods) {
					if (method.Name != ".ctor" && method.Name != ".cctor" && module.EntryPoint != method)
						continue;
					foreach (var calledMethod in DotNetUtils.GetCalledMethods(module, method)) {
						if (!calledMethod.IsStatic || calledMethod.Body == null)
							continue;
						if (!DotNetUtils.IsMethod(calledMethod, "System.Void", "()"))
							continue;
						if (IsEmptyClass(calledMethod)) {
							callCounter.Add(calledMethod);
							count++;
						}
					}
				}
			}

			int numCalls;
			var theMethod = (MethodDef)callCounter.Most(out numCalls);
			if (numCalls >= 10)
				emptyMethod = theMethod;
		}
		void Check(MethodDef method) {
			if (method.Body == null)
				return;
			if (possiblyUnusedMethods.ContainsKey(method))
				return;
			if (removedMethods.Exists(method))
				return;

			foreach (var instr in method.Body.Instructions) {
				switch (instr.OpCode.Code) {
				case Code.Call:
				case Code.Calli:
				case Code.Callvirt:
				case Code.Newobj:
				case Code.Ldtoken:
				case Code.Ldftn:
				case Code.Ldvirtftn:
					break;
				default:
					continue;
				}

				var calledMethod = DotNetUtils.GetMethod2(module, instr.Operand as IMethod);
				if (calledMethod == null)
					continue;
				if (possiblyUnusedMethods.ContainsKey(calledMethod))
					notUnusedStack.Push(calledMethod);
			}
		}
        public AnalyzedMethodUsesTreeNode(MethodDef analyzedMethod)
        {
            if (analyzedMethod == null)
                throw new ArgumentNullException("analyzedMethod");

            this.analyzedMethod = analyzedMethod;
        }
 public static bool CanShow(MethodDef method)
 {
     return method.IsVirtual &&
         !method.IsFinal &&
         !method.DeclaringType.IsSealed &&
         !method.DeclaringType.IsInterface;	// interface methods are definitions not implementations - cannot be overridden
 }
		static short[] FindKey(MethodDef initMethod, FieldDefAndDeclaringTypeDict<bool> fields) {
			var instrs = initMethod.Body.Instructions;
			for (int i = 0; i < instrs.Count - 2; i++) {
				var ldci4 = instrs[i];
				if (!ldci4.IsLdcI4())
					continue;
				var newarr = instrs[i + 1];
				if (newarr.OpCode.Code != Code.Newarr)
					continue;
				if (newarr.Operand.ToString() != "System.Char")
					continue;

				var stloc = instrs[i + 2];
				if (!stloc.IsStloc())
					continue;
				var local = stloc.GetLocal(initMethod.Body.Variables);

				int startInitIndex = i;
				i++;
				var array = ArrayFinder.GetInitializedInt16Array(ldci4.GetLdcI4Value(), initMethod, ref i);
				if (array == null)
					continue;

				var field = GetStoreField(initMethod, startInitIndex, local);
				if (field == null)
					continue;
				if (fields.Find(field))
					return array;
			}

			return null;
		}
Example #14
0
		public static ITextOutput Write(ITextOutput output, MethodDef method, Language language) {
			output.Write(UIUtils.CleanUpIdentifier(method.Name), TextTokenHelper.GetTextTokenType(method));
			output.Write('(', TextTokenType.Operator);
			for (int i = 0; i < method.Parameters.Count; i++) {
				if (method.Parameters[i].IsHiddenThisParameter)
					continue;
				if (method.Parameters[i].MethodSigIndex > 0) {
					output.Write(',', TextTokenType.Operator);
					output.WriteSpace();
				}
				language.TypeToString(output, method.Parameters[i].Type.ToTypeDefOrRef(), false, method.Parameters[i].ParamDef);
			}
			if (method.CallingConvention == CallingConvention.VarArg || method.CallingConvention == CallingConvention.NativeVarArg) {
				if (method.MethodSig.GetParamCount() > 0) {
					output.Write(',', TextTokenType.Operator);
					output.WriteSpace();
				}
				output.Write("...", TextTokenType.Operator);
			}
			output.Write(')', TextTokenType.Operator);
			output.WriteSpace();
			output.Write(':', TextTokenType.Operator);
			output.WriteSpace();
			language.TypeToString(output, method.ReturnType.ToTypeDefOrRef(), false, method.Parameters.ReturnParameter.ParamDef);
			method.MDToken.WriteSuffixString(output);
			return output;
		}
Example #15
0
		public override void Decompile(MethodDef method, IDecompilerOutput output, DecompilationContext ctx) {
			WriteCommentBegin(output, true);
			output.Write("Method: ", BoxedTextColor.Comment);
			output.Write(IdentifierEscaper.Escape(method.FullName), method, DecompilerReferenceFlags.Definition, BoxedTextColor.Comment);
			WriteCommentEnd(output, true);
			output.WriteLine();

			if (!method.HasBody) {
				return;
			}

			StartKeywordBlock(output, ".body", method);

			ILAstBuilder astBuilder = new ILAstBuilder();
			ILBlock ilMethod = new ILBlock();
			DecompilerContext context = new DecompilerContext(method.Module, MetadataTextColorProvider) { CurrentType = method.DeclaringType, CurrentMethod = method };
			ilMethod.Body = astBuilder.Build(method, inlineVariables, context);

			if (abortBeforeStep != null) {
				new ILAstOptimizer().Optimize(context, ilMethod, abortBeforeStep.Value);
			}

			if (context.CurrentMethodIsAsync) {
				output.Write("async", BoxedTextColor.Keyword);
				output.Write("/", BoxedTextColor.Punctuation);
				output.WriteLine("await", BoxedTextColor.Keyword);
			}

			var allVariables = ilMethod.GetSelfAndChildrenRecursive<ILExpression>().Select(e => e.Operand as ILVariable)
				.Where(v => v != null && !v.IsParameter).Distinct();
			foreach (ILVariable v in allVariables) {
				output.Write(IdentifierEscaper.Escape(v.Name), v, DecompilerReferenceFlags.Local | DecompilerReferenceFlags.Definition, v.IsParameter ? BoxedTextColor.Parameter : BoxedTextColor.Local);
				if (v.Type != null) {
					output.Write(" ", BoxedTextColor.Text);
					output.Write(":", BoxedTextColor.Punctuation);
					output.Write(" ", BoxedTextColor.Text);
					if (v.IsPinned) {
						output.Write("pinned", BoxedTextColor.Keyword);
						output.Write(" ", BoxedTextColor.Text);
					}
					v.Type.WriteTo(output, ILNameSyntax.ShortTypeName);
				}
				if (v.GeneratedByDecompiler) {
					output.Write(" ", BoxedTextColor.Text);
					output.Write("[", BoxedTextColor.Punctuation);
					output.Write("generated", BoxedTextColor.Keyword);
					output.Write("]", BoxedTextColor.Punctuation);
				}
				output.WriteLine();
			}

			var builder = new MethodDebugInfoBuilder(method);
			foreach (ILNode node in ilMethod.Body) {
				node.WriteTo(output, builder);
				if (!node.WritesNewLine)
					output.WriteLine();
			}
			output.AddDebugInfo(builder.Create());
			EndKeywordBlock(output);
		}
        public static bool findRegisterMethod(TypeDef type, out MethodDef regMethod, out MethodDef handler)
        {
            foreach (var method in type.Methods) {
                if (!method.IsStatic || method.Body == null)
                    continue;
                if (method.Body.ExceptionHandlers.Count != 1)
                    continue;

                foreach (var instr in method.Body.Instructions) {
                    if (instr.OpCode.Code != Code.Ldftn)
                        continue;
                    var handlerRef = instr.Operand as IMethod;
                    if (handlerRef == null)
                        continue;
                    if (!DotNetUtils.isMethod(handlerRef, "System.Reflection.Assembly", "(System.Object,System.ResolveEventArgs)"))
                        continue;
                    if (!new SigComparer().Equals(type, handlerRef.DeclaringType))
                        continue;
                    handler = DotNetUtils.getMethod(type, handlerRef);
                    if (handler == null)
                        continue;
                    if (handler.Body == null || handler.Body.ExceptionHandlers.Count != 1)
                        continue;

                    regMethod = method;
                    return true;
                }
            }

            regMethod = null;
            handler = null;
            return false;
        }
Example #17
0
		HashSet<ILVariable> localVariablesToDefine = new HashSet<ILVariable>(); // local variables that are missing a definition
		
		/// <summary>
		/// Creates the body for the method definition.
		/// </summary>
		/// <param name="methodDef">Method definition to decompile.</param>
		/// <param name="context">Decompilation context.</param>
		/// <param name="parameters">Parameter declarations of the method being decompiled.
		/// These are used to update the parameter names when the decompiler generates names for the parameters.</param>
		/// <returns>Block for the method body</returns>
		public static BlockStatement CreateMethodBody(MethodDef methodDef,
		                                              DecompilerContext context,
		                                              IEnumerable<ParameterDeclaration> parameters,
													  out MemberMapping mm)
		{
			MethodDef oldCurrentMethod = context.CurrentMethod;
			Debug.Assert(oldCurrentMethod == null || oldCurrentMethod == methodDef);
			context.CurrentMethod = methodDef;
			context.CurrentMethodIsAsync = false;
			try {
				AstMethodBodyBuilder builder = new AstMethodBodyBuilder();
				builder.methodDef = methodDef;
				builder.context = context;
				builder.corLib = methodDef.Module.CorLibTypes;
				if (Debugger.IsAttached) {
					return builder.CreateMethodBody(parameters, out mm);
				} else {
					try {
						return builder.CreateMethodBody(parameters, out mm);
					} catch (OperationCanceledException) {
						throw;
					} catch (Exception ex) {
						throw new ICSharpCode.Decompiler.DecompilerException(methodDef, ex);
					}
				}
			} finally {
				context.CurrentMethod = oldCurrentMethod;
			}
		}
Example #18
0
		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;
		}
		public void Find() {
			var requiredTypes = new string[] {
				"System.Reflection.Assembly",
				"System.Object",
				"System.Int32",
				"System.String[]",
			};
			foreach (var type in module.Types) {
				if (type.HasEvents)
					continue;
				if (!new FieldTypes(type).All(requiredTypes))
					continue;

				MethodDef regMethod, handler;
				if (!BabelUtils.FindRegisterMethod(type, out regMethod, out handler))
					continue;

				var resource = BabelUtils.FindEmbeddedResource(module, type);
				if (resource == null)
					continue;

				var decryptMethod = FindDecryptMethod(type);
				if (decryptMethod == null)
					throw new ApplicationException("Couldn't find resource type decrypt method");
				resourceDecrypter.DecryptMethod = ResourceDecrypter.FindDecrypterMethod(decryptMethod);
				InitXorKeys(decryptMethod);

				resolverType = type;
				registerMethod = regMethod;
				encryptedResource = resource;
				return;
			}
		}
		public AnalyzedInterfacePropertyImplementedByTreeNode(PropertyDef analyzedProperty) {
			if (analyzedProperty == null)
				throw new ArgumentNullException("analyzedProperty");

			this.analyzedProperty = analyzedProperty;
			this.analyzedMethod = this.analyzedProperty.GetMethod ?? this.analyzedProperty.SetMethod;
		}
Example #21
0
		protected override bool CheckHandlerMethod(MethodDef method) {
			if (!method.IsStatic || !method.HasBody)
				return false;

			EmbeddedAssemblyInfo info = null;
			var instructions = method.Body.Instructions;
			for (int i = 0; i < instructions.Count; i++) {
				var instrs = DotNetUtils.GetInstructions(instructions, i, OpCodes.Ldstr, OpCodes.Call);
				if (instrs == null)
					continue;

				var s = instrs[0].Operand as string;
				var calledMethod = instrs[1].Operand as IMethod;
				if (s == null || calledMethod == null)
					continue;

				info = assemblyResolverInfo.Find(Utils.GetAssemblySimpleName(s));
				if (info != null)
					break;
			}
			if (info == null)
				return false;

			resourceInfo = info;
			Logger.v("Found embedded assemblies resource {0}", Utils.ToCsharpString(info.resourceName));
			return true;
		}
		public void Find() {
			if (decrypterInfo == null)
				return;
			decryptMethod = FindDecryptMethod(decrypterInfo.mainType.Type);
			if (decryptMethod == null)
				return;
		}
		public void Initialize(MethodDef method, bool emulateFromFirstInstruction) {
			this.parameterDefs = method.Parameters;
			this.localDefs = method.Body.Variables;
			valueStack.Initialize();
			protectedStackValues.Clear();

			if (method != prev_method) {
				prev_method = method;

				cached_args.Clear();
				for (int i = 0; i < parameterDefs.Count; i++)
					cached_args.Add(GetUnknownValue(parameterDefs[i].Type));

				cached_locals.Clear();
				cached_zeroed_locals.Clear();
				for (int i = 0; i < localDefs.Count; i++) {
					cached_locals.Add(GetUnknownValue(localDefs[i].Type));
					cached_zeroed_locals.Add(GetDefaultValue(localDefs[i].Type));
				}
			}

			args.Clear();
			args.AddRange(cached_args);
			locals.Clear();
			locals.AddRange(method.Body.InitLocals && emulateFromFirstInstruction ? cached_zeroed_locals : cached_locals);
		}
        public static bool canInline(MethodDef method)
        {
            if (method == null || method.Body == null)
                return false;
            if (method.Attributes != (MethodAttributes.Assembly | MethodAttributes.Static))
                return false;
            if (method.Body.ExceptionHandlers.Count > 0)
                return false;

            var parameters = method.MethodSig.GetParams();
            int paramCount = parameters.Count;
            if (paramCount < 2)
                return false;

            if (method.GenericParameters.Count > 0) {
                foreach (var gp in method.GenericParameters) {
                    if (gp.GenericParamConstraints.Count == 0)
                        return false;
                }
            }

            var param1 = parameters[paramCount - 1];
            var param2 = parameters[paramCount - 2];
            if (!isIntType(param1.ElementType))
                return false;
            if (!isIntType(param2.ElementType))
                return false;

            return true;
        }
Example #25
0
		bool CheckMethod(MethodDef cctor) {
			if (cctor == null || cctor.Body == null)
				return false;
			var localTypes = new LocalTypes(cctor);
			if (!localTypes.Exactly(ilpLocalsV1x) &&
				!localTypes.Exactly(ilpLocalsV2x))
				return false;

			var type = cctor.DeclaringType;
			var methods = GetPinvokeMethods(type, "Protect");
			if (methods.Count == 0)
				methods = GetPinvokeMethods(type, "P0");
			if (methods.Count != 2)
				return false;
			if (type.Fields.Count < 1 || type.Fields.Count > 2)
				return false;

			if (!GetDelegate(type, out invokerInstanceField, out invokerDelegate))
				return false;

			runtimeFileInfos = new List<RuntimeFileInfo>(methods.Count);
			foreach (var method in methods)
				runtimeFileInfos.Add(new RuntimeFileInfo(method));
			return true;
		}
        public override void SetParameter(MethodDef.Param param, object obj, bool bReadonly)
        {
            base.SetParameter(param, obj, bReadonly);

            _resetProperties = false;

            string selectionName = string.Empty;
            VariableDef variable = param.Value as VariableDef;

            if (variable != null) {
                _valueOwner = variable.ValueClass;
                selectionName = (variable.Property != null) ? variable.Property.DisplayName : variable.DisplayName;

            } else {
                RightValueDef variableRV = param.Value as RightValueDef;

                if (variableRV != null)
                {
                    _valueOwner = variableRV.ValueClassReal;
                    selectionName = variableRV.DisplayName;
                }
            }

            Nodes.Behavior behavior = GetBehavior();
            _agentType = (behavior != null) ? behavior.AgentType : null;
            if (_valueOwner != VariableDef.kSelf)
            {
                _agentType = Plugin.GetInstanceAgentType(_valueOwner, behavior, _agentType);
            }

            setComboBox(selectionName);
        }
Example #27
0
 /// <summary>
 ///     Injects the specified MethodDef to another module.
 /// </summary>
 /// <param name="methodDef">The source MethodDef.</param>
 /// <param name="target">The target module.</param>
 /// <returns>The injected MethodDef.</returns>
 public static MethodDef Inject(MethodDef methodDef, ModuleDef target)
 {
     var ctx = new InjectContext(methodDef.Module, target);
     ctx.Map[methodDef] = Clone(methodDef);
     CopyMethodDef(methodDef, ctx);
     return (MethodDef)ctx.Map[methodDef];
 }
Example #28
0
        public ILAST(MethodDef method)
        {
            Method = method;
            Elements = new List<Element>();

            ProcessMethod();
        }
Example #29
0
		public static void WriteTo(this ExceptionHandler exceptionHandler, ITextOutput writer, MethodDef method)
		{
			writer.Write("Try", TextTokenType.Keyword);
			writer.WriteSpace();
			WriteOffsetReference(writer, exceptionHandler.TryStart, method);
			writer.Write('-', TextTokenType.Operator);
			WriteOffsetReference(writer, exceptionHandler.TryEnd, method);
			writer.WriteSpace();
			writer.Write(exceptionHandler.HandlerType.ToString(), TextTokenType.Keyword);
			if (exceptionHandler.FilterStart != null) {
				writer.WriteSpace();
				WriteOffsetReference(writer, exceptionHandler.FilterStart, method);
				writer.WriteSpace();
				writer.Write("handler", TextTokenType.Keyword);
				writer.WriteSpace();
			}
			if (exceptionHandler.CatchType != null) {
				writer.WriteSpace();
				exceptionHandler.CatchType.WriteTo(writer);
			}
			writer.WriteSpace();
			WriteOffsetReference(writer, exceptionHandler.HandlerStart, method);
			writer.Write('-', TextTokenType.Operator);
			WriteOffsetReference(writer, exceptionHandler.HandlerEnd, method);
		}
		public InterfaceEventImplementedByNode(EventDef analyzedEvent) {
			if (analyzedEvent == null)
				throw new ArgumentNullException("analyzedEvent");

			this.analyzedEvent = analyzedEvent;
			this.analyzedMethod = this.analyzedEvent.AddMethod ?? this.analyzedEvent.RemoveMethod;
		}
Example #31
0
        public override void DecompileMethod(MethodDef method, ITextOutput output, DecompilationOptions options)
        {
            WriteComment(output, "Method: ");
            output.WriteDefinition(IdentifierEscaper.Escape(method.FullName), method, TextTokenType.Comment, false);
            output.WriteLine();

            if (!method.HasBody)
            {
                return;
            }

            StartKeywordBlock(output, ".body", method);

            ILAstBuilder      astBuilder = new ILAstBuilder();
            ILBlock           ilMethod   = new ILBlock();
            DecompilerContext context    = new DecompilerContext(method.Module)
            {
                CurrentType = method.DeclaringType, CurrentMethod = method
            };

            ilMethod.Body = astBuilder.Build(method, inlineVariables, context);

            if (abortBeforeStep != null)
            {
                new ILAstOptimizer().Optimize(context, ilMethod, abortBeforeStep.Value);
            }

            if (context.CurrentMethodIsAsync)
            {
                output.Write("async", TextTokenType.Keyword);
                output.Write('/', TextTokenType.Operator);
                output.WriteLine("await", TextTokenType.Keyword);
            }

            var allVariables = ilMethod.GetSelfAndChildrenRecursive <ILExpression>().Select(e => e.Operand as ILVariable)
                               .Where(v => v != null && !v.IsParameter).Distinct();

            foreach (ILVariable v in allVariables)
            {
                output.WriteDefinition(IdentifierEscaper.Escape(v.Name), v, v.IsParameter ? TextTokenType.Parameter : TextTokenType.Local);
                if (v.Type != null)
                {
                    output.WriteSpace();
                    output.Write(':', TextTokenType.Operator);
                    output.WriteSpace();
                    if (v.IsPinned)
                    {
                        output.Write("pinned", TextTokenType.Keyword);
                        output.WriteSpace();
                    }
                    v.Type.WriteTo(output, ILNameSyntax.ShortTypeName);
                }
                if (v.IsGenerated)
                {
                    output.WriteSpace();
                    output.Write('[', TextTokenType.Operator);
                    output.Write("generated", TextTokenType.Keyword);
                    output.Write(']', TextTokenType.Operator);
                }
                output.WriteLine();
            }

            var memberMapping = new MemberMapping(method);

            foreach (ILNode node in ilMethod.Body)
            {
                node.WriteTo(output, memberMapping);
                if (!node.WritesNewLine)
                {
                    output.WriteLine();
                }
            }
            output.AddDebugSymbols(memberMapping);
            EndKeywordBlock(output);
        }
Example #32
0
 public static bool IsPublicOrInternal(this MethodDef methodDef)
 => methodDef?.IsPublic == true || methodDef?.IsAssembly == true;
        public string detect()
        {
            var decryptStringType   = stringDecrypter.Type;
            var decryptStringMethod = stringDecrypter.Method;

            if (decryptStringType == null || decryptStringMethod == null)
            {
                return(null);
            }

            var       otherMethods = new List <MethodDef>();
            MethodDef cctor        = null;

            foreach (var method in decryptStringType.Methods)
            {
                if (method == decryptStringMethod)
                {
                    continue;
                }
                if (method.Name == ".cctor")
                {
                    cctor = method;
                }
                else
                {
                    otherMethods.Add(method);
                }
            }
            if (cctor == null)
            {
                return(null);
            }

            bool hasConstantM2 = DeobUtils.hasInteger(decryptStringMethod, -2);

            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////

            var fields11 = new string[] {
                "System.Collections.Generic.Dictionary`2<System.Int32,System.String>",
                "System.IO.BinaryReader",
                "System.Byte[]",
                "System.Int16",
                "System.Boolean",
            };
            var locals11 = createLocalsArray(
                "System.Boolean",
                "System.Byte[]",
                "System.Char[]",
                "System.Int16",
                "System.Int32",
                "System.Reflection.Assembly",
                "System.String"
                );

            if (otherMethods.Count == 0 &&
                decryptStringType.NestedTypes.Count == 0 &&
                !hasConstantM2 &&
                !decryptStringMethod.IsNoInlining &&
                decryptStringMethod.IsPublic &&
                decryptStringMethod.IsSynchronized &&
                decryptStringMethod.Body.MaxStack >= 35 &&
                decryptStringMethod.Body.MaxStack <= 50 &&
                decryptStringMethod.Body.ExceptionHandlers.Count == 0 &&
                new LocalTypes(decryptStringMethod).exactly(locals11) &&
                checkTypeFields(fields11))
            {
                return("1.1 - 1.2");
            }

            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////

            var fields13 = new string[] {
                "System.Collections.Generic.Dictionary`2<System.Int32,System.String>",
                "System.IO.BinaryReader",
                "System.Byte[]",
                "System.Int16",
                "System.Boolean",
                "System.Byte[]",
            };
            var locals13 = createLocalsArray(
                "System.Boolean",
                "System.Byte",
                "System.Byte[]",
                "System.Char[]",
                "System.Int16",
                "System.Int32",
                "System.Reflection.Assembly",
                "System.String"
                );

            if (otherMethods.Count == 0 &&
                decryptStringType.NestedTypes.Count == 0 &&
                !hasConstantM2 &&
                !decryptStringMethod.IsNoInlining &&
                decryptStringMethod.IsPublic &&
                decryptStringMethod.IsSynchronized &&
                decryptStringMethod.Body.MaxStack >= 35 &&
                decryptStringMethod.Body.MaxStack <= 50 &&
                decryptStringMethod.Body.ExceptionHandlers.Count == 0 &&
                new LocalTypes(decryptStringMethod).exactly(locals13) &&
                checkTypeFields(fields13))
            {
                return("1.3");
            }

            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////

            var fields14 = new string[] {
                "System.Collections.Generic.Dictionary`2<System.Int32,System.String>",
                "System.IO.BinaryReader",
                "System.Byte[]",
                "System.Int16",
                "System.Boolean",
                "System.Byte[]",
            };
            var locals14 = createLocalsArray(
                "System.Boolean",
                "System.Byte",
                "System.Byte[]",
                "System.Char[]",
                "System.Int16",
                "System.Int32",
                "System.Reflection.Assembly",
                "System.String"
                );

            if (otherMethods.Count == 0 &&
                decryptStringType.NestedTypes.Count == 0 &&
                !hasConstantM2 &&
                !decryptStringMethod.IsNoInlining &&
                decryptStringMethod.IsPublic &&
                decryptStringMethod.IsSynchronized &&
                decryptStringMethod.Body.MaxStack >= 150 &&
                decryptStringMethod.Body.MaxStack <= 200 &&
                decryptStringMethod.Body.ExceptionHandlers.Count == 0 &&
                new LocalTypes(decryptStringMethod).exactly(locals14) &&
                checkTypeFields(fields14))
            {
                return("1.4 - 2.3");
            }

            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////

            var fields24 = new string[] {
                "System.Collections.Generic.Dictionary`2<System.Int32,System.String>",
                "System.IO.BinaryReader",
                "System.Byte[]",
                "System.Int16",
                "System.Boolean",
                "System.Byte[]",
            };
            var locals24 = createLocalsArray(
                "System.Boolean",
                "System.Byte",
                "System.Byte[]",
                "System.Char[]",
                "System.Int16",
                "System.Int32",
                "System.Reflection.Assembly",
                "System.Reflection.AssemblyName",
                "System.String"
                );

            if (otherMethods.Count == 0 &&
                decryptStringType.NestedTypes.Count == 0 &&
                !hasConstantM2 &&
                !decryptStringMethod.IsNoInlining &&
                decryptStringMethod.IsPublic &&
                decryptStringMethod.IsSynchronized &&
                decryptStringMethod.Body.MaxStack >= 1 &&
                decryptStringMethod.Body.MaxStack <= 8 &&
                decryptStringMethod.Body.ExceptionHandlers.Count == 0 &&
                new LocalTypes(decryptStringMethod).exactly(locals24) &&
                checkTypeFields(fields24))
            {
                return("2.4 - 2.5");
            }

            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////

            var fields26 = new string[] {
                "System.Collections.Generic.Dictionary`2<System.Int32,System.String>",
                "System.IO.BinaryReader",
                "System.Byte[]",
                "System.Int16",
                "System.Boolean",
                "System.Byte[]",
            };
            var locals26 = createLocalsArray(
                "System.Boolean",
                "System.Byte",
                "System.Byte[]",
                "System.Char[]",
                "System.Collections.Generic.Dictionary`2<System.Int32,System.String>",
                "System.Int16",
                "System.Int32",
                "System.Reflection.Assembly",
                "System.Reflection.AssemblyName",
                "System.String"
                );

            if (otherMethods.Count == 0 &&
                decryptStringType.NestedTypes.Count == 0 &&
                !hasConstantM2 &&
                !decryptStringMethod.IsNoInlining &&
                decryptStringMethod.IsPublic &&
                !decryptStringMethod.IsSynchronized &&
                decryptStringMethod.Body.MaxStack >= 1 &&
                decryptStringMethod.Body.MaxStack <= 8 &&
                decryptStringMethod.Body.ExceptionHandlers.Count == 1 &&
                new LocalTypes(decryptStringMethod).exactly(locals26) &&
                checkTypeFields(fields26))
            {
                return("2.6");
            }

            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////

            var fields27 = new string[] {
                "System.Collections.Generic.Dictionary`2<System.Int32,System.String>",
                "System.IO.BinaryReader",
                "System.Byte[]",
                "System.Int16",
                "System.Boolean",
                "System.Byte[]",
            };
            var locals27 = createLocalsArray(
                "System.Boolean",
                "System.Byte",
                "System.Byte[]",
                "System.Char[]",
                "System.Collections.Generic.Dictionary`2<System.Int32,System.String>",
                "System.Int16",
                "System.Int32",
                "System.Reflection.Assembly",
                "System.Reflection.AssemblyName",
                "System.String"
                );

            if (otherMethods.Count == 0 &&
                decryptStringType.NestedTypes.Count == 0 &&
                !hasConstantM2 &&
                decryptStringMethod.IsNoInlining &&
                decryptStringMethod.IsPublic &&
                !decryptStringMethod.IsSynchronized &&
                decryptStringMethod.Body.MaxStack >= 1 &&
                decryptStringMethod.Body.MaxStack <= 8 &&
                decryptStringMethod.Body.ExceptionHandlers.Count == 1 &&
                new LocalTypes(decryptStringMethod).exactly(locals27) &&
                checkTypeFields(fields27))
            {
                return("2.7");
            }

            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////

            var fields28 = new string[] {
                "System.Collections.Generic.Dictionary`2<System.Int32,System.String>",
                "System.IO.BinaryReader",
                "System.Byte[]",
                "System.Int16",
                "System.Boolean",
                "System.Byte[]",
                "System.Boolean",
            };
            var locals28 = createLocalsArray(
                "System.Boolean",
                "System.Byte",
                "System.Byte[]",
                "System.Char[]",
                "System.Collections.Generic.Dictionary`2<System.Int32,System.String>",
                "System.Int16",
                "System.Int32",
                "System.Reflection.Assembly",
                "System.Reflection.AssemblyName",
                "System.String"
                );

            if (otherMethods.Count == 0 &&
                decryptStringType.NestedTypes.Count == 0 &&
                !hasConstantM2 &&
                decryptStringMethod.IsNoInlining &&
                decryptStringMethod.IsAssembly &&
                !decryptStringMethod.IsSynchronized &&
                decryptStringMethod.Body.MaxStack >= 1 &&
                decryptStringMethod.Body.MaxStack <= 8 &&
                decryptStringMethod.Body.ExceptionHandlers.Count == 1 &&
                new LocalTypes(decryptStringMethod).exactly(locals28) &&
                checkTypeFields(fields28))
            {
                return("2.8");
            }

            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////

            var fields29 = new string[] {
                "System.Collections.Generic.Dictionary`2<System.Int32,System.String>",
                "System.IO.BinaryReader",
                "System.Byte[]",
                "System.Int16",
                "System.Int32",
                "System.Byte[]",
            };
            var locals29 = createLocalsArray(
                "System.Boolean",
                "System.Byte",
                "System.Byte[]",
                "System.Char[]",
                "System.Collections.Generic.Dictionary`2<System.Int32,System.String>",
                "System.Diagnostics.StackFrame",
                "System.Diagnostics.StackTrace",
                "System.Int16",
                "System.Int32",
                "System.IO.Stream",
                "System.Reflection.Assembly",
                "System.Reflection.AssemblyName",
                "System.Reflection.MethodBase",
                "System.String",
                "System.Type"
                );

            if (otherMethods.Count == 0 &&
                decryptStringType.NestedTypes.Count == 0 &&
                !hasConstantM2 &&
                decryptStringMethod.IsNoInlining &&
                decryptStringMethod.IsAssembly &&
                !decryptStringMethod.IsSynchronized &&
                decryptStringMethod.Body.MaxStack >= 1 &&
                decryptStringMethod.Body.MaxStack <= 8 &&
                (decryptStringMethod.Body.ExceptionHandlers.Count == 1 || decryptStringMethod.Body.ExceptionHandlers.Count == 2) &&
                new LocalTypes(decryptStringMethod).exactly(locals29) &&
                checkTypeFields(fields29))
            {
                return("2.9");
            }

            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////

            var fields30 = new string[] {
                "System.Collections.Generic.Dictionary`2<System.Int32,System.String>",
                "System.IO.BinaryReader",
                "System.Byte[]",
                "System.Int16",
                "System.Int32",
                "System.Byte[]",
            };
            var locals30 = createLocalsArray(
                "System.Boolean",
                "System.Byte",
                "System.Byte[]",
                "System.Char[]",
                "System.Collections.Generic.Dictionary`2<System.Int32,System.String>",
                "System.Diagnostics.StackFrame",
                "System.Diagnostics.StackTrace",
                "System.Int16",
                "System.Int32",
                "System.IO.Stream",
                "System.Reflection.Assembly",
                "System.Reflection.AssemblyName",
                "System.Reflection.MethodBase",
                "System.String",
                "System.Type"
                );
            var olocals30 = createLocalsArray(
                "System.Int32"
                );

            if (otherMethods.Count == 1 &&
                decryptStringType.NestedTypes.Count == 0 &&
                DotNetUtils.isMethod(otherMethods[0], "System.Int32", "(System.Byte[],System.Int32,System.Byte[])") &&
                otherMethods[0].IsPrivate &&
                otherMethods[0].IsStatic &&
                new LocalTypes(otherMethods[0]).exactly(olocals30) &&
                !hasConstantM2 &&
                decryptStringMethod.IsNoInlining &&
                decryptStringMethod.IsAssembly &&
                !decryptStringMethod.IsSynchronized &&
                decryptStringMethod.Body.MaxStack >= 1 &&
                decryptStringMethod.Body.MaxStack <= 8 &&
                (decryptStringMethod.Body.ExceptionHandlers.Count == 1 || decryptStringMethod.Body.ExceptionHandlers.Count == 2) &&
                new LocalTypes(decryptStringMethod).exactly(locals30) &&
                checkTypeFields(fields30))
            {
                return("3.0");
            }

            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////

            var fields31 = new string[] {
                "System.Collections.Generic.Dictionary`2<System.Int32,System.String>",
                "System.IO.BinaryReader",
                "System.Byte[]",
                "System.Int16",
                "System.Int32",
                "System.Byte[]",
            };
            var locals31 = createLocalsArray(
                "System.Boolean",
                "System.Byte",
                "System.Byte[]",
                "System.Char[]",
                "System.Collections.Generic.Dictionary`2<System.Int32,System.String>",
                "System.Diagnostics.StackFrame",
                "System.Diagnostics.StackTrace",
                "System.Int16",
                "System.Int32",
                "System.IO.Stream",
                "System.Reflection.Assembly",
                "System.Reflection.AssemblyName",
                "System.Reflection.MethodBase",
                "System.String",
                "System.Type"
                );
            var olocals31 = createLocalsArray(
                "System.Int32"
                );

            if (otherMethods.Count == 1 &&
                decryptStringType.NestedTypes.Count == 0 &&
                DotNetUtils.isMethod(otherMethods[0], "System.Int32", "(System.Byte[],System.Int32,System.Byte[])") &&
                otherMethods[0].IsPrivate &&
                otherMethods[0].IsStatic &&
                new LocalTypes(otherMethods[0]).exactly(olocals31) &&
                hasConstantM2 &&
                decryptStringMethod.IsNoInlining &&
                decryptStringMethod.IsAssembly &&
                !decryptStringMethod.IsSynchronized &&
                decryptStringMethod.Body.MaxStack >= 1 &&
                decryptStringMethod.Body.MaxStack <= 8 &&
                (decryptStringMethod.Body.ExceptionHandlers.Count == 1 || decryptStringMethod.Body.ExceptionHandlers.Count == 2) &&
                new LocalTypes(decryptStringMethod).exactly(locals31) &&
                checkTypeFields(fields31))
            {
                return("3.1");
            }

            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////

            var fields32 = new string[] {
                "System.Collections.Generic.Dictionary`2<System.Int32,System.String>",
                "System.IO.BinaryReader",
                "System.Byte[]",
                "System.Int16",
                "System.Int32",
                "System.Byte[]",
                "System.Int32",
            };
            var locals32 = createLocalsArray(
                "System.Boolean",
                "System.Byte",
                "System.Byte[]",
                "System.Char[]",
                "System.Collections.Generic.Dictionary`2<System.Int32,System.String>",
                "System.Diagnostics.StackFrame",
                "System.Diagnostics.StackTrace",
                "System.Int16",
                "System.Int32",
                "System.Int64",
                "System.IO.Stream",
                "System.Reflection.Assembly",
                "System.Reflection.AssemblyName",
                "System.Reflection.MethodBase",
                "System.String",
                "System.Type"
                );
            var olocals32 = createLocalsArray(
                "System.Int32"
                );

            if (otherMethods.Count == 1 &&
                decryptStringType.NestedTypes.Count == 0 &&
                DotNetUtils.isMethod(otherMethods[0], "System.Void", "(System.Byte[],System.Int32,System.Byte[])") &&
                otherMethods[0].IsPrivate &&
                otherMethods[0].IsStatic &&
                new LocalTypes(otherMethods[0]).exactly(olocals32) &&
                hasConstantM2 &&
                decryptStringMethod.IsNoInlining &&
                decryptStringMethod.IsAssembly &&
                !decryptStringMethod.IsSynchronized &&
                decryptStringMethod.Body.MaxStack >= 1 &&
                decryptStringMethod.Body.MaxStack <= 8 &&
                (decryptStringMethod.Body.ExceptionHandlers.Count == 1 || decryptStringMethod.Body.ExceptionHandlers.Count == 2) &&
                new LocalTypes(decryptStringMethod).exactly(locals32) &&
                checkTypeFields(fields32))
            {
                return("3.2");
            }

            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////

            if (decryptStringType.NestedTypes.Count == 1)
            {
                var fields33 = new string[] {
                    "System.Collections.Generic.Dictionary`2<System.Int32,System.String>",
                    "System.IO.BinaryReader",
                    "System.Byte[]",
                    "System.Int16",
                    "System.Int32",
                    "System.Byte[]",
                    "System.Int32",
                    "System.Int32",
                    decryptStringType.NestedTypes[0].FullName,
                };
                var locals33 = createLocalsArray(
                    "System.Boolean",
                    "System.Byte",
                    "System.Byte[]",
                    "System.Char[]",
                    "System.Collections.Generic.Dictionary`2<System.Int32,System.String>",
                    "System.Diagnostics.StackFrame",
                    "System.Diagnostics.StackTrace",
                    "System.Int16",
                    "System.Int32",
                    "System.Int64",
                    "System.IO.Stream",
                    "System.Reflection.Assembly",
                    "System.Reflection.AssemblyName",
                    "System.Reflection.MethodBase",
                    "System.String",
                    "System.Type"
                    );
                var olocals33 = createLocalsArray(
                    "System.Int32"
                    );
                if (otherMethods.Count == 1 &&
                    decryptStringType.NestedTypes.Count == 1 &&
                    DotNetUtils.isMethod(otherMethods[0], "System.Void", "(System.Byte[],System.Int32,System.Byte[])") &&
                    otherMethods[0].IsPrivate &&
                    otherMethods[0].IsStatic &&
                    new LocalTypes(otherMethods[0]).exactly(olocals33) &&
                    hasConstantM2 &&
                    decryptStringMethod.IsNoInlining &&
                    decryptStringMethod.IsAssembly &&
                    !decryptStringMethod.IsSynchronized &&
                    decryptStringMethod.Body.MaxStack >= 1 &&
                    decryptStringMethod.Body.MaxStack <= 8 &&
                    (decryptStringMethod.Body.ExceptionHandlers.Count == 1 || decryptStringMethod.Body.ExceptionHandlers.Count == 2) &&
                    new LocalTypes(decryptStringMethod).exactly(locals33) &&
                    checkTypeFields(fields33))
                {
                    return("3.3.29 - 3.3.57 (BETA)");
                }
            }

            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////

            if (decryptStringType.NestedTypes.Count == 3)
            {
                var fields33 = new string[] {
                    getNestedTypeName(0),
                    getNestedTypeName(1),
                    "System.Byte[]",
                    "System.Int16",
                    "System.Int32",
                    "System.Byte[]",
                    "System.Int32",
                    "System.Int32",
                    getNestedTypeName(2),
                };
                var locals33 = createLocalsArray(
                    "System.Boolean",
                    "System.Byte",
                    "System.Byte[]",
                    "System.Char[]",
                    getNestedTypeName(0),
                    "System.Diagnostics.StackFrame",
                    "System.Diagnostics.StackTrace",
                    "System.Int16",
                    "System.Int32",
                    "System.Int64",
                    "System.IO.Stream",
                    "System.Reflection.Assembly",
                    "System.Reflection.AssemblyName",
                    "System.Reflection.MethodBase",
                    "System.String",
                    "System.Type"
                    );
                var olocals33 = createLocalsArray(
                    "System.Int32"
                    );
                if (otherMethods.Count == 1 &&
                    decryptStringType.NestedTypes.Count == 3 &&
                    DotNetUtils.isMethod(otherMethods[0], "System.Void", "(System.Byte[],System.Int32,System.Byte[])") &&
                    otherMethods[0].IsPrivate &&
                    otherMethods[0].IsStatic &&
                    new LocalTypes(otherMethods[0]).exactly(olocals33) &&
                    decryptStringMethod.IsNoInlining &&
                    decryptStringMethod.IsAssembly &&
                    !decryptStringMethod.IsSynchronized &&
                    decryptStringMethod.Body.MaxStack >= 1 &&
                    decryptStringMethod.Body.MaxStack <= 8 &&
                    (decryptStringMethod.Body.ExceptionHandlers.Count == 1 || decryptStringMethod.Body.ExceptionHandlers.Count == 2) &&
                    new LocalTypes(decryptStringMethod).exactly(locals33) &&
                    checkTypeFields(fields33))
                {
                    return("3.3");
                }

                /////////////////////////////////////////////////////////////////
                /////////////////////////////////////////////////////////////////
                /////////////////////////////////////////////////////////////////

                var fields33_149 = new string[] {
                    getNestedTypeName(0),
                    getNestedTypeName(1),
                    "System.Byte[]",
                    "System.Int16",
                    "System.Int32",
                    "System.Byte[]",
                    "System.Int32",
                    "System.Int32",
                    getNestedTypeName(2),
                };
                var locals33_149 = createLocalsArray(
                    "System.Boolean",
                    "System.Byte",
                    "System.Byte[]",
                    "System.Char[]",
                    getNestedTypeName(0),
                    "System.Diagnostics.StackFrame",
                    "System.Diagnostics.StackTrace",
                    "System.Int16",
                    "System.Int32",
                    "System.Int64",
                    "System.IO.Stream",
                    "System.Reflection.Assembly",
                    "System.Reflection.AssemblyName",
                    "System.Reflection.MethodBase",
                    "System.String",
                    "System.Text.StringBuilder",
                    "System.Type"
                    );
                var olocals33_149 = createLocalsArray(
                    "System.Int32"
                    );
                if (otherMethods.Count == 1 &&
                    decryptStringType.NestedTypes.Count == 3 &&
                    DotNetUtils.isMethod(otherMethods[0], "System.Void", "(System.Byte[],System.Int32,System.Byte[])") &&
                    otherMethods[0].IsPrivate &&
                    otherMethods[0].IsStatic &&
                    new LocalTypes(otherMethods[0]).exactly(olocals33_149) &&
                    decryptStringMethod.IsNoInlining &&
                    decryptStringMethod.IsAssembly &&
                    !decryptStringMethod.IsSynchronized &&
                    decryptStringMethod.Body.MaxStack >= 1 &&
                    decryptStringMethod.Body.MaxStack <= 8 &&
                    (decryptStringMethod.Body.ExceptionHandlers.Count == 1 || decryptStringMethod.Body.ExceptionHandlers.Count == 2) &&
                    new LocalTypes(decryptStringMethod).exactly(locals33_149) &&
                    checkTypeFields2(fields33_149))
                {
                    return("3.3.149 - 3.4");                    // 3.3.149+ (but not SL or CF)
                }

                /////////////////////////////////////////////////////////////////
                /////////////////////////////////////////////////////////////////
                /////////////////////////////////////////////////////////////////

                var fields35 = new string[] {
                    getNestedTypeName(0),
                    getNestedTypeName(1),
                    "System.Byte[]",
                    "System.Int16",
                    "System.Int32",
                    "System.Byte[]",
                    "System.Int32",
                    "System.Int32",
                    getNestedTypeName(2),
                };
                var locals35 = createLocalsArray(
                    "System.Boolean",
                    "System.Byte",
                    "System.Byte[]",
                    "System.Char[]",
                    "System.Collections.Generic.IEnumerator`1<System.Int32>",
                    getNestedTypeName(0),
                    "System.Diagnostics.StackFrame",
                    "System.Diagnostics.StackTrace",
                    "System.Int16",
                    "System.Int32",
                    "System.Int64",
                    "System.IO.Stream",
                    "System.Reflection.Assembly",
                    "System.Reflection.AssemblyName",
                    "System.Reflection.MethodBase",
                    "System.String",
                    "System.Text.StringBuilder",
                    "System.Type"
                    );
                var olocals35 = createLocalsArray(
                    "System.Int32"
                    );
                if (otherMethods.Count == 1 &&
                    decryptStringType.NestedTypes.Count == 3 &&
                    DotNetUtils.isMethod(otherMethods[0], "System.Void", "(System.Byte[],System.Int32,System.Byte[])") &&
                    otherMethods[0].IsPrivate &&
                    otherMethods[0].IsStatic &&
                    new LocalTypes(otherMethods[0]).exactly(olocals35) &&
                    decryptStringMethod.IsNoInlining &&
                    decryptStringMethod.IsAssembly &&
                    !decryptStringMethod.IsSynchronized &&
                    decryptStringMethod.Body.MaxStack >= 1 &&
                    decryptStringMethod.Body.MaxStack <= 8 &&
                    decryptStringMethod.Body.ExceptionHandlers.Count >= 2 &&
                    new LocalTypes(decryptStringMethod).all(locals35) &&
                    checkTypeFields2(fields35))
                {
                    return("3.5 - 3.6");
                }
            }

            return(null);
        }
Example #34
0
 public StringEncrypterInfo(MethodDef method)
 {
     this.method = method;
 }
Example #35
0
        public string Decrypt(MethodDef method, int magic1, int magic2, int magic3)
        {
            var info = stringEncrypterInfos.Find(method);

            return(info.Decrypt(magic1, magic2, magic3));
        }
Example #36
0
 EmbeddedResource FindResource(MethodDef method)
 {
     return(DotNetUtils.GetResource(module, DotNetUtils.GetCodeStrings(method)) as EmbeddedResource);
 }
Example #37
0
 public abstract void ProcessInstruction(TypeService service, MethodDef method, IList <Instruction> body, ref int index, Instruction i);
Example #38
0
 public CodeGen(Instruction[] arg, MethodDef method, IList <Instruction> instrs) : base(method, instrs)
 {
     this.arg = arg;
 }
Example #39
0
 public override IMethod Map(MethodDef methodDef)
 {
     return(map.ContainsKey(methodDef) ? (MethodDef)map[methodDef] : null);
 }
Example #40
0
 public int Encode(MethodDef init, RPContext ctx, int value) =>
 this.GetKey(ctx, init).Item2(value);
 public Lshow(MethodDef md, int show)
 {
     method    = md;
     showindex = show;
     InitializeComponent();
 }
Example #42
0
        private static void CopyMethodDef(MethodDef methodDef, InjectContext ctx)
        {
            var newMethodDef = (MethodDef)ctx.map[methodDef];

            newMethodDef.Signature = ctx.Importer.Import(methodDef.Signature);
            newMethodDef.Parameters.UpdateParameterTypes();

            if (methodDef.ImplMap != null)
            {
                newMethodDef.ImplMap = new ImplMapUser(new ModuleRefUser(ctx.TargetModule, methodDef.ImplMap.Module.Name), methodDef.ImplMap.Name, methodDef.ImplMap.Attributes);
            }

            foreach (var ca in methodDef.CustomAttributes)
            {
                newMethodDef.CustomAttributes.Add(new CustomAttribute((ICustomAttributeType)ctx.Importer.Import(ca.Constructor)));
            }

            if (!methodDef.HasBody)
            {
                return;
            }
            newMethodDef.Body = new CilBody(methodDef.Body.InitLocals, new List <Instruction>(),
                                            new List <ExceptionHandler>(), new List <Local>())
            {
                MaxStack = methodDef.Body.MaxStack
            };

            var bodyMap = new Dictionary <object, object>();

            foreach (var local in methodDef.Body.Variables)
            {
                var newLocal = new Local(ctx.Importer.Import(local.Type));
                newMethodDef.Body.Variables.Add(newLocal);
                newLocal.Name       = local.Name;
                newLocal.Attributes = local.Attributes;

                bodyMap[local] = newLocal;
            }

            foreach (var instr in methodDef.Body.Instructions)
            {
                var newInstr = new Instruction(instr.OpCode, instr.Operand)
                {
                    SequencePoint = instr.SequencePoint
                };

                switch (newInstr.Operand)
                {
                case IType type:
                    newInstr.Operand = ctx.Importer.Import(type);
                    break;

                case IMethod method:
                    newInstr.Operand = ctx.Importer.Import(method);
                    break;

                case IField field:
                    newInstr.Operand = ctx.Importer.Import(field);
                    break;
                }

                newMethodDef.Body.Instructions.Add(newInstr);
                bodyMap[instr] = newInstr;
            }

            foreach (var instr in newMethodDef.Body.Instructions)
            {
                if (instr.Operand != null && bodyMap.ContainsKey(instr.Operand))
                {
                    instr.Operand = bodyMap[instr.Operand];
                }
                else if (instr.Operand is Instruction[] v)
                {
                    instr.Operand = v.Select(target => (Instruction)bodyMap[target]).ToArray();
                }
            }

            foreach (var eh in methodDef.Body.ExceptionHandlers)
            {
                newMethodDef.Body.ExceptionHandlers.Add(new ExceptionHandler(eh.HandlerType)
                {
                    CatchType    = eh.CatchType == null ? null : ctx.Importer.Import(eh.CatchType),
                    TryStart     = (Instruction)bodyMap[eh.TryStart],
                    TryEnd       = (Instruction)bodyMap[eh.TryEnd],
                    HandlerStart = (Instruction)bodyMap[eh.HandlerStart],
                    HandlerEnd   = (Instruction)bodyMap[eh.HandlerEnd],
                    FilterStart  = eh.FilterStart == null ? null : (Instruction)bodyMap[eh.FilterStart]
                });
            }

            newMethodDef.Body.SimplifyMacros(newMethodDef.Parameters);
        }
Example #43
0
 static string GetFullName(MethodDef md) => md == null ? "null" : md.FullName;
        public override void SetProperty(DesignerPropertyInfo property, object obj)
        {
            base.SetProperty(property, obj);

            _resetProperties = false;

            Type enumtype = null;
            DesignerPropertyEnum enumAtt = property.Attribute as DesignerPropertyEnum;

            if (enumAtt != null)
            {
                enumtype = property.Property.PropertyType;
            }

            if (enumtype == null)
            {
                throw new Exception(string.Format(Resources.ExceptionDesignerAttributeExpectedEnum, property.Property.Name));
            }

            Behaviac.Design.Attachments.Attach evt      = obj as Behaviac.Design.Attachments.Attach;
            Behaviac.Design.Nodes.BaseNode     baseNode = (evt != null) ? evt.Node : obj as Behaviac.Design.Nodes.BaseNode;
            Behaviac.Design.Nodes.Behavior     behavior = (baseNode != null) ? baseNode.Behavior as Behaviac.Design.Nodes.Behavior : null;

            if (behavior == null && this._root != null)
            {
                behavior = this._root.Behavior as Behaviac.Design.Nodes.Behavior;
            }

            _agentType = null;
            if (behavior != null)
            {
                _agentType = behavior.AgentType;
                if (_agentType == null)
                {
                    return;
                }
            }

            object        propertyMember = property.Property.GetValue(obj, null);
            VariableDef   variable       = propertyMember as VariableDef;
            RightValueDef variableRV     = propertyMember as RightValueDef;

            if (variable != null && variable.ValueClass != VariableDef.kSelf)
            {
                _agentType = Plugin.GetInstanceAgentType(variable.ValueClass);
            }

            if (variableRV != null && variableRV.ValueClassReal != VariableDef.kSelf)
            {
                string gloablClass = variableRV.ValueClassReal;

                _agentType = Plugin.GetInstanceAgentType(gloablClass);
            }

            string selectionName = string.Empty;

            if (variable != null && variable.Property != null)
            {
                selectionName = variable.Property.DisplayName;
            }
            else if (variableRV != null && variableRV.Var != null && variableRV.Var.Property != null)
            {
                selectionName = variableRV.Var.Property.DisplayName;
            }

            this.FilterType = null;
            if (enumAtt != null)
            {
                if (enumAtt.DependedProperty != "")
                {
                    Type         objType    = _object.GetType();
                    PropertyInfo pi         = objType.GetProperty(enumAtt.DependedProperty);
                    object       propMember = pi.GetValue(obj, null);
                    VariableDef  var        = propMember as VariableDef;
                    if (var != null)
                    {
                        this.FilterType = var.GetValueType();
                    }
                    else
                    {
                        MethodDef method = propMember as MethodDef;
                        if (method != null)
                        {
                            this.FilterType = method.ReturnType;
                        }
                        else
                        {
                            RightValueDef varRV = propMember as RightValueDef;
                            if (varRV != null)
                            {
                                this.FilterType = varRV.ValueType;
                            }
                        }
                    }
                }
                else
                {
                    this.FilterType = enumAtt.FilterType;
                }
            }

            setComboBox(selectionName);

            //after the left is changed, the right might need to be invalidated
            if (this.comboBox.Text != selectionName)
            {
                property.Property.SetValue(_object, null, null);
            }
        }
Example #45
0
        public void Process(IAssemblyHelper asmHelper)
        {
            asm = asmHelper;

            Logger.Log(this, string.Format("Processing"));

            // Set regex/bool
            foreach (PluginValue ps in asm.Settings)
            {
                switch (ps.Name)
                {
                case "OpCodeRegex": OpCodeRegex = (List <string>)ps.Value; break;

                case "OperandRegex": OperandRegex = (List <string>)ps.Value; break;

                case "AttributeRegex": AttributeRegex = (List <string>)ps.Value; break;

                case "MethodNameRegex": MethodNameRegex = (List <string>)ps.Value; break;

                case "MethodTokenRegex": MethodTokenRegex = (List <string>)ps.Value; break;

                case "MatchAll": MatchAll = (bool)ps.Value; break;

                case "RemoveInlined": RemoveInlined = (bool)ps.Value; break;

                case "UseHexToken": UseHexToken = (bool)ps.Value; break;

                case "UseFullName": UseFullName = (bool)ps.Value; break;
                }
            }

            Logger.Log(this, string.Format("Loaded {0} OpCodeRegex", OpCodeRegex.Count));
            Logger.Log(this, string.Format("Loaded {0} OperandRegex", OperandRegex.Count));
            Logger.Log(this, string.Format("Loaded {0} AttributeRegex", AttributeRegex.Count));
            Logger.Log(this, string.Format("Loaded {0} TokenRegex", MethodTokenRegex.Count));
            Logger.Log(this, string.Format("Loaded {0} NameRegex", MethodNameRegex.Count));


            List <CallInfo> toPatch = new List <CallInfo>();

            foreach (TypeDef td in asm.Module.GetTypes())
            {
                foreach (MethodDef md in td.Methods)
                {
                    if (!md.HasBody)
                    {
                        continue;
                    }
                    md.Body.SimplifyMacros(md.Parameters);
                }
            }

            List <MethodDef> allMatches = new List <MethodDef>();

            foreach (TypeDef td in asm.Module.GetTypes())
            {
                List <MethodDef> methodMatches = GetMatching(td).Distinct().ToList();
                Logger.Log(this, string.Format("Found {0} Matches for {1}", methodMatches.Count, td.Name));
                allMatches.AddRange(methodMatches);
            }
            Logger.Log(this, string.Format("Found {0} Matches Total", allMatches.Count));
            foreach (TypeDef td in asm.Module.GetTypes())
            {
                foreach (MethodDef md in td.Methods)
                {
                    if (!md.HasBody)
                    {
                        continue;
                    }

                    for (int i = 0; i < md.Body.Instructions.Count; i++)
                    {
                        Instruction inst = md.Body.Instructions[i];
                        if ((inst.OpCode == OpCodes.Call || inst.OpCode == OpCodes.Callvirt) && inst.Operand is MethodDef)
                        {
                            // MethodDef
                            MethodDef mDef = inst.Operand as MethodDef;

                            if (allMatches.Any(x => x.MDToken == mDef.MDToken))
                            {
                                // Patch this call
                                toPatch.Add(new CallInfo()
                                {
                                    CallingInst = inst, ParentMethod = md, TargetMethod = mDef
                                });
                            }
                        }
                    }
                }
            }


            Logger.Log(this, string.Format("Found {0} calls to inline", toPatch.Count));

            List <CallInfo> toPatch2 = new List <CallInfo>(toPatch);

            // Have to do priority, if a method is already in the topatch and another has it as a target method then there needs to be priority for the latter.
            List <CallInfo> cInfos = new List <CallInfo>();

            foreach (CallInfo cInfo in toPatch)
            {
                if (cInfos.Any(x => x.TargetMethod == cInfo.ParentMethod))
                {
                    // if it already exists in the list, insert it before
                    CallInfo cMatch = cInfos.Where(x => x.TargetMethod == cInfo.ParentMethod).FirstOrDefault();

                    if (cMatch == null)
                    {
                        // what the f**k
                        cInfos.Add(cInfo);
                        continue;
                    }

                    int index = cInfos.IndexOf(cMatch);
                    if (index >= 0)
                    {
                        Logger.Log(this, string.Format("Prioritizing {0} over {1}", cInfo.TargetMethod.Name, cMatch.TargetMethod.Name));
                        cInfos.Insert(index != 0 ? index - 1 : index, cInfo);
                    }
                    else
                    {
                        cInfos.Add(cInfo);
                    }
                }
                else
                {
                    cInfos.Add(cInfo);
                }
            }

            foreach (CallInfo cInfo in cInfos)
            {
                if (cInfo.CallingInst == null || cInfo.ParentMethod == null || cInfo.ParentMethod.Body == null)
                {
                    continue;
                }
                int instIndex = cInfo.ParentMethod.Body.Instructions.IndexOf(cInfo.CallingInst);
                if (!cInfo.TargetMethod.IsStatic)
                {
                    if (cInfo.ParentMethod.Body.Instructions[instIndex - 1].OpCode == OpCodes.Ldarg)
                    {
                        cInfo.ParentMethod.Body.Instructions[instIndex - 1].OpCode  = OpCodes.Nop;
                        cInfo.ParentMethod.Body.Instructions[instIndex - 1].Operand = null;
                    }
                }
                List <Instruction> toCopy = cInfo.TargetMethod.Body.Instructions.Where(x =>
                                                                                       x.OpCode != OpCodes.Ldarg &&
                                                                                       x.OpCode != OpCodes.Starg &&
                                                                                       x.OpCode != OpCodes.Nop &&
                                                                                       x.OpCode != OpCodes.Ret &&
                                                                                       x.OpCode != OpCodes.Br &&
                                                                                       x.OpCode != OpCodes.Switch
                                                                                       ).ToList();

                for (int i = 0; i < toCopy.Count; i++)
                {
                    toCopy[i] = toCopy[i].Clone();
                }

                Dictionary <int, Local> OldLocals = new Dictionary <int, Local>();


                if (cInfo.TargetMethod.Body.HasVariables)
                {
                    foreach (var loc in cInfo.TargetMethod.Body.Variables)
                    {
                        Local l = new Local(loc.Type)
                        {
                            Name = loc.Name, PdbAttributes = loc.PdbAttributes
                        };
                        l = cInfo.ParentMethod.Body.Variables.Add(l);

                        OldLocals.Add(loc.Index, l);
                    }
                    Logger.Log(this, string.Format("Copied {0} Locals", OldLocals.Count));
                }
                for (int i = 0; i < toCopy.Count; i++)
                {
                    if (toCopy[i].OpCode == OpCodes.Stloc || toCopy[i].OpCode == OpCodes.Ldloc)
                    {
                        if (OldLocals.ContainsKey((toCopy[i].Operand as Local).Index))
                        {
                            toCopy[i].Operand = OldLocals[(toCopy[i].Operand as Local).Index];
                        }
                    }
                    Instruction tReplace = toCopy[i].Clone();
                    if (i == 0)
                    {
                        cInfo.ParentMethod.Body.Instructions[instIndex].OpCode  = tReplace.OpCode;
                        cInfo.ParentMethod.Body.Instructions[instIndex].Operand = tReplace.Operand;
                    }
                    else
                    {
                        cInfo.ParentMethod.Body.Instructions.Insert(instIndex + i, tReplace);
                        cInfo.ParentMethod.Body.UpdateInstructionOffsets();
                    }
                }

                Logger.Log(this, string.Format("Inlined {0} Instructions", toCopy.Count));
                toPatch2.Remove(cInfo);


                if (RemoveInlined && !toPatch2.Any(x => x.TargetMethod == cInfo.TargetMethod))
                {
                    cInfo.TargetMethod.Body.Variables.Clear();
                    cInfo.TargetMethod.Body.Instructions.Clear();
                    cInfo.TargetMethod.Body = null;

                    cInfo.TargetMethod.DeclaringType.Methods.Remove(cInfo.TargetMethod);

                    Logger.Log(this, string.Format("Removed Method {0}", cInfo.TargetMethod.Name));
                }
            }

            Logger.Log(this, string.Format("Processing has finished"));
        }
 private bool IsUsedInMethodDefinition(MethodDef method)
 {
     return(IsUsedInMethodReference(method) ||
            IsUsedInMethodBody(method));
 }
Example #47
0
        /*
         *  loc_8D86:
         *      ldc.i4   0xF967D444    ; switchStartIndex
         *  loc_8D8B:
         *      ldc.i4   0xE36F2C9D
         *      xor
         *      dup
         *      stloc    0x13
         *      ldc.i4   5
         *      rem.un
         *      switch   loc_8DED, loc_8E55, loc_8E2A, loc_8D86, loc_8DBA
         *      br       loc_8E55
         */
        private void DeobfuscateSwitch(MethodDef method, int switchStartIndex)
        {
            IList <Instruction> insns = method.Body.Instructions;

            uint initialState  = (uint)(int)insns[switchStartIndex].Operand;
            uint stateConstant = (uint)(int)insns[switchStartIndex + 1].Operand;

            Instruction defaultBranch  = (Instruction)insns[switchStartIndex + 8].Operand;
            int         switchEndIndex = OffsetToIndex(insns, defaultBranch.Offset);

            List <int> switchTargets = ExtractTargetIndexes(insns, (IList <Instruction>)insns[switchStartIndex + 7].Operand);
            List <SwitchTargetInfo> switchTargetInfos = AnalyzeSwitchTargets(insns, switchStartIndex, switchEndIndex, switchTargets);

            Dictionary <int, List <int> > cfg = AnalyzeControlFlowGraph(initialState, stateConstant, switchStartIndex, switchEndIndex, switchTargetInfos);

            foreach (KeyValuePair <int, List <int> > item in cfg)
            {
                if (item.Key < 0)
                {
                    continue;
                }

                SwitchTargetInfo info = switchTargetInfos[item.Key];

                switch (info.Type)
                {
                case SwitchTargetType.Type1:
                case SwitchTargetType.Type2:
                    for (int i = info.PatternIndex; i <= info.EndIndex; i++)
                    {
                        insns[i].OpCode = OpCodes.Nop;
                    }

                    insns[info.PatternIndex].OpCode  = OpCodes.Br;
                    insns[info.PatternIndex].Operand = insns[switchTargetInfos[item.Value[0]].StartIndex];
                    break;

                case SwitchTargetType.Type3:
                case SwitchTargetType.Type4:
                    for (int i = info.PatternIndex; i <= info.EndIndex; i++)
                    {
                        insns[i].OpCode = OpCodes.Nop;
                    }

                    insns[info.PatternIndex - 1].Operand = insns[switchTargetInfos[item.Value[0]].StartIndex];
                    insns[info.PatternIndex].OpCode      = OpCodes.Br;
                    insns[info.PatternIndex].Operand     = insns[switchTargetInfos[item.Value[1]].StartIndex];
                    break;

                default:
                    throw new InvalidMethodException();
                }
            }

            for (int i = switchStartIndex; i < switchStartIndex + SwitchProloguePattern.Length; i++)
            {
                insns[i].OpCode = OpCodes.Nop;
            }

            int entryIndex = switchTargetInfos[cfg[-1][0]].StartIndex;

            insns[switchStartIndex].OpCode  = OpCodes.Br;
            insns[switchStartIndex].Operand = insns[entryIndex];
        }
Example #48
0
        void RemoveMethods()
        {
            if (methodsDecrypter.Method != null)
            {
                AddEntryPointCallToBeRemoved(methodsDecrypter.Method);
            }

            MethodDef antiTamper = null;
            MethodDef antiDebug  = null;

            foreach (var type in module.GetTypes())
            {
                foreach (var method in type.Methods)
                {
                    if (!method.HasBody)
                    {
                        continue;
                    }

                    foreach (var str in DotNetUtils.GetCodeStrings(method))
                    {
                        if (str == " is tampered.")
                        {
                            antiTamper = method;
                            AddMethodToBeRemoved(antiTamper, "Anti tamper method");
                            break;
                        }

                        if (str == "Debugger Detected")
                        {
                            antiDebug = method;
                            AddMethodToBeRemoved(antiDebug, "Anti debug method");
                            break;
                        }
                    }
                }
            }

            foreach (var type in module.GetTypes())
            {
                foreach (var method in type.Methods)
                {
                    if (!method.HasBody)
                    {
                        continue;
                    }
                    if (emptyClass?.Method != null)
                    {
                        AddCallToBeRemoved(method, emptyClass.Method);
                    }

                    if (antiTamper != null)
                    {
                        AddCallToBeRemoved(method, antiTamper);
                    }

                    if (antiDebug != null)
                    {
                        AddCallToBeRemoved(method, antiDebug);
                    }

                    if (methodsDecrypter.Method != null)
                    {
                        AddCallToBeRemoved(method, methodsDecrypter.Method);
                    }

                    // AntiILDASM
                    var instr = method.Body.Instructions;

                    for (int i = 0; i < instr.Count; i++)
                    {
                        if (instr[i].OpCode == OpCodes.Call && instr[i].Operand is null && instr[i + 1].IsStloc() && instr[i + 2].IsLdloc())
                        {
                            instr[i].OpCode     = OpCodes.Nop;                         // v6.0.0.0
                            instr[i + 2].OpCode = OpCodes.Nop;
                        }
                        if (instr[i].OpCode == OpCodes.Call && instr[i].Operand is null)
                        {
                            instr[i].OpCode = OpCodes.Nop;
                        }
                    }
                }
            }
        }
Example #49
0
        void InjectStub(DotProtectContext context, CompressorContext compCtx, ProtectionParameters parameters, ModuleDef stubModule)
        {
            var             rt     = context.Registry.GetService <IRuntimeService>();
            RandomGenerator random = context.Registry.GetService <IRandomService>().GetRandomGenerator(Id);
            var             comp   = context.Registry.GetService <ICompressionService>();

            var rtType = rt.GetRuntimeType(compCtx.CompatMode ? "DotProtect.Runtime.CompressorCompat" : "DotProtect.Runtime.Compressor");
            IEnumerable <IDnlibDef> defs = InjectHelper.Inject(rtType, stubModule.GlobalType, stubModule);

            switch (parameters.GetParameter(context, context.CurrentModule, "key", Mode.Normal))
            {
            case Mode.Normal:
                compCtx.Deriver = new NormalDeriver();
                break;

            case Mode.Dynamic:
                compCtx.Deriver = new DynamicDeriver();
                break;

            default:
                throw new UnreachableException();
            }
            compCtx.Deriver.Init(context, random);

            context.Logger.Debug("Encrypting modules...");

            // Main
            MethodDef entryPoint = defs.OfType <MethodDef>().Single(method => method.Name == "Main");

            stubModule.EntryPoint = entryPoint;

            if (compCtx.EntryPoint.HasAttribute("System.STAThreadAttribute"))
            {
                var attrType = stubModule.CorLibTypes.GetTypeRef("System", "STAThreadAttribute");
                var ctorSig  = MethodSig.CreateInstance(stubModule.CorLibTypes.Void);
                entryPoint.CustomAttributes.Add(new CustomAttribute(
                                                    new MemberRefUser(stubModule, ".ctor", ctorSig, attrType)));
            }
            else if (compCtx.EntryPoint.HasAttribute("System.MTAThreadAttribute"))
            {
                var attrType = stubModule.CorLibTypes.GetTypeRef("System", "MTAThreadAttribute");
                var ctorSig  = MethodSig.CreateInstance(stubModule.CorLibTypes.Void);
                entryPoint.CustomAttributes.Add(new CustomAttribute(
                                                    new MemberRefUser(stubModule, ".ctor", ctorSig, attrType)));
            }

            uint seed = random.NextUInt32();

            compCtx.OriginModule = context.OutputModules[compCtx.ModuleIndex];

            byte[] encryptedModule = compCtx.Encrypt(comp, compCtx.OriginModule, seed,
                                                     progress => context.Logger.Progress((int)(progress * 10000), 10000));
            context.Logger.EndProgress();
            context.CheckCancellation();

            compCtx.EncryptedModule = encryptedModule;

            MutationHelper.InjectKeys(entryPoint,
                                      new[] { 0, 1 },
                                      new[] { encryptedModule.Length >> 2, (int)seed });
            InjectData(stubModule, entryPoint, encryptedModule);

            // Decrypt
            MethodDef decrypter = defs.OfType <MethodDef>().Single(method => method.Name == "Decrypt");

            decrypter.Body.SimplifyMacros(decrypter.Parameters);
            List <Instruction> instrs = decrypter.Body.Instructions.ToList();

            for (int i = 0; i < instrs.Count; i++)
            {
                Instruction instr = instrs[i];
                if (instr.OpCode == OpCodes.Call)
                {
                    var method = (IMethod)instr.Operand;
                    if (method.DeclaringType.Name == "Mutation" &&
                        method.Name == "Crypt")
                    {
                        Instruction ldDst = instrs[i - 2];
                        Instruction ldSrc = instrs[i - 1];
                        Debug.Assert(ldDst.OpCode == OpCodes.Ldloc && ldSrc.OpCode == OpCodes.Ldloc);
                        instrs.RemoveAt(i);
                        instrs.RemoveAt(i - 1);
                        instrs.RemoveAt(i - 2);
                        instrs.InsertRange(i - 2, compCtx.Deriver.EmitDerivation(decrypter, context, (Local)ldDst.Operand, (Local)ldSrc.Operand));
                    }
                    else if (method.DeclaringType.Name == "Lzma" &&
                             method.Name == "Decompress")
                    {
                        MethodDef decomp = comp.GetRuntimeDecompressor(stubModule, member => { });
                        instr.Operand = decomp;
                    }
                }
            }
            decrypter.Body.Instructions.Clear();
            foreach (Instruction instr in instrs)
            {
                decrypter.Body.Instructions.Add(instr);
            }

            // Pack modules
            PackModules(context, compCtx, stubModule, comp, random);
        }
        public bool Restore(MethodDef method)
        {
            this.method = method;
            bool atLeastOneFailed = false;

            if (method == null || method.Body == null)
            {
                return(!atLeastOneFailed);
            }

            var instrs = method.Body.Instructions;

            for (int i = 0; i < instrs.Count; i++)
            {
                var instr = instrs[i];
                if (instr.Operand != null)
                {
                    continue;
                }

                TypeSig    operandType = null, operandTypeTmp;
                OpCode     newOpCode = null;
                SZArraySig arrayType;
                switch (instr.OpCode.Code)
                {
                case Code.Ldelem:
                    arrayType = MethodStack.GetLoadedType(method, instrs, i, 1) as SZArraySig;
                    if (arrayType == null)
                    {
                        break;
                    }
                    operandTypeTmp = arrayType.Next;
                    if (operandTypeTmp == null)
                    {
                        newOpCode = OpCodes.Ldelem_Ref;
                    }
                    else
                    {
                        switch (operandTypeTmp.ElementType)
                        {
                        case ElementType.Boolean: newOpCode = OpCodes.Ldelem_I1; break;

                        case ElementType.Char: newOpCode = OpCodes.Ldelem_U2; break;

                        case ElementType.I:  newOpCode = OpCodes.Ldelem_I; break;

                        case ElementType.I1: newOpCode = OpCodes.Ldelem_I1; break;

                        case ElementType.I2: newOpCode = OpCodes.Ldelem_I2; break;

                        case ElementType.I4: newOpCode = OpCodes.Ldelem_I4; break;

                        case ElementType.I8: newOpCode = OpCodes.Ldelem_I8; break;

                        case ElementType.U:  newOpCode = OpCodes.Ldelem_I; break;

                        case ElementType.U1: newOpCode = OpCodes.Ldelem_U1; break;

                        case ElementType.U2: newOpCode = OpCodes.Ldelem_U2; break;

                        case ElementType.U4: newOpCode = OpCodes.Ldelem_U4; break;

                        case ElementType.U8: newOpCode = OpCodes.Ldelem_I8; break;

                        case ElementType.R4: newOpCode = OpCodes.Ldelem_R4; break;

                        case ElementType.R8: newOpCode = OpCodes.Ldelem_R8; break;

                        default:             newOpCode = OpCodes.Ldelem_Ref; break;
                            //TODO: Ldelem
                        }
                    }
                    break;

                case Code.Stelem:
                    arrayType = MethodStack.GetLoadedType(method, instrs, i, 2) as SZArraySig;
                    if (arrayType == null)
                    {
                        break;
                    }
                    operandTypeTmp = arrayType.Next;
                    if (operandTypeTmp == null)
                    {
                        newOpCode = OpCodes.Stelem_Ref;
                    }
                    else
                    {
                        switch (operandTypeTmp.ElementType)
                        {
                        case ElementType.U:
                        case ElementType.I:  newOpCode = OpCodes.Stelem_I; break;

                        case ElementType.Boolean:
                        case ElementType.U1:
                        case ElementType.I1: newOpCode = OpCodes.Stelem_I1; break;

                        case ElementType.Char:
                        case ElementType.U2:
                        case ElementType.I2: newOpCode = OpCodes.Stelem_I2; break;

                        case ElementType.U4:
                        case ElementType.I4: newOpCode = OpCodes.Stelem_I4; break;

                        case ElementType.U8:
                        case ElementType.I8: newOpCode = OpCodes.Stelem_I8; break;

                        case ElementType.R4: newOpCode = OpCodes.Stelem_R4; break;

                        case ElementType.R8: newOpCode = OpCodes.Stelem_R8; break;

                        default: newOpCode = OpCodes.Stelem_Ref; break;
                            //TODO: Stelem
                        }
                    }
                    break;

                case Code.Ldelema:
                    arrayType = MethodStack.GetLoadedType(method, instrs, i, 1) as SZArraySig;
                    if (arrayType == null)
                    {
                        break;
                    }
                    operandType = arrayType.Next;
                    if (!operandType.IsValueType)
                    {
                        newOpCode   = OpCodes.Ldelem_Ref;
                        operandType = null;
                    }
                    break;

                case Code.Ldobj:
                    operandType = GetPtrElementType(MethodStack.GetLoadedType(method, instrs, i, 0));
                    break;

                case Code.Stobj:
                    operandType = MethodStack.GetLoadedType(method, instrs, i, 0);
                    if (!IsValidType(operandType))
                    {
                        operandType = GetPtrElementType(MethodStack.GetLoadedType(method, instrs, i, 1));
                    }
                    break;

                default:
                    continue;
                }
                if (newOpCode == null && !IsValidType(operandType))
                {
                    atLeastOneFailed = true;
                    continue;
                }

                instr.Operand = operandType.ToTypeDefOrRef();
                if (newOpCode != null)
                {
                    instr.OpCode = newOpCode;
                }
            }

            return(!atLeastOneFailed);
        }
Example #51
0
        private MosaInstruction ResolveInstruction(MethodDef methodDef, CilBody body, int index, GenericArgumentResolver resolver)
        {
            Instruction instruction = body.Instructions[index];
            int?        prev        = index == 0 ? null : (int?)body.Instructions[index - 1].Offset;
            int?        next        = index == body.Instructions.Count - 1 ? null : (int?)body.Instructions[index + 1].Offset;

            object operand = instruction.Operand;

            // Special case: newarr instructions need to have their operand changed now so that the type is a SZArray
            if (instruction.OpCode == OpCodes.Newarr)
            {
                var typeSig    = resolver.Resolve(((ITypeDefOrRef)instruction.Operand).ToTypeSig());
                var szArraySig = new SZArraySig(typeSig);
                operand = metadata.Loader.GetType(szArraySig);
            }
            else if (instruction.Operand is ITypeDefOrRef)
            {
                operand = ResolveTypeOperand((ITypeDefOrRef)instruction.Operand, resolver);
            }
            else if (instruction.Operand is MemberRef)
            {
                MemberRef memberRef = (MemberRef)instruction.Operand;
                if (memberRef.IsFieldRef)
                {
                    operand = ResolveFieldOperand(memberRef, resolver);
                }
                else
                {
                    operand = ResolveMethodOperand(memberRef, resolver);
                }
            }
            else if (instruction.Operand is IField)
            {
                operand = ResolveFieldOperand((IField)instruction.Operand, resolver);
            }
            else if (instruction.Operand is IMethod)
            {
                operand = ResolveMethodOperand((IMethod)instruction.Operand, resolver);
            }
            else if (instruction.Operand is Local)
            {
                operand = ((Local)instruction.Operand).Index;
            }
            else if (instruction.Operand is Parameter)
            {
                operand = ((Parameter)instruction.Operand).Index;
            }
            else if (instruction.Operand is Instruction)
            {
                operand = (int)((Instruction)instruction.Operand).Offset;
            }
            else if (instruction.Operand is Instruction[])
            {
                Instruction[] targets = (Instruction[])instruction.Operand;
                int[]         offsets = new int[targets.Length];
                for (int i = 0; i < offsets.Length; i++)
                {
                    offsets[i] = (int)targets[i].Offset;
                }
                operand = offsets;
            }
            else if (instruction.Operand is string)
            {
                operand = metadata.Cache.GetStringId((string)instruction.Operand);
            }

            ushort code = (ushort)instruction.OpCode.Code;

            if (code > 0xff)                // To match compiler's opcode values
            {
                code = (ushort)(0x100 + (code & 0xff));
            }

            return(new MosaInstruction((int)instruction.Offset, code, operand, prev, next));
        }
Example #52
0
 public void ExcludeMethod(ConfuserContext context, MethodDef method)
 {
     ProtectionParameters.GetParameters(context, method).Remove(this);
 }
Example #53
0
 public SelectCtorTransform(MethodDef ctorDef) => this.ctorDef = ctorDef;
Example #54
0
        public override bool ResetMembers(bool check, AgentType agentType, bool clear, MethodDef method = null, PropertyDef property = null)
        {
            bool bReset = false;

            if (this._time != null)
            {
                bReset |= this._time.ResetMembers(check, agentType, clear, property);
            }

            bReset |= base.ResetMembers(check, agentType, clear, method, property);

            return(bReset);
        }
Example #55
0
 public abstract void AfterInjectionCallback(MethodDef injectedMethodDef, object obj);
Example #56
0
 public OriginalInstructionBytesReader(MethodDef method)
 {
     //TODO: This fails and returns null if it's a CorMethodDef!
     stream = GetImageStream(method.Module, (uint)method.RVA + method.Body.HeaderSize);
 }
Example #57
0
        async Task <CompilerMetadataReference[]> DecompileAndGetRefsAsync(MethodDef method, MethodSourceStatement?methodSourceStatement)
        {
            await DecompileAsync(method, methodSourceStatement).ConfigureAwait(false);

            return(await CreateCompilerMetadataReferencesAsync(method, assemblyReferenceResolver, languageCompiler.RequiredAssemblyReferences, decompileCodeState.CancellationToken).ConfigureAwait(false));
        }
Example #58
0
 public virtual void DecompileMethod(MethodDef method, ITextOutput output, DecompilationOptions options)
 {
     WriteCommentLine(output, TypeToString(method.DeclaringType, true) + "." + method.Name);
 }
Example #59
0
        async Task StartDecompileAsync(MethodDef method, MethodSourceStatement?methodSourceStatement)
        {
            bool   canCompile = false, canceled = false;
            var    assemblyReferences = Array.Empty <CompilerMetadataReference>();
            string mainCode, hiddenCode;
            var    refSpan = new Span(0, 0);

            try {
                assemblyReferences = await DecompileAndGetRefsAsync(method, methodSourceStatement);

                mainCode   = decompileCodeState.MainOutput.ToString();
                hiddenCode = decompileCodeState.HiddenOutput.ToString();
                canCompile = true;
                var span = decompileCodeState.MainOutput.Span;
                if (span != null)
                {
                    refSpan = span.Value;
                }
            }
            catch (OperationCanceledException) {
                canceled   = true;
                mainCode   = string.Empty;
                hiddenCode = string.Empty;
            }
            catch (Exception ex) {
                mainCode   = ex.ToString();
                hiddenCode = string.Empty;
            }

            const string MAIN_CODE_NAME = "main";
            var          codeDocs       = Array.Empty <ICodeDocument>();

            if (!canceled)
            {
                // This helps a little to speed up the code
                ProfileOptimizationHelper.StartProfile("add-decompiled-code-" + decompiler.UniqueGuid.ToString());
                var docs = new List <IDecompiledDocument>();
                docs.Add(new DecompiledDocument(mainCode, MAIN_CODE_NAME));
                if (hiddenCode != string.Empty)
                {
                    docs.Add(new DecompiledDocument(hiddenCode, MAIN_CODE_NAME + ".g"));
                }
                codeDocs = languageCompiler.AddDecompiledCode(new DecompiledCodeResult(docs.ToArray(), assemblyReferences, assemblyReferenceResolver, PlatformHelper.GetPlatform(method.Module)));
            }

            decompileCodeState?.Dispose();
            decompileCodeState = null;

            foreach (var doc in codeDocs)
            {
                doc.TextView.Properties.AddProperty(editCodeTextViewKey, this);
            }
            Documents.AddRange(codeDocs.Select(a => new CodeDocument(a)));
            SelectedDocument = Documents.FirstOrDefault(a => a.NameNoExtension == MAIN_CODE_NAME) ?? Documents.FirstOrDefault();
            foreach (var doc in Documents)
            {
                if (doc.NameNoExtension == MAIN_CODE_NAME && refSpan.End <= doc.TextView.TextSnapshot.Length)
                {
                    doc.Initialize(new SnapshotPoint(doc.TextView.TextSnapshot, refSpan.Start));
                }
                else
                {
                    doc.Initialize(new SnapshotPoint(doc.TextView.TextSnapshot, 0));
                }
            }

            CanCompile    = canCompile;
            HasDecompiled = true;
            OnPropertyChanged(nameof(HasDecompiled));
        }
Example #60
0
        static Task <CompilerMetadataReference[]> CreateCompilerMetadataReferencesAsync(MethodDef method, AssemblyReferenceResolver assemblyReferenceResolver, IEnumerable <string> extraAssemblyReferences, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var modules = new HashSet <ModuleDef>(new MetadataReferenceFinder(method.Module, cancellationToken).Find(extraAssemblyReferences));

            var mdRefs = new List <CompilerMetadataReference>();

            foreach (var module in modules)
            {
                cancellationToken.ThrowIfCancellationRequested();

                CompilerMetadataReference?cmr;
                if (module.IsManifestModule)
                {
                    cmr = assemblyReferenceResolver.Create(module.Assembly);
                }
                else
                {
                    cmr = assemblyReferenceResolver.Create(module);
                }
                if (cmr == null)
                {
                    continue;
                }

                mdRefs.Add(cmr.Value);
            }

            return(Task.FromResult(mdRefs.ToArray()));
        }