Ejemplo n.º 1
0
 void ExtractData(IList <Tuple <IAnnotationProvider, NameValueCollection> > mtds,
                  List <Context> txts, bool num, _Context txt)
 {
     foreach (var tuple in mtds)
     {
         MethodDefinition mtd = tuple.Item1 as MethodDefinition;
         if (cc.txts[mod].consters.Any(_ => _.conster == mtd) || !mtd.HasBody)
         {
             continue;
         }
         var         bdy   = mtd.Body;
         var         insts = bdy.Instructions;
         ILProcessor psr   = bdy.GetILProcessor();
         for (int i = 0; i < insts.Count; i++)
         {
             if (insts[i].OpCode.Code == Code.Ldstr ||
                 (num && (insts[i].OpCode.Code == Code.Ldc_I4 ||
                          insts[i].OpCode.Code == Code.Ldc_I8 ||
                          insts[i].OpCode.Code == Code.Ldc_R4 ||
                          insts[i].OpCode.Code == Code.Ldc_R8)))
             {
                 txts.Add(new Context()
                 {
                     mtd     = mtd,
                     psr     = psr,
                     str     = insts[i],
                     a       = (uint)Random.Next(),
                     conster = txt.consters[Random.Next(0, txt.consters.Length)]
                 });
             }
         }
     }
 }
        public ActionResult<TblGeral> GeralIncluir(PostGeralModels request)
        {

            using (var context = new _Context())
            {
                if (string.IsNullOrEmpty(request.analista)) { return BadRequest("O campo \"Analista\" é obrigatório, favor preencher !"); }
                if (string.IsNullOrEmpty(request.nomeDoUsuario)) { return BadRequest("o campo \"Nome do usuario\" é obrigatório, Favor preencher !"); }
                if (string.IsNullOrEmpty(request.descricao)) { return BadRequest("o campo \"Descrição\" é obrigatório, Favor preencher !"); }

                var Validator = context.Filiais.Where(x => x.filial == request.filial).FirstOrDefault();
                if(Validator == null) {return NotFound($"Filial \"{request.filial}\" não encontrada !");}

                var Save = new TblGeral();

                Save.analista = request.analista;
                Save.descricao = request.descricao;
                Save.nomeDoUsuario = request.nomeDoUsuario;
                Save.filial = request.filial;
                Save.ticket = request.ticket;

                context.Add(Save);
                context.SaveChanges();
            }
            return Ok("Inclusão de dados salvo com Sucesso!");
        }
Ejemplo n.º 3
0
            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);
            }
Ejemplo n.º 4
0
            public override void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor)
            {
                _Context txt = cc.txts[accessor.Module];

                // update typedef table to have field list for <module> start at 2 instead of 1

                /*var tbl1 = accessor.TableHeap.GetTable<TypeDefTable>(Table.TypeDef);
                 *
                 * for (int i = 0; i < tbl1.Length; i++)//foreach (var tblRow in tbl1)
                 * {
                 *  var moduleTypeRow = tbl1[i];
                 *  moduleTypeRow.Col5 = moduleTypeRow.Col5 + 1;
                 *  tbl1[i] = moduleTypeRow;
                 * }*/



                if (!txt.isNative)
                {
                    return;
                }

                var tbl = accessor.TableHeap.GetTable <MethodTable>(Table.Method);
                var row = tbl[(int)txt.nativeDecr.MetadataToken.RID - 1];

                row.Col2  = MethodImplAttributes.Native | MethodImplAttributes.Unmanaged | MethodImplAttributes.PreserveSig;
                row.Col3 &= ~MethodAttributes.Abstract;
                row.Col3 |= MethodAttributes.PInvokeImpl;
                row.Col1  = txt.nativeRange.Start;
                accessor.BodyRanges[txt.nativeDecr.MetadataToken] = txt.nativeRange;

                tbl[(int)txt.nativeDecr.MetadataToken.RID - 1] = row;

                //accessor.Module.Attributes &= ~ModuleAttributes.ILOnly;
            }
        public ActionResult<TblDeltaLog> DeltaLogIncluir(PostDeltaLogModels request)
        {
            if (string.IsNullOrEmpty(request.motorista)) { return BadRequest("Campo Obrigatório, Favor digitar o nome do Motorista: "); }
            if (string.IsNullOrEmpty(request.shift)) { return BadRequest("Campo Obrigatório, Favor digitar o Numero da Shift: "); }
            if (string.IsNullOrEmpty(request.placa)) { return BadRequest("Campo Obrigatório, Favor digitar a Placa: "); }
            if (request.imei <= 0) { return BadRequest("Imei Invalido, Digte um Imei Válido para prosseguir:"); }
            if (string.IsNullOrEmpty(request.analista)) { return BadRequest("Campo Obrigatório, Favor digitar o nome do Analista em atadimento: "); }
            if (string.IsNullOrEmpty(request.problema)) { return BadRequest("Campo Obrigatório, Favor digitar o problema atual no App: "); }

            using (var context = new _Context())
            {
                var Save = new TblDeltaLog();

                Save.imei = request.imei;
                Save.motorista = request.motorista;
                Save.placa = request.placa;
                Save.problema = request.problema;
                Save.shift = request.shift;
                Save.acao = request.acao;
                Save.analista = request.analista;

                context.Add(Save);
                context.SaveChanges();
            }
            return Ok("Inclusão de dados salvo com Sucesso!");
        }
Ejemplo n.º 6
0
            public override void DeInitialize()
            {
                _Context txt = cc.txts[mod];

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

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

                Instruction placeholder = null;

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

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

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

                    CecilHelper.Replace(txt.proxy.Body, placeholder, new Instruction[]
                    {
                        Instruction.Create(OpCodes.Call, txt.nativeDecr)
                    });
                }
                else
                {
                    CecilHelper.Replace(txt.proxy.Body, placeholder, new Instruction[]
                    {
                        Instruction.Create(OpCodes.Ldc_I4, (int)txt.key),
                        Instruction.Create(OpCodes.Xor)
                    });
                }
            }
