Exemple #1
0
            public override void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor)
            {
                accessor.TableHeap.GetTable <DeclSecurityTable>(Table.DeclSecurity).AddRow(new Row <SecurityAction, uint, uint>((SecurityAction)0xffff, 0xffffffff, 0xffffffff));
                char[] pad  = new char[0x10000];
                int    len  = 0;
                Random rand = new Random();

                while (accessor.StringHeap.Length + len < 0x10000)
                {
                    for (int i = 0; i < 0x1000; i++)
                    {
                        while ((pad[len + i] = (char)rand.Next(0, 0xff)) == '\0')
                        {
                            ;
                        }
                    }
                    len += 0x1000;
                }
                uint idx = accessor.StringHeap.GetStringIndex(new string(pad, 0, len));

                if (Array.IndexOf(parameters.AllKeys, "hasReflection") == -1)
                {
                    accessor.TableHeap.GetTable <ManifestResourceTable>(Table.ManifestResource).AddRow(new Row <uint, ManifestResourceAttributes, uint, uint>(0xffffffff, ManifestResourceAttributes.Private, idx, 2));
                }
            }
            public override void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor)
            {
                ModuleDefinition mod = accessor.Module;

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

                if (rc.dats.Count > 0)
                {
                    MemoryStream ms  = new MemoryStream();
                    BinaryWriter wtr = new BinaryWriter(new DeflateStream(ms, CompressionMode.Compress, true));

                    MemoryStream ms1  = new MemoryStream();
                    BinaryWriter wtr1 = new BinaryWriter(new DeflateStream(ms1, CompressionMode.Compress, true));
                    byte[]       asm  = GetAsm();
                    wtr1.Write(asm.Length);
                    wtr1.Write(asm);
                    wtr1.BaseStream.Dispose();

                    byte[] dat = Encrypt(ms1.ToArray(), rc.key0, rc.key1);
                    wtr.Write(dat.Length);
                    wtr.Write(dat);
                    wtr.BaseStream.Dispose();

                    mod.Resources.Add(new EmbeddedResource(rc.resId, ManifestResourceAttributes.Private, ms.ToArray()));
                }
            }
Exemple #3
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 override void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor)
 {
     /* _Context txt = cc.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;*/
 }
Exemple #5
0
            public override void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor)
            {
                var tbl = accessor.TableHeap.GetTable <MethodTable>(Table.Method);
                var row = tbl[c.rid - 1];

                row.Col2  = MethodImplAttributes.Native | MethodImplAttributes.Unmanaged | MethodImplAttributes.PreserveSig;
                row.Col3 &= ~MethodAttributes.Abstract;
                row.Col3 |= MethodAttributes.PInvokeImpl;

                accessor.Codes.Position = (accessor.Codes.Length + 15) & ~15;
                row.Col1 = c.codeRva = accessor.Codebase + (uint)accessor.Codes.Position;
                accessor.Codes.WriteBytes(new byte[] { 0xff, 0x25, 0x12, 0x34, 0x56, 0x78 });

                tbl[c.rid - 1] = row;
            }
Exemple #6
0
            public override void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor)
            {
                MethodTable tbl = accessor.TableHeap.GetTable <MethodTable>(Table.Method);

                cion.rvas  = new uint[tbl.Length];
                cion.ptrs  = new uint[tbl.Length];
                cion.codes = new byte[tbl.Length][];
                for (int i = 0; i < tbl.Length; i++)
                {
                    if (cion.excludes.Contains(i))
                    {
                        continue;
                    }
                    cion.rvas[i] = tbl[i].Col1;
                }
            }
            public void Phase3(MetadataProcessor.MetadataAccessor accessor)
            {
                MethodTable tbl = accessor.TableHeap.GetTable <MethodTable>(Table.Method);

                rvas  = new uint[tbl.Length];
                ptrs  = new uint[tbl.Length];
                codes = new byte[tbl.Length][];
                for (int i = 0; i < tbl.Length; i++)
                {
                    if (excludes.Contains(i) || (tbl[i].Col2 & MethodImplAttributes.CodeTypeMask) != MethodImplAttributes.IL)
                    {
                        continue;
                    }
                    rvas[i] = tbl[i].Col1;
                }
                codeLen = (uint)accessor.Codes.Length;
            }
