コード例 #1
0
            public override void Process(ConfusionParameter parameter)
            {
                IAntiTamper ver;

                Confuser.Database.AddEntry("AntiTamper", "Type", parameter.GlobalParameters["type"] ?? "normal");
                if (parameter.GlobalParameters["type"] == "jit")
                {
                    ver = new JIT();
                }
                else
                {
                    ver = new Mem();
                }
                ver.AddHelper  = AddHelper;
                ver.Confuser   = Confuser;
                cion.vers[mod] = ver;

                ver.InitPhase1(mod);
                ver.Phase1(mod);
            }
コード例 #2
0
ファイル: TestConfusion.cs プロジェクト: zippy1981/Confuser
            public override void Process(ConfusionParameter parameter)
            {
                MethodDefinition t = null;

                foreach (var i in mod.GetType("Confuser.Test.Program").Methods)
                {
                    if (i.Name == "T")
                    {
                        t = i;
                        break;
                    }
                }

                t.IsStatic = true;
                t.HasThis  = false;

                t.DeclaringType.Methods.Remove(t);
                t.DeclaringType = null;
                mod.GetType("<Module>").Methods.Add(t);
            }
コード例 #3
0
        public override void Process(ConfusionParameter parameter)
        {
            AssemblyDefinition self = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location);
            TypeDefinition     type = CecilHelper.Inject(mod, self.MainModule.GetType("AntiDumping"));

            mod.Types.Add(type);
            TypeDefinition modType = mod.GetType("<Module>");
            ILProcessor    psr     = modType.GetStaticConstructor().Body.GetILProcessor();

            psr.InsertBefore(psr.Body.Instructions.Count - 1, Instruction.Create(OpCodes.Call, type.Methods.FirstOrDefault(mtd => mtd.Name == "Initalize")));

            type.Name      = ObfuscationHelper.GetNewName("AntiDumping" + Guid.NewGuid().ToString());
            type.Namespace = "";
            AddHelper(type, HelperAttribute.NoInjection);
            foreach (MethodDefinition mtdDef in type.Methods)
            {
                mtdDef.Name = ObfuscationHelper.GetNewName(mtdDef.Name + Guid.NewGuid().ToString());
                AddHelper(mtdDef, HelperAttribute.NoInjection);
            }
        }
コード例 #4
0
            public override void Process(ConfusionParameter parameter)
            {
                IList <IAnnotationProvider> targets = parameter.Target as IList <IAnnotationProvider>;

                for (int i = 0; i < targets.Count; i++)
                {
                    MethodDefinition mtd = targets[i] as MethodDefinition;
                    if (!mtd.HasBody || mtd.DeclaringType.FullName == "<Module>")
                    {
                        continue;
                    }

                    MethodBody bdy = mtd.Body;
                    foreach (Instruction inst in bdy.Instructions)
                    {
                        if (inst.OpCode.Code == Code.Newobj &&
                            !((inst.Operand as MethodReference).DeclaringType is GenericInstanceType) &&
                            !(inst.Operand is GenericInstanceMethod))
                        {
                            CreateDelegate(mtd.Body, inst, inst.Operand as MethodReference, mod);
                        }
                    }
                    progresser.SetProgress((i + 1) / (double)targets.Count);
                }
                double total    = cc.txts.Count;
                int    interval = 1;

                if (total > 1000)
                {
                    interval = (int)total / 100;
                }
                for (int i = 0; i < cc.txts.Count; i++)
                {
                    CreateFieldBridge(mod, cc.txts[i]);
                    if (i % interval == 0 || i == cc.txts.Count - 1)
                    {
                        progresser.SetProgress((i + 1) / total);
                    }
                }
            }
コード例 #5
0
 public override void Process(ConfusionParameter parameter)
 {
     /*_Context _txt = cc.txts[mod];
      *
      * int total = _txt.txts.Count;
      * int interval = 1;
      * if (total > 1000)
      *  interval = (int)total / 100;
      * for (int i = 0; i < _txt.txts.Count; i++)
      * {
      *  Context txt = _txt.txts[i];
      *  txt.fld.Name = GetId(txt.mtdRef.Module, txt.mtdRef);
      *
      *  if (!(txt.fld as IAnnotationProvider).Annotations.Contains("CtorProxyCtored"))
      *  {
      *      ILProcessor psr = txt.dele.GetStaticConstructor().Body.GetILProcessor();
      *      psr.Emit(OpCodes.Ldtoken, txt.fld);
      *      psr.Emit(OpCodes.Call, _txt.proxy);
      *      (txt.fld as IAnnotationProvider).Annotations["CtorProxyCtored"] = true;
      *  }
      *
      *  if (i % interval == 0 || i == _txt.txts.Count - 1)
      *      progresser.SetProgress(i + 1, total);
      * }
      *
      * total = _txt.delegates.Count;
      * interval = 1;
      * if (total > 1000)
      *  interval = (int)total / 100;
      * IEnumerator<TypeDefinition> etor = _txt.delegates.Values.GetEnumerator();
      * etor.MoveNext();
      * for (int i = 0; i < _txt.delegates.Count; i++)
      * {
      *  etor.Current.GetStaticConstructor().Body.GetILProcessor().Emit(OpCodes.Ret);
      *  etor.MoveNext();
      *  if (i % interval == 0 || i == cc.txts.Count - 1)
      *      progresser.SetProgress(i + 1, total);
      * }*/
 }
コード例 #6
0
            public override void Process(ConfusionParameter parameter)
            {
                IMemberDefinition mem = parameter.Target as IMemberDefinition;

                if (mem is TypeDefinition)
                {
                    TypeDefinition type = mem as TypeDefinition;
                    if ((bool)(type as IAnnotationProvider).Annotations["RenOk"])
                    {
                        type.Name      = ObfuscationHelper.GetNewName(type.FullName);
                        type.Namespace = "";
                        Identifier id = (Identifier)(type as IAnnotationProvider).Annotations["RenId"];
                        Identifier n  = id;
                        n.name  = type.Name;
                        n.scope = type.Namespace;
                        foreach (IReference refer in (type as IAnnotationProvider).Annotations["RenRef"] as List <IReference> )
                        {
                            refer.UpdateReference(id, n);
                        }
                    }
                }
                else if (mem is MethodDefinition)
                {
                    MethodDefinition mtd = mem as MethodDefinition;
                    PerformMethod(mtd);
                }
                else if ((bool)(mem as IAnnotationProvider).Annotations["RenOk"])
                {
                    mem.Name = ObfuscationHelper.GetNewName(mem.Name);
                    Identifier id = (Identifier)(mem as IAnnotationProvider).Annotations["RenId"];
                    Identifier n  = id;
                    n.scope = mem.DeclaringType.FullName;
                    n.name  = mem.Name;
                    foreach (IReference refer in (mem as IAnnotationProvider).Annotations["RenRef"] as List <IReference> )
                    {
                        refer.UpdateReference(id, n);
                    }
                }
            }
コード例 #7
0
            void ProcessSafe(ConfusionParameter parameter)
            {
                List <Context> txts = new List <Context>();

                ExtractData(parameter.Target as IList <IAnnotationProvider>, txts, Array.IndexOf(parameter.GlobalParameters.AllKeys, "numeric") != -1);

                int[] ids = new int[txts.Count];
                for (int i = 0; i < txts.Count; i++)
                {
                    int    idx = txts[i].mtd.Body.Instructions.IndexOf(txts[i].str);
                    object val = txts[i].str.Operand;
                    if (IsNull(val))
                    {
                        continue;
                    }

                    if (cc.dict.ContainsKey(val))
                    {
                        ids[i] = (int)(cc.dict[val] ^ ComputeHash(txts[i].mtd.MetadataToken.ToUInt32(), (uint)cc.key0, (uint)cc.key1, (uint)cc.key2, (uint)cc.key3));
                    }
                    else
                    {
                        byte   t;
                        byte[] ori = GetOperand(val, out t);
                        byte[] dat = EncryptSafe(ori, cc.key0 ^ cc.idx);
                        ids[i] = (int)(cc.idx ^ ComputeHash(txts[i].mtd.MetadataToken.ToUInt32(), (uint)cc.key0, (uint)cc.key1, (uint)cc.key2, (uint)cc.key3));

                        cc.dats.Add(new Data()
                        {
                            Dat = dat, Type = t
                        });
                        cc.dict[val] = cc.idx;
                        cc.idx      += dat.Length + 5;
                    }
                }

                FinalizeBodies(txts, ids);
            }
コード例 #8
0
        public override void Process(ConfusionParameter parameter)
        {
            method = parameter.Target as MethodDefinition;
            if (!method.HasBody)
            {
                return;
            }

            int slv = 5;

            if (Array.IndexOf(parameter.Parameters.AllKeys, "level") != -1)
            {
                if (!int.TryParse(parameter.Parameters["level"], out slv) && (slv <= 0 || slv > 10))
                {
                    Log("Invaild level, 5 will be used.");
                    slv = 5;
                }
            }
            genJunk = false;
            if (method.Module.Architecture != TargetArchitecture.I386)
            {
                genJunk = false;
            }
            else if (Array.IndexOf(parameter.Parameters.AllKeys, "genjunk") != -1)
            {
                if (!bool.TryParse(parameter.Parameters["genjunk"], out genJunk))
                {
                    Log("Invaild junk code parameter, junk code would not generated.");
                    genJunk = false;
                }
            }
            double trueLv = slv / 10.0;

            MethodBody body = method.Body;

            body.ComputeHeader();
            body.MaxStackSize += 5;
            Dictionary <Instruction, Level> Ids = GetIds(body);

            Level[] lvs = GetLvs(Ids);
            List <Instruction[]> scopes = new List <Instruction[]>();

            foreach (Level lv in lvs)
            {
                scopes.Add(GetInstructionsByLv(lv, Ids));
            }

            body.Instructions.Clear();
            Dictionary <Instruction, Instruction> HdrTbl = new Dictionary <Instruction, Instruction>();

            for (int i = 0; i < scopes.Count; i++)
            {
                Instruction[]   scope = scopes[i];
                Instruction[][] blocks;
                blocks = BranchesSplit(scope, trueLv);
                AddBranches(body, ref blocks);
                Reorder(ref blocks);

                HdrTbl.Add(scope[0], blocks[0][0]);

                foreach (Instruction[] iblk in blocks)
                {
                    body.Instructions.Add(iblk[0]);
                    for (int ii = 1; ii < iblk.Length; ii++)
                    {
                        Instruction tmp;
                        if (iblk[ii].Operand is Instruction)
                        {
                            if (HdrTbl.TryGetValue(iblk[ii].Operand as Instruction, out tmp) && tmp != blocks[0][0])
                            {
                                iblk[ii].Operand = tmp;
                            }
                        }
                        else if (iblk[ii].Operand is Instruction[])
                        {
                            Instruction[] op = iblk[ii].Operand as Instruction[];
                            for (int iii = 0; iii < op.Length; iii++)
                            {
                                if (HdrTbl.TryGetValue(op[iii], out tmp) && tmp != blocks[0][0])
                                {
                                    op[iii] = tmp;
                                }
                            }
                            iblk[ii].Operand = op;
                        }
                        body.Instructions.Add(iblk[ii]);
                    }
                }
                SetLvHandler(lvs[i], body, blocks);
            }

            foreach (ExceptionHandler eh in body.ExceptionHandlers)
            {
                eh.TryEnd     = eh.TryEnd.Next;
                eh.HandlerEnd = eh.HandlerEnd.Next;
                //if ((eh.HandlerType & ExceptionHandlerType.Filter) == ExceptionHandlerType.Filter)
                //{
                //    eh.FilterEnd = eh.FilterEnd.Next;
                //}
            }

            body.ComputeOffsets();
            body.PreserveMaxStackSize = true;
        }