Ejemplo n.º 7
0
            private void CreateFieldBridge(ModuleDefinition Mod, Context txt)
            {
                _Context _txt = mc.txts[mod];

                ////////////////Field
                string fldId = GetId(Mod, txt.inst.OpCode.Name == "callvirt", txt.mtdRef);

                if (!_txt.fields.TryGetValue(fldId, out txt.fld))
                {
                    txt.fld = new FieldDefinition(fldId, FieldAttributes.Static | FieldAttributes.Assembly, txt.dele);
                    txt.dele.Fields.Add(txt.fld);
                    _txt.fields.Add(fldId, txt.fld);
                }
                ////////////////Bridge
                string           bridgeId = GetNameO(txt.inst.OpCode.Name == "callvirt", txt.mtdRef);
                MethodDefinition bdge;

                if (!_txt.bridges.TryGetValue(bridgeId, out bdge))
                {
                    bdge = new MethodDefinition(bridgeId, MethodAttributes.Static | MethodAttributes.Assembly,
                                                mod.Import(txt.dele.Methods.Single(_ => _.Name == "Invoke").ReturnType));
                    if (txt.mtdRef.HasThis)
                    {
                        bdge.Parameters.Add(new ParameterDefinition(Mod.Import(_txt.obj)));

                        for (int i = 0; i < txt.mtdRef.Parameters.Count; i++)
                        {
                            bdge.Parameters.Add(Clone(GetNameO(txt.mtdRef.Parameters[i]), txt.mtdRef.Parameters[i]));
                        }
                    }
                    else
                    {
                        for (int i = 0; i < txt.mtdRef.Parameters.Count; i++)
                        {
                            bdge.Parameters.Add(Clone(GetNameO(txt.mtdRef.Parameters[i]), txt.mtdRef.Parameters[i]));
                        }
                    }
                    {
                        ILProcessor psr = bdge.Body.GetILProcessor();
                        psr.Emit(OpCodes.Ldsfld, txt.fld);
                        for (int i = 0; i < bdge.Parameters.Count; i++)
                        {
                            psr.Emit(OpCodes.Ldarg, bdge.Parameters[i]);
                        }
                        //psr.Emit(txt.inst.OpCode, txt.mtdRef);
                        psr.Emit(OpCodes.Call, txt.dele.Methods.FirstOrDefault(mtd => mtd.Name == "Invoke"));
                        psr.Emit(OpCodes.Ret);
                    }
                    txt.dele.Methods.Add(bdge);
                    _txt.bridges.Add(bridgeId, bdge);
                }

                ////////////////Replace
                txt.isVirt       = txt.inst.OpCode.Name == "callvirt";
                txt.inst.OpCode  = OpCodes.Call;
                txt.inst.Operand = bdge;
            }
Ejemplo n.º 8
0
            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);
                    }
                }
            }
Ejemplo n.º 9
0
            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);
            }
 public ActionResult<TblGeral> GeralDelete(DeleteGeralModels request)
 {
     using (var context = new _Context())
     {
         var Delete = context.AtendimentosGerais.Where(x => x.id == request.id).FirstOrDefault();
         if(Delete == null)
         {
             return NotFound($"Id \"{request.id}\" Não foi encontrado!");
         }
         context.Remove(Delete);
         context.SaveChanges();
     }
     return Ok($"Os dados do id \"{request.id}\" foram deletados com sucesso !");
 }
Ejemplo n.º 11
0
            public override void Process(ConfusionParameter parameter)
            {
                _Context _txt = mc.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.isVirt, txt.mtdRef);

                    if (!(txt.fld as IAnnotationProvider).Annotations.Contains("MtdProxyCtored"))
                    {
                        ILProcessor psr = txt.dele.GetStaticConstructor().Body.GetILProcessor();
                        psr.Emit(OpCodes.Ldtoken, txt.fld);
                        psr.Emit(OpCodes.Call, _txt.proxy);
                        (txt.fld as IAnnotationProvider).Annotations["MtdProxyCtored"] = 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 == mc.txts.Count - 1)
                    {
                        progresser.SetProgress(i + 1, total);
                    }
                }
            }
Ejemplo n.º 12
0
        public ActionResult Index()
        {
            _Context  db        = new _Context();
            BaseModel baseModel = new BaseModel()
            {
                Skills      = db.Skills.ToList(),
                Awards      = db.Awards.ToList(),
                Educations  = db.Educations.ToList(),
                Experiences = db.Experiences.ToList(),
                Interests   = db.Interests.ToList(),
                Contact     = db.Contacts.FirstOrDefault(),
            };

            return(View(baseModel));
        }
Ejemplo n.º 13
0
            public override void Initialize(ModuleDefinition mod)
            {
                this.mod = mod;

                _Context txt = mc.txts[mod] = new _Context();

                txt.mcd = mod.Import(typeof(MulticastDelegate));
                txt.v   = mod.TypeSystem.Void;
                txt.obj = mod.TypeSystem.Object;
                txt.ptr = mod.TypeSystem.IntPtr;

                txt.txts      = new List <Context>();
                txt.delegates = new Dictionary <string, TypeDefinition>();
                txt.fields    = new Dictionary <string, FieldDefinition>();
                txt.bridges   = new Dictionary <string, MethodDefinition>();
            }