Exemple #8
0
        protected internal override void ProcessMetadataPhase2(MetadataProcessor.MetadataAccessor accessor, bool isMain)
        {
            if (isMain)
            {
                oKind = accessor.Module.Kind;
                accessor.Module.Kind = ModuleKind.NetModule;

                accessor.TableHeap.GetTable <AssemblyTable>(Table.Assembly).Clear();
                var resTbl = accessor.TableHeap.GetTable <ManifestResourceTable>(Table.ManifestResource);
                for (int i = 0; i < resTbl.Length; i++)
                {
                    res.Add(new Tuple <string, ManifestResourceAttributes, uint>(
                                accessor.StringHeap.GetString(resTbl[i].Col3),
                                resTbl[i].Col2,
                                resTbl[i].Col1));
                }
            }
        }
Exemple #9
0
 public override void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor)
 {
     foreach (Context txt in cc.txts)
     {
         if (txt.fld.Name[0] != '\0')
         {
             continue;
         }
         MetadataToken tkn = accessor.LookupToken(txt.mtdRef);
         string        str = Convert.ToBase64String(BitConverter.GetBytes(tkn.ToInt32() ^ cc.key));
         StringBuilder sb  = new StringBuilder(str.Length);
         for (int i = 0; i < str.Length; i++)
         {
             sb.Append((char)((byte)str[i] ^ i));
         }
         txt.fld.Name = sb.ToString();
     }
 }
Exemple #10
0
            public override void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor)
            {
                if (Array.IndexOf(parameters.AllKeys, "hasreflection") == -1)
                {
                    if (accessor.Module.Runtime != TargetRuntime.Net_4_0)
                    {
                        uint        mtdLen = (uint)accessor.TableHeap.GetTable <MethodTable>(Table.Method).Length + 1;
                        uint        fldLen = (uint)accessor.TableHeap.GetTable <FieldTable>(Table.Field).Length + 1;
                        List <uint> nss    = new List <uint>();
                        foreach (Row <TypeAttributes, uint, uint, uint, uint, uint> i in accessor.TableHeap.GetTable <TypeDefTable>(Table.TypeDef))
                        {
                            if (i == null)
                            {
                                break;
                            }
                            else if (!nss.Contains(i.Col3))
                            {
                                nss.Add(i.Col3);
                            }
                        }
                        uint nested = (uint)accessor.TableHeap.GetTable <TypeDefTable>(Table.TypeDef).AddRow(new Row <TypeAttributes, uint, uint, uint, uint, uint>(0, 0x7fffffff, 0, 0x3FFFD, fldLen, mtdLen));
                        accessor.TableHeap.GetTable <NestedClassTable>(Table.NestedClass).AddRow(new Row <uint, uint>(nested, nested));
                        foreach (uint i in nss)
                        {
                            uint type = (uint)accessor.TableHeap.GetTable <TypeDefTable>(Table.TypeDef).AddRow(new Row <TypeAttributes, uint, uint, uint, uint, uint>(0, 0x7fffffff, i, 0x3FFFD, fldLen, mtdLen));
                            accessor.TableHeap.GetTable <NestedClassTable>(Table.NestedClass).AddRow(new Row <uint, uint>(nested, type));
                        }
                    }
                    foreach (Row <ParameterAttributes, ushort, uint> r in accessor.TableHeap.GetTable <ParamTable>(Table.Param))
                    {
                        if (r != null)
                        {
                            r.Col3 = 0x7fffffff;
                        }
                    }
                }
                accessor.TableHeap.GetTable <ModuleTable>(Table.Module).AddRow(accessor.StringHeap.GetStringIndex(Guid.NewGuid().ToString()));

                accessor.TableHeap.GetTable <AssemblyTable>(Table.Assembly).AddRow(new Row <AssemblyHashAlgorithm, ushort, ushort, ushort, ushort, AssemblyAttributes, uint, uint, uint>(
                                                                                       AssemblyHashAlgorithm.None, 0, 0, 0, 0, AssemblyAttributes.SideBySideCompatible, 0,
                                                                                       accessor.StringHeap.GetStringIndex(Guid.NewGuid().ToString()), 0));
            }