コード例 #9
0
ファイル: ResEncryptConfusion.cs プロジェクト: n017/Confuser
            public override void Process(ConfusionParameter parameter)
            {
                _Context txt = rc.txts[mod];
                txt.dats = new List<KeyValuePair<string, byte[]>>();

                TypeDefinition modType = mod.GetType("<Module>");

                AssemblyDefinition i = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location);
                i.MainModule.ReadSymbols();
                txt.reso = i.MainModule.GetType("Encryptions").Methods.FirstOrDefault(mtd => mtd.Name == "Resources");
                txt.reso = CecilHelper.Inject(mod, txt.reso);
                modType.Methods.Add(txt.reso);
                txt.reso.Name = ObfuscationHelper.GetRandomName();
                txt.reso.IsAssembly = true;
                AddHelper(txt.reso, HelperAttribute.NoInjection);
                Database.AddEntry("ResEncrypt", "Resolver", txt.reso.FullName);

                TypeDefinition lzma = mod.GetType("Lzma" + mod.GetHashCode());
                if (lzma == null)
                {
                    lzma = CecilHelper.Inject(mod, i.MainModule.GetType("Lzma"));
                    lzma.IsNotPublic = true;
                    lzma.Name = "Lzma" + mod.GetHashCode();
                    mod.Types.Add(lzma);
                }

                FieldDefinition datAsm = new FieldDefinition(
                    ObfuscationHelper.GetRandomName(),
                    FieldAttributes.Static | FieldAttributes.CompilerControlled,
                    mod.Import(typeof(System.Reflection.Assembly)));
                modType.Fields.Add(datAsm);
                AddHelper(datAsm, HelperAttribute.NoInjection);
                Database.AddEntry("ResEncrypt", "Store", datAsm.FullName);

                txt.key0 = (byte)Random.Next(0, 0x100);
                do
                {
                    txt.key1 = (byte)Random.Next(1, 0x100);
                } while (txt.key1 == txt.key0);
                Database.AddEntry("ResEncrypt", "Key0", txt.key0);
                Database.AddEntry("ResEncrypt", "Key1", txt.key1);

                txt.resId = ObfuscationHelper.GetRandomName();
                Database.AddEntry("ResEncrypt", "ResID", txt.resId);

                Mutator mutator = new Mutator();
                mutator.StringKeys = new string[] { txt.resId };
                mutator.IntKeys = new int[] { txt.key0, txt.key1 };
                mutator.Mutate(Random, txt.reso.Body);
                foreach (Instruction inst in txt.reso.Body.Instructions)
                {
                    if (inst.Operand is FieldReference && (inst.Operand as FieldReference).Name == "datAsm")
                        inst.Operand = datAsm;
                    else if (inst.Operand is TypeReference && (inst.Operand as TypeReference).FullName == "System.Exception")
                        inst.Operand = modType;
                    else if (inst.Operand is MethodReference &&
                            (inst.Operand as MethodReference).DeclaringType.Name == "LzmaDecoder")
                        inst.Operand = lzma.NestedTypes
                            .Single(_ => _.Name == "LzmaDecoder").Methods
                            .Single(_ => _.Name == (inst.Operand as MethodReference).Name);
                }
                foreach (var x in txt.reso.Body.Variables)
                    if (x.VariableType.Name == "LzmaDecoder")
                        x.VariableType = lzma.NestedTypes.Single(_ => _.Name == "LzmaDecoder");

                MethodDefinition cctor = mod.GetType("<Module>").GetStaticConstructor();
                MethodBody bdy = cctor.Body as MethodBody;
                ILProcessor psr = bdy.GetILProcessor();
                //Reverse order
                psr.InsertBefore(0, Instruction.Create(OpCodes.Callvirt, mod.Import(typeof(AppDomain).GetEvent("ResourceResolve").GetAddMethod())));
                psr.InsertBefore(0, Instruction.Create(OpCodes.Newobj, mod.Import(typeof(ResolveEventHandler).GetConstructor(new Type[] { typeof(object), typeof(IntPtr) }))));
                psr.InsertBefore(0, Instruction.Create(OpCodes.Ldftn, txt.reso));
                psr.InsertBefore(0, Instruction.Create(OpCodes.Ldnull));
                psr.InsertBefore(0, Instruction.Create(OpCodes.Call, mod.Import(typeof(AppDomain).GetProperty("CurrentDomain").GetGetMethod())));
            }
コード例 #10
0
ファイル: CtorProxyConfusion.cs プロジェクト: n017/Confuser
            public override void Process(ConfusionParameter parameter)
            {
                _Context _txt = cc.txts[mod];

                int total = _txt.txts.Count;
                int interval = 1;
                if (total > 1000)
                    interval = (int)total / 100;
                for (int i = 0; i < _txt.txts.Count; i++)
                {
                    Context txt = _txt.txts[i];
                    txt.fld.Name = GetId(txt.mtdRef.Module, txt.mtdRef);

                    if (!(txt.fld as IAnnotationProvider).Annotations.Contains("CtorProxyCtored"))
                    {
                        ILProcessor psr = txt.dele.GetStaticConstructor().Body.GetILProcessor();
                        psr.Emit(OpCodes.Ldtoken, txt.fld);
                        psr.Emit(OpCodes.Call, _txt.proxy);
                        (txt.fld as IAnnotationProvider).Annotations["CtorProxyCtored"] = true;
                    }

                    if (i % interval == 0 || i == _txt.txts.Count - 1)
                        progresser.SetProgress(i + 1, total);
                }

                total = _txt.delegates.Count;
                interval = 1;
                if (total > 1000)
                    interval = (int)total / 100;
                IEnumerator<TypeDefinition> etor = _txt.delegates.Values.GetEnumerator();
                etor.MoveNext();
                for (int i = 0; i < _txt.delegates.Count; i++)
                {
                    etor.Current.GetStaticConstructor().Body.GetILProcessor().Emit(OpCodes.Ret);
                    etor.MoveNext();
                    if (i % interval == 0 || i == cc.txts.Count - 1)
                        progresser.SetProgress(i + 1, total);
                }
            }
コード例 #11
0
ファイル: AntiDebugConfusion.cs プロジェクト: n017/Confuser
        public override void Process(ConfusionParameter parameter)
        {
            AssemblyDefinition self = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location);
            Database.AddEntry("AntiDebug", "Win32", Array.IndexOf(parameter.GlobalParameters.AllKeys, "win32") != -1);
            if (Array.IndexOf(parameter.GlobalParameters.AllKeys, "win32") != -1)
            {
                TypeDefinition type = CecilHelper.Inject(mod, self.MainModule.GetType("AntiDebugger"));
                type.Methods.Remove(type.Methods.FirstOrDefault(mtd => mtd.Name == "AntiDebugSafe"));
                type.Methods.Remove(type.Methods.FirstOrDefault(mtd => mtd.Name == "InitializeSafe"));
                mod.Types.Add(type);
                TypeDefinition modType = mod.GetType("<Module>");
                ILProcessor psr = modType.GetStaticConstructor().Body.GetILProcessor();
                psr.InsertBefore(psr.Body.Instructions.Count - 1, Instruction.Create(OpCodes.Call, type.Methods.FirstOrDefault(mtd => mtd.Name == "Initialize")));

                type.Name = ObfuscationHelper.GetRandomName();
                type.Namespace = "";
                AddHelper(type, HelperAttribute.NoInjection);
                foreach (MethodDefinition mtdDef in type.Methods)
                {
                    mtdDef.Name = ObfuscationHelper.GetRandomName();
                    AddHelper(mtdDef, HelperAttribute.NoInjection);
                }
                Database.AddEntry("AntiDebug", "Helper", type.FullName);
            }
            else
            {
                TypeDefinition type = CecilHelper.Inject(mod, self.MainModule.GetType("AntiDebugger"));
                type.Methods.Remove(type.Methods.FirstOrDefault(mtd => mtd.Name == "AntiDebug"));
                type.Methods.Remove(type.Methods.FirstOrDefault(mtd => mtd.Name == "Initialize"));
                mod.Types.Add(type);
                TypeDefinition modType = mod.GetType("<Module>");
                ILProcessor psr = modType.GetStaticConstructor().Body.GetILProcessor();
                psr.InsertBefore(psr.Body.Instructions.Count - 1, Instruction.Create(OpCodes.Call, type.Methods.FirstOrDefault(mtd => mtd.Name == "InitializeSafe")));

                type.Name = ObfuscationHelper.GetRandomName();
                type.Namespace = "";
                AddHelper(type, HelperAttribute.NoInjection);
                foreach (MethodDefinition mtdDef in type.Methods)
                {
                    mtdDef.Name = ObfuscationHelper.GetRandomName();
                    AddHelper(mtdDef, HelperAttribute.NoInjection);
                }
                Database.AddEntry("AntiDebug", "Helper", type.FullName);
            }
        }
コード例 #12
0
ファイル: ConstantConfusion.cs プロジェクト: n017/Confuser
            private void ProcessSafe(ConfusionParameter parameter)
            {
                _Context txt = cc.txts[mod];

                TypeDefinition modType = mod.GetType("<Module>");

                FieldDefinition constTbl = new FieldDefinition(
                    ObfuscationHelper.GetRandomName(),
                    FieldAttributes.Static | FieldAttributes.CompilerControlled,
                    mod.Import(typeof(Dictionary<uint, object>)));
                modType.Fields.Add(constTbl);
                AddHelper(constTbl, HelperAttribute.NoInjection);
                Database.AddEntry("Const", "ConstTbl", constTbl.FullName);

                FieldDefinition constBuffer = new FieldDefinition(
                    ObfuscationHelper.GetRandomName(),
                    FieldAttributes.Static | FieldAttributes.CompilerControlled,
                    mod.Import(typeof(byte[])));
                modType.Fields.Add(constBuffer);
                AddHelper(constBuffer, HelperAttribute.NoInjection);
                Database.AddEntry("Const", "ConstBuffer", constBuffer.FullName);

                txt.consters = CreateConsters(txt, Random, "InitializeSafe", constTbl, constBuffer);
            }
コード例 #13
0
ファイル: DisConstConfusion.cs プロジェクト: n017/Confuser
        public override void Process(ConfusionParameter parameter)
        {
            List<Context> txts = new List<Context>();
            IList<IAnnotationProvider> targets = parameter.Target as IList<IAnnotationProvider>;
            for (int i = 0; i < targets.Count; i++)
            {
                MethodDefinition mtd = targets[i] as MethodDefinition;
                if (!mtd.HasBody) continue;
                mtd.Body.SimplifyMacros();
                int lv = 5;
                if (Array.IndexOf(parameter.Parameters.AllKeys, mtd.GetHashCode().ToString("X8") + "_level") != -1)
                {
                    if (!int.TryParse(parameter.Parameters[mtd.GetHashCode().ToString("X8") + "_level"], out lv) && (lv <= 0 || lv > 10))
                    {
                        Log("Invaild level, 5 will be used.");
                        lv = 5;
                    }
                }
                foreach(Instruction inst in mtd.Body.Instructions)
                {
                    if ((inst.OpCode.Name == "ldc.i4" && (int)inst.Operand != -1 && (int)inst.Operand != 0 && (int)inst.Operand != 1) ||
                        //(inst.OpCode.Name == "ldc.i8" && (long)inst.Operand != -1 && (long)inst.Operand != 0 && (long)inst.Operand != 1) ||
                        (inst.OpCode.Name == "ldc.r4" && (float)inst.Operand != -1 && (float)inst.Operand != 0 && (float)inst.Operand != 1) ||
                        (inst.OpCode.Name == "ldc.r8" && (double)inst.Operand != -1 && (double)inst.Operand != 0 && (double)inst.Operand != 1))
                        txts.Add(new Context() { mtd = mtd, psr = mtd.Body.GetILProcessor(), inst = inst, lv = lv });
                }
                progresser.SetProgress((i + 1) / (double)targets.Count);
            }

            for (int i = 0; i < txts.Count; i++)
            {
                Context txt = txts[i];
                int instIdx = txt.mtd.Body.Instructions.IndexOf(txt.inst);
                double val = Convert.ToDouble(txt.inst.Operand);
                int seed;

                Expression exp;
                double eval = 0;
                double tmp = 0;
                do
                {
                    exp = ExpressionGenerator.Generate(txt.lv, out seed);
                    eval = DoubleExpressionEvaluator.Evaluate(exp, val);
                    try
                    {
                        tmp = DoubleExpressionEvaluator.ReverseEvaluate(exp, eval);
                    }
                    catch { continue; }
                } while (tmp != val);

                Instruction[] expInsts = new CecilVisitor(exp, true, new Instruction[] { Instruction.Create(OpCodes.Ldc_R8, eval) }, true).GetInstructions();
                if (expInsts.Length == 0) continue;
                string op = txt.inst.OpCode.Name;
                txt.psr.Replace(instIdx, expInsts[0]);
                for (int ii = 1; ii < expInsts.Length; ii++)
                {
                    txt.psr.InsertAfter(instIdx + ii - 1, expInsts[ii]);
                }
                switch (op)
                {
                    case "ldc.i4":
                        txt.psr.InsertAfter(instIdx +expInsts.Length - 1, Instruction.Create(OpCodes.Conv_I4)); break;
                    //case "ldc.i8":
                    //    txt.psr.InsertAfter(instIdx +expInsts.Length - 1, Instruction.Create(OpCodes.Conv_I8)); break;
                    case "ldc.r4":
                        txt.psr.InsertAfter(instIdx +expInsts.Length - 1, Instruction.Create(OpCodes.Conv_R4)); break;
                    case "ldc.r8":
                        txt.psr.InsertAfter(instIdx +expInsts.Length - 1, Instruction.Create(OpCodes.Conv_R8)); break;
                }

                progresser.SetProgress((i + 1) / (double)txts.Count);
            }
        }