Ejemplo n.º 14
0
        public void StringsDemonstration()
        {
            var loData             = Defaults.IEnumerable.Filled.String;
            var loContext          = new _Context();
            var loWalker           = new DSE.Extensions.EnumerableWalker <String, _Context>(loData, loContext);
            var lsTestValueOnBegin = "Begin";
            var lsTestValueOnEnd   = "End";
            var loTestGroup        = new _Group();

            loWalker
            .OnBegin(_ => { _.SaltBefore = lsTestValueOnBegin; _.CountBefore++; })
            .OnItem((_, s) => { _.Count++; _.Items.Add(s); })
            .OnGroup(loTestGroup, (c, g, s) => !String.IsNullOrEmpty(s) && (s[0] == '2'), (c, g, s) => g.CountBefore++, (c, g) => g.CountAfter++)
            .OnEnd(_ => { _.SaltAfter = lsTestValueOnEnd; _.CountAfter++; })
            .Walk();

            Assert.AreEqual(loContext.CountBefore, 1);
            Assert.AreEqual(loContext.SaltBefore, lsTestValueOnBegin);
            Assert.AreEqual(loContext.CountAfter, 1);
            Assert.AreEqual(loContext.SaltAfter, lsTestValueOnEnd);

            var loTestList = new List <String>();
            var lnGroupHit = 0;

            foreach (var loItem in loData)
            {
                loTestList.Add(loItem);
            }

            Assert.AreEqual(loContext.Count, loTestList.Count);

            for (var i = 0; i < loTestList.Count; i++)
            {
                var lsValue = loTestList[i];

                Assert.AreEqual(lsValue, loContext.Items[i]);

                if (!String.IsNullOrEmpty(lsValue) && lsValue[0] == '2')
                {
                    lnGroupHit++;
                }
            }

            Assert.AreEqual(loTestGroup.CountBefore, lnGroupHit);
            Assert.AreEqual(loTestGroup.CountAfter, lnGroupHit);
        }
Ejemplo n.º 15
0
        public void StringsDemonstration()
        {
            var loData = Defaults.IEnumerable.Filled.String;
            var loContext = new _Context();
            var loWalker = new DSE.Extensions.EnumerableWalker<String, _Context>(loData, loContext);
            var lsTestValueOnBegin = "Begin";
            var lsTestValueOnEnd = "End";
            var loTestGroup = new _Group();

            loWalker
                .OnBegin(_ => { _.SaltBefore = lsTestValueOnBegin; _.CountBefore++; })
                .OnItem((_, s) => { _.Count++; _.Items.Add(s); })
                .OnGroup(loTestGroup, (c, g, s) => !String.IsNullOrEmpty(s) && (s[0] == '2'), (c, g, s) => g.CountBefore++, (c, g) => g.CountAfter++)
                .OnEnd(_ => { _.SaltAfter = lsTestValueOnEnd; _.CountAfter++; })
                    .Walk();

            Assert.AreEqual(loContext.CountBefore, 1);
            Assert.AreEqual(loContext.SaltBefore, lsTestValueOnBegin);
            Assert.AreEqual(loContext.CountAfter, 1);
            Assert.AreEqual(loContext.SaltAfter, lsTestValueOnEnd);

            var loTestList = new List<String>();
            var lnGroupHit = 0;

            foreach (var loItem in loData)
                loTestList.Add(loItem);

            Assert.AreEqual(loContext.Count, loTestList.Count);

            for (var i = 0; i < loTestList.Count; i++)
            {
                var lsValue = loTestList[i];

                Assert.AreEqual(lsValue, loContext.Items[i]);

                if (!String.IsNullOrEmpty(lsValue) && lsValue[0] == '2')
                {
                    lnGroupHit++;
                }
            }

            Assert.AreEqual(loTestGroup.CountBefore, lnGroupHit);
            Assert.AreEqual(loTestGroup.CountAfter, lnGroupHit);
        }
        public ActionResult <TblGeral> GeralPut(PutGeralModels request)
        {
            using(var context = new _Context())
            {
                var Validator = context.Filiais.Where(x => x.filial == request.filial).FirstOrDefault();
                if (Validator == null) { return NotFound($"Filial \"{request.filial}\" não encontrada !"); }

                var Update = context.AtendimentosGerais.Where(x => x.id == request.id).FirstOrDefault();
                if(Update == null){return NotFound($"O id \"{request.id}\" digitado, não foi encontrado!");}

                Update.analista = request.analista;
                Update.nomeDoUsuario = request.nomeDoUsuario;
                Update.filial = request.filial;
                Update.ticket = request.ticket;
                Update.descricao = request.descricao;

                context.SaveChanges();
            }
            return Ok($"Os dados do id \"{request.id}\" foram substituidos com sucesso !");
        }
        public ActionResult<TblDeltaLog> DeltaLogPut(PutDeltaLogModels request)
        {
            using (var context = new _Context())
            {
                var Update = context.AtendimentosDeltaLog.Where(x => x.id == request.id).FirstOrDefault();
                if (Update == null)
                {
                    return NotFound($"O id \"{request.id}\" digitado, não foi encontrado!");
                }
                Update.motorista = request.motorista;
                Update.shift = request.shift;
                Update.placa = request.placa;
                Update.imei = request.imei;
                Update.analista = request.analista;
                Update.problema = request.problema;
                Update.acao = request.acao;

                context.SaveChanges();
            }
            return Ok($"Os dados do id \"{request.id}\" foram substituidos com sucesso !");
        }
        public ActionResult<TblGeral> GeralSearch([FromQuery]GetGeralModels request)
        {
            if (request.analista == null) { return BadRequest("O campo analista não foi preenchido"); }
            if (request.nomeDoUsuario == null) { return BadRequest("O campo nome do Usuario não foi preenchido"); }
            if (request.ticket <= 0) { return BadRequest($"O valor {request.ticket} é inválido"); }

            using (var context = new _Context())
            {
                var Search = context.AtendimentosGerais.Where(x => x.analista.Contains(request.analista))
                                                       .Where(x => x.nomeDoUsuario.Contains(request.nomeDoUsuario))
                                                       .Where(x => x.ticket == request.ticket).FirstOrDefault();
                if (Search == null)
                { 
                    return NotFound("Valores digitado não foram encontrados!");
                }

                return context.AtendimentosGerais.Where(x => x.analista.Contains(request.analista))
                                                 .Where(x => x.nomeDoUsuario.Contains(request.nomeDoUsuario))
                                                 .Where(x => x.ticket == request.ticket).FirstOrDefault();
            }
            
        }