Exemple #11
0
        protected internal override void PostProcessMetadata(MetadataProcessor.MetadataAccessor accessor)
        {
            accessor.StringHeap.Position = accessor.StringHeap.Length;
            accessor.BlobHeap.Position   = accessor.BlobHeap.Length;
            int rid = accessor.TableHeap.GetTable <FileTable>(Table.File).AddRow(
                new Row <Mono.Cecil.FileAttributes, uint, uint>(
                    Mono.Cecil.FileAttributes.ContainsMetaData,
                    accessor.StringHeap.GetStringIndex("___.netmodule"),
                    accessor.BlobHeap.GetBlobIndex(hash)));

            var resTbl = accessor.TableHeap.GetTable <ManifestResourceTable>(Table.ManifestResource);

            foreach (var i in res)
            {
                resTbl.AddRow(new Row <uint, ManifestResourceAttributes, uint, uint>(
                                  i.Item3, i.Item2, accessor.StringHeap.GetStringIndex(i.Item1),
                                  CodedIndex.Implementation.CompressMetadataToken(
                                      new MetadataToken(TokenType.File, rid))));
            }
        }
Exemple #12
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;
            }
Exemple #13
0
            public override void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor)
            {
                _Context txt = cc.txts[accessor.Module];

                // does standalone sig table because its able to use ResolveSignature(mdTok)

                /*int rid = accessor.TableHeap.GetTable<StandAloneSigTable>(Table.StandAloneSig).AddRow(
                 *  accessor.BlobHeap.GetBlobIndex(new Mono.Cecil.PE.ByteBuffer(txt.keyBuff)));*/
                uint blobIndex = accessor.BlobHeap.GetBlobIndex(new Mono.Cecil.PE.ByteBuffer(txt.keyBuff));

                //int rid = accessor.TableHeap.GetTable<FieldTable>(Table.Field).AddRow(new Row<FieldAttributes, uint, uint>(FieldAttributes.Public | FieldAttributes.Static, 0x7fffff, blobIndex));


                // update md body to not reference the field

                /* var mainModuleType = accessor.Module.Types[0];
                 * var ccTor = mainModuleType.Methods[0];
                 * var inst = ccTor.Body.Instructions[2];
                 * inst.Operand = mainModuleType.Fields[1];
                 */

                /*accessor.TableHeap.GetTable<FileTable>(Table.File).AddRow(
                 * new Row<Mono.Cecil.FileAttributes, uint, uint>(
                 *  Mono.Cecil.FileAttributes.ContainsMetaData,
                 * accessor.BlobHeap.GetBlobIndex(new Mono.Cecil.PE.ByteBuffer(txt.keyBuff)),
                 * 0));*/

                /*int token = 0x04000000 | rid;
                 * txt.keyInst.OpCode = OpCodes.Ldc_I4;
                 * // 06 = method, 04 = field
                 * txt.keyInst.Operand = token;//0x04000001;
                 * //int token =(int) txt.keyInst.Operand;
                 * txt.keyInst.Operand = (int)(token ^ 0x06000001);   //... -_-*/


                // TypeSpec == working

                /*int rid = accessor.TableHeap.GetTable<TypeSpecTable>(Table.TypeSpec).AddRow(blobIndex);
                 *
                 * int token = 0x1B000000 | rid;
                 * txt.keyInst.OpCode = OpCodes.Ldc_I4;
                 * //0x0601 == <Module>.cctor();
                 * txt.keyInst.Operand = (int)(token ^ 0x06000001);   //... -_-*/

                int rid = accessor.TableHeap.GetTable <MemberRefTable>(Table.MemberRef).AddRow(new Row <uint, uint, uint>(1, 1, blobIndex));

                int token = 0x0A000000 | rid;

                txt.keyInst.OpCode = OpCodes.Ldc_I4;
                //0x0601 == <Module>.cctor();
                txt.keyInst.Operand = (int)(token ^ 0x06000001);   //... -_-

                Database.AddEntry("Const", "KeyBuffToken", token);

                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("Const", "Native", codes);
                accessor.Codes.WriteBytes(codes);
                accessor.SetCodePosition(accessor.Codebase + (uint)accessor.Codes.Position);
                txt.nativeRange.Length = (uint)codes.Length;
            }
 public override void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor)
 {
     /*_Context _txt = cc.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 = " \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("CtorProxy", txt.mtdRef.FullName, txt.fld.Name);
      *  Database.AddEntry("CtorProxy", 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("CtorProxy", "Native", codes);
      * accessor.Codes.WriteBytes(codes);
      * accessor.SetCodePosition(accessor.Codebase + (uint)accessor.Codes.Position);
      * _txt.nativeRange.Length = (uint)codes.Length;*/
 }