コード例 #14
0
            public override void Process(ConfusionParameter parameter)
            {
                if (Array.IndexOf(parameter.GlobalParameters.AllKeys, "dynamic") == -1)
                {
                    ProcessSafe(parameter); return;
                }

                List <Context> txts = new List <Context>();

                ExtractData(parameter.Target as IList <IAnnotationProvider>, txts, Array.IndexOf(parameter.GlobalParameters.AllKeys, "numeric") != -1);

                int[] ids;
                bool  retry;

                do
                {
                    ids   = new int[txts.Count];
                    retry = false;
                    cc.dict.Clear();
                    int seed;
                    cc.exp = ExpressionGenerator.Generate(5, out seed);

                    for (int i = 0; i < txts.Count; i++)
                    {
                        object val = txts[i].str.Operand as object;
                        if (IsNull(val))
                        {
                            continue;
                        }

                        if (cc.dict.ContainsKey(val))
                        {
                            ids[i] = (int)(cc.dict[val] ^ ComputeHash(txts[i].mtd.MetadataToken.ToUInt32(), (uint)cc.key0, (uint)cc.key1, (uint)cc.key2, (uint)cc.key3));
                        }
                        else
                        {
                            ids[i] = (int)(cc.idx ^ ComputeHash(txts[i].mtd.MetadataToken.ToUInt32(), (uint)cc.key0, (uint)cc.key1, (uint)cc.key2, (uint)cc.key3));
                            byte   t;
                            byte[] ori = GetOperand(val, out t);

                            int    len;
                            byte[] dat = Encrypt(ori, cc.exp, out len);
                            try
                            {
                                if (!IsEqual(Decrypt(dat, len, cc.exp), ori))
                                {
                                    retry = true;
                                    break;
                                }
                            }
                            catch
                            {
                                retry = true;
                                break;
                            }
                            byte[] final = new byte[dat.Length + 4];
                            Buffer.BlockCopy(dat, 0, final, 4, dat.Length);
                            Buffer.BlockCopy(BitConverter.GetBytes(len), 0, final, 0, 4);
                            cc.dats.Add(new Data()
                            {
                                Dat = final, Type = t
                            });
                            cc.dict[val] = cc.idx;
                            cc.idx      += final.Length + 5;
                        }
                        System.Diagnostics.Debug.WriteLine(cc.dict[val].ToString() + "        " + val.ToString());
                    }
                } while (retry);

                for (int i = 0; i < cc.strer.Body.Instructions.Count; i++)
                {
                    Instruction inst = cc.strer.Body.Instructions[i];
                    if (inst.Operand is MethodReference && ((MethodReference)inst.Operand).Name == "PolyStart")
                    {
                        List <Instruction> insts = new List <Instruction>();
                        int ptr = i + 1;
                        while (ptr < cc.strer.Body.Instructions.Count)
                        {
                            Instruction z = cc.strer.Body.Instructions[ptr];
                            cc.strer.Body.Instructions.Remove(z);
                            if (z.Operand is MethodReference && ((MethodReference)z.Operand).Name == "PlaceHolder")
                            {
                                break;
                            }
                            insts.Add(z);
                        }

                        Instruction[] expInsts = new CecilVisitor(cc.exp, true, insts.ToArray(), false).GetInstructions();
                        ILProcessor   psr      = cc.strer.Body.GetILProcessor();
                        psr.Replace(inst, expInsts[0]);
                        for (int ii = 1; ii < expInsts.Length; ii++)
                        {
                            psr.InsertAfter(expInsts[ii - 1], expInsts[ii]);
                        }
                    }
                }
                cc.strer.Body.OptimizeMacros();
                cc.strer.Body.ComputeOffsets();

                FinalizeBodies(txts, ids);
            }
コード例 #15
0
            public override void Process(ConfusionParameter parameter)
            {
                rc.dats = new List <KeyValuePair <string, byte[]> >();

                TypeDefinition modType = mod.GetType("<Module>");

                AssemblyDefinition i = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location);

                rc.reso = i.MainModule.GetType("Encryptions").Methods.FirstOrDefault(mtd => mtd.Name == "Resources");
                rc.reso = CecilHelper.Inject(mod, rc.reso);
                modType.Methods.Add(rc.reso);
                byte[] n = Guid.NewGuid().ToByteArray();
                rc.reso.Name       = Encoding.UTF8.GetString(n);
                rc.reso.IsAssembly = true;
                AddHelper(rc.reso, HelperAttribute.NoInjection);

                n       = Guid.NewGuid().ToByteArray();
                rc.key0 = rc.key1 = n[0];
                for (int x = 0; x < n.Length; x++)
                {
                    if (n[x] != 0)
                    {
                        rc.key1 = n[x];
                        break;
                    }
                }

                n = Guid.NewGuid().ToByteArray();

                rc.reso.Body.SimplifyMacros();
                foreach (Instruction inst in rc.reso.Body.Instructions)
                {
                    if ((inst.Operand as string) == "PADDINGPADDINGPADDING")
                    {
                        inst.Operand = Encoding.UTF8.GetString(n);
                    }
                    else if (inst.Operand is int && (int)inst.Operand == 0x11)
                    {
                        inst.Operand = (int)rc.key0;
                    }
                    else if (inst.Operand is int && (int)inst.Operand == 0x22)
                    {
                        inst.Operand = (int)rc.key1;
                    }
                    else if (inst.Operand is TypeReference && (inst.Operand as TypeReference).FullName == "System.Exception")
                    {
                        inst.Operand = modType;
                    }
                }
                rc.reso.Body.OptimizeMacros();
                rc.reso.Body.ComputeOffsets();

                rc.resId = Encoding.UTF8.GetString(n);

                MethodDefinition cctor = mod.GetType("<Module>").GetStaticConstructor();
                MethodBody       bdy   = cctor.Body as MethodBody;

                bdy.Instructions.RemoveAt(bdy.Instructions.Count - 1);
                ILProcessor psr = bdy.GetILProcessor();

                psr.Emit(OpCodes.Call, mod.Import(typeof(AppDomain).GetProperty("CurrentDomain").GetGetMethod()));
                psr.Emit(OpCodes.Ldnull);
                psr.Emit(OpCodes.Ldftn, rc.reso);
                psr.Emit(OpCodes.Newobj, mod.Import(typeof(ResolveEventHandler).GetConstructor(new Type[] { typeof(object), typeof(IntPtr) })));
                psr.Emit(OpCodes.Callvirt, mod.Import(typeof(AppDomain).GetEvent("ResourceResolve").GetAddMethod()));
                psr.Emit(OpCodes.Ret);
            }
コード例 #16
0
ファイル: AntiTamperConfusion.cs プロジェクト: n017/Confuser
 public override void Process(ConfusionParameter parameter)
 {
     cion.vers[mod].Phase2(progresser, mod);
 }
コード例 #17
0
ファイル: AntiTamperConfusion.cs プロジェクト: n017/Confuser
            public override void Process(ConfusionParameter parameter)
            {
                IAntiTamper ver;

                Confuser.Database.AddEntry("AntiTamper", "Type", parameter.GlobalParameters["type"] ?? "normal");
                if (parameter.GlobalParameters["type"] == "jit")
                    ver = new JIT();
                else
                    ver = new Mem();
                ver.AddHelper = AddHelper;
                ver.Confuser = Confuser;
                cion.vers[mod] = ver;

                ver.InitPhase1(mod);
                ver.Phase1(mod);
            }
コード例 #18
0
ファイル: AntiILDasmConfusion.cs プロジェクト: n017/Confuser
        public override void Process(ConfusionParameter parameter)
        {
            MethodReference ctor = mod.Import(typeof(SuppressIldasmAttribute).GetConstructor(Type.EmptyTypes));
            bool has = false;
            foreach (CustomAttribute att in mod.CustomAttributes)
                if (att.Constructor.ToString() == ctor.ToString())
                {
                    has = true;
                    break;
                }

            if (!has)
                mod.CustomAttributes.Add(new CustomAttribute(ctor));
        }
コード例 #19
0
ファイル: MtdProxyConfusion.cs プロジェクト: n017/Confuser
            public override void Process(ConfusionParameter parameter)
            {
                _Context txt = mc.txts[mod];
                txt.isNative = parameter.GlobalParameters["type"] == "native";
                bool onlyExternal = true;
                if (Array.IndexOf(parameter.GlobalParameters.AllKeys, "onlyExternal") != -1)
                {
                    if (!bool.TryParse(parameter.GlobalParameters["onlyExternal"], out onlyExternal))
                    {
                        Log("Invaild onlyExternal parameter, only external reference will be proxied.");
                        onlyExternal = true;
                    }
                }
                Database.AddEntry("MtdProxy", "OnlyExternal", onlyExternal);

                IList<Tuple<IAnnotationProvider, NameValueCollection>> targets = parameter.Target as IList<Tuple<IAnnotationProvider, NameValueCollection>>;
                for (int i = 0; i < targets.Count; i++)
                {
                    MethodDefinition mtd = targets[i].Item1 as MethodDefinition;
                    if (!mtd.HasBody || mtd.DeclaringType.FullName == "<Module>") continue;

                    MethodBody bdy = mtd.Body;
                    foreach (Instruction inst in bdy.Instructions)
                    {
                        if ((inst.OpCode.Code == Code.Call || inst.OpCode.Code == Code.Callvirt) &&
                            (!onlyExternal || !(inst.Operand is MethodDefinition)) &&

                            (inst.Operand as MethodReference).Name != ".ctor" && (inst.Operand as MethodReference).Name != ".cctor" &&  //no constructor

                            !((inst.Operand as MethodReference).DeclaringType is GenericInstanceType) &&                                //no generic

                            ((inst.Operand as MethodReference).DeclaringType.Resolve() == null ||
                             !(inst.Operand as MethodReference).DeclaringType.Resolve().IsInterface) &&                                 //no interface

                            (!(inst.Operand is MethodDefinition) ||
                             (inst.Operand as MethodDefinition).ImplAttributes != MethodImplAttributes.Native) &&                       //no native

                            (inst.Previous == null || inst.Previous.OpCode.OpCodeType != OpCodeType.Prefix))                            //no prefix
                        {
                            CreateDelegate(mtd.Body, inst, inst.Operand as MethodReference, mod);
                        }
                    }
                    progresser.SetProgress(i + 1, targets.Count);
                }
                int total = mc.txts.Count;
                int interval = 1;
                if (total > 1000)
                    interval = (int)total / 100;
                for (int i = 0; i < txt.txts.Count; i++)
                {
                    CreateFieldBridge(mod, txt.txts[i]);
                    if (i % interval == 0 || i == txt.txts.Count - 1)
                        progresser.SetProgress(i + 1, total);
                }
            }
コード例 #20
0
            void ProcessSafe(ConfusionParameter parameter)
            {
                List <Context> txts = new List <Context>();

                foreach (MethodDefinition mtd in parameter.Target as IList <IAnnotationProvider> )
                {
                    if (mtd == sc.strer || !mtd.HasBody)
                    {
                        continue;
                    }
                    var bdy = mtd.Body;
                    bdy.SimplifyMacros();
                    var         insts = bdy.Instructions;
                    ILProcessor psr   = bdy.GetILProcessor();
                    for (int i = 0; i < insts.Count; i++)
                    {
                        if (insts[i].OpCode.Code == Code.Ldstr)
                        {
                            txts.Add(new Context()
                            {
                                mtd = mtd, psr = psr, str = insts[i]
                            });
                        }
                    }
                }

                double total    = txts.Count;
                int    interval = 1;

                if (total > 1000)
                {
                    interval = (int)total / 100;
                }
                for (int i = 0; i < txts.Count; i++)
                {
                    int    idx = txts[i].mtd.Body.Instructions.IndexOf(txts[i].str);
                    string val = txts[i].str.Operand as string;
                    if (val == "")
                    {
                        continue;
                    }

                    int id;
                    if (sc.dict.ContainsKey(val))
                    {
                        id = (int)((sc.dict[val] + sc.key0) ^ txts[i].mtd.MetadataToken.ToUInt32());
                    }
                    else
                    {
                        byte[] dat = EncryptSafe(val, sc.key2);
                        id = (int)((sc.idx + sc.key0) ^ txts[i].mtd.MetadataToken.ToUInt32());
                        int len = (int)~(dat.Length ^ sc.key1);

                        byte[] final = new byte[dat.Length + 4];
                        Buffer.BlockCopy(dat, 0, final, 4, dat.Length);
                        Buffer.BlockCopy(BitConverter.GetBytes(len), 0, final, 0, 4);
                        sc.dats.Add(final);
                        sc.dict[val] = sc.idx;
                        sc.idx      += final.Length;
                    }

                    Instruction now = txts[i].str;
                    txts[i].psr.InsertAfter(idx, txts[i].psr.Create(OpCodes.Call, sc.strer));
                    txts[i].psr.Replace(idx, txts[i].psr.Create(OpCodes.Ldc_I4, id));

                    if (i % interval == 0 || i == txts.Count - 1)
                    {
                        progresser.SetProgress((i + 1) / total);
                    }
                }

                List <int> hashs = new List <int>();

                for (int i = 0; i < txts.Count; i++)
                {
                    if (hashs.IndexOf(txts[i].mtd.GetHashCode()) == -1)
                    {
                        txts[i].mtd.Body.OptimizeMacros();
                        txts[i].mtd.Body.ComputeHeader();
                        hashs.Add(txts[i].mtd.GetHashCode());
                    }
                }
            }