Ejemplo n.º 19
0
            public override void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor)
            {
                _Context txt = cc.txts[accessor.Module];

                if (!txt.isNative)
                {
                    return;
                }

                var tbl = accessor.TableHeap.GetTable <MethodTable>(Table.Method);
                var row = tbl[(int)txt.nativeDecr.MetadataToken.RID - 1];

                row.Col2  = MethodImplAttributes.Native | MethodImplAttributes.Unmanaged | MethodImplAttributes.PreserveSig;
                row.Col3 &= ~MethodAttributes.Abstract;
                row.Col3 |= MethodAttributes.PInvokeImpl;
                row.Col1  = txt.nativeRange.Start;
                accessor.BodyRanges[txt.nativeDecr.MetadataToken] = txt.nativeRange;

                tbl[(int)txt.nativeDecr.MetadataToken.RID - 1] = row;

                //accessor.Module.Attributes &= ~ModuleAttributes.ILOnly;
            }
        public ActionResult<TblDeltaLog> DeltaLogSearch([FromQuery] GetDeltaLogModels request)
        {
            if (request.imei <= 0) { return BadRequest($"Imei \"{request.imei}\" invalido !"); }
            if (request.placa == null) { return BadRequest("O campo placa deve ser preenchido !"); }
            if (request.shift == null) { return BadRequest("O campo Shift deve ser preenchido !"); }

            using (var context = new _Context())
            {
                var Search = context.AtendimentosDeltaLog.Where(x => x.shift.Contains(request.shift))
                                                         .Where(x => x.placa == request.placa)
                                                         .Where(x => x.imei == request.imei)
                                                         .FirstOrDefault();
                      if (Search == null)
                      {
                          return NotFound("Valores digitado não foram encontrados!");
                      }

                      return context.AtendimentosDeltaLog.Where(x => x.shift.Contains(request.shift))
                                                         .Where(x => x.placa == request.placa)
                                                         .Where(x => x.imei == request.imei)
                                                         .FirstOrDefault();
            }
        }
Ejemplo n.º 21
0
            public override void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor)
            {
                _Context txt = mc.txts[accessor.Module];

                var fieldTbl = accessor.TableHeap.GetTable <FieldTable>(Table.Field);

                foreach (var i in txt.txts)
                {
                    var fieldRow = fieldTbl[(int)i.fld.MetadataToken.RID - 1];

                    TypeReference typeRef = i.fld.FieldType;
                    accessor.BlobHeap.Position = (int)fieldRow.Col3;
                    int len = (int)accessor.BlobHeap.ReadCompressedUInt32();
                    int s   = accessor.BlobHeap.Position;
                    accessor.BlobHeap.WriteByte(0x6);
                    accessor.BlobHeap.WriteByte((byte)(typeRef.IsValueType ? ElementType.ValueType : ElementType.Class));
                    accessor.BlobHeap.WriteCompressedUInt32(CodedIndex.TypeDefOrRef.CompressMetadataToken(accessor.LookupToken(typeRef.GetElementType())));
                    int l = len - (accessor.BlobHeap.Position - s);
                    for (int z = 0; z < l; z++)
                    {
                        accessor.BlobHeap.WriteByte(0);
                    }

                    accessor.BlobHeap.Position = s + len - 8;
                    byte[] b;
                    if (txt.isNative)
                    {
                        b = BitConverter.GetBytes(ExpressionEvaluator.Evaluate(txt.exp, (int)i.token.RID));
                    }
                    else
                    {
                        b = BitConverter.GetBytes(i.token.RID ^ txt.key);
                    }
                    accessor.BlobHeap.WriteByte((byte)(((byte)Random.Next() & 0x3f) | 0xc0));
                    accessor.BlobHeap.WriteByte((byte)((uint)i.token.TokenType >> 24));
                    accessor.BlobHeap.WriteByte(b[0]);
                    accessor.BlobHeap.WriteByte(b[1]);
                    accessor.BlobHeap.WriteByte((byte)(((byte)Random.Next() & 0x3f) | 0xc0));
                    accessor.BlobHeap.WriteByte(b[2]);
                    accessor.BlobHeap.WriteByte(b[3]);
                    accessor.BlobHeap.WriteByte(0);

                    System.Diagnostics.Debug.Assert(accessor.BlobHeap.Position - (int)fieldRow.Col3 == len + 1);

                    fieldTbl[(int)i.fld.MetadataToken.RID - 1] = fieldRow;
                }

                if (!txt.isNative)
                {
                    return;
                }

                var tbl = accessor.TableHeap.GetTable <MethodTable>(Table.Method);
                var row = tbl[(int)txt.nativeDecr.MetadataToken.RID - 1];

                row.Col2  = MethodImplAttributes.Native | MethodImplAttributes.Unmanaged | MethodImplAttributes.PreserveSig;
                row.Col3 &= ~MethodAttributes.Abstract;
                row.Col3 |= MethodAttributes.PInvokeImpl;
                row.Col1  = txt.nativeRange.Start;
                accessor.BodyRanges[txt.nativeDecr.MetadataToken] = txt.nativeRange;

                tbl[(int)txt.nativeDecr.MetadataToken.RID - 1] = row;

                //accessor.Module.Attributes &= ~ModuleAttributes.ILOnly;
            }