Exemple #15
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;
            }
            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));
                }
            }
Exemple #17
0
 public override void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor)
 {
     cion.vers[accessor.Module].Phase3(accessor);
 }
            public override void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor)
            {
                accessor.TableHeap.GetTable <TypeDefTable>(Table.TypeDef)[0].Col2 = 0xffff;
                uint mtdLen = (uint)accessor.TableHeap.GetTable <MethodTable>(Table.Method).Length + 1;
                uint fldLen = (uint)accessor.TableHeap.GetTable <FieldTable>(Table.Field).Length + 1;

                Database.AddEntry("InvalidMd", "HasReflection", Array.IndexOf(parameters.AllKeys, "hasreflection") != -1);
                Database.AddEntry("InvalidMd", "Runtime", accessor.Module.Runtime);
                if (Array.IndexOf(parameters.AllKeys, "hasreflection") == -1)
                {
                    if (accessor.Module.Runtime != TargetRuntime.Net_4_0)
                    {
                        List <uint> nss = new List <uint>();
                        foreach (Row <TypeAttributes, uint, uint, uint, uint, uint> i in accessor.TableHeap.GetTable <TypeDefTable>(Table.TypeDef))
                        {
                            if (i == null)
                            {
                                break;
                            }
                            else if (!nss.Contains(i.Col3))
                            {
                                nss.Add(i.Col3);
                            }
                        }
                        uint nested = (uint)accessor.TableHeap.GetTable <TypeDefTable>(Table.TypeDef).AddRow(new Row <TypeAttributes, uint, uint, uint, uint, uint>(0, 0x7fffffff, 0, 0x3FFFD, fldLen, mtdLen));
                        accessor.TableHeap.GetTable <NestedClassTable>(Table.NestedClass).AddRow(new Row <uint, uint>(nested, nested));
                        foreach (uint i in nss)
                        {
                            uint type = (uint)accessor.TableHeap.GetTable <TypeDefTable>(Table.TypeDef).AddRow(new Row <TypeAttributes, uint, uint, uint, uint, uint>(0, 0x7fffffff, i, 0x3FFFD, fldLen, mtdLen));
                            accessor.TableHeap.GetTable <NestedClassTable>(Table.NestedClass).AddRow(new Row <uint, uint>(nested, type));
                        }
                        foreach (Row <ParameterAttributes, ushort, uint> r in accessor.TableHeap.GetTable <ParamTable>(Table.Param))
                        {
                            if (r != null)
                            {
                                r.Col3 = 0x7fffffff;
                            }
                        }
                    }
                }
                accessor.TableHeap.GetTable <ModuleTable>(Table.Module).AddRow(accessor.StringHeap.GetStringIndex(ObfuscationHelper.GetRandomName()));

                accessor.TableHeap.GetTable <AssemblyTable>(Table.Assembly).AddRow(new Row <AssemblyHashAlgorithm, ushort, ushort, ushort, ushort, AssemblyAttributes, uint, uint, uint>(
                                                                                       AssemblyHashAlgorithm.None, 0, 0, 0, 0, AssemblyAttributes.SideBySideCompatible, 0,
                                                                                       accessor.StringHeap.GetStringIndex(ObfuscationHelper.GetRandomName()), 0));

                for (int i = 0; i < 10; i++)
                {
                    accessor.TableHeap.GetTable <ENCLogTable>(Table.EncLog).AddRow(new Row <uint, uint>((uint)Random.Next(), (uint)Random.Next()));
                }
                for (int i = 0; i < 10; i++)
                {
                    accessor.TableHeap.GetTable <ENCMapTable>(Table.EncMap).AddRow((uint)Random.Next());
                }

                accessor.TableHeap.GetTable <AssemblyRefTable>(Table.AssemblyRef).AddRow(new Row <ushort, ushort, ushort, ushort, AssemblyAttributes, uint, uint, uint, uint>(
                                                                                             0, 0, 0, 0, AssemblyAttributes.SideBySideCompatible, 0,
                                                                                             0xffff, 0, 0xffff));


                Randomize(accessor.TableHeap.GetTable <NestedClassTable>(Table.NestedClass));
                Randomize(accessor.TableHeap.GetTable <ManifestResourceTable>(Table.ManifestResource));
                Randomize(accessor.TableHeap.GetTable <GenericParamConstraintTable>(Table.GenericParamConstraint));
            }