コード例 #21
0
        public override void Process(ConfusionParameter parameter)
        {
            MethodDefinition mtd = parameter.Target as MethodDefinition;

            if (!mtd.HasBody)
            {
                return;
            }

            int slv = 5;

            if (Array.IndexOf(parameter.Parameters.AllKeys, "level") != -1)
            {
                if (!int.TryParse(parameter.Parameters["level"], out slv) && (slv <= 0 || slv > 10))
                {
                    Log("Invaild level, 5 will be used.");
                    slv = 5;
                }
            }
            genJunk = false;
            if (mtd.Module.Architecture != TargetArchitecture.I386)
            {
                genJunk = false;
            }
            else if (Array.IndexOf(parameter.Parameters.AllKeys, "genjunk") != -1)
            {
                if (!bool.TryParse(parameter.Parameters["genjunk"], out genJunk))
                {
                    Log("Invaild junk code parameter, junk code would not generated.");
                    genJunk = false;
                }
            }
            double trueLv = slv / 10.0;

            MethodBody bdy = mtd.Body;

            bdy.SimplifyMacros();
            bdy.ComputeHeader();
            Dictionary <Instruction, Level> Ids = GetIds(bdy);

            Level[] lvs = GetLvs(Ids);
            List <Instruction[]> blks = new List <Instruction[]>();

            foreach (Level lv in lvs)
            {
                blks.Add(GetInstructionsByLv(lv, Ids));
            }

            bdy.Instructions.Clear();
            ILProcessor wkr = bdy.GetILProcessor();
            Dictionary <Instruction, Instruction> HdrTbl = new Dictionary <Instruction, Instruction>();

            for (int i = 0; i < blks.Count; i++)
            {
                Instruction[]   blk = blks[i];
                Instruction[][] iblks;
                if (Array.IndexOf(parameter.Parameters.AllKeys, "switch") == -1)
                {
                    iblks = BrizeSplit(blk, trueLv);
                    BrizeFlow(bdy, ref iblks);
                }
                else
                {
                    iblks = SwitcizeSplit(mtd, blk, trueLv);
                    if (iblks.Length == 1)
                    {
                        iblks = BrizeSplit(blk, trueLv);
                        BrizeFlow(bdy, ref iblks);
                    }
                    else
                    {
                        SwitcizeFlow(bdy, ref iblks);
                    }
                }
                Reorder(ref iblks);

                HdrTbl.Add(blk[0], iblks[0][0]);

                foreach (Instruction[] iblk in iblks)
                {
                    wkr.Append(iblk[0]);
                    for (int ii = 1; ii < iblk.Length; ii++)
                    {
                        Instruction tmp;
                        if (iblk[ii].Operand is Instruction)
                        {
                            if (HdrTbl.TryGetValue(iblk[ii].Operand as Instruction, out tmp) && tmp != iblks[0][0])
                            {
                                iblk[ii].Operand = tmp;
                            }
                        }
                        else if (iblk[ii].Operand is Instruction[])
                        {
                            Instruction[] op = iblk[ii].Operand as Instruction[];
                            for (int iii = 0; iii < op.Length; iii++)
                            {
                                if (HdrTbl.TryGetValue(op[iii], out tmp) && tmp != iblks[0][0])
                                {
                                    op[iii] = tmp;
                                }
                            }
                            iblk[ii].Operand = op;
                        }
                        wkr.Append(iblk[ii]);
                    }
                }
                SetLvHandler(lvs[i], bdy, iblks);
            }

            foreach (ExceptionHandler eh in bdy.ExceptionHandlers)
            {
                eh.TryEnd     = eh.TryEnd.Next;
                eh.HandlerEnd = eh.HandlerEnd.Next;
                //if ((eh.HandlerType & ExceptionHandlerType.Filter) == ExceptionHandlerType.Filter)
                //{
                //    eh.FilterEnd = eh.FilterEnd.Next;
                //}
            }

            bdy.OptimizeMacros();
            bdy.PreserveMaxStackSize = true;
        }
コード例 #22
0
        public override void Process(ConfusionParameter parameter)
        {
            method = parameter.Target as MethodDefinition;
            if (!method.HasBody || method.Body.Instructions.Count == 0) return;

            level = 5;
            if (Array.IndexOf(parameter.Parameters.AllKeys, "level") != -1)
            {
                if (!int.TryParse(parameter.Parameters["level"], out level) && (level <= 0 || level > 10))
                {
                    Log("Invalid level, 5 will be used.");
                    level = 5;
                }
            }

            genJunk = false;
            if (method.Module.Architecture != TargetArchitecture.I386)
                genJunk = false;
            else if (Array.IndexOf(parameter.Parameters.AllKeys, "genjunk") != -1)
            {
                if (!bool.TryParse(parameter.Parameters["genjunk"], out genJunk))
                {
                    Log("Invalid junk code parameter, junk code would not be generated.");
                    genJunk = false;
                }
            }

            fakeBranch = false;
            if (Array.IndexOf(parameter.Parameters.AllKeys, "fakebranch") != -1)
            {
                if (!bool.TryParse(parameter.Parameters["fakebranch"], out fakeBranch))
                {
                    Log("Invalid fake branch parameter, fake branch would not be generated.");
                    fakeBranch = false;
                }
            }

            MethodBody body = method.Body;
            body.SimplifyMacros();
            body.ComputeHeader();
            body.MaxStackSize += 0x10;

            PropagateSeqPoints(body);

            VariableDefinition stateVar = new VariableDefinition(method.Module.TypeSystem.Int32);
            body.Variables.Add(stateVar);
            body.InitLocals = true;

            //Compute stacks
            var stacks = GetStacks(body);

            Dictionary<Instruction, Instruction> ReplTbl = new Dictionary<Instruction, Instruction>();
            List<Scope> scopes = new List<Scope>();
            foreach (var scope in ScopeDetector.DetectScopes(body))
            {
                scopes.Add(scope);

                //Split statements when stack = empty
                //First statement maybe have non-empty stack because of handlers/filter
                List<Statement> sts = new List<Statement>();
                foreach (var i in SplitStatements(body, scope.Instructions, stacks))
                    sts.Add(new Statement()
                    {
                        Instructions = i,
                        Type = StatementType.Normal,
                        Key = 0,
                        BeginStack = stacks[i[0].Index]
                    });

                //Constructor fix
                if (body.Method.IsConstructor && body.Method.HasThis)
                {
                    Statement init = new Statement();
                    init.Type = StatementType.Normal;
                    List<Instruction> z = new List<Instruction>();
                    while (sts.Count != 0)
                    {
                        z.AddRange(sts[0].Instructions);
                        Instruction lastInst = sts[0].Instructions[sts[0].Instructions.Length - 1];
                        sts.RemoveAt(0);
                        if (lastInst.OpCode == OpCodes.Call &&
                            (lastInst.Operand as MethodReference).Name == ".ctor")
                            break;
                    }
                    init.Instructions = z.ToArray();
                    sts.Insert(0, init);
                }

                if (sts.Count == 1 || sts.All(st => st.BeginStack != 0)) continue;

                //Merge statements for level
                for (int i = 0; i < sts.Count - 1; i++)
                {
                    if (Random.Next(1, 10) > level || sts[i + 1].BeginStack != 0)
                    {
                        Statement newSt = new Statement();
                        newSt.Type = sts[i + 1].Type;
                        newSt.BeginStack = sts[i].BeginStack;
                        newSt.Instructions = new Instruction[sts[i].Instructions.Length + sts[i + 1].Instructions.Length];
                        Array.Copy(sts[i].Instructions, 0, newSt.Instructions, 0, sts[i].Instructions.Length);
                        Array.Copy(sts[i + 1].Instructions, 0, newSt.Instructions, sts[i].Instructions.Length, sts[i + 1].Instructions.Length);
                        sts[i] = newSt;
                        sts.RemoveAt(i + 1);
                        i--;
                    }
                }

                //Detect branches
                int k = 0;
                foreach (var st in sts)
                {
                    Instruction last = st.Instructions[st.Instructions.Length - 1];
                    if (last.Operand is Instruction &&
                        sts.Exists(_ => _.Instructions[0] == last.Operand))
                        st.Type = StatementType.Branch;
                    st.Key = k; k++;
                }

                //Shuffle the statements
                List<Instruction> insts = new List<Instruction>();
                for (int i = 1; i < sts.Count; i++)
                {
                    int j = Random.Next(1, sts.Count);
                    var tmp = sts[j];
                    sts[j] = sts[i];
                    sts[i] = tmp;
                }
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < sts.Count; i++)
                {
                    if (i != 0) sb.Append(", ");
                    sb.Append(sts[i].Key);
                }
                Database.AddEntry("CtrlFlow", method.FullName, sb);

                Instruction[] stHdrs = new Instruction[sts.Count];
                k = 0;
                for (int i = 0; i < sts.Count; i++)
                {
                    sts[i].Key = k;
                    if (sts[i].BeginStack == 0)
                        k++;

                    if (sts[i].Instructions.Length > 0)
                        stHdrs[i] = sts[i].Instructions[0];
                }
                Func<object, Statement> resolveHdr = inst =>
                {
                    int _ = Array.IndexOf(stHdrs, inst as Instruction);
                    return _ == -1 ? null : sts[_];
                };

                exp = generator.Generate(level);
                invExp = ExpressionInverser.InverseExpression(exp);
                Instruction[] ldloc = new Instruction[] { Instruction.Create(OpCodes.Ldloc, stateVar) };// new CecilVisitor(invExp, new Instruction[] { Instruction.Create(OpCodes.Ldloc, stateVar) }).GetInstructions();
                Instruction begin = ldloc[0];
                Instruction swit = Instruction.Create(OpCodes.Switch, Empty<Instruction>.Array);
                Instruction end = Instruction.Create(OpCodes.Nop);
                List<Instruction> targets = new List<Instruction>();
                Statement beginSt = resolveHdr(scope.Instructions[0]);

                //Convert branches -> switch
                bool firstSt = true;
                foreach (var st in sts)
                {
                    List<Instruction> stInsts = new List<Instruction>(st.Instructions);
                    Instruction last = st.Instructions[st.Instructions.Length - 1];
                    if (st.Type == StatementType.Branch)
                    {
                        if (last.OpCode.Code == Code.Br)  //uncond
                        {
                            int index = stInsts.Count - 1;
                            stInsts.RemoveAt(index);
                            Statement targetSt = resolveHdr(last.Operand);
                            Statement fallSt;
                            if (fakeBranch && (fallSt = resolveHdr(last.Next)) != null)
                            {
                                ReplTbl[last] = GenFakeBranch(st, targetSt, fallSt, stInsts, stateVar, begin);
                            }
                            else
                            {
                                ReplTbl[last] = EncryptNum(st.Key, stateVar, targetSt.Key, stInsts);
                                stInsts.Add(Instruction.Create(OpCodes.Br, begin));
                                stInsts.AddRange(GetJunk(stateVar));
                            }
                            stInsts[index].SequencePoint = last.SequencePoint;
                        }
                        else if (last.OpCode.Code != Code.Leave)  //cond
                        {
                            int index = stInsts.Count - 1;
                            stInsts.RemoveAt(index);
                            Statement targetSt = resolveHdr(last.Operand);
                            Statement fallSt = resolveHdr(last.Next);

                            if (fallSt == null) //fall into exception block
                            {
                                ReplTbl[last] = EncryptNum(st.Key, stateVar, targetSt.Key, stInsts);
                                stInsts.Add(Instruction.Create(last.OpCode, begin));
                                stInsts.Add(Instruction.Create(OpCodes.Br, last.Next));
                                stInsts.AddRange(GetJunk(stateVar));
                            }
                            else
                            {
                                ReplTbl[last] = EncryptNum(st.Key, stateVar, targetSt.Key, stInsts);
                                stInsts.Add(Instruction.Create(last.OpCode, begin));
                                EncryptNum(st.Key, stateVar, fallSt.Key, stInsts);
                                stInsts.Add(Instruction.Create(OpCodes.Br, begin));
                                stInsts.AddRange(GetJunk(stateVar));
                            }
                            stInsts[index].SequencePoint = last.SequencePoint;
                        }
                    }
                    else
                    {
                        Statement fallSt = resolveHdr(last.Next);
                        if (fallSt != null)
                        {
                            if (fakeBranch)
                            {
                                Statement fakeSt = sts[Random.Next(0, sts.Count)];
                                GenFakeBranch(st, fallSt, fakeSt, stInsts, stateVar, begin);
                            }
                            else
                            {
                                EncryptNum(st.Key, stateVar, fallSt.Key, stInsts);
                                stInsts.Add(Instruction.Create(OpCodes.Br, begin));
                                stInsts.AddRange(GetJunk(stateVar));
                            }
                        }
                        else
                            stInsts.Add(Instruction.Create(OpCodes.Br, end));
                    }
                    if (!firstSt)
                    {
                        targets.Add(stInsts[0]);
                        insts.AddRange(stInsts.ToArray());
                    }
                    else
                    {
                        insts.AddRange(stInsts.ToArray());
                        insts.AddRange(ldloc);
                        insts.Add(swit);
                        if (st.BeginStack == 0)
                            targets.Add(stInsts[0]);
                        firstSt = false;
                    }
                }
                swit.Operand = targets.ToArray();
                insts.Add(end);

                //fix peverify
                foreach (var i in scope.Type.Scopes)
                {
                    if (ScopeDetector.IsFilter(i.Item2) &&
                        (ScopeDetector.IsOnly(i.Item2) || ScopeDetector.IsEnd(i.Item2)))
                    {
                        insts.Add(Instruction.Create(OpCodes.Ldc_I4, Random.Next()));
                        insts.Add(Instruction.Create(OpCodes.Endfilter));
                        break;
                    }
                    else if (ScopeDetector.IsTry(i.Item2) &&
                             (ScopeDetector.IsOnly(i.Item2) || ScopeDetector.IsEnd(i.Item2)))
                    {
                        if (i.Item1.HandlerEnd == null)
                        {
                            insts.Add(Instruction.Create(OpCodes.Ldnull));
                            insts.Add(Instruction.Create(OpCodes.Throw));
                        }
                        else
                        {
                            Instruction last = scope.Instructions[scope.Instructions.Length - 1];
                            insts.Add(Instruction.Create(OpCodes.Leave, last.OpCode != OpCodes.Leave ? i.Item1.HandlerEnd : last.Operand as Instruction));
                        }
                        break;
                    }
                    else if (ScopeDetector.IsHandler(i.Item2) &&
                             (ScopeDetector.IsOnly(i.Item2) || ScopeDetector.IsEnd(i.Item2)))
                    {
                        //it must either finally/fault or catch, not both
                        if (i.Item1.HandlerType == ExceptionHandlerType.Finally ||
                            i.Item1.HandlerType == ExceptionHandlerType.Fault)
                            insts.Add(Instruction.Create(OpCodes.Endfinally));
                        else if (i.Item1.HandlerEnd == null)
                        {
                            insts.Add(Instruction.Create(OpCodes.Ldnull));
                            insts.Add(Instruction.Create(OpCodes.Throw));
                        }
                        else
                        {
                            Instruction last = i.Item1.TryEnd.Previous;
                            insts.Add(Instruction.Create(OpCodes.Leave, last.OpCode != OpCodes.Leave ? i.Item1.HandlerEnd : last.Operand as Instruction));
                        }
                        break;
                    }
                }

                ReplTbl[scope.Instructions[0]] = insts[0];
                scope.Instructions = insts.ToArray();
            }

            //emit
            body.Instructions.Clear();
            foreach (var scope in scopes)
                foreach (var i in scope.Instructions)
                {
                    if (i.Operand is Instruction &&
                        ReplTbl.ContainsKey(i.Operand as Instruction))
                    {
                        i.Operand = ReplTbl[i.Operand as Instruction];
                    }
                    else if (i.Operand is Instruction[])
                    {
                        Instruction[] insts = i.Operand as Instruction[];
                        for (int j = 0; j < insts.Length; j++)
                            if (ReplTbl.ContainsKey(insts[j]))
                                insts[j] = ReplTbl[insts[j]];
                    }
                }
            foreach (var scope in scopes)
            {
                SetLvHandler(scope, body, scope.Instructions);
                foreach (var i in scope.Instructions)
                    body.Instructions.Add(i);
            }

            //fix peverify
            if (!method.ReturnType.IsTypeOf("System", "Void"))
            {
                body.Instructions.Add(Instruction.Create(OpCodes.Ldnull));
                body.Instructions.Add(Instruction.Create(OpCodes.Unbox_Any, method.ReturnType));
            }
            body.Instructions.Add(Instruction.Create(OpCodes.Ret));

            foreach (ExceptionHandler eh in body.ExceptionHandlers)
            {
                eh.TryEnd = eh.TryEnd.Next;
                eh.HandlerEnd = eh.HandlerEnd.Next;
            }

            body.ComputeOffsets();
            body.PreserveMaxStackSize = true;

            ReduceSeqPoints(body);
        }