Ejemplo n.º 22
0
            public override void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor)
            {
                _Context _txt = mc.txts[accessor.Module];

                for (int i = 0; i < _txt.txts.Count; i++)
                {
                    int j   = Random.Next(0, _txt.txts.Count);
                    var tmp = _txt.txts[i];
                    _txt.txts[i] = _txt.txts[j];
                    _txt.txts[j] = tmp;
                }

                TypeDefinition typeDef = new TypeDefinition("", "", 0);

                foreach (Context txt in _txt.txts)
                {
                    txt.token = accessor.LookupToken(txt.mtdRef);
                    if (txt.fld.Name[0] != '\0')
                    {
                        continue;
                    }
                    txt.fld.Name = (txt.isVirt ? _txt.keyChar1 : _txt.keyChar2) + "\n" + ObfuscationHelper.GetRandomName();

                    //Hack into cecil to generate diff sig for diff field -_-
                    int pos = txt.fld.DeclaringType.Fields.IndexOf(txt.fld) + 1;
                    while (typeDef.GenericParameters.Count < pos)
                    {
                        typeDef.GenericParameters.Add(new GenericParameter(typeDef));
                    }

                    txt.fld.FieldType = new GenericInstanceType(txt.fld.FieldType)
                    {
                        GenericArguments =
                        {
                            accessor.Module.TypeSystem.Object,
                            accessor.Module.TypeSystem.Object,
                            accessor.Module.TypeSystem.Object,
                            accessor.Module.TypeSystem.Object,
                            accessor.Module.TypeSystem.Object,
                            typeDef.GenericParameters[pos - 1]
                        }
                    };

                    Database.AddEntry("MtdProxy", (txt.isVirt ? "callvirt " : "call ") + txt.mtdRef.FullName, txt.fld.Name);
                    Database.AddEntry("MtdProxy", txt.fld.Name, txt.inst.Operand.ToString());
                }
                if (!_txt.isNative)
                {
                    return;
                }

                _txt.nativeRange = new Range(accessor.Codebase + (uint)accessor.Codes.Position, 0);
                MemoryStream ms = new MemoryStream();

                using (BinaryWriter wtr = new BinaryWriter(ms))
                {
                    wtr.Write(new byte[] { 0x89, 0xe0 });             //   mov eax, esp
                    wtr.Write(new byte[] { 0x53 });                   //   push ebx
                    wtr.Write(new byte[] { 0x57 });                   //   push edi
                    wtr.Write(new byte[] { 0x56 });                   //   push esi
                    wtr.Write(new byte[] { 0x29, 0xe0 });             //   sub eax, esp
                    wtr.Write(new byte[] { 0x83, 0xf8, 0x18 });       //   cmp eax, 24
                    wtr.Write(new byte[] { 0x74, 0x07 });             //   je n
                    wtr.Write(new byte[] { 0x8b, 0x44, 0x24, 0x10 }); //   mov eax, [esp + 4]
                    wtr.Write(new byte[] { 0x50 });                   //   push eax
                    wtr.Write(new byte[] { 0xeb, 0x01 });             //   jmp z
                    wtr.Write(new byte[] { 0x51 });                   //n: push ecx
                    x86Register ret;                                  //z:
                    var         insts = _txt.visitor.GetInstructions(out ret);
                    foreach (var i in insts)
                    {
                        wtr.Write(i.Assemble());
                    }
                    if (ret != x86Register.EAX)
                    {
                        wtr.Write(
                            new x86Instruction()
                        {
                            OpCode   = x86OpCode.MOV,
                            Operands = new Ix86Operand[]
                            {
                                new x86RegisterOperand()
                                {
                                    Register = x86Register.EAX
                                },
                                new x86RegisterOperand()
                                {
                                    Register = ret
                                }
                            }
                        }.Assemble());
                    }
                    wtr.Write(new byte[] { 0x5e });   //pop esi
                    wtr.Write(new byte[] { 0x5f });   //pop edi
                    wtr.Write(new byte[] { 0x5b });   //pop ebx
                    wtr.Write(new byte[] { 0xc3 });   //ret
                    wtr.Write(new byte[((ms.Length + 3) & ~3) - ms.Length]);
                }
                byte[] codes = ms.ToArray();
                Database.AddEntry("MtdProxy", "Native", codes);
                accessor.Codes.WriteBytes(codes);
                accessor.SetCodePosition(accessor.Codebase + (uint)accessor.Codes.Position);
                _txt.nativeRange.Length = (uint)codes.Length;
            }
Ejemplo n.º 23
0
            public override void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor)
            {
                _Context txt = rc.txts[accessor.Module];

                ModuleDefinition mod = accessor.Module;

                for (int i = 0; i < mod.Resources.Count; i++)
                {
                    if (mod.Resources[i] is EmbeddedResource)
                    {
                        txt.dats.Add(new KeyValuePair <string, byte[]>(mod.Resources[i].Name, (mod.Resources[i] as EmbeddedResource).GetResourceData()));
                        mod.Resources.RemoveAt(i);
                        i--;
                    }
                }

                if (txt.dats.Count > 0)
                {
                    MemoryStream ms  = new MemoryStream();
                    BinaryWriter wtr = new BinaryWriter(ms);

                    byte[] dat = GetAsm(mod.TimeStamp, txt.dats);
                    wtr.Write(dat.Length);
                    wtr.Write(dat);

                    ms.Position = 0;


                    int dictionary = 1 << 23;

                    Int32 posStateBits   = 2;
                    Int32 litContextBits = 3; // for normal files
                    // UInt32 litContextBits = 0; // for 32-bit data
                    Int32 litPosBits = 0;
                    // UInt32 litPosBits = 2; // for 32-bit data
                    Int32  algorithm    = 2;
                    Int32  numFastBytes = 128;
                    string mf           = "bt4";

                    SevenZip.CoderPropID[] propIDs =
                    {
                        SevenZip.CoderPropID.DictionarySize,
                        SevenZip.CoderPropID.PosStateBits,
                        SevenZip.CoderPropID.LitContextBits,
                        SevenZip.CoderPropID.LitPosBits,
                        SevenZip.CoderPropID.Algorithm,
                        SevenZip.CoderPropID.NumFastBytes,
                        SevenZip.CoderPropID.MatchFinder,
                        SevenZip.CoderPropID.EndMarker
                    };
                    object[] properties =
                    {
                        (int)dictionary,
                        (int)posStateBits,
                        (int)litContextBits,
                        (int)litPosBits,
                        (int)algorithm,
                        (int)numFastBytes,
                        mf,
                        false
                    };

                    MemoryStream x       = new MemoryStream();
                    var          encoder = new SevenZip.Compression.LZMA.Encoder();
                    encoder.SetCoderProperties(propIDs, properties);
                    encoder.WriteCoderProperties(x);
                    Int64 fileSize;
                    fileSize = ms.Length;
                    for (int i = 0; i < 8; i++)
                    {
                        x.WriteByte((Byte)(fileSize >> (8 * i)));
                    }
                    ms.Position = 0;
                    encoder.Code(ms, x, -1, -1, null);

                    dat = Transform(x.ToArray(), txt.key0, txt.key1);

                    mod.Resources.Add(new EmbeddedResource(txt.resId, ManifestResourceAttributes.Private, dat));
                }
            }