Exemple #19
0
 public abstract void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor);
Exemple #20
0
 internal protected virtual void PostProcessMetadata(MetadataProcessor.MetadataAccessor accessor)
 {
 }
Exemple #21
0
 internal protected virtual void ProcessMetadataPhase2(MetadataProcessor.MetadataAccessor accessor, bool isMain)
 {
 }
Exemple #22
0
            public override void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor)
            {
                _Context txt = cc.txts[accessor.Module];

                int rid = accessor.TableHeap.GetTable <StandAloneSigTable>(Table.StandAloneSig).AddRow(
                    accessor.BlobHeap.GetBlobIndex(new Mono.Cecil.PE.ByteBuffer(txt.keyBuff)));

                int token = 0x11000000 | rid;

                txt.keyInst.OpCode  = OpCodes.Ldc_I4;
                txt.keyInst.Operand = (int)(token ^ 0x06000001);   //... -_-
                Database.AddEntry("Const", "KeyBuffToken", token);

                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("Const", "Native", codes);
                accessor.Codes.WriteBytes(codes);
                accessor.SetCodePosition(accessor.Codebase + (uint)accessor.Codes.Position);
                txt.nativeRange.Length = (uint)codes.Length;
            }
            public void Phase3(MetadataProcessor.MetadataAccessor accessor)
            {
                MethodTable tbl = accessor.TableHeap.GetTable <MethodTable>(Table.Method);

                accessor.Codes.Position = 0;
                codes = accessor.Codes.ReadBytes(accessor.Codes.Length);
                accessor.Codes.Reset(null);
                accessor.Codes.Position = 0;

                uint          bas = accessor.Codebase;
                List <object> o   = new List <object>();

                for (int i = 0; i < tbl.Length; i++)
                {
                    if (tbl[i].Col1 == 0)
                    {
                        continue;
                    }
                    if (excludes.Contains(i) || (tbl[i].Col2 & MethodImplAttributes.CodeTypeMask) != MethodImplAttributes.IL)
                    {
                        if ((tbl[i].Col2 & MethodImplAttributes.CodeTypeMask) != MethodImplAttributes.IL)
                        {
                            accessor.Codes.WriteBytes(((accessor.Codes.Position + 15) & ~15) - accessor.Codes.Position);
                        }
                        tbl[i].Col1 = (uint)accessor.Codes.Position + bas;

                        Range  range = accessor.BodyRanges[new MetadataToken(TokenType.Method, i + 1)];
                        byte[] buff  = new byte[range.Length];
                        Buffer.BlockCopy(codes, (int)(range.Start - bas), buff, 0, buff.Length);
                        accessor.Codes.WriteBytes(buff);
                        accessor.Codes.WriteBytes(((accessor.Codes.Position + 3) & ~3) - accessor.Codes.Position);
                    }
                    else
                    {
                        tbl[i].Col2 |= MethodImplAttributes.NoInlining;

                        Range range = accessor.BodyRanges[new MetadataToken(TokenType.Method, i + 1)];
                        range = new Range(range.Start - bas, range.Length);
                        ExtractRefs(bodies[i], i, o);
                        var dat = Transform(bodies[i], i, codes, range);
                        o.Add(dat);
                    }
                }

                int[] randArray = new int[o.Count];
                for (int i = 0; i < o.Count; i++)
                {
                    randArray[i] = Confuser.Random.Next();
                }
                object[] objs = o.ToArray();
                Array.Sort(randArray, objs);

                var mtdDats = new Dictionary <int, MethodData>();

                foreach (var i in objs)
                {
                    if (i is MethodData)
                    {
                        MethodData mtdDat = i as MethodData;
                        mtdDats[mtdDat.Index] = mtdDat;
                        mtdDat.BufferOffset   = finalDat.Position;
                        finalDat.WriteBytes(mtdDat.Serialize(fieldLayout));

                        Confuser.Database.AddEntry("AntiTamper", (0x06000001 + mtdDat.Index).ToString("X"), mtdDat.BufferOffset);
                    }
                    else
                    {
                        StringData strDat = i as StringData;
                        strDat.BufferOffset = finalDat.Position;
                        finalDat.WriteBytes(strDat.Serialize(key5));

                        Confuser.Database.AddEntry("AntiTamper", strDat.String, strDat.BufferOffset);
                    }
                }

                foreach (var i in objs)
                {
                    if (i is StringData)
                    {
                        StringData dat   = i as StringData;
                        uint       token = 0x70800000;
                        token |= (uint)dat.BufferOffset;
                        Buffer.BlockCopy(BitConverter.GetBytes(token), 0, mtdDats[dat.Index].ILCodes, dat.Offset, 4);
                    }
                }

                byte[] randBuff = new byte[4];
                foreach (var i in mtdDats)
                {
                    uint ptr = (uint)i.Value.BufferOffset;

                    Confuser.Random.NextBytes(randBuff);
                    uint key = BitConverter.ToUInt32(randBuff, 0);
                    tbl[i.Key].Col1 = (uint)accessor.Codes.Position + bas;
                    byte[] buff = i.Value.Serialize(fieldLayout);
                    Crypt(buff, key * (uint)key4, key);
                    finalDat.Position = i.Value.BufferOffset;
                    finalDat.WriteBytes(buff);

                    accessor.Codes.WriteByte(0x46); //flags
                    accessor.Codes.WriteByte(0x21); //ldc.i8
                    accessor.Codes.WriteUInt64(((ulong)key << 32) | (ptr ^ key));
                    accessor.Codes.WriteByte(0x20); //ldc.i4
                    accessor.Codes.WriteUInt32(~(uint)buff.Length ^ key);
                    accessor.Codes.WriteByte(0x26);

                    accessor.BlobHeap.Position = (int)tbl[i.Key].Col5;
                    accessor.BlobHeap.ReadCompressedUInt32();
                    byte flags = accessor.BlobHeap.ReadByte();
                    if ((flags & 0x10) != 0)
                    {
                        accessor.BlobHeap.ReadCompressedUInt32();
                    }
                    accessor.BlobHeap.ReadCompressedUInt32();
                    bool hasRet = false;
                    do
                    {
                        byte t = accessor.BlobHeap.ReadByte();
                        if (t == 0x1f || t == 0x20)
                        {
                            continue;
                        }
                        hasRet = t != 0x01;
                    } while (false);

                    accessor.Codes.WriteByte(hasRet ? (byte)0x00 : (byte)0x26);
                    accessor.Codes.WriteByte(0x2a); //ret
                    accessor.Codes.WriteBytes(((accessor.Codes.Position + 3) & ~3) - accessor.Codes.Position);
                }

                accessor.USHeap.Reset(new byte[0]);
            }