コード例 #23
0
            public override void Process(ConfusionParameter parameter)
            {
                Database.AddEntry("Const", "Type", parameter.GlobalParameters["type"] ?? "normal");
                if (parameter.GlobalParameters["type"] != "dynamic" &&
                    parameter.GlobalParameters["type"] != "native")
                {
                    ProcessSafe(parameter); return;
                }
                _Context txt = cc.txts[mod];

                txt.isNative = parameter.GlobalParameters["type"] == "native";
                txt.isDyn    = parameter.GlobalParameters["type"] == "dynamic";

                TypeDefinition modType = mod.GetType("<Module>");

                FieldDefinition constTbl = new FieldDefinition(
                    ObfuscationHelper.GetRandomName(),
                    FieldAttributes.Static | FieldAttributes.CompilerControlled,
                    mod.Import(typeof(Dictionary <uint, object>)));

                modType.Fields.Add(constTbl);
                AddHelper(constTbl, HelperAttribute.NoInjection);

                Database.AddEntry("Const", "ConstTbl", constTbl.FullName);

                FieldDefinition constBuffer = new FieldDefinition(
                    ObfuscationHelper.GetRandomName(),
                    FieldAttributes.Static | FieldAttributes.CompilerControlled,
                    mod.Import(typeof(byte[])));

                modType.Fields.Add(constBuffer);
                AddHelper(constBuffer, HelperAttribute.NoInjection);
                Database.AddEntry("Const", "ConstBuffer", constBuffer.FullName);


                if (txt.isNative)
                {
                    txt.nativeDecr = new MethodDefinition(
                        ObfuscationHelper.GetRandomName(),
                        MethodAttributes.Abstract | MethodAttributes.CompilerControlled |
                        MethodAttributes.ReuseSlot | MethodAttributes.Static,
                        mod.TypeSystem.Int32);
                    txt.nativeDecr.ImplAttributes = MethodImplAttributes.Native;
                    txt.nativeDecr.Parameters.Add(new ParameterDefinition(mod.TypeSystem.Int32));
                    modType.Methods.Add(txt.nativeDecr);
                    Database.AddEntry("Const", "NativeDecr", txt.nativeDecr.FullName);
                }

                var expGen = new ExpressionGenerator(Random.Next());
                int seed   = expGen.Seed;

                if (txt.isNative)
                {
                    do
                    {
                        txt.exp    = new ExpressionGenerator(Random.Next()).Generate(6);
                        txt.invExp = ExpressionInverser.InverseExpression(txt.exp);
                    } while ((txt.visitor = new x86Visitor(txt.invExp, null)).RegisterOverflowed);
                }
                else
                {
                    txt.exp    = expGen.Generate(10);
                    txt.invExp = ExpressionInverser.InverseExpression(txt.exp);
                }
                Database.AddEntry("Const", "Exp", txt.exp);
                Database.AddEntry("Const", "InvExp", txt.invExp);

                txt.consters = CreateConsters(txt, Confuser.Random, "Initialize", constTbl, constBuffer);
            }
コード例 #24
0
ファイル: MdReduceConfusion.cs プロジェクト: n017/Confuser
        public override void Process(ConfusionParameter parameter)
        {
            IMemberDefinition def = parameter.Target as IMemberDefinition;

            TypeDefinition t;
            if ((t = def as TypeDefinition) != null && !IsTypePublic(t))
            {
                if (t.IsEnum)
                {
                    int idx = 0;
                    while (t.Fields.Count != 1)
                        if (t.Fields[idx].Name != "value__")
                            t.Fields.RemoveAt(idx);
                        else
                            idx++;
                    Database.AddEntry("MdReduce", t.FullName, "Enum");
                }
            }
            else if (def is EventDefinition)
            {
                if (def.DeclaringType != null)
                {
                    Database.AddEntry("MdReduce", def.FullName, "Evt");
                    def.DeclaringType.Events.Remove(def as EventDefinition);
                }
            }
            else if (def is PropertyDefinition)
            {
                if (def.DeclaringType != null)
                {
                    Database.AddEntry("MdReduce", def.FullName, "Prop");
                    def.DeclaringType.Properties.Remove(def as PropertyDefinition);
                }
            }
        }
コード例 #25
0
ファイル: ConstantConfusion.cs プロジェクト: n017/Confuser
            public override void Process(ConfusionParameter parameter)
            {
                Database.AddEntry("Const", "Type", parameter.GlobalParameters["type"] ?? "normal");
                if (parameter.GlobalParameters["type"] != "dynamic" &&
                    parameter.GlobalParameters["type"] != "native")
                {
                    ProcessSafe(parameter); return;
                }
                _Context txt = cc.txts[mod];
                txt.isNative = parameter.GlobalParameters["type"] == "native";
                txt.isDyn = parameter.GlobalParameters["type"] == "dynamic";

                TypeDefinition modType = mod.GetType("<Module>");

                FieldDefinition constTbl = new FieldDefinition(
                    ObfuscationHelper.GetRandomName(),
                    FieldAttributes.Static | FieldAttributes.CompilerControlled,
                    mod.Import(typeof(Dictionary<uint, object>)));
                modType.Fields.Add(constTbl);
                AddHelper(constTbl, HelperAttribute.NoInjection);

                Database.AddEntry("Const", "ConstTbl", constTbl.FullName);

                FieldDefinition constBuffer = new FieldDefinition(
                    ObfuscationHelper.GetRandomName(),
                    FieldAttributes.Static | FieldAttributes.CompilerControlled,
                    mod.Import(typeof(byte[])));
                modType.Fields.Add(constBuffer);
                AddHelper(constBuffer, HelperAttribute.NoInjection);
                Database.AddEntry("Const", "ConstBuffer", constBuffer.FullName);

                if (txt.isNative)
                {
                    txt.nativeDecr = new MethodDefinition(
                        ObfuscationHelper.GetRandomName(),
                        MethodAttributes.Abstract | MethodAttributes.CompilerControlled |
                        MethodAttributes.ReuseSlot | MethodAttributes.Static,
                        mod.TypeSystem.Int32);
                    txt.nativeDecr.ImplAttributes = MethodImplAttributes.Native;
                    txt.nativeDecr.Parameters.Add(new ParameterDefinition(mod.TypeSystem.Int32));
                    modType.Methods.Add(txt.nativeDecr);
                    Database.AddEntry("Const", "NativeDecr", txt.nativeDecr.FullName);
                }

                var expGen = new ExpressionGenerator(Random.Next());
                int seed = expGen.Seed;
                if (txt.isNative)
                {
                    do
                    {
                        txt.exp = new ExpressionGenerator(Random.Next()).Generate(6);
                        txt.invExp = ExpressionInverser.InverseExpression(txt.exp);
                    } while ((txt.visitor = new x86Visitor(txt.invExp, null)).RegisterOverflowed);
                }
                else
                {
                    txt.exp = expGen.Generate(10);
                    txt.invExp = ExpressionInverser.InverseExpression(txt.exp);
                }
                Database.AddEntry("Const", "Exp", txt.exp);
                Database.AddEntry("Const", "InvExp", txt.invExp);

                txt.consters = CreateConsters(txt, Confuser.Random, "Initialize", constTbl, constBuffer);
            }
コード例 #26
0
ファイル: StringConfusion.cs プロジェクト: n017/Confuser
            public override void Process(ConfusionParameter parameter)
            {
                if (Array.IndexOf(parameter.GlobalParameters.AllKeys, "dynamic") == -1)
                {
                    ProcessSafe(parameter); return;
                }

                Random rand = new Random();
                TypeDefinition modType = mod.GetType("<Module>");

                AssemblyDefinition id = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location);
                sc.strer = id.MainModule.GetType("Encryptions").Methods.FirstOrDefault(mtd => mtd.Name == "Strings");
                sc.strer = CecilHelper.Inject(mod, sc.strer);
                modType.Methods.Add(sc.strer);
                byte[] n = new byte[0x10]; rand.NextBytes(n);
                sc.strer.Name = Encoding.UTF8.GetString(n);
                sc.strer.IsAssembly = true;
                AddHelper(sc.strer, HelperAttribute.NoInjection);

                sc.key0 = (int)(rand.NextDouble() * int.MaxValue);
                sc.key1 = (int)(rand.NextDouble() * int.MaxValue);

                rand.NextBytes(n);
                byte[] dat = new byte[0x10];
                rand.NextBytes(dat);

                sc.strer.Body.SimplifyMacros();
                for (int i = 0; i < sc.strer.Body.Instructions.Count; i++)
                {
                    Instruction inst = sc.strer.Body.Instructions[i];
                    if ((inst.Operand as string) == "PADDINGPADDINGPADDING")
                        inst.Operand = Encoding.UTF8.GetString(n);
                    if ((inst.Operand as string) == "PADDINGPADDINGPADDINGPADDING")
                        inst.Operand = Encoding.UTF8.GetString(dat);
                    else if (inst.Operand is int && (int)inst.Operand == 12345678)
                        inst.Operand = sc.key0;
                    else if (inst.Operand is int && (int)inst.Operand == 87654321)
                        inst.Operand = sc.key1;
                }

                sc.resId = Encoding.UTF8.GetString(n);
            }
コード例 #27
0
ファイル: ConstantConfusion.cs プロジェクト: n017/Confuser
            public override void Process(ConfusionParameter parameter)
            {
                _Context txt = cc.txts[mod];

                foreach (var i in txt.consters)
                {
                    i.keyInst.OpCode = OpCodes.Ldc_I4;
                    i.keyInst.Operand = (int)(txt.key ^ i.conster.MetadataToken.ToUInt32());
                }

                List<Context> txts = new List<Context>();
                ExtractData(
                    parameter.Target as IList<Tuple<IAnnotationProvider, NameValueCollection>>, txts,
                    Array.IndexOf(parameter.GlobalParameters.AllKeys, "numeric") != -1, txt);

                txt.dict.Clear();

                for (int i = 0; i < txts.Count; i++)
                {
                    object val = txts[i].str.Operand as object;
                    if (IsNull(val)) continue;

                    uint x = txts[i].conster.conster.DeclaringType.MetadataToken.ToUInt32() * txts[i].a;
                    ulong hash = ComputeHash(x,
                                (uint)txts[i].conster.key3,
                                (ulong)txts[i].conster.key0,
                                (ulong)txts[i].conster.key1,
                                (ulong)txts[i].conster.key2);
                    uint idx, len;
                    if (txt.dict.ContainsKey(val))
                        txts[i].b = Combine(idx = (uint)txt.dict[val], len = GetOperandLen(val)) ^ hash;
                    else
                    {
                        byte[] dat = GetOperand(val);
                        txts[i].b = Combine(idx = (uint)txt.idx, len = (uint)dat.Length) ^ hash;

                        txt.dats.Add(dat);
                        txt.dict[val] = txt.idx;

                        txt.idx += dat.Length;
                    }
                    Database.AddEntry("Const", val.ToString(), string.Format("{0:X}, {1:X}, {2:X}, {3:X}", txts[i].a, txts[i].b, idx, len));
                }

                FinalizeBodies(txts);
            }