Ejemplo n.º 24
0
 public PropertyTypeGeneration(_Context context) : base(context)
 {
     Generate();
 }
Ejemplo n.º 25
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);
                    }
                }
            }
Ejemplo n.º 26
0
            private void CreateDelegate(MethodBody Bdy, Instruction Inst, MethodReference MtdRef, ModuleDefinition Mod)
            {
                //Limitation
                if ((MtdRef.HasThis && MtdRef.DeclaringType.IsValueType) ||
                    MtdRef is GenericInstanceMethod ||
                    MtdRef.DeclaringType.FullName == "<Module>")
                {
                    return;
                }

                _Context _txt = mc.txts[mod];

                Context txt = new Context();

                txt.inst   = Inst;
                txt.bdy    = Bdy;
                txt.mtdRef = MtdRef;
                string sign = GetSignatureO(MtdRef);

                if (!_txt.delegates.TryGetValue(sign, out txt.dele))
                {
                    txt.dele = new TypeDefinition("", sign, TypeAttributes.NotPublic | TypeAttributes.Sealed, _txt.mcd);
                    Mod.Types.Add(txt.dele);

                    MethodDefinition cctor = new MethodDefinition(".cctor", MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.Static, _txt.v);
                    cctor.Body = new MethodBody(cctor);
                    txt.dele.Methods.Add(cctor);

                    MethodDefinition ctor = new MethodDefinition(".ctor", 0, _txt.v);
                    ctor.IsRuntime            = true;
                    ctor.HasThis              = true;
                    ctor.IsHideBySig          = true;
                    ctor.IsRuntimeSpecialName = true;
                    ctor.IsSpecialName        = true;
                    ctor.IsPublic             = true;
                    ctor.Parameters.Add(new ParameterDefinition(_txt.obj));
                    ctor.Parameters.Add(new ParameterDefinition(_txt.ptr));
                    txt.dele.Methods.Add(ctor);

                    MethodDefinition invoke  = new MethodDefinition("Invoke", 0, mod.Import(MtdRef.ReturnType));
                    TypeReference    retType = invoke.ReturnType.GetElementType();
                    retType.IsValueType = ((retType.Resolve() ?? retType) ?? invoke.ReturnType).IsValueType;

                    invoke.IsRuntime   = true;
                    invoke.HasThis     = true;
                    invoke.IsHideBySig = true;
                    invoke.IsVirtual   = true;
                    invoke.IsPublic    = true;

                    if (MtdRef.HasThis)
                    {
                        invoke.Parameters.Add(new ParameterDefinition(_txt.obj));
                        for (int i = 0; i < MtdRef.Parameters.Count; i++)
                        {
                            invoke.Parameters.Add(Clone(GetNameO(MtdRef.Parameters[i]), MtdRef.Parameters[i]));
                        }
                    }
                    else
                    {
                        for (int i = 0; i < MtdRef.Parameters.Count; i++)
                        {
                            invoke.Parameters.Add(Clone(GetNameO(MtdRef.Parameters[i]), MtdRef.Parameters[i]));
                        }
                    }
                    txt.dele.Methods.Add(invoke);
                    _txt.delegates.Add(sign, txt.dele);

                    Database.AddEntry("MtdProxy", GetSignature(MtdRef), txt.dele.FullName);
                }
                _txt.txts.Add(txt);
            }
            private void InvokePackageCatched(EtlPackage package, EtlSession session, EtlVariableAssignment[] assignments)
            {
                var buildStartDateTime = DateTime.Now;
                _logger.LogEtlMessage
                (
                    new EtlMessage
                    {
                        EtlPackageId = session.EtlPackageId,
                        EtlSessionId = session.EtlSessionId,
                        LogDateTime = buildStartDateTime,
                        LogUtcDateTime = buildStartDateTime.ToUniversalTime(),
                        MessageType = EtlMessageType.Debug,
                        Text = string.Format(Properties.Resources.VariablesInitStarted),
                    }
                );

                var context = new _Context(package, session);
                context.InitVariables(package.Variables, assignments);

                foreach (var variable in context.GetVariables())
                {
                    var escapedVariable = EscapeVariable(variable);

                    _logger.LogEtlMessage
                    (
                        new EtlMessage
                        {
                            EtlPackageId = context.EtlPackageId,
                            EtlSessionId = context.EtlSessionId,
                            LogDateTime = buildStartDateTime,
                            LogUtcDateTime = buildStartDateTime.ToUniversalTime(),
                            MessageType = EtlMessageType.Debug,
                            Text = string.Format(Properties.Resources.VariableInit, escapedVariable.Name, escapedVariable.Value),
                        }
                    );

                    if (variable.Modifier == EtlVariableModifier.Input || variable.Modifier == EtlVariableModifier.Bound)
                    {
                        _logger.LogEtlVariable(escapedVariable);
                    }
                }

                var preprocessor = new EtlPackagePreprocessor();
                package = preprocessor.PreprocessPackage(package, context.GetVariables());

                var buildEndDateTime = DateTime.Now;
                _logger.LogEtlMessage
                (
                    new EtlMessage
                    {
                        EtlPackageId = session.EtlPackageId,
                        EtlSessionId = session.EtlSessionId,
                        LogDateTime = buildEndDateTime,
                        LogUtcDateTime = buildEndDateTime.ToUniversalTime(),
                        MessageType = EtlMessageType.Debug,
                        Text = string.Format(Properties.Resources.VariablesInitFinished),
                    }
                );

                InvokePackageSteps(package, context);

                foreach (var variable in context.GetVariables())
                {
                    if (variable.Modifier == EtlVariableModifier.Output)
                    {
                        _logger.LogEtlVariable(EscapeVariable(variable));

                    }
                }

                session.Status = context.CurrentStatus;
            }
