void InjectData(ModuleDef stubModule, MethodDef method, byte[] data) { var dataType = new TypeDefUser("", "DataType", stubModule.CorLibTypes.GetTypeRef("System", "ValueType")); dataType.Layout = TypeAttributes.ExplicitLayout; dataType.Visibility = TypeAttributes.NestedPrivate; dataType.IsSealed = true; dataType.ClassLayout = new ClassLayoutUser(1, (uint)data.Length); stubModule.GlobalType.NestedTypes.Add(dataType); var dataField = new FieldDefUser("DataField", new FieldSig(dataType.ToTypeSig())) { IsStatic = true, HasFieldRVA = true, InitialValue = data, Access = FieldAttributes.CompilerControlled }; stubModule.GlobalType.Fields.Add(dataField); MutationHelper.ReplacePlaceholder(method, arg => { var repl = new List <Instruction>(); repl.AddRange(arg); repl.Add(Instruction.Create(OpCodes.Dup)); repl.Add(Instruction.Create(OpCodes.Ldtoken, dataField)); repl.Add(Instruction.Create(OpCodes.Call, stubModule.Import( typeof(RuntimeHelpers).GetMethod("InitializeArray")))); return(repl.ToArray()); }); }
private void Encodestring(Context krawk, MethodDef method, int i) { body = method.Body; string key = RandomString(); string key2 = RandomString(); string key3 = RandomString(); FieldDef field = new FieldDefUser(Guid.NewGuid().ToString(), new FieldSig(krawk.ManifestModule.CorLibTypes.String), FieldAttributes.Public | FieldAttributes.Static); FieldDef field2 = new FieldDefUser(Guid.NewGuid().ToString(), new FieldSig(krawk.ManifestModule.CorLibTypes.String), FieldAttributes.Public | FieldAttributes.Static); krawk.GlobalType.Fields.Add(field); krawk.GlobalType.Fields.Add(field2); int cctor = krawk.cctor.Body.Instructions.Count; int cctor2 = krawk.cctor.Body.Instructions.Count; string operand = method.Body.Instructions[i].Operand.ToString(); string newoperand = EnCipher(Convert.ToBase64String(Encoding.UTF8.GetBytes(operand)), key, key2, key3); string newoperand2 = newoperand.Substring(0, newoperand.Length / 2); string newoperand3 = newoperand.Substring(newoperand2.Length); krawk.cctor.Body.Instructions.Insert(cctor - 1, Instruction.Create(OpCodes.Stsfld, field)); krawk.cctor.Body.Instructions.Insert(cctor - 1, Instruction.Create(OpCodes.Call, krawk.ManifestModule.Import(typeof(string).GetMethod("Concat", new Type[] { typeof(object), typeof(object) })))); krawk.cctor.Body.Instructions.Insert(cctor - 1, Instruction.Create(OpCodes.Ldstr, newoperand3)); krawk.cctor.Body.Instructions.Insert(cctor - 1, Instruction.Create(OpCodes.Ldstr, newoperand2)); krawk.cctor.Body.Instructions.Insert(cctor2 - 1, Instruction.Create(OpCodes.Stsfld, field2)); krawk.cctor.Body.Instructions.Insert(cctor2 - 1, Instruction.Create(OpCodes.Ldstr, key.ToString())); body.Instructions[i] = Instruction.Create(OpCodes.Ldsfld, field); body.Instructions.Insert(i + 1, Instruction.Create(OpCodes.Ldsfld, field2)); var krawk_DecryptMtd = decryptionMethod(krawk); Krawk.Helpers.InjectDynamic.InjectString(krawk_DecryptMtd, "a", key2); Krawk.Helpers.InjectDynamic.InjectString(krawk_DecryptMtd, "b", key3); Krawk.Helpers.MutationHelperNative.InjectKey(krawk_DecryptMtd, 0, native_); body.Instructions.Insert(i + 2, Instruction.Create(OpCodes.Call, krawk_DecryptMtd)); }
private void PatchNuclearUpgrade_SubRoot(ModuleDefMD module) { var subRootType = module.Find("SubRoot", false); var fieldToAdd = new FieldDefUser("nuclearUpgrade", new FieldSig(module.CorLibTypes.Int32)) { Attributes = FieldAttributes.Public | FieldAttributes.NotSerialized }; subRootType.Fields.Add(fieldToAdd); var setCyclopsUpgradesMethod = subRootType.FindMethod("SetCyclopsUpgrades"); var importer = new Importer(module); var setCyclopsUpgradesPatchMethod = importer.Import(typeof(NuclearUpgradeHelper).GetMethod("SetCyclopsUpgrades")); var body = setCyclopsUpgradesMethod.Body = new CilBody(); body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction()); body.Instructions.Add(OpCodes.Call.ToInstruction(setCyclopsUpgradesPatchMethod)); body.Instructions.Add(OpCodes.Ret.ToInstruction()); PatchNuclearUpgrade_SubRoot_Update(module, subRootType, importer); }
static void InjectMidUpdate() { var update = typeDef_Player.GetMethod("RealUpdate" /* method is wrapped */, MethodFlags.Public | MethodFlags.Instance, typeSys.Int32.ToTypeDefOrRef()); var grabItems = typeDef_Player.GetMethod("GrabItems", MethodFlags.Public | MethodFlags.Instance, typeSys.Int32.ToTypeDefOrRef()); MethodDef invokeMidUpdate; var onMidUpdateDel = context.CreateDelegate("Terraria.PrismInjections", "Player_MidUpdateDel", typeSys.Void, out invokeMidUpdate, typeDef_Player.ToTypeSig(), typeSys.Int32); var onMidUpdate = new FieldDefUser("P_OnMidUpdate", new FieldSig(onMidUpdateDel.ToTypeSig()), FieldAttributes.Public | FieldAttributes.Static); typeDef_Player.Fields.Add(onMidUpdate); var ub = update.Body; using (var uproc = ub.GetILProcessor()) { OpCode[] callGrabItems = { OpCodes.Ldarg_0, // this OpCodes.Ldarg_1, // id OpCodes.Call, // Player.GrabItems OpCodes.Ldsfld, // Main.mapFullScreen OpCodes.Brtrue }; Instruction instrs; int startInd = 0; while (true) { instrs = ub.FindInstrSeqStart(callGrabItems, startInd); if (instrs == null) { break; } startInd = ub.Instructions.IndexOf(instrs) + 3; var mtdToCall = instrs.Next(uproc).Next(uproc).Operand as MethodDef; if (mtdToCall == null) { continue; } // close enough if (context.SigComparer.Equals(mtdToCall.DeclaringType, grabItems.DeclaringType) && mtdToCall.FullName == grabItems.FullName) { break; } } instrs = instrs.Next(uproc).Next(uproc).Next(uproc); uproc.InsertBefore(instrs, Instruction.Create(OpCodes.Ldsfld, onMidUpdate)); uproc.EmitWrapperCall(invokeMidUpdate, instrs); } }
private static void HijackFont(ModuleDefMD module) { TypeDef UICoords = module.Find("UICoords", false); FieldDef m_Text = UICoords.Fields.First(f => f.Name == "m_Text"); PropertyDef font = m_Text.DeclaringType.FindProperty("font"); TypeSig fontType = font.DeclaringType.ToTypeSig(); FieldDef Exo = new FieldDefUser("Exo", new FieldSig(fontType), FieldAttributes.Public | FieldAttributes.Static); UICoords.Fields.Add(Exo); var body = UICoords.Methods.First(m => m.Name == "OnPool").Body.Instructions; body.Insert(body.Count - 1, OpCodes.Ldarg_0.ToInstruction()); body.Insert(body.Count - 1, OpCodes.Ldfld.ToInstruction(m_Text)); body.Insert(body.Count - 1, OpCodes.Callvirt.ToInstruction(font.GetMethod)); body.Insert(body.Count - 1, OpCodes.Stsfld.ToInstruction(Exo)); /* * 11 002B ldarg.0 * 12 002C ldfld class [UnityEngine.UI]UnityEngine.UI.Text UICoords::m_Text * 13 0031 callvirt instance class [UnityEngine]UnityEngine.Font [UnityEngine.UI]UnityEngine.UI.Text::get_font() * 14 0036 stsfld class [UnityEngine]UnityEngine.Font UICoords::Exo */ }
/// <summary> /// Introduces the member. /// </summary> /// <param name="moduleDefinition">The module definition.</param> /// <param name="memberName">Name of the member.</param> /// <param name="memberType">Type of the member.</param> /// <param name="isStatic">if set to <c>true</c> [is static].</param> /// <param name="adviceType">The advice.</param> /// <param name="advisedType">The type definition.</param> /// <param name="markerAttribute">The marker attribute ctor.</param> /// <param name="introducedMemberName">Name of the introduced member.</param> /// <param name="isNotSerialized">if set to <c>true</c> [is not serialized].</param> /// <param name="context">The context.</param> private void IntroduceMember(ModuleDef moduleDefinition, string memberName, ITypeDefOrRef memberType, bool isStatic, ITypeDefOrRef adviceType, TypeDef advisedType, ICustomAttributeType markerAttribute, string introducedMemberName, bool isNotSerialized, WeavingContext context) { if (IsIntroduction(memberType, out var introducedFieldType, out var isShared, context)) { var introducedFieldName = IntroductionRules.GetName(adviceType.Namespace, adviceType.Name, introducedMemberName, memberName, isShared); lock (advisedType.Fields) { if (advisedType.Fields.All(f => f.Name != introducedFieldName)) { var fieldAttributes = (InjectAsPrivate ? FieldAttributes.Private : FieldAttributes.Public) | (isNotSerialized ? FieldAttributes.NotSerialized : 0); if (isStatic) { fieldAttributes |= FieldAttributes.Static; } Logging.WriteDebug("Introduced field type '{0}'", introducedFieldType.FullName); var introducedFieldTypeReference = TypeImporter.Import(moduleDefinition, introducedFieldType.ToTypeSig()); var introducedField = new FieldDefUser(introducedFieldName, new FieldSig(introducedFieldTypeReference), fieldAttributes); introducedField.CustomAttributes.Add(new CustomAttribute(markerAttribute)); advisedType.Fields.Add(introducedField); } } } }
/// <summary> /// Adds a public automatic property. /// </summary> /// <param name="typeDefinition">The type definition.</param> /// <param name="name">The name.</param> /// <param name="typeReference">The type reference.</param> /// <param name="moduleDefinition">The module definition.</param> /// <param name="typeResolver">The type resolver.</param> internal static void AddPublicAutoProperty(this TypeDef typeDefinition, string name, ITypeDefOrRef typeReference, ModuleDef moduleDefinition, TypeResolver typeResolver) { var compilerGeneratedAttribute = moduleDefinition.SafeImport(typeof(CompilerGeneratedAttribute)); // backing field var backingFieldDefinition = new FieldDefUser($"<{name}>k__BackingField", new FieldSig(typeReference.ToTypeSig()), FieldAttributes.Private); backingFieldDefinition.CustomAttributes.Add(moduleDefinition.CreateCustomAttribute(compilerGeneratedAttribute, typeResolver)); typeDefinition.Fields.Add(backingFieldDefinition); // property... var propertyDefinition = new PropertyDefUser(name, new PropertySig(true, typeReference.ToTypeSig())); typeDefinition.Properties.Add(propertyDefinition); // ...setter propertyDefinition.SetMethod = CreatePropertyMethod("set_" + name, moduleDefinition.CorLibTypes.Void, Tuple.Create(typeReference.ToTypeSig(), "value")); propertyDefinition.SetMethod.CustomAttributes.Add(moduleDefinition.CreateCustomAttribute(compilerGeneratedAttribute, typeResolver)); typeDefinition.Methods.Add(propertyDefinition.SetMethod); var setterParameter = new ParamDefUser("value"); propertyDefinition.SetMethod.ParamDefs.Add(setterParameter); var setterInstructions = new Instructions(propertyDefinition.SetMethod.Body.Instructions, moduleDefinition); setterInstructions.Emit(OpCodes.Ldarg_0); setterInstructions.Emit(OpCodes.Ldarg_1); setterInstructions.Emit(OpCodes.Stfld, backingFieldDefinition); setterInstructions.Emit(OpCodes.Ret); // ...getter propertyDefinition.GetMethod = CreatePropertyMethod("get_" + name, typeReference.ToTypeSig()); propertyDefinition.GetMethod.CustomAttributes.Add(moduleDefinition.CreateCustomAttribute(compilerGeneratedAttribute, typeResolver)); typeDefinition.Methods.Add(propertyDefinition.GetMethod); var getterInstructions = new Instructions(propertyDefinition.GetMethod.Body.Instructions, moduleDefinition); getterInstructions.Emit(OpCodes.Ldarg_0); getterInstructions.Emit(OpCodes.Ldfld, backingFieldDefinition); getterInstructions.Emit(OpCodes.Ret); }
/// <summary> /// Clones the specified origin FieldDef. /// </summary> /// <param name="origin">The origin FieldDef.</param> /// <returns>The cloned FieldDef.</returns> static FieldDefUser Clone(FieldDef origin) { var ret = new FieldDefUser(origin.Name, null, origin.Attributes); ret.HasFieldRVA = origin.HasFieldRVA; return(ret); }
private void InjectNewClasses(Save save, ModuleDefMD originalModule) { save.NewClasses.ForEach(newClass => { var className = Helpers.GetClassFromFullName(newClass.FullName); var newType = new TypeDefUser(className, originalModule.CorLibTypes.Object.TypeDefOrRef); newType.Attributes = (dnlib.DotNet.TypeAttributes)Helpers.GetTypeAttributes(newClass.Attributes); originalModule.Types.Add(newType); newClass.Fields.ForEach(field => { var fieldName = Helpers.GetNameFromFullName(field.FullName); var fieldTypeNamespace = Helpers.GetNameSpaceOfTypeFromFullName(field.FullName); var fieldType = Helpers.GetTypeFromFullName(field.FullName); var fieldSig = new FieldSig(originalModule.CorLibTypes.GetTypeRef(fieldTypeNamespace, fieldType).ToTypeSig()); var attributes = (FieldAttributes)Helpers.GetFieldAttributes(field.Attributes); var newField = new FieldDefUser(fieldName, fieldSig, attributes); newType.Fields.Add(newField); }); newClass.Methods.ForEach(method => { var methodName = Helpers.GetNameFromFullName(method.FullName); var methodImplFlags = MethodImplAttributes.IL | MethodImplAttributes.Managed; var methodFlags = (MethodAttributes)Helpers.GetMethodAttributes(method.Attributes); }); }); }
// This will open the current assembly, add a new class and method to it, // and then save the assembly to disk. public static void Run() { // Open the current module var mod = ModuleDefMD.Load(typeof(Example2).Module); // Create a new public class that derives from System.Object var type1 = new TypeDefUser("My.Namespace", "MyType", mod.CorLibTypes.Object.TypeDefOrRef); type1.Attributes = TypeAttributes.Public | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.AnsiClass; // Make sure to add it to the module or any other type in the module. This is // not a nested type, so add it to mod.Types. mod.Types.Add(type1); // Create a public static System.Int32 field called MyField var field1 = new FieldDefUser("MyField", new FieldSig(mod.CorLibTypes.Int32), FieldAttributes.Public | FieldAttributes.Static); // Add it to the type we created earlier type1.Fields.Add(field1); // Add a static method that adds both inputs and the static field // and returns the result var methImplFlags = MethodImplAttributes.IL | MethodImplAttributes.Managed; var methFlags = MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot; var meth1 = new MethodDefUser("MyMethod", MethodSig.CreateStatic(mod.CorLibTypes.Int32, mod.CorLibTypes.Int32, mod.CorLibTypes.Int32), methImplFlags, methFlags); type1.Methods.Add(meth1); // Create the CIL method body var body = new CilBody(); meth1.Body = body; // Name the 1st and 2nd args a and b, respectively meth1.ParamDefs.Add(new ParamDefUser("a", 1)); meth1.ParamDefs.Add(new ParamDefUser("b", 2)); // Create a local. We don't really need it but let's add one anyway var local1 = new Local(mod.CorLibTypes.Int32); body.Variables.Add(local1); // Add the instructions, and use the useless local body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction()); body.Instructions.Add(OpCodes.Ldarg_1.ToInstruction()); body.Instructions.Add(OpCodes.Add.ToInstruction()); body.Instructions.Add(OpCodes.Ldsfld.ToInstruction(field1)); body.Instructions.Add(OpCodes.Add.ToInstruction()); body.Instructions.Add(OpCodes.Stloc.ToInstruction(local1)); body.Instructions.Add(OpCodes.Ldloc.ToInstruction(local1)); body.Instructions.Add(OpCodes.Ret.ToInstruction()); // Save the assembly to a file on disk mod.Write(@"C:\saved-assembly.dll"); }
protected override void Execute(ConfuserContext context, ProtectionParameters parameters) { using (IEnumerator <MethodDef> enumerator = parameters.Targets.OfType <MethodDef>().GetEnumerator()) { while (enumerator.MoveNext()) { MethodDef method = enumerator.Current; bool flag = !method.HasBody; if (!flag) { method.Body.SimplifyMacros(method.Parameters); IList <Instruction> instructions = method.Body.Instructions; for (int i = 0; i < instructions.Count; i++) { object operand = instructions[i].Operand; Local local = operand as Local; bool flag2 = local != null; if (flag2) { bool flag3 = !this.convertedLocals.ContainsKey(local); FieldDef def; if (flag3) { def = new FieldDefUser(RandomString(3), new FieldSig(local.Type), FieldAttributes.FamANDAssem | FieldAttributes.Family | FieldAttributes.Static); context.CurrentModule.GlobalType.Fields.Add(def); this.convertedLocals.Add(local, def); } else { def = this.convertedLocals[local]; } OpCode eq = null; switch (instructions[i].OpCode.Code) { case Code.Ldloc: eq = OpCodes.Ldsfld; break; case Code.Ldloca: eq = OpCodes.Ldsflda; break; case Code.Stloc: eq = OpCodes.Stsfld; break; } instructions[i].OpCode = eq; instructions[i].Operand = def; } } this.convertedLocals.ToList <KeyValuePair <Local, FieldDef> >().ForEach(delegate(KeyValuePair <Local, FieldDef> x) { method.Body.Variables.Remove(x.Key); }); this.convertedLocals = new Dictionary <Local, FieldDef>(); } } } }
private static FieldDef CreateField(ModuleDefMD module) { FieldAttributes attrb = FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.HasFieldRVA | FieldAttributes.CompilerControlled; FieldDef field = new FieldDefUser("", new FieldSig(module.CorLibTypes.String), attrb); RenameTask.Rename(field); return(field); }
static FieldDef CopyFieldDef(FieldDef fieldDef) { var newFieldDef = new FieldDefUser(fieldDef.Name, null, fieldDef.Attributes); newFieldDef.Signature = Importer.Import(fieldDef.Signature); return(newFieldDef); }
// 这将打开当前程序集,向其添加新类和方法,然后将程序集保存到磁盘。 public static void Run() { // 打开当前模块 ModuleDefMD mod = ModuleDefMD.Load(typeof(Example2).Module); // 创建一个派生自System.Object的新公共类 TypeDef typeDef = new TypeDefUser("My.Namespace", "MyType", mod.CorLibTypes.Object.TypeDefOrRef); typeDef.Attributes = TypeAttributes.Public | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.AnsiClass; // 确保将其添加到模块或模块中的任何其他类型。 // 这不是嵌套类型,因此将其添加到mod.Types。 mod.Types.Add(typeDef); // 创建一个名为MyField的公共静态System.Int32字段 FieldDef fieldDef = new FieldDefUser("MyField", new FieldSig(mod.CorLibTypes.Int32), FieldAttributes.Public | FieldAttributes.Static); // 将其添加到我们之前创建的类型中 typeDef.Fields.Add(fieldDef); // 添加一个静态方法,添加输入和静态字段并返回结果 MethodImplAttributes methImplFlags = MethodImplAttributes.IL | MethodImplAttributes.Managed; MethodAttributes methFlags = MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot; MethodDef methodDef = new MethodDefUser( "MyMethod", MethodSig.CreateStatic(mod.CorLibTypes.Int32, mod.CorLibTypes.Int32, mod.CorLibTypes.Int32), methImplFlags, methFlags ); typeDef.Methods.Add(methodDef); // 创建CIL方法体 CilBody body = new CilBody(); methodDef.Body = body; // 分别命名第一和第二个参数a和b methodDef.ParamDefs.Add(new ParamDefUser("a", 1)); methodDef.ParamDefs.Add(new ParamDefUser("b", 2)); // 创建一个本地。我们真的不需要它,但无论如何我们要加一个 Local local1 = new Local(mod.CorLibTypes.Int32); body.Variables.Add(local1); // 添加说明,并使用无用的本地 body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction()); body.Instructions.Add(OpCodes.Ldarg_1.ToInstruction()); body.Instructions.Add(OpCodes.Add.ToInstruction()); body.Instructions.Add(OpCodes.Ldsfld.ToInstruction(fieldDef)); body.Instructions.Add(OpCodes.Add.ToInstruction()); body.Instructions.Add(OpCodes.Stloc.ToInstruction(local1)); body.Instructions.Add(OpCodes.Ldloc.ToInstruction(local1)); body.Instructions.Add(OpCodes.Ret.ToInstruction()); // 将程序集保存到磁盘上的文件中 mod.Write(@"saved-assembly.dll"); }
public void ProcessMethod(MethodDef method) { var instructions = method.Body.Instructions; for (int i = 0; i < instructions.Count; i++) { if (instructions[i].Operand is Local local) { FieldDef def = null; if (!convertedLocals.ContainsKey(local)) { def = new FieldDefUser("卐AsStrongAsFuckᅠByᅠCharter卍" + Convert.ToBase64String(Encoding.Default.GetBytes(Runtime.GetRandomName() + method.Name)), new FieldSig(local.Type), FieldAttributes.Public | FieldAttributes.Static); Module.GlobalType.Fields.Add(def); convertedLocals.Add(local, def); } else { def = convertedLocals[local]; } OpCode eq = null; switch (instructions[i].OpCode.Code) { case Code.Ldloc: case Code.Ldloc_S: case Code.Ldloc_0: case Code.Ldloc_1: case Code.Ldloc_2: case Code.Ldloc_3: eq = OpCodes.Ldsfld; break; case Code.Ldloca: case Code.Ldloca_S: eq = OpCodes.Ldsflda; break; case Code.Stloc: case Code.Stloc_0: case Code.Stloc_1: case Code.Stloc_2: case Code.Stloc_3: case Code.Stloc_S: eq = OpCodes.Stsfld; break; } if (eq == null) { Console.WriteLine(instructions[i].OpCode); } instructions[i].OpCode = eq; instructions[i].Operand = def; } } }
/// <summary> /// Clones the specified origin FieldDef. /// </summary> /// <param name="origin">The origin FieldDef.</param> /// <returns>The cloned FieldDef.</returns> private static FieldDefUser Clone(FieldDef origin) { //This was modified to also clone FieldOffset and MarshalType which is required for the structs used to read the pe header var ret = new FieldDefUser(origin.Name, null, origin.Attributes) { FieldOffset = origin.FieldOffset, MarshalType = origin.MarshalType }; return(ret); }
public static void Process(ModuleDef module, MethodDef method) { var instructions = method.Body.Instructions; foreach (var t in instructions) { if (!(t.Operand is Local local)) { continue; } FieldDef def; if (!convertedLocals.ContainsKey(local)) { def = new FieldDefUser(RenamerPhase.GenerateString(RenamerPhase.RenameMode.Normal), new FieldSig(local.Type), FieldAttributes.Public | FieldAttributes.Static); module.GlobalType.Fields.Add(def); convertedLocals.Add(local, def); } else { def = convertedLocals[local]; } OpCode eq = null; switch (t.OpCode.Code) { case Code.Ldloc: case Code.Ldloc_S: case Code.Ldloc_0: case Code.Ldloc_1: case Code.Ldloc_2: case Code.Ldloc_3: eq = OpCodes.Ldsfld; break; case Code.Ldloca: case Code.Ldloca_S: eq = OpCodes.Ldsflda; break; case Code.Stloc: case Code.Stloc_0: case Code.Stloc_1: case Code.Stloc_2: case Code.Stloc_3: case Code.Stloc_S: eq = OpCodes.Stsfld; break; } t.OpCode = eq; t.Operand = def; } }
public void ProcessMethod(MethodDef method, ModuleDef modulee) { var instructions = method.Body.Instructions; for (int i = 0; i < instructions.Count; i++) { if (instructions[i].Operand is Local local) { FieldDef def = null; if (!convertedLocals.ContainsKey(local)) { def = new FieldDefUser("Beds-Protector-The-Quick-Brown-Fox-Jumped-Over-The-Lazy-Dog", new FieldSig(local.Type), FieldAttributes.Public | FieldAttributes.Static); modulee.GlobalType.Fields.Add(def); convertedLocals.Add(local, def); } else { def = convertedLocals[local]; } OpCode eq = null; switch (instructions[i].OpCode.Code) { case Code.Ldloc: case Code.Ldloc_S: case Code.Ldloc_0: case Code.Ldloc_1: case Code.Ldloc_2: case Code.Ldloc_3: eq = OpCodes.Ldsfld; break; case Code.Ldloca: case Code.Ldloca_S: eq = OpCodes.Ldsflda; break; case Code.Stloc: case Code.Stloc_0: case Code.Stloc_1: case Code.Stloc_2: case Code.Stloc_3: case Code.Stloc_S: eq = OpCodes.Stsfld; break; } instructions[i].OpCode = eq; instructions[i].Operand = def; } } }
public FieldDef create(byte[] data) { var arrayType = getArrayType(data.LongLength); var fieldSig = new FieldSig(new ValueTypeSig(arrayType)); var attrs = FieldAttributes.Assembly | FieldAttributes.Static; var field = new FieldDefUser(string.Format("field_{0}", unique++), fieldSig, attrs); module.UpdateRowId(field); field.HasFieldRVA = true; ourType.Fields.Add(field); var iv = new byte[data.Length]; Array.Copy(data, iv, data.Length); field.InitialValue = iv; return field; }
protected override void Execute(ConfuserContext context, ProtectionParameters parameters) { foreach (var method in parameters.Targets.OfType <MethodDef>()) { if (!method.HasBody) { continue; } method.Body.SimplifyMacros(method.Parameters); var instructions = method.Body.Instructions; for (int i = 0; i < instructions.Count; i++) { if (instructions[i].Operand is Local local) { FieldDef def = null; if (!convertedLocals.ContainsKey(local)) { def = new FieldDefUser(Guid.NewGuid().ToString(), new FieldSig(local.Type), FieldAttributes.Public | FieldAttributes.Static); context.CurrentModule.GlobalType.Fields.Add(def); convertedLocals.Add(local, def); } else { def = convertedLocals[local]; } OpCode eq = null; switch (instructions[i].OpCode.Code) { case Code.Ldloc: eq = OpCodes.Ldsfld; break; case Code.Ldloca: eq = OpCodes.Ldsflda; break; case Code.Stloc: eq = OpCodes.Stsfld; break; } instructions[i].OpCode = eq; instructions[i].Operand = def; } } convertedLocals.ToList().ForEach(x => method.Body.Variables.Remove(x.Key)); convertedLocals = new Dictionary <Local, FieldDef>(); } }
private FieldDef CreateInt32Field(TypeDef type) { Importer importer = new Importer(type.Module); ITypeDefOrRef reference = importer.Import(typeof(Int32)); TypeSig signature = reference.ToTypeSig(); FieldAttributes attributes = FieldAttributes.Static | FieldAttributes.Public; FieldDef field = new FieldDefUser(GetRandomString(60), new FieldSig(signature), attributes); type.Fields.Add(field); return(field); }
public static void Execute(ModuleDefMD module) { cctor = module.GlobalType.FindStaticConstructor(); Dictionary <FieldDef, Tuple <byte[], int> > fields = new Dictionary <FieldDef, Tuple <byte[], int> >(); List <byte> data = new List <byte>(); int count = 0; foreach (var method in module.GetTypes().SelectMany(type => type.Methods)) { if (method.HasBody) { List <Instruction> stringInstr = method.Body.Instructions.Where(instr => instr.OpCode == OpCodes.Ldstr).ToList(); for (int i = 0; i < stringInstr.Count; i++) { byte[] stringByte = Encoding.UTF8.GetBytes(stringInstr[i].Operand as string); data.AddRange(stringByte); FieldDef field = CreateField(module); fields.Add(field, Tuple.Create(stringByte, count)); method.DeclaringType.Fields.Add(field); stringInstr[i].OpCode = OpCodes.Ldsfld; stringInstr[i].Operand = field; count++; } } } staticFields = fields; data = Encrypt(data.ToArray()).ToList(); var dataType = new TypeDefUser("", "", module.CorLibTypes.GetTypeRef("System", "ValueType")); RenameTask.Rename(dataType); dataType.Layout = TypeAttributes.ExplicitLayout; dataType.Visibility = TypeAttributes.NestedPrivate; dataType.IsSealed = true; dataType.ClassLayout = new ClassLayoutUser(1, (uint)data.Count); module.GlobalType.NestedTypes.Add(dataType); var dataField = new FieldDefUser("", new FieldSig(dataType.ToTypeSig())) { IsStatic = true, HasFieldRVA = true, InitialValue = data.ToArray(), Access = FieldAttributes.CompilerControlled }; module.GlobalType.Fields.Add(dataField); GlobalDataField = dataField; RenameTask.Rename(dataField); NETUtils.listener.OnWriterEvent += OnWriterEvent; }
// Token: 0x0600005F RID: 95 RVA: 0x00005D38 File Offset: 0x00003F38 public static void Execute(ModuleDef module) { MethodDef methodDef = module.GlobalType.FindOrCreateStaticConstructor(); foreach (TypeDef typeDef in module.GetTypes()) { bool flag = !typeDef.IsGlobalModuleType; if (flag) { foreach (MethodDef methodDef2 in typeDef.Methods) { bool flag2 = !methodDef2.IsConstructor && methodDef2.Body != null && methodDef2.HasBody && methodDef2.Body.HasInstructions && !methodDef2.FullName.Contains("My.") && !methodDef2.FullName.Contains(".My") && !methodDef2.IsConstructor && !methodDef2.DeclaringType.IsGlobalModuleType; if (flag2) { IList <Instruction> instructions = methodDef2.Body.Instructions; for (int i = 0; i < instructions.Count <Instruction>(); i++) { bool flag3 = instructions[i].OpCode == OpCodes.Call || instructions[i].OpCode == OpCodes.Callvirt; if (flag3) { MemberRef memberRef = instructions[i].Operand as MemberRef; bool flag4 = memberRef != null; if (flag4) { bool flag5 = new FileInfo(module.Location).Length > 1000000L; if (flag5) { instructions[i].OpCode = OpCodes.Ldftn; instructions[i].Operand = memberRef; instructions.Insert(++i, Instruction.Create(OpCodes.Calli, memberRef.MethodSig)); } else { FieldDef fieldDef = new FieldDefUser("BlinkVM_" + Renamer.rnd.Next(1, int.MaxValue).ToString(), new FieldSig(module.CorLibTypes.Object), FieldAttributes.FamANDAssem | FieldAttributes.Family | FieldAttributes.Static); methodDef2.DeclaringType.Fields.Add(fieldDef); methodDef.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Stsfld, fieldDef)); methodDef.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Ldftn, memberRef)); instructions[i].OpCode = OpCodes.Ldsfld; instructions[i].Operand = fieldDef; instructions.Insert(++i, Instruction.Create(OpCodes.Calli, memberRef.MethodSig)); } } } } } } } } }
private void PatchNuclearUpgrade_EquipmentType(ModuleDefMD module) { var equipmentType = module.Find("EquipmentType", false); FieldDef fieldToAdd = new FieldDefUser("NuclearReactorOrCyclopsModule", new FieldSig(new ValueTypeSig(equipmentType))) { Constant = module.UpdateRowId(new ConstantUser(NuclearUpgradeHelper.NuclearReactorOrCyclopsModule, equipmentType.GetEnumUnderlyingType().ElementType)), Attributes = FieldAttributes.Literal | FieldAttributes.Static | FieldAttributes.HasDefault | FieldAttributes.Public }; equipmentType.Fields.Add(fieldToAdd); }
protected override void Execute(ConfuserContext context, ProtectionParameters parameters) { var cctor = context.CurrentModule.GlobalType.FindOrCreateStaticConstructor(); foreach (MethodDef method in parameters.Targets.OfType <MethodDef>()) { if (method.IsConstructor) { continue; } if (method.Body == null) { continue; } if (method.HasBody && method.Body.HasInstructions && !method.FullName.Contains("My.") && !method.FullName.Contains(".My") && !method.IsConstructor && !method.DeclaringType.IsGlobalModuleType) { var instr = method.Body.Instructions; for (int i = 0; i < instr.Count(); i++) { if ((instr[i].OpCode == OpCodes.Call || instr[i].OpCode == OpCodes.Callvirt) && (instr[i].Operand is MemberRef member)) { if (!IsPublicKEK(context, member, method.Body.Instructions[i])) { continue; } if (new System.IO.FileInfo(context.CurrentModule.Location).Length > 1000000) // 1000000 = 1mb { instr[i].OpCode = OpCodes.Ldftn; instr[i].Operand = member; instr.Insert(++i, Instruction.Create(OpCodes.Calli, member.MethodSig)); } else { FieldDef field = new FieldDefUser(RandomString(6), new FieldSig(context.CurrentModule.CorLibTypes.Object), FieldAttributes.Public | FieldAttributes.Static); method.DeclaringType.Fields.Add(field); cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Stsfld, field)); cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Ldftn, member)); instr[i].OpCode = OpCodes.Ldsfld; instr[i].Operand = field; instr.Insert(++i, Instruction.Create(OpCodes.Calli, member.MethodSig)); } } } } } }
public FieldDef Create(byte[] data) { var arrayType = GetArrayType(data.LongLength); var fieldSig = new FieldSig(new ValueTypeSig(arrayType)); var attrs = FieldAttributes.Assembly | FieldAttributes.Static; var field = new FieldDefUser($"field_{_unique++}", fieldSig, attrs); _module.UpdateRowId(field); field.HasFieldRVA = true; _ourType.Fields.Add(field); var iv = new byte[data.Length]; Array.Copy(data, iv, data.Length); field.InitialValue = iv; return(field); }
public static void junkfield(ModuleDefMD module) { foreach (TypeDef typeDef in module.Types) { foreach (MethodDef methodDef in typeDef.Methods.ToArray <MethodDef>()) { FieldDefUser fieldDefUser = new FieldDefUser(RandomString(Random.Next(10, 20), Ascii2), new FieldSig(module.CorLibTypes.String), FieldAttributes.FamANDAssem | FieldAttributes.Family | FieldAttributes.Static); FieldDefUser fieldDefUser2 = new FieldDefUser(RandomString(Random.Next(10, 20), Ascii2), new FieldSig(module.CorLibTypes.UIntPtr), FieldAttributes.FamANDAssem | FieldAttributes.Family | FieldAttributes.Static); FieldDefUser fieldDefUser3 = new FieldDefUser(RandomString(Random.Next(10, 20), Ascii2), new FieldSig(module.CorLibTypes.IntPtr), FieldAttributes.FamANDAssem | FieldAttributes.Family | FieldAttributes.Static); FieldDefUser fieldDefUser4 = new FieldDefUser(RandomString(Random.Next(10, 20), Ascii2), new FieldSig(module.CorLibTypes.UInt32), FieldAttributes.FamANDAssem | FieldAttributes.Family | FieldAttributes.Static); typeDef.Fields.Add(fieldDefUser); typeDef.Fields.Add(fieldDefUser2); typeDef.Fields.Add(fieldDefUser3); typeDef.Fields.Add(fieldDefUser4); if (methodDef.HasBody && methodDef.Body.HasInstructions && !methodDef.Body.HasExceptionHandlers) { ; } { if (methodDef.IsVirtual) { continue; } Local local = new Local(module.CorLibTypes.UIntPtr); Local local2 = new Local(module.CorLibTypes.UInt32); Local local3 = new Local(module.CorLibTypes.IntPtr); Local local4 = new Local(module.CorLibTypes.String); methodDef.Body.Variables.Add(local); methodDef.Body.Variables.Add(local2); methodDef.Body.Variables.Add(local3); methodDef.Body.Variables.Add(local4); for (int i = 0; i < methodDef.Body.Instructions.Count - 2; i++) { methodDef.Body.Instructions.Insert(i + 1, OpCodes.Ldsfld.ToInstruction(fieldDefUser)); methodDef.Body.Instructions.Insert(i + 2, OpCodes.Stloc.ToInstruction(local4)); methodDef.Body.Instructions.Insert(i + 3, OpCodes.Ldsfld.ToInstruction(fieldDefUser2)); methodDef.Body.Instructions.Insert(i + 4, OpCodes.Stloc.ToInstruction(local)); methodDef.Body.Instructions.Insert(i + 5, OpCodes.Ldsfld.ToInstruction(fieldDefUser4)); methodDef.Body.Instructions.Insert(i + 6, OpCodes.Stloc.ToInstruction(local2)); methodDef.Body.Instructions.Insert(i + 7, OpCodes.Ldsfld.ToInstruction(fieldDefUser3)); methodDef.Body.Instructions.Insert(i + 8, OpCodes.Stloc.ToInstruction(local3)); i += 8; } } } } }
private FieldDef CreateField(RPContext ctx, TypeDef delegateType) { TypeDef def; do { def = ctx.Module.Types[ctx.Random.NextInt32(ctx.Module.Types.Count)]; }while ((def.HasGenericParameters || def.IsGlobalModuleType) || def.IsDelegate()); TypeSig type = new CModOptSig(def, delegateType.ToTypeSig()); FieldDefUser item = new FieldDefUser("", new FieldSig(type), FieldAttributes.Assembly | FieldAttributes.Static); item.CustomAttributes.Add(new CustomAttribute(this.GetKeyAttr(ctx).FindInstanceConstructors().First <MethodDef>())); delegateType.Fields.Add(item); ctx.Marker.Mark(item, ctx.Protection); ctx.Name.SetCanRename(item, false); return(item); }
private static FieldDef GetOrCreateDataField(ModuleDef module, byte[] data) { var privateImplementationDetails = module.FindNormal("<PrivateImplementationDetails>"); if (privateImplementationDetails is null) { privateImplementationDetails = new TypeDefUser(UTF8String.Empty, "<PrivateImplementationDetails>", module.CorLibTypes.Object.TypeRef) { Attributes = TypeAttributes.NotPublic | TypeAttributes.Sealed }; var compilerGeneratedAttribute = module.CorLibTypes.GetTypeRef("System.Runtime.CompilerServices", "CompilerGeneratedAttribute"); var ca = new CustomAttribute(new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), compilerGeneratedAttribute)); privateImplementationDetails.CustomAttributes.Add(ca); module.Types.Add(privateImplementationDetails); } string storageStructName = $"__StaticArrayInitTypeSize={data.Length}"; var storageStruct = privateImplementationDetails.NestedTypes.FirstOrDefault(t => t.Name == storageStructName); if (storageStruct is null) { storageStruct = new TypeDefUser(string.Empty, storageStructName, module.CorLibTypes.GetTypeRef("System", "ValueType")) { Attributes = TypeAttributes.NestedPrivate | TypeAttributes.ExplicitLayout | TypeAttributes.Sealed, ClassLayout = new ClassLayoutUser(1, (uint)data.Length) }; privateImplementationDetails.NestedTypes.Add(storageStruct); } string dataFieldName; using (var sha256 = SHA256.Create()) dataFieldName = BitConverter.ToString(sha256.ComputeHash(data)).Replace("-", string.Empty); var dataField = privateImplementationDetails.FindField(dataFieldName); if (!(dataField is null)) { return(dataField); } dataField = new FieldDefUser(dataFieldName, new FieldSig(storageStruct.ToTypeSig())) { Attributes = FieldAttributes.Assembly | FieldAttributes.Static | FieldAttributes.InitOnly | FieldAttributes.HasFieldRVA, InitialValue = data }; privateImplementationDetails.Fields.Add(dataField); return(dataField); }
static void InjectBuffEffectsCall() { var updateNpc = typeDef_NPC.GetMethod("RealUpdateNPC"); MethodDef invokeEffects; var onBuffEffects = context.CreateDelegate("Terraria.PrismInjections", "NPC_BuffEffectsDel", typeSys.Void, out invokeEffects, typeDef_NPC.ToTypeSig()); var buffEffects = new FieldDefUser("P_OnBuffEffects", new FieldSig(onBuffEffects.ToTypeSig()), FieldAttributes.Public | FieldAttributes.Static); typeDef_NPC.Fields.Add(buffEffects); OpCode[] toRem = { OpCodes.Ldarg_0, OpCodes.Ldfld, OpCodes.Brfalse }; var unb = updateNpc.Body; using (var unproc = unb.GetILProcessor()) { Instruction instr; var soulDrain = typeDef_NPC.GetField("soulDrain"); int start = 0; while (true) { instr = unb.FindInstrSeqStart(toRem, start); if (context.SigComparer.Equals((FieldDef)instr.Next(unproc).Operand, soulDrain)) { break; } else { start = unb.Instructions.IndexOf(instr) + 1; } } unproc.InsertBefore(instr, Instruction.Create(OpCodes.Ldsfld, buffEffects)); unproc.EmitWrapperCall(invokeEffects, instr); } }