コード例 #28
0
ファイル: StringConfusion.cs プロジェクト: n017/Confuser
            private void ProcessSafe(ConfusionParameter parameter)
            {
                Random rand = new Random();
                TypeDefinition modType = mod.GetType("<Module>");

                AssemblyDefinition i = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location);
                sc.strer = i.MainModule.GetType("Encryptions").Methods.FirstOrDefault(mtd => mtd.Name == "SafeStrings");
                sc.strer = CecilHelper.Inject(mod, sc.strer);
                modType.Methods.Add(sc.strer);
                byte[] n = new byte[0x10]; rand.NextBytes(n);
                sc.strer.Name = Encoding.UTF8.GetString(n);
                sc.strer.IsAssembly = true;

                sc.key0 = (int)(rand.NextDouble() * int.MaxValue);
                sc.key1 = (int)(rand.NextDouble() * int.MaxValue);
                sc.key2 = (int)(rand.NextDouble() * int.MaxValue);

                rand.NextBytes(n);
                byte[] dat = new byte[0x10];
                rand.NextBytes(dat);

                sc.strer.Body.SimplifyMacros();
                foreach (Instruction inst in sc.strer.Body.Instructions)
                {
                    if ((inst.Operand as string) == "PADDINGPADDINGPADDING")
                        inst.Operand = Encoding.UTF8.GetString(n);
                    if ((inst.Operand as string) == "PADDINGPADDINGPADDINGPADDING")
                        inst.Operand = Encoding.UTF8.GetString(dat);
                    else if (inst.Operand is int && (int)inst.Operand == 12345678)
                        inst.Operand = sc.key0;
                    else if (inst.Operand is int && (int)inst.Operand == 87654321)
                        inst.Operand = sc.key1;
                    else if (inst.Operand is int && (int)inst.Operand == 88888888)
                        inst.Operand = sc.key2;
                }
                sc.strer.Body.OptimizeMacros();
                sc.strer.Body.ComputeOffsets();

                sc.resId = Encoding.UTF8.GetString(n);
            }
コード例 #29
0
ファイル: CtorProxyConfusion.cs プロジェクト: n017/Confuser
            public override void Process(ConfusionParameter parameter)
            {
                _Context txt = cc.txts[mod];
                txt.isNative = parameter.GlobalParameters["type"] == "native";
                bool onlyExternal = true;
                if (Array.IndexOf(parameter.GlobalParameters.AllKeys, "onlyExternal") != -1)
                {
                    if (!bool.TryParse(parameter.GlobalParameters["onlyExternal"], out onlyExternal))
                    {
                        Log("Invaild onlyExternal parameter, only external reference will be proxied.");
                        onlyExternal = true;
                    }
                }
                Database.AddEntry("CtorProxy", "OnlyExternal", onlyExternal);

                IList<Tuple<IAnnotationProvider, NameValueCollection>> targets = parameter.Target as IList<Tuple<IAnnotationProvider, NameValueCollection>>;
                for (int i = 0; i < targets.Count; i++)
                {
                    MethodDefinition mtd = targets[i].Item1 as MethodDefinition;
                    if (!mtd.HasBody || mtd.DeclaringType.FullName == "<Module>") continue;

                    MethodBody bdy = mtd.Body;
                    foreach (Instruction inst in bdy.Instructions)
                    {
                        if (inst.OpCode.Code == Code.Newobj &&
                            (!onlyExternal || !(inst.Operand is MethodDefinition)) &&
                            !((inst.Operand as MethodReference).DeclaringType is GenericInstanceType) &&
                            !((inst.Operand as MethodReference).DeclaringType is ArrayType) &&  //avoid array
                            !(inst.Operand is GenericInstanceMethod))
                        {
                            CreateDelegate(mtd.Body, inst, inst.Operand as MethodReference, mod);
                        }
                    }
                    progresser.SetProgress(i + 1, targets.Count);
                }
                int total = cc.txts.Count;
                int interval = 1;
                if (total > 1000)
                    interval = (int)total / 100;
                for (int i = 0; i < txt.txts.Count; i++)
                {
                    CreateFieldBridge(mod, txt.txts[i]);
                    if (i % interval == 0 || i == txt.txts.Count - 1)
                        progresser.SetProgress(i + 1, total);
                }
            }
コード例 #30
0
ファイル: StringConfusion.cs プロジェクト: n017/Confuser
            public override void Process(ConfusionParameter parameter)
            {
                if (Array.IndexOf(parameter.GlobalParameters.AllKeys, "dynamic") == -1)
                {
                    ProcessSafe(parameter); return;
                }

                List<Context> txts = new List<Context>();

                foreach (MethodDefinition mtd in parameter.Target as IList<IAnnotationProvider>)
                {
                    if (mtd == sc.strer || !mtd.HasBody) continue;
                    var bdy = mtd.Body;
                    bdy.SimplifyMacros();
                    var insts = bdy.Instructions;
                    ILProcessor psr = bdy.GetILProcessor();
                    for (int i = 0; i < insts.Count; i++)
                    {
                        if (insts[i].OpCode.Code == Code.Ldstr)
                            txts.Add(new Context() { mtd = mtd, psr = psr, str = insts[i] });
                    }
                }

                double total = txts.Count;
                int interval = 1;
                if (total > 1000)
                    interval = (int)total / 100;

                int[] ids;
                bool retry;
                do
                {
                    ids = new int[txts.Count];
                    retry = false;
                    sc.dict.Clear();
                    int seed;
                    sc.exp = ExpressionGenerator.Generate(5, out seed);

                    for (int i = 0; i < txts.Count; i++)
                    {
                        string val = txts[i].str.Operand as string;
                        if (val == "") continue;

                        if (sc.dict.ContainsKey(val))
                            ids[i] = (int)((sc.dict[val] + sc.key0) ^ txts[i].mtd.MetadataToken.ToUInt32());
                        else
                        {
                            ids[i] = (int)((sc.idx + sc.key0) ^ txts[i].mtd.MetadataToken.ToUInt32());
                            int len;
                            byte[] dat = Encrypt(val, sc.exp, out len);
                            try
                            {
                                if (Decrypt(dat, len, sc.exp) != val)
                                {
                                    retry = true;
                                    break;
                                }
                            }
                            catch
                            {
                                retry = true;
                                break;
                            }
                            len = (int)~(len ^ sc.key1);

                            byte[] final = new byte[dat.Length + 4];
                            Buffer.BlockCopy(dat, 0, final, 4, dat.Length);
                            Buffer.BlockCopy(BitConverter.GetBytes(len), 0, final, 0, 4);
                            sc.dats.Add(final);
                            sc.dict[val] = sc.idx;
                            sc.idx += final.Length;
                        }
                    }
                } while (retry);

                for (int i = 0; i < sc.strer.Body.Instructions.Count; i++)
                {
                    Instruction inst = sc.strer.Body.Instructions[i];
                    if (inst.Operand is MethodReference && ((MethodReference)inst.Operand).Name == "PolyStart")
                    {
                        List<Instruction> insts = new List<Instruction>();
                        int ptr = i + 1;
                        while (ptr < sc.strer.Body.Instructions.Count)
                        {
                            Instruction z = sc.strer.Body.Instructions[ptr];
                            sc.strer.Body.Instructions.Remove(z);
                            if (z.Operand is MethodReference && ((MethodReference)z.Operand).Name == "PlaceHolder")
                                break;
                            insts.Add(z);
                        }

                        Instruction[] expInsts = new CecilVisitor(sc.exp, true, insts.ToArray(), false).GetInstructions();
                        ILProcessor psr = sc.strer.Body.GetILProcessor();
                        psr.Replace(inst, expInsts[0]);
                        for (int ii = 1; ii < expInsts.Length; ii++)
                        {
                            psr.InsertAfter(expInsts[ii - 1], expInsts[ii]);
                        }
                    }
                }
                sc.strer.Body.OptimizeMacros();
                sc.strer.Body.ComputeOffsets();

                for (int i = 0; i < txts.Count; i++)
                {
                    int idx = txts[i].mtd.Body.Instructions.IndexOf(txts[i].str);
                    Instruction now = txts[i].str;
                    if (now.Operand as string == "") continue;
                    txts[i].psr.InsertAfter(idx, txts[i].psr.Create(OpCodes.Call, sc.strer));
                    txts[i].psr.Replace(idx, txts[i].psr.Create(OpCodes.Ldc_I4, ids[i]));
                    if (i % interval == 0 || i == txts.Count - 1)
                        progresser.SetProgress((i + 1) / total);
                }

                List<int> hashs = new List<int>();
                for (int i = 0; i < txts.Count; i++)
                {
                    if (hashs.IndexOf(txts[i].mtd.GetHashCode()) == -1)
                    {
                        txts[i].mtd.Body.OptimizeMacros();
                        txts[i].mtd.Body.ComputeHeader();
                        hashs.Add(txts[i].mtd.GetHashCode());
                    }
                }
            }
コード例 #31
0
            private void ProcessSafe(ConfusionParameter parameter)
            {
                Random         rand    = new Random();
                TypeDefinition modType = mod.GetType("<Module>");

                AssemblyDefinition i = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location);

                cc.strer = i.MainModule.GetType("Encryptions").Methods.FirstOrDefault(mtd => mtd.Name == "SafeConstants");
                cc.strer = CecilHelper.Inject(mod, cc.strer);
                modType.Methods.Add(cc.strer);
                byte[] n = new byte[0x10]; rand.NextBytes(n);
                cc.strer.Name       = Encoding.UTF8.GetString(n);
                cc.strer.IsAssembly = true;

                cc.key0 = rand.Next();
                cc.key1 = rand.Next();
                cc.key2 = rand.Next();
                cc.key3 = rand.Next();

                rand.NextBytes(n);
                byte[] dat = new byte[0x10];
                rand.NextBytes(dat);
                rand.NextBytes(cc.types);
                while (cc.types.Distinct().Count() != 5)
                {
                    rand.NextBytes(cc.types);
                }

                cc.strer.Body.SimplifyMacros();
                foreach (Instruction inst in cc.strer.Body.Instructions)
                {
                    if ((inst.Operand as string) == "PADDINGPADDINGPADDING")
                    {
                        inst.Operand = Encoding.UTF8.GetString(n);
                    }
                    if ((inst.Operand as string) == "PADDINGPADDINGPADDINGPADDING")
                    {
                        inst.Operand = Encoding.UTF8.GetString(dat);
                    }
                    else if (inst.Operand is int && (int)inst.Operand == 12345678)
                    {
                        inst.Operand = cc.key0;
                    }
                    else if (inst.Operand is int && (int)inst.Operand == 0x67452301)
                    {
                        inst.Operand = cc.key1;
                    }
                    else if (inst.Operand is int && (int)inst.Operand == 0x3bd523a0)
                    {
                        inst.Operand = cc.key2;
                    }
                    else if (inst.Operand is int && (int)inst.Operand == 0x5f6f36c0)
                    {
                        inst.Operand = cc.key3;
                    }
                    else if (inst.Operand is int && (int)inst.Operand == 11)
                    {
                        inst.Operand = (int)cc.types[0];
                    }
                    else if (inst.Operand is int && (int)inst.Operand == 22)
                    {
                        inst.Operand = (int)cc.types[1];
                    }
                    else if (inst.Operand is int && (int)inst.Operand == 33)
                    {
                        inst.Operand = (int)cc.types[2];
                    }
                    else if (inst.Operand is int && (int)inst.Operand == 44)
                    {
                        inst.Operand = (int)cc.types[3];
                    }
                    else if (inst.Operand is int && (int)inst.Operand == 55)
                    {
                        inst.Operand = (int)cc.types[4];
                    }
                }
                cc.strer.Body.OptimizeMacros();
                cc.strer.Body.ComputeOffsets();

                cc.resId = Encoding.UTF8.GetString(n);
            }