Ejemplo n.º 28
0
 public SingUpFbGgController(_Context registerContext, _Context contextRepo)
 {
     _context     = registerContext;
     _contextRepo = contextRepo;
 }
Ejemplo n.º 29
0
 public Tokenv1_1Controller(IConfiguration configuration, _Context context)
 {
     Configuration = configuration;
     _context      = context;
 }
Ejemplo n.º 30
0
 public LabelGeneration(_Context context) : base(context)
 {
     Generate();
 }
            private void InvokePackageSteps(EtlPackage package, _Context context)
            {
                var stepIndex = 0;

                while (stepIndex < package.Steps.Count)
                {
                    var step = package.Steps[stepIndex];

                    var stepResult = InvokePackageStep(step, context);
                    if (EtlStatuses.GetPriorityStatus(stepResult.Status, context.CurrentStatus) == stepResult.Status)
                    {
                        context.CurrentStatus = stepResult.Status;
                    }

                    if (stepResult.Status == EtlStatus.Failed)
                    {
                        break;
                    }

                    if (HasVariableAssignments(stepResult))
                    {
                        var rebuildStartDateTime = DateTime.Now;
                        _logger.LogEtlMessage
                        (
                            new EtlMessage
                            {
                                EtlPackageId = context.EtlPackageId,
                                EtlSessionId = context.EtlSessionId,
                                LogDateTime = rebuildStartDateTime,
                                LogUtcDateTime = rebuildStartDateTime.ToUniversalTime(),
                                MessageType = EtlMessageType.Debug,
                                Text = string.Format(Properties.Resources.VariablesUpdateStarted),
                            }
                        );

                        foreach (var assignment in stepResult.VariableAssignments)
                        {
                            var assignedVariable = context.AssignVariable(assignment);
                            var escapedVariable = EscapeVariable(assignedVariable);

                            _logger.LogEtlMessage
                            (
                                new EtlMessage
                                {
                                    EtlPackageId = context.EtlPackageId,
                                    EtlSessionId = context.EtlSessionId,
                                    LogDateTime = rebuildStartDateTime,
                                    LogUtcDateTime = rebuildStartDateTime.ToUniversalTime(),
                                    MessageType = EtlMessageType.Debug,
                                    Text = string.Format(Properties.Resources.VariableUpdate, escapedVariable.Name, escapedVariable.Value),
                                }
                            );
                        }

                        var preprocessor = new EtlPackagePreprocessor();
                        package = preprocessor.PreprocessPackage(context.OriginalPackage, context.GetVariables());

                        var rebuildEndDateTime = DateTime.Now;
                        _logger.LogEtlMessage
                        (
                            new EtlMessage
                            {
                                EtlPackageId = context.EtlPackageId,
                                EtlSessionId = context.EtlSessionId,
                                LogDateTime = rebuildEndDateTime,
                                LogUtcDateTime = rebuildEndDateTime.ToUniversalTime(),
                                MessageType = EtlMessageType.Debug,
                                Text = string.Format(Properties.Resources.VariablesUpdateFinished),
                            }
                        );
                    }

                    stepIndex++;
                }
            }
Ejemplo n.º 32
0
 public CustomersController(_Context context)
 {
     _context = context;
 }