コード例 #32
0
ファイル: StringConfusion.cs プロジェクト: n017/Confuser
            void ProcessSafe(ConfusionParameter parameter)
            {
                List<Context> txts = new List<Context>();

                foreach (MethodDefinition mtd in parameter.Target as IList<IAnnotationProvider>)
                {
                    if (mtd == sc.strer || !mtd.HasBody) continue;
                    var bdy = mtd.Body;
                    bdy.SimplifyMacros();
                    var insts = bdy.Instructions;
                    ILProcessor psr = bdy.GetILProcessor();
                    for (int i = 0; i < insts.Count; i++)
                    {
                        if (insts[i].OpCode.Code == Code.Ldstr)
                            txts.Add(new Context() { mtd = mtd, psr = psr, str = insts[i] });
                    }
                }

                double total = txts.Count;
                int interval = 1;
                if (total > 1000)
                    interval = (int)total / 100;
                for (int i = 0; i < txts.Count; i++)
                {
                    int idx = txts[i].mtd.Body.Instructions.IndexOf(txts[i].str);
                    string val = txts[i].str.Operand as string;
                    if (val == "") continue;

                    int id;
                    if (sc.dict.ContainsKey(val))
                        id = (int)((sc.dict[val] + sc.key0) ^ txts[i].mtd.MetadataToken.ToUInt32());
                    else
                    {
                        byte[] dat = EncryptSafe(val, sc.key2);
                        id = (int)((sc.idx + sc.key0) ^ txts[i].mtd.MetadataToken.ToUInt32());
                        int len = (int)~(dat.Length ^ sc.key1);

                        byte[] final = new byte[dat.Length + 4];
                        Buffer.BlockCopy(dat, 0, final, 4, dat.Length);
                        Buffer.BlockCopy(BitConverter.GetBytes(len), 0, final, 0, 4);
                        sc.dats.Add(final);
                        sc.dict[val] = sc.idx;
                        sc.idx += final.Length;
                    }

                    Instruction now = txts[i].str;
                    txts[i].psr.InsertAfter(idx, txts[i].psr.Create(OpCodes.Call, sc.strer));
                    txts[i].psr.Replace(idx, txts[i].psr.Create(OpCodes.Ldc_I4, id));

                    if (i % interval == 0 || i == txts.Count - 1)
                        progresser.SetProgress((i + 1) / total);
                }

                List<int> hashs = new List<int>();
                for (int i = 0; i < txts.Count; i++)
                {
                    if (hashs.IndexOf(txts[i].mtd.GetHashCode()) == -1)
                    {
                        txts[i].mtd.Body.OptimizeMacros();
                        txts[i].mtd.Body.ComputeHeader();
                        hashs.Add(txts[i].mtd.GetHashCode());
                    }
                }
            }
コード例 #33
0
        public override void Process(ConfusionParameter parameter)
        {

            List<Context> txts = new List<Context>();
            IList<IAnnotationProvider> targets = parameter.Target as IList<IAnnotationProvider>;
            for (int i = 0; i < targets.Count; i++)
            {
                MethodDefinition mtd = targets[i] as MethodDefinition;
                if (!mtd.HasBody) continue;
                mtd.Body.SimplifyMacros();
                int lv = 5;
                if (Array.IndexOf(parameter.Parameters.AllKeys, mtd.GetHashCode().ToString("X8") + "_level") != -1)
                {
                    if (!int.TryParse(parameter.Parameters[mtd.GetHashCode().ToString("X8") + "_level"], out lv) && (lv <= 0 || lv > 10))
                    {
                        Log("Invaild level, 5 will be used.");
                        lv = 5;
                    }
                }
                foreach(Instruction inst in mtd.Body.Instructions)
                {
                    if ((inst.OpCode.Name == "ldc.i4" && (int)inst.Operand != -1 && (int)inst.Operand != 0 && (int)inst.Operand != 1) ||
                        //(inst.OpCode.Name == "ldc.i8" && (long)inst.Operand != -1 && (long)inst.Operand != 0 && (long)inst.Operand != 1) ||
                        (inst.OpCode.Name == "ldc.r4" && (float)inst.Operand != -1 && (float)inst.Operand != 0 && (float)inst.Operand != 1) ||
                        (inst.OpCode.Name == "ldc.r8" && (double)inst.Operand != -1 && (double)inst.Operand != 0 && (double)inst.Operand != 1))
                        txts.Add(new Context() { mtd = mtd, psr = mtd.Body.GetILProcessor(), inst = inst, lv = lv });
                }
                progresser.SetProgress((i + 1) / (double)targets.Count);
            }

            for (int i = 0; i < txts.Count; i++)
            {
                Context txt = txts[i];
                int instIdx = txt.mtd.Body.Instructions.IndexOf(txt.inst);
                double val = Convert.ToDouble(txt.inst.Operand);
                int seed;

                Expression exp;
                double eval = 0;
                double tmp = 0;
                do
                {
                    exp = ExpressionGenerator.Generate(txt.lv, out seed);
                    eval = DoubleExpressionEvaluator.Evaluate(exp, val);
                    try
                    {
                        tmp = DoubleExpressionEvaluator.ReverseEvaluate(exp, eval);
                    }
                    catch { continue; }
                } while (tmp != val);

                Instruction[] expInsts = new CecilVisitor(exp, true, new Instruction[] { Instruction.Create(OpCodes.Ldc_R8, eval) }, true).GetInstructions();
                if (expInsts.Length == 0) continue;
                string op = txt.inst.OpCode.Name;
                txt.psr.Replace(instIdx, expInsts[0]);
                for (int ii = 1; ii < expInsts.Length; ii++)
                {
                    txt.psr.InsertAfter(instIdx + ii - 1, expInsts[ii]);
                }
                switch (op)
                {
                    case "ldc.i4":
                        txt.psr.InsertAfter(instIdx +expInsts.Length - 1, Instruction.Create(OpCodes.Conv_I4)); break;
                    //case "ldc.i8":
                    //    txt.psr.InsertAfter(instIdx +expInsts.Length - 1, Instruction.Create(OpCodes.Conv_I8)); break;
                    case "ldc.r4":
                        txt.psr.InsertAfter(instIdx +expInsts.Length - 1, Instruction.Create(OpCodes.Conv_R4)); break;
                    case "ldc.r8":
                        txt.psr.InsertAfter(instIdx +expInsts.Length - 1, Instruction.Create(OpCodes.Conv_R8)); break;
                }

                progresser.SetProgress((i + 1) / (double)txts.Count);
            }
        }
コード例 #34
0
 public override void Process(ConfusionParameter parameter)
 {
 }
コード例 #35
0
            public override void Process(ConfusionParameter parameter)
            {
                if (Array.IndexOf(parameter.GlobalParameters.AllKeys, "dynamic") == -1)
                {
                    ProcessSafe(parameter); return;
                }

                List <Context> txts = new List <Context>();

                foreach (MethodDefinition mtd in parameter.Target as IList <IAnnotationProvider> )
                {
                    if (mtd == sc.strer || !mtd.HasBody)
                    {
                        continue;
                    }
                    var bdy = mtd.Body;
                    bdy.SimplifyMacros();
                    var         insts = bdy.Instructions;
                    ILProcessor psr   = bdy.GetILProcessor();
                    for (int i = 0; i < insts.Count; i++)
                    {
                        if (insts[i].OpCode.Code == Code.Ldstr)
                        {
                            txts.Add(new Context()
                            {
                                mtd = mtd, psr = psr, str = insts[i]
                            });
                        }
                    }
                }

                double total    = txts.Count;
                int    interval = 1;

                if (total > 1000)
                {
                    interval = (int)total / 100;
                }

                int[] ids;
                bool  retry;

                do
                {
                    ids   = new int[txts.Count];
                    retry = false;
                    sc.dict.Clear();
                    int seed;
                    sc.exp = ExpressionGenerator.Generate(5, out seed);

                    for (int i = 0; i < txts.Count; i++)
                    {
                        string val = txts[i].str.Operand as string;
                        if (val == "")
                        {
                            continue;
                        }

                        if (sc.dict.ContainsKey(val))
                        {
                            ids[i] = (int)((sc.dict[val] + sc.key0) ^ txts[i].mtd.MetadataToken.ToUInt32());
                        }
                        else
                        {
                            ids[i] = (int)((sc.idx + sc.key0) ^ txts[i].mtd.MetadataToken.ToUInt32());
                            int    len;
                            byte[] dat = Encrypt(val, sc.exp, out len);
                            try
                            {
                                if (Decrypt(dat, len, sc.exp) != val)
                                {
                                    retry = true;
                                    break;
                                }
                            }
                            catch
                            {
                                retry = true;
                                break;
                            }
                            len = (int)~(len ^ sc.key1);

                            byte[] final = new byte[dat.Length + 4];
                            Buffer.BlockCopy(dat, 0, final, 4, dat.Length);
                            Buffer.BlockCopy(BitConverter.GetBytes(len), 0, final, 0, 4);
                            sc.dats.Add(final);
                            sc.dict[val] = sc.idx;
                            sc.idx      += final.Length;
                        }
                    }
                } while (retry);

                for (int i = 0; i < sc.strer.Body.Instructions.Count; i++)
                {
                    Instruction inst = sc.strer.Body.Instructions[i];
                    if (inst.Operand is MethodReference && ((MethodReference)inst.Operand).Name == "PolyStart")
                    {
                        List <Instruction> insts = new List <Instruction>();
                        int ptr = i + 1;
                        while (ptr < sc.strer.Body.Instructions.Count)
                        {
                            Instruction z = sc.strer.Body.Instructions[ptr];
                            sc.strer.Body.Instructions.Remove(z);
                            if (z.Operand is MethodReference && ((MethodReference)z.Operand).Name == "PlaceHolder")
                            {
                                break;
                            }
                            insts.Add(z);
                        }

                        Instruction[] expInsts = new CecilVisitor(sc.exp, true, insts.ToArray(), false).GetInstructions();
                        ILProcessor   psr      = sc.strer.Body.GetILProcessor();
                        psr.Replace(inst, expInsts[0]);
                        for (int ii = 1; ii < expInsts.Length; ii++)
                        {
                            psr.InsertAfter(expInsts[ii - 1], expInsts[ii]);
                        }
                    }
                }
                sc.strer.Body.OptimizeMacros();
                sc.strer.Body.ComputeOffsets();

                for (int i = 0; i < txts.Count; i++)
                {
                    int         idx = txts[i].mtd.Body.Instructions.IndexOf(txts[i].str);
                    Instruction now = txts[i].str;
                    if (now.Operand as string == "")
                    {
                        continue;
                    }
                    txts[i].psr.InsertAfter(idx, txts[i].psr.Create(OpCodes.Call, sc.strer));
                    txts[i].psr.Replace(idx, txts[i].psr.Create(OpCodes.Ldc_I4, ids[i]));
                    if (i % interval == 0 || i == txts.Count - 1)
                    {
                        progresser.SetProgress((i + 1) / total);
                    }
                }

                List <int> hashs = new List <int>();

                for (int i = 0; i < txts.Count; i++)
                {
                    if (hashs.IndexOf(txts[i].mtd.GetHashCode()) == -1)
                    {
                        txts[i].mtd.Body.OptimizeMacros();
                        txts[i].mtd.Body.ComputeHeader();
                        hashs.Add(txts[i].mtd.GetHashCode());
                    }
                }
            }
コード例 #36
0
ファイル: StackUnfConfusion.cs プロジェクト: n017/Confuser
        public override void Process(ConfusionParameter parameter)
        {
            MethodDefinition mtd = parameter.Target as MethodDefinition;

            if (!mtd.HasBody) return;
            MethodBody bdy = mtd.Body;
            ILProcessor wkr = bdy.GetILProcessor();

            Instruction original = bdy.Instructions[0];
            Instruction jmp = wkr.Create(OpCodes.Br_S, original);

            Instruction stackundering = wkr.Create(OpCodes.Pop);
            Instruction stackrecovering;
            switch (rad.Next(0, 4))
            {
                case 0:
                    stackrecovering = wkr.Create(OpCodes.Ldnull); break;
                case 1:
                    stackrecovering = wkr.Create(OpCodes.Ldc_I4_0); break;
                case 2:
                    stackrecovering = wkr.Create(OpCodes.Ldstr, ""); break;
                default:
                    stackrecovering = wkr.Create(OpCodes.Ldc_I8, (long)rad.Next()); break;
            }
            wkr.InsertBefore(original, stackrecovering);
            wkr.InsertBefore(stackrecovering, stackundering);
            wkr.InsertBefore(stackundering, jmp);

            foreach (ExceptionHandler eh in bdy.ExceptionHandlers)
            {
                if (eh.TryStart == original)
                    eh.TryStart = jmp;
                else if (eh.HandlerStart == original)
                    eh.HandlerStart = jmp;
                else if (eh.FilterStart == original)
                    eh.FilterStart = jmp;
            }
        }
コード例 #37
0
            public override void Process(ConfusionParameter parameter)
            {
                _Context txt = mc.txts[mod];

                txt.isNative = parameter.GlobalParameters["type"] == "native";
                bool onlyExternal = true;

                if (Array.IndexOf(parameter.GlobalParameters.AllKeys, "onlyExternal") != -1)
                {
                    if (!bool.TryParse(parameter.GlobalParameters["onlyExternal"], out onlyExternal))
                    {
                        Log("Invaild onlyExternal parameter, only external reference will be proxied.");
                        onlyExternal = true;
                    }
                }
                Database.AddEntry("MtdProxy", "OnlyExternal", onlyExternal);

                IList <Tuple <IAnnotationProvider, NameValueCollection> > targets = parameter.Target as IList <Tuple <IAnnotationProvider, NameValueCollection> >;

                for (int i = 0; i < targets.Count; i++)
                {
                    MethodDefinition mtd = targets[i].Item1 as MethodDefinition;
                    if (!mtd.HasBody || mtd.DeclaringType.FullName == "<Module>")
                    {
                        continue;
                    }

                    MethodBody bdy = mtd.Body;
                    foreach (Instruction inst in bdy.Instructions)
                    {
                        if ((inst.OpCode.Code == Code.Call || inst.OpCode.Code == Code.Callvirt) &&
                            (!onlyExternal || !(inst.Operand is MethodDefinition)) &&

                            (inst.Operand as MethodReference).Name != ".ctor" && (inst.Operand as MethodReference).Name != ".cctor" &&  //no constructor

                            !((inst.Operand as MethodReference).DeclaringType is GenericInstanceType) &&                                //no generic

                            ((inst.Operand as MethodReference).DeclaringType.Resolve() == null ||
                             !(inst.Operand as MethodReference).DeclaringType.Resolve().IsInterface) &&                                 //no interface

                            (!(inst.Operand is MethodDefinition) ||
                             (inst.Operand as MethodDefinition).ImplAttributes != MethodImplAttributes.Native) &&                       //no native

                            (inst.Previous == null || inst.Previous.OpCode.OpCodeType != OpCodeType.Prefix))                            //no prefix
                        {
                            CreateDelegate(mtd.Body, inst, inst.Operand as MethodReference, mod);
                        }
                    }
                    progresser.SetProgress(i + 1, targets.Count);
                }
                int total    = mc.txts.Count;
                int interval = 1;

                if (total > 1000)
                {
                    interval = (int)total / 100;
                }
                for (int i = 0; i < txt.txts.Count; i++)
                {
                    CreateFieldBridge(mod, txt.txts[i]);
                    if (i % interval == 0 || i == txt.txts.Count - 1)
                    {
                        progresser.SetProgress(i + 1, total);
                    }
                }
            }
コード例 #38
0
            public override void Process(ConfusionParameter parameter)
            {
                if (Array.IndexOf(parameter.GlobalParameters.AllKeys, "dynamic") == -1)
                {
                    ProcessSafe(parameter); return;
                }

                Random         rand    = new Random();
                TypeDefinition modType = mod.GetType("<Module>");

                AssemblyDefinition id = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location);

                cc.strer = id.MainModule.GetType("Encryptions").Methods.FirstOrDefault(mtd => mtd.Name == "Constants");
                cc.strer = CecilHelper.Inject(mod, cc.strer);
                modType.Methods.Add(cc.strer);
                byte[] n = new byte[0x10]; rand.NextBytes(n);
                cc.strer.Name       = Encoding.UTF8.GetString(n);
                cc.strer.IsAssembly = true;
                AddHelper(cc.strer, HelperAttribute.NoInjection);

                cc.key0 = (int)(rand.NextDouble() * int.MaxValue);
                cc.key1 = (int)(rand.NextDouble() * int.MaxValue);
                cc.key2 = (int)(rand.NextDouble() * int.MaxValue);
                cc.key3 = (int)(rand.NextDouble() * int.MaxValue);

                rand.NextBytes(n);
                byte[] dat = new byte[0x10];
                rand.NextBytes(dat);
                rand.NextBytes(cc.types);
                while (cc.types.Distinct().Count() != 5)
                {
                    rand.NextBytes(cc.types);
                }

                cc.strer.Body.SimplifyMacros();
                foreach (Instruction inst in cc.strer.Body.Instructions)
                {
                    if ((inst.Operand as string) == "PADDINGPADDINGPADDING")
                    {
                        inst.Operand = Encoding.UTF8.GetString(n);
                    }
                    if ((inst.Operand as string) == "PADDINGPADDINGPADDINGPADDING")
                    {
                        inst.Operand = Encoding.UTF8.GetString(dat);
                    }
                    else if (inst.Operand is int && (int)inst.Operand == 12345678)
                    {
                        inst.Operand = cc.key0;
                    }
                    else if (inst.Operand is int && (int)inst.Operand == 0x67452301)
                    {
                        inst.Operand = cc.key1;
                    }
                    else if (inst.Operand is int && (int)inst.Operand == 0x3bd523a0)
                    {
                        inst.Operand = cc.key2;
                    }
                    else if (inst.Operand is int && (int)inst.Operand == 0x5f6f36c0)
                    {
                        inst.Operand = cc.key3;
                    }
                    else if (inst.Operand is int && (int)inst.Operand == 11)
                    {
                        inst.Operand = (int)cc.types[0];
                    }
                    else if (inst.Operand is int && (int)inst.Operand == 22)
                    {
                        inst.Operand = (int)cc.types[1];
                    }
                    else if (inst.Operand is int && (int)inst.Operand == 33)
                    {
                        inst.Operand = (int)cc.types[2];
                    }
                    else if (inst.Operand is int && (int)inst.Operand == 44)
                    {
                        inst.Operand = (int)cc.types[3];
                    }
                    else if (inst.Operand is int && (int)inst.Operand == 55)
                    {
                        inst.Operand = (int)cc.types[4];
                    }
                }

                cc.resId = Encoding.UTF8.GetString(n);
            }
コード例 #39
0
ファイル: NameConfusion.cs プロジェクト: zippy1981/Confuser
        public override void Process(ConfusionParameter parameter)
        {
            IMemberDefinition mem = parameter.Target as IMemberDefinition;

            if (GetCancel(mem))
            {
                return;
            }

            var      mode = (NameMode)(mem.Module as IAnnotationProvider).Annotations[NameAnalyzer.RenMode];
            NameMode specMode;

            if (TryParse <NameMode>(parameter.GlobalParameters["type"], out specMode) && specMode > mode)
            {
                mode = specMode;
            }

            if (mem is TypeDefinition)
            {
                TypeDefinition type = mem as TypeDefinition;
                if (GetRenOk(type))
                {
                    string originalName  = type.Name;
                    string originalFName = TypeParser.ToParseable(type);

                    type.Name = ObfuscationHelper.GetNewName(originalFName, mode);
                    switch (mode)
                    {
                    case NameMode.Unreadable:
                        type.Namespace = ""; break;

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

                    case NameMode.Letters:
                        type.Namespace = "BANANA"; break;
                    }
                    Identifier id = (Identifier)(type as IAnnotationProvider).Annotations[NameAnalyzer.RenId];
                    Identifier n  = id;
                    n.name  = CecilHelper.GetName(type);
                    n.scope = CecilHelper.GetNamespace(type);
                    foreach (IReference refer in (type as IAnnotationProvider).Annotations[NameAnalyzer.RenRef] as List <IReference> )
                    {
                        refer.UpdateReference(id, n);
                    }
                    Database.AddEntry("Rename", originalName, type.Name);
                }
            }
            else if (mem is MethodDefinition)
            {
                MethodDefinition mtd = mem as MethodDefinition;
                PerformMethod(mtd, mode);
            }
            else if (GetRenOk(mem as IAnnotationProvider))
            {
                mem.Name = ObfuscationHelper.GetNewName(mem.Name, mode);
                Identifier id = (Identifier)(mem as IAnnotationProvider).Annotations[NameAnalyzer.RenId];
                Identifier n  = id;
                n.scope = mem.DeclaringType.FullName;
                n.name  = mem.Name;
                foreach (IReference refer in (mem as IAnnotationProvider).Annotations[NameAnalyzer.RenRef] as List <IReference> )
                {
                    refer.UpdateReference(id, n);
                }
            }
        }
コード例 #40
0
        public override void Process(ConfusionParameter parameter)
        {
            IMemberDefinition mem = parameter.Target as IMemberDefinition;
            if (GetCancel(mem))
                return;

            if (mem is TypeDefinition)
            {
                TypeDefinition type = mem as TypeDefinition;
                if (GetRenOk(type))
                {
                    string originalName = type.Name;
                    string originalFName = TypeParser.ToParseable(type);
                    var mode = (NameMode)(mem.Module as IAnnotationProvider).Annotations[NameAnalyzer.RenMode];
                    type.Name = ObfuscationHelper.GetNewName(originalFName, mode);
                    switch (mode)
                    {
                        case NameMode.Unreadable:
                            type.Namespace = ""; break;
                        case NameMode.ASCII:
                            type.Namespace = " "; break;
                        case NameMode.Letters:
                            type.Namespace = "BANANA"; break;
                    }
                    Identifier id = (Identifier)(type as IAnnotationProvider).Annotations[NameAnalyzer.RenId];
                    Identifier n = id;
                    n.name = CecilHelper.GetName(type);
                    n.scope = CecilHelper.GetNamespace(type);
                    foreach (IReference refer in (type as IAnnotationProvider).Annotations[NameAnalyzer.RenRef] as List<IReference>)
                    {
                        refer.UpdateReference(id, n);
                    }
                    Database.AddEntry("Rename", originalName, type.Name);
                }
            }
            else if (mem is MethodDefinition)
            {
                MethodDefinition mtd = mem as MethodDefinition;
                PerformMethod(mtd);
            }
            else if (GetRenOk(mem as IAnnotationProvider))
            {
                mem.Name = ObfuscationHelper.GetNewName(mem.Name, (NameMode)(mem.Module as IAnnotationProvider).Annotations[NameAnalyzer.RenMode]);
                Identifier id = (Identifier)(mem as IAnnotationProvider).Annotations[NameAnalyzer.RenId];
                Identifier n = id;
                n.scope = mem.DeclaringType.FullName;
                n.name = mem.Name;
                foreach (IReference refer in (mem as IAnnotationProvider).Annotations[NameAnalyzer.RenRef] as List<IReference>)
                {
                    refer.UpdateReference(id, n);
                }
            }
        }
コード例 #41
0
            public override void Process(ConfusionParameter parameter)
            {
                _Context txt = rc.txts[mod];

                txt.dats = new List <KeyValuePair <string, byte[]> >();

                TypeDefinition modType = mod.GetType("<Module>");

                AssemblyDefinition i = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location);

                i.MainModule.ReadSymbols();
                txt.reso = i.MainModule.GetType("Encryptions").Methods.FirstOrDefault(mtd => mtd.Name == "Resources");
                txt.reso = CecilHelper.Inject(mod, txt.reso);
                modType.Methods.Add(txt.reso);
                txt.reso.Name       = ObfuscationHelper.GetRandomName();
                txt.reso.IsAssembly = true;
                AddHelper(txt.reso, HelperAttribute.NoInjection);
                Database.AddEntry("ResEncrypt", "Resolver", txt.reso.FullName);

                TypeDefinition lzma = mod.GetType("Lzma" + mod.GetHashCode());

                if (lzma == null)
                {
                    lzma             = CecilHelper.Inject(mod, i.MainModule.GetType("Lzma"));
                    lzma.IsNotPublic = true;
                    lzma.Name        = "Lzma" + mod.GetHashCode();
                    mod.Types.Add(lzma);
                }

                FieldDefinition datAsm = new FieldDefinition(
                    ObfuscationHelper.GetRandomName(),
                    FieldAttributes.Static | FieldAttributes.CompilerControlled,
                    mod.Import(typeof(System.Reflection.Assembly)));

                modType.Fields.Add(datAsm);
                AddHelper(datAsm, HelperAttribute.NoInjection);
                Database.AddEntry("ResEncrypt", "Store", datAsm.FullName);

                txt.key0 = (byte)Random.Next(0, 0x100);
                do
                {
                    txt.key1 = (byte)Random.Next(1, 0x100);
                } while (txt.key1 == txt.key0);
                Database.AddEntry("ResEncrypt", "Key0", txt.key0);
                Database.AddEntry("ResEncrypt", "Key1", txt.key1);

                txt.resId = ObfuscationHelper.GetRandomName();
                Database.AddEntry("ResEncrypt", "ResID", txt.resId);

                Mutator mutator = new Mutator();

                mutator.StringKeys = new string[] { txt.resId };
                mutator.IntKeys    = new int[] { txt.key0, txt.key1 };
                mutator.Mutate(Random, txt.reso.Body, mod);
                foreach (Instruction inst in txt.reso.Body.Instructions)
                {
                    if (inst.Operand is FieldReference && (inst.Operand as FieldReference).Name == "datAsm")
                    {
                        inst.Operand = datAsm;
                    }
                    else if (inst.Operand is TypeReference && (inst.Operand as TypeReference).FullName == "System.Exception")
                    {
                        inst.Operand = modType;
                    }
                    else if (inst.Operand is MethodReference &&
                             (inst.Operand as MethodReference).DeclaringType.Name == "LzmaDecoder")
                    {
                        inst.Operand = lzma.NestedTypes
                                       .Single(_ => _.Name == "LzmaDecoder").Methods
                                       .Single(_ => _.Name == (inst.Operand as MethodReference).Name);
                    }
                }
                foreach (var x in txt.reso.Body.Variables)
                {
                    if (x.VariableType.Name == "LzmaDecoder")
                    {
                        x.VariableType = lzma.NestedTypes.Single(_ => _.Name == "LzmaDecoder");
                    }
                }

                MethodDefinition cctor = mod.GetType("<Module>").GetStaticConstructor();
                MethodBody       bdy   = cctor.Body as MethodBody;
                ILProcessor      psr   = bdy.GetILProcessor();

                //Reverse order
                psr.InsertBefore(0, Instruction.Create(OpCodes.Callvirt, mod.Import(typeof(AppDomain).GetEvent("ResourceResolve").GetAddMethod())));
                psr.InsertBefore(0, Instruction.Create(OpCodes.Newobj, mod.Import(typeof(ResolveEventHandler).GetConstructor(new Type[] { typeof(object), typeof(IntPtr) }))));
                psr.InsertBefore(0, Instruction.Create(OpCodes.Ldftn, txt.reso));
                psr.InsertBefore(0, Instruction.Create(OpCodes.Ldnull));
                psr.InsertBefore(0, Instruction.Create(OpCodes.Call, mod.Import(typeof(AppDomain).GetProperty("CurrentDomain").GetGetMethod())));
            }
コード例 #42
0
 public override void Process(ConfusionParameter parameter)
 {
     cion.vers[mod].Phase2(progresser, mod);
 }