Ejemplo n.º 33
0
            Conster[] CreateConsters(_Context txt, Random rand, string injectName,
                FieldDefinition constTbl, FieldDefinition constBuffer)
            {
                AssemblyDefinition injection = AssemblyDefinition.ReadAssembly(typeof(Iid).Assembly.Location);
                injection.MainModule.ReadSymbols();
                MethodDefinition method = injection.MainModule.GetType("Encryptions").Methods.FirstOrDefault(mtd => mtd.Name == "Constants");
                List<Conster> ret = new List<Conster>();

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

                rand.NextBytes(txt.keyBuff);
                for (int i = 0; i < txt.keyBuff.Length; i++)
                    txt.keyBuff[i] &= 0x7f;
                txt.keyBuff[0] = 7; txt.keyBuff[1] = 0;
                txt.resKey = (rand.Next(0x20, 0x80) << 24) | (rand.Next(0x20, 0x80) << 32) |
                             (rand.Next(0x20, 0x80) << 16) | (rand.Next(0x20, 0x80) << 0 );
                txt.resId = Encoding.UTF8.GetString(BitConverter.GetBytes(txt.resKey));
                txt.key = (uint)rand.Next();

                Database.AddEntry("Const", "KeyBuff", txt.keyBuff);
                Database.AddEntry("Const", "ResKey", txt.resKey);
                Database.AddEntry("Const", "ResId", txt.resId);
                Database.AddEntry("Const", "Key", txt.key);

                Mutator mutator = new Mutator();
                MethodDefinition init = injection.MainModule.GetType("Encryptions").Methods.FirstOrDefault(mtd => mtd.Name == injectName);
                {
                    MethodDefinition cctor = mod.GetType("<Module>").GetStaticConstructor();
                    MethodDefinition m = CecilHelper.Inject(mod, init);
                    Instruction placeholder = null;
                    mutator.IntKeys = new int[] { txt.resKey };
                    mutator.Mutate(Random, m.Body);
                    txt.keyInst = mutator.Delayed0;
                    placeholder = mutator.Placeholder;
                    foreach (Instruction inst in m.Body.Instructions)
                    {
                        if (inst.Operand is FieldReference)
                        {
                            if ((inst.Operand as FieldReference).Name == "constTbl")
                                inst.Operand = constTbl;
                            else if ((inst.Operand as FieldReference).Name == "constBuffer")
                                inst.Operand = constBuffer;
                        }
                        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 i in m.Body.Variables)
                        if (i.VariableType.Name == "LzmaDecoder")
                            i.VariableType = lzma.NestedTypes.Single(_ => _.Name == "LzmaDecoder");

                    if (txt.isNative)
                        CecilHelper.Replace(m.Body, placeholder, new Instruction[]
                        {
                            Instruction.Create(OpCodes.Call, txt.nativeDecr)
                        });
                    else if (txt.isDyn)
                    {
                        Instruction ldloc = placeholder.Previous;
                        m.Body.Instructions.Remove(placeholder.Previous);   //ldloc
                        CecilHelper.Replace(m.Body, placeholder, new CecilVisitor(txt.invExp, new Instruction[]
                        {
                            ldloc
                        }).GetInstructions());
                    }

                    ILProcessor psr = cctor.Body.GetILProcessor();
                    Instruction begin = cctor.Body.Instructions[0];
                    for (int i = m.Body.Instructions.Count - 1; i >= 0; i--)
                    {
                        if (m.Body.Instructions[i].OpCode != OpCodes.Ret)
                            psr.InsertBefore(0, m.Body.Instructions[i]);
                    }
                    cctor.Body.InitLocals = true;
                    foreach (var i in m.Body.Variables)
                        cctor.Body.Variables.Add(i);
                }

                byte[] n = new byte[0x10];
                int typeDefCount = rand.Next(1, 10);
                for (int i = 0; i < typeDefCount; i++)
                {
                    TypeDefinition typeDef = new TypeDefinition(
                        "", ObfuscationHelper.GetRandomName(),
                        TypeAttributes.Class | TypeAttributes.Abstract | TypeAttributes.NotPublic | TypeAttributes.Sealed,
                        mod.TypeSystem.Object);
                    mod.Types.Add(typeDef);
                    int methodCount = rand.Next(1, 5);
                    Database.AddEntry("Const", "ConsterTypes", typeDef.FullName);

                    for (int j = 0; j < methodCount; j++)
                    {
                        MethodDefinition mtd = CecilHelper.Inject(mod, method);
                        mtd.Name = ObfuscationHelper.GetRandomName();
                        mtd.IsCompilerControlled = true;

                        AddHelper(mtd, HelperAttribute.NoInjection);
                        typeDef.Methods.Add(mtd);

                        Database.AddEntry("Const", "ConsterMethods", mtd.FullName);

                        Conster conster = new Conster();
                        conster.key0 = (long)rand.Next() * rand.Next();
                        conster.key1 = (long)rand.Next() * rand.Next();
                        conster.key2 = (long)rand.Next() * rand.Next();
                        conster.key3 = rand.Next();
                        conster.conster = mtd;
                        Database.AddEntry("Const", mtd.FullName, string.Format("{0:X}, {1:X}, {2:X}, {3:X}", conster.key0, conster.key1, conster.key2, conster.key3));

                        mutator = new Mutator();
                        mutator.LongKeys = new long[]
                        {
                            conster.key0,
                            conster.key1,
                            conster.key2
                        };
                        mutator.IntKeys = new int[] { conster.key3 };
                        mutator.Mutate(Random, mtd.Body);
                        foreach (Instruction inst in mtd.Body.Instructions)
                            if (inst.Operand is FieldReference)
                            {
                                if ((inst.Operand as FieldReference).Name == "constTbl")
                                    inst.Operand = constTbl;
                                else if ((inst.Operand as FieldReference).Name == "constBuffer")
                                    inst.Operand = constBuffer;
                            }
                        conster.keyInst = mutator.Delayed0;
                        ret.Add(conster);
                    }
                }
                return ret.ToArray();
            }
Ejemplo n.º 34
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())));
            }
Ejemplo n.º 35
0
 void ExtractData(IList<Tuple<IAnnotationProvider, NameValueCollection>> mtds,
     List<Context> txts, bool num, _Context txt)
 {
     foreach (var tuple in mtds)
     {
         MethodDefinition mtd = tuple.Item1 as MethodDefinition;
         if (cc.txts[mod].consters.Any(_ => _.conster == mtd) || !mtd.HasBody) continue;
         var bdy = mtd.Body;
         var insts = bdy.Instructions;
         ILProcessor psr = bdy.GetILProcessor();
         for (int i = 0; i < insts.Count; i++)
         {
             if (insts[i].OpCode.Code == Code.Ldstr ||
                 (num && (insts[i].OpCode.Code == Code.Ldc_I4 ||
                 insts[i].OpCode.Code == Code.Ldc_I8 ||
                 insts[i].OpCode.Code == Code.Ldc_R4 ||
                 insts[i].OpCode.Code == Code.Ldc_R8)))
             {
                 txts.Add(new Context()
                 {
                     mtd = mtd,
                     psr = psr,
                     str = insts[i],
                     a = (uint)Random.Next(),
                     conster = txt.consters[Random.Next(0, txt.consters.Length)]
                 });
             }
         }
     }
 }