private List <PackageInfo> ObtainAndFillMetadata(List <PackageInfo> infos)
        {
            foreach (var packageInfo in infos)
            {
                foreach (var instPair in packageInfo.VersionedInstances)
                {
                    foreach (var inst in instPair.Value)
                    {
                        var addr = new Uri(RepositoryAddress);

                        var address = RepositoryAddress + (RepositoryAddress.EndsWith("/")?"":"/") + packageInfo.PackageName + "/" + instPair.Key + "/" +
                                      (inst.VersionName == null ? "trunk" : "tags/" + inst.VersionName) +
                                      "/" + MetadataFileName;

                        string filePath = null;
                        Common.Utility.ExceptionablePlaceWrapper(() =>
                        {
                            filePath = Utility.DownloadFileFromSVN(address);
                        }, string.Format("Attempt to get metadata by Address: {0} failed", address), "", false);

                        if (filePath == null)
                        {
                            continue;
                        }

                        MetadataProcessor.Process(filePath, inst);
                    }
                }
            }
            return(infos);
        }
Exemple #2
0
        public async Task Processing_Test()
        {
            // Arrange
            var postText = @"---
tags:
- Tag1
- Tag2
title: SimpleTitle
---
<p>Post</p>";
            var store    = new Mock <IPostStore>();

            store.Setup(x => x.GetContentByFilename(It.IsAny <string>()))
            .Returns((string val) => Task.FromResult(postText));

            var metadataProcessor = new MetadataProcessor(store.Object);
            var post = new Post {
                Filename = "MyPost"
            };

            // Act
            var postWithMeta = (await metadataProcessor.GetMetadataForPosts(new [] { post })).First();

            // Assert
            postWithMeta.Tags.Count.Should().Be(2);
            postWithMeta.Title.Should().Be("SimpleTitle");
        }
        void VideoStartup(Model model, VideoResolution resolution)
        {
            //subscribe to metadata
            IMetadataReceiver metadataReceiver = null;

            if (AppDefaults.visualSettings.EnableGraphicAnnotation)
            {
                string vaConfToken            = model.engineConfToken;
                var    eventMetadataProcessor = new EventMetadataProcessor();
                //eventMetadataProcessor.Processors.Add(new ObjectMotionMetadataProcessor(null, vaConfToken, movingObjectsHolder.EntityInitialized, movingObjectsHolder.EntityChanged, movingObjectsHolder.EntityDeleted));
                eventMetadataProcessor.Processors.Add(new MotionAlarmMetadataProcessor(null, vaConfToken, alarmsHolder.EntityInitialized, alarmsHolder.EntityChanged, alarmsHolder.EntityDeleted));
                eventMetadataProcessor.Processors.Add(new RegionMotionAlarmMetadataProcessor(null, vaConfToken, alarmsHolder.EntityInitialized, alarmsHolder.EntityChanged, alarmsHolder.EntityDeleted));
                eventMetadataProcessor.Processors.Add(new LoiteringAlarmMetadataProcessor(null, vaConfToken, alarmsHolder.EntityInitialized, alarmsHolder.EntityChanged, alarmsHolder.EntityDeleted));
                eventMetadataProcessor.Processors.Add(new AbandonedItemAlarmMetadataProcessor(null, vaConfToken, alarmsHolder.EntityInitialized, alarmsHolder.EntityChanged, alarmsHolder.EntityDeleted));
                eventMetadataProcessor.Processors.Add(new TripwireAlarmMetadataProcessor(null, vaConfToken, alarmsHolder.EntityInitialized, alarmsHolder.EntityChanged, alarmsHolder.EntityDeleted));
                eventMetadataProcessor.Processors.Add(new TamperingDetectorAlarmMetadataProcessor(null, vaConfToken, alarmsHolder.EntityInitialized, alarmsHolder.EntityChanged, alarmsHolder.EntityDeleted));
                var sceneMetadataProcessor = new SceneMetadataProcessor(movingObjectsHolder.EntityInitialized, movingObjectsHolder.EntityChanged, movingObjectsHolder.EntityDeleted);
                var metadataProcessor      = new MetadataProcessor(eventMetadataProcessor, sceneMetadataProcessor);
                metadataReceiver = new MetadataFramer(metadataProcessor.Process);
            }

            vidBuff = new VideoBuffer(resolution.width, resolution.height);

            var streamSetup = new StreamSetup()
            {
                transport = new Transport()
                {
                    protocol = AppDefaults.visualSettings.Transport_Type
                }
            };

            VideoPlayerView playview = new VideoPlayerView();

            disposables.Add(playview);

            player.Child = playview;

            playview.Init(new VideoPlayerView.Model(
                              streamSetup: streamSetup,
                              mediaUri: new MediaUri()
            {
                uri = model.uri
            },
                              encoderResolution: new VideoResolution()
            {
                height = resolution.height,
                width  = resolution.width
            },
                              isUriEnabled: false,   //TODO if true then annotation is not positioned correctly
                              metadataReceiver: metadataReceiver
                              ));

            uriString.Visibility = System.Windows.Visibility.Visible;
            uriString.Text       = model.uri;
        }
 public ResourceProcessorManager(XmlConversionProcessor xmlConversionProcessor,
                                 MetadataProcessor metadataProcessor, RelationalDbStoreProcessor relationalDbStoreProcessor,
                                 FileDbStoreProcessor fileDbStoreProcessor, ExistDbStoreProcessor existDbStoreProcessor,
                                 ExtractableArchiveProcessor extractableArchiveProcessor, TransformationsProcessor transformationsProcessor,
                                 AudioBookArchiveProcessor audiobookArchiveProcessor)
 {
     m_xmlConversionProcessor      = xmlConversionProcessor;
     m_metadataProcessor           = metadataProcessor;
     m_relationalDbStoreProcessor  = relationalDbStoreProcessor;
     m_fileDbStoreProcessor        = fileDbStoreProcessor;
     m_existDbStoreProcessor       = existDbStoreProcessor;
     m_extractableArchiveProcessor = extractableArchiveProcessor;
     m_transformationsProcessor    = transformationsProcessor;
     m_audiobookArchiveProcessor   = audiobookArchiveProcessor;
 }
        void VideoStartup(Model model)
        {
            var playerAct = activityContext.container.Resolve <IVideoPlayerActivity>();


            //subscribe to metadata
            IMetadataReceiver metadataReceiver = null;

            if (AppDefaults.visualSettings.EnableGraphicAnnotation)
            {
                var eventMetadataProcessor = new EventMetadataProcessor();
                eventMetadataProcessor.Processors.Add(new ObjectMotionMetadataProcessor(model.videoSourceToken, null, movingObjectsHolder.EntityInitialized, movingObjectsHolder.EntityChanged, movingObjectsHolder.EntityDeleted));
                eventMetadataProcessor.Processors.Add(new MotionAlarmMetadataProcessor(model.videoSourceToken, null, alarmsHolder.EntityInitialized, alarmsHolder.EntityChanged, alarmsHolder.EntityDeleted));
                eventMetadataProcessor.Processors.Add(new RegionMotionAlarmMetadataProcessor(model.videoSourceConfToken, model.videoAnalyticsConfToken, alarmsHolder.EntityInitialized, alarmsHolder.EntityChanged, alarmsHolder.EntityDeleted));
                eventMetadataProcessor.Processors.Add(new LoiteringAlarmMetadataProcessor(model.videoSourceConfToken, model.videoAnalyticsConfToken, alarmsHolder.EntityInitialized, alarmsHolder.EntityChanged, alarmsHolder.EntityDeleted));
                eventMetadataProcessor.Processors.Add(new AbandonedItemAlarmMetadataProcessor(model.videoSourceConfToken, model.videoAnalyticsConfToken, alarmsHolder.EntityInitialized, alarmsHolder.EntityChanged, alarmsHolder.EntityDeleted));
                eventMetadataProcessor.Processors.Add(new TripwireAlarmMetadataProcessor(model.videoSourceConfToken, model.videoAnalyticsConfToken, alarmsHolder.EntityInitialized, alarmsHolder.EntityChanged, alarmsHolder.EntityDeleted));
                eventMetadataProcessor.Processors.Add(new TamperingDetectorAlarmMetadataProcessor(model.videoSourceToken, null, alarmsHolder.EntityInitialized, alarmsHolder.EntityChanged, alarmsHolder.EntityDeleted));
                var metadataProcessor = new MetadataProcessor(eventMetadataProcessor, null);
                metadataReceiver = new MetadataFramer(metadataProcessor.Process);
            }

            var playerModel = new VideoPlayerActivityModel(
                profileToken: model.profToken,
                showStreamUrl: false,//TODO when true, annotation is not positioned correctly
                streamSetup: new StreamSetup()
            {
                stream    = StreamType.rtpUnicast,
                transport = new Transport()
                {
                    protocol = AppDefaults.visualSettings.Transport_Type,
                    tunnel   = null
                }
            },
                metadataReceiver: metadataReceiver
                );



            disposables.Add(
                activityContext.container.RunChildActivity(player, playerModel, (c, m) => playerAct.Run(c, m))
                );

            ShowStreamURI();
        }
Exemple #6
0
        static void Main(string[] args)
        {
            #region Index-Manager

            Console.WriteLine("Initializing index manager");
            _Indices = new KomodoIndices(
                new DbSettings("./indices.db"),
                new StorageSettings(new DiskSettings("./source/")),
                new StorageSettings(new DiskSettings("./parsed/")));

            #endregion

            #region Indices

            Console.WriteLine("Initializing indices");
            _Index1 = new Index("default", "default", "default");
            _Index2 = new Index("metadata", "default", "metadata");
            _Indices.Add(_Index1);
            _Indices.Add(_Index2);

            #endregion

            #region Adding-Documents

            _IndexClient1 = _Indices.GetIndexClient("default");
            _IndexClient2 = _Indices.GetIndexClient("metadata");

            byte[]         doc1 = File.ReadAllBytes("person1.json");
            SourceDocument sd1  = new SourceDocument(
                "default",
                "default",
                "Person 1",
                "Person 1",
                null,
                DocType.Json,
                null,
                "application/json",
                doc1.Length,
                Common.Md5(doc1));

            byte[]         doc2 = File.ReadAllBytes("person2.json");
            SourceDocument sd2  = new SourceDocument(
                "default",
                "default",
                "Person 2",
                "Person 2",
                null,
                DocType.Json,
                null,
                "application/json",
                doc2.Length,
                Common.Md5(doc2));

            byte[]         doc3 = File.ReadAllBytes("person3.json");
            SourceDocument sd3  = new SourceDocument(
                "default",
                "default",
                "Person 3",
                "Person 3",
                null,
                DocType.Json,
                null,
                "application/json",
                doc3.Length,
                Common.Md5(doc3));

            IndexResult r1 = _IndexClient1.Add(sd1, doc1, new ParseOptions(), true).Result;
            IndexResult r2 = _IndexClient1.Add(sd2, doc2, new ParseOptions(), true).Result;
            IndexResult r3 = _IndexClient1.Add(sd3, doc3, new ParseOptions(), true).Result;

            #endregion

            #region Blobs

            _Blobs = new Blobs(new DiskSettings("./Metadata/"));
            if (!Directory.Exists("./Metadata/"))
            {
                Directory.CreateDirectory("./Metadata/");
            }

            #endregion

            #region Policy

            byte[] bytes = File.ReadAllBytes("./policy.json");
            _Policy = Common.DeserializeJson <MetadataPolicy>(File.ReadAllBytes("./policy.json"));

            #endregion

            #region Initialize-Metadata

            Console.WriteLine("Initializing metadata processor");

            _Metadata = new MetadataProcessor(_Policy, _Indices);

            #endregion

            #region Apply-Metadata

            Console.WriteLine("Processing metadata");

            _Result1 = _Metadata.ProcessDocument(
                r1.SourceDocument,
                r1.ParsedDocument,
                r1.ParseResult).Result;

            // Console.WriteLine("Document 1: " + Environment.NewLine + Common.SerializeJson(_Result1, true));

            _Result2 = _Metadata.ProcessDocument(
                r2.SourceDocument,
                r2.ParsedDocument,
                r2.ParseResult).Result;

            // Console.WriteLine("Document 2: " + Environment.NewLine + Common.SerializeJson(_Result2, true));

            _Result3 = _Metadata.ProcessDocument(
                r3.SourceDocument,
                r3.ParsedDocument,
                r3.ParseResult).Result;

            Console.WriteLine("Document 3: " + Environment.NewLine + Common.SerializeJson(_Result3, true));

            #endregion
        }
Exemple #7
0
 public override void Process(NameValueCollection parameters, Stream stream, MetadataProcessor.ImageAccessor accessor)
 {
     cion.vers[accessor.Module].Phase5(stream, accessor);
 }
Exemple #8
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));
                }
            }
            public void Phase5(Stream stream, MetadataProcessor.ImageAccessor accessor)
            {
                stream.Seek(0, SeekOrigin.Begin);
                uint csOffset;
                uint sn;
                uint snLen;
                ExtractCodes(stream, accessor, out csOffset, out sn, out snLen);
                stream.Position = 0;

                MemoryStream ms = new MemoryStream();
                ms.WriteByte(0xd6);
                ms.WriteByte(0x6f);
                BinaryWriter wtr = new BinaryWriter(ms);
                wtr.Write((uint)codes.Length);
                for (int i = 0; i < codes.Length; i++)
                {
                    wtr.Write((int)(ptrs[i] ^ key4));
                    if (ptrs[i] == 0) continue;
                    Confuser.Database.AddEntry("AntiTamper", rvas[i].ToString("X8"), ms.Position);
                    wtr.Write((int)(rvas[i] ^ key5));
                    wtr.Write(codes[i].Length);
                    wtr.Write(codes[i]);
                }

                byte[] buff;
                BinaryReader sReader = new BinaryReader(stream);
                using (MemoryStream str = new MemoryStream())
                {
                    var mdPtr = accessor.ResolveVirtualAddress(accessor.GetTextSegmentRange(TextSegment.MetadataHeader).Start);
                    stream.Position = mdPtr + 12;
                    stream.Position += sReader.ReadUInt32() + 4;
                    stream.Position += 2;

                    ushort streams = sReader.ReadUInt16();

                    for (int i = 0; i < streams; i++)
                    {
                        uint offset = mdPtr + sReader.ReadUInt32();
                        uint size = sReader.ReadUInt32();

                        int c = 0;
                        while (sReader.ReadByte() != 0) c++;
                        long ori = stream.Position += (((c + 1) + 3) & ~3) - (c + 1);

                        stream.Position = offset;
                        str.Write(sReader.ReadBytes((int)size), 0, (int)size);
                        stream.Position = ori;
                    }

                    buff = str.ToArray();
                }

                byte[] iv;
                byte[] dat = Encrypt(Confuser.ObfuscationHelper, buff, ms.ToArray(), out iv, key6);

                byte[] md5 = MD5.Create().ComputeHash(buff);
                long checkSum = BitConverter.ToInt64(md5, 0) ^ BitConverter.ToInt64(md5, 8);
                wtr = new BinaryWriter(stream);
                stream.Seek(csOffset, SeekOrigin.Begin);
                wtr.Write(accessor.GetTextSegmentRange(TextSegment.MetadataHeader).Start ^ (uint)key0);
                stream.Seek(accessor.GetSection(sectName).PointerToRawData, SeekOrigin.Begin);
                wtr.Write(checkSum ^ key1);
                wtr.Write(sn);
                wtr.Write(snLen);
                wtr.Write(iv.Length ^ key2);
                wtr.Write(iv);
                wtr.Write(dat.Length ^ key3);
                wtr.Write(dat);
            }
 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 #11
0
            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 #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 string[] Pack(ConfuserParameter crParam, PackerParameter param)
        {
            AssemblyDefinition asm;

            PackCore(out asm, param);

            string tmp = Path.GetTempPath() + "\\" + Path.GetRandomFileName() + "\\";

            Directory.CreateDirectory(tmp);
            MetadataProcessor psr     = new MetadataProcessor();
            Section           oldRsrc = null;

            foreach (Section s in param.Modules[0].GetSections())
            {
                if (s.Name == ".rsrc")
                {
                    oldRsrc = s; break;
                }
            }
            if (oldRsrc != null)
            {
                psr.ProcessImage += accessor =>
                {
                    Section sect = null;
                    foreach (Section s in accessor.Sections)
                    {
                        if (s.Name == ".rsrc")
                        {
                            sect = s; break;
                        }
                    }
                    if (sect == null)
                    {
                        sect = new Section()
                        {
                            Name            = ".rsrc",
                            Characteristics = 0x40000040
                        };
                        foreach (Section s in accessor.Sections)
                        {
                            if (s.Name == ".text")
                            {
                                accessor.Sections.Insert(accessor.Sections.IndexOf(s) + 1, sect); break;
                            }
                        }
                    }
                    sect.VirtualSize   = oldRsrc.VirtualSize;
                    sect.SizeOfRawData = oldRsrc.PointerToRawData;
                    int idx = accessor.Sections.IndexOf(sect);
                    sect.VirtualAddress   = accessor.Sections[idx - 1].VirtualAddress + ((accessor.Sections[idx - 1].VirtualSize + 0x2000U - 1) & ~(0x2000U - 1));
                    sect.PointerToRawData = accessor.Sections[idx - 1].PointerToRawData + accessor.Sections[idx - 1].SizeOfRawData;
                    for (int i = idx + 1; i < accessor.Sections.Count; i++)
                    {
                        accessor.Sections[i].VirtualAddress   = accessor.Sections[i - 1].VirtualAddress + ((accessor.Sections[i - 1].VirtualSize + 0x2000U - 1) & ~(0x2000U - 1));
                        accessor.Sections[i].PointerToRawData = accessor.Sections[i - 1].PointerToRawData + accessor.Sections[i - 1].SizeOfRawData;
                    }
                    ByteBuffer buff = new ByteBuffer(oldRsrc.Data);
                    PatchResourceDirectoryTable(buff, oldRsrc, sect);
                    sect.Data = buff.GetBuffer();
                };
            }
            psr.Process(asm.MainModule, tmp + asm.MainModule.Name);

            Confuser          cr  = new Confuser();
            ConfuserParameter par = new ConfuserParameter();

            par.SourceAssembly = tmp + asm.MainModule.Name;
            par.ReferencesPath = tmp;
            tmp = Path.GetTempPath() + "\\" + Path.GetRandomFileName() + "\\";
            par.DestinationPath   = tmp;
            par.Confusions        = crParam.Confusions;
            par.DefaultPreset     = crParam.DefaultPreset;
            par.StrongNameKeyPath = crParam.StrongNameKeyPath;
            par.Marker            = new PackerMarker(param.Modules[0]);
            cr.Confuse(par);

            return(Directory.GetFiles(tmp));
        }
Exemple #14
0
 public void SetUp()
 {
     processor = new MetadataProcessor();
     CreateTables();
 }
            static void ExtractOffsets(Stream stream, MetadataProcessor.ImageAccessor accessor, out uint csOffset, out uint sn, out uint snLen)
            {
                BinaryReader rdr = new BinaryReader(stream);
                stream.Seek(0x3c, SeekOrigin.Begin);
                uint offset = rdr.ReadUInt32();
                stream.Seek(offset, SeekOrigin.Begin);
                stream.Seek(0x6, SeekOrigin.Current);
                uint sections = rdr.ReadUInt16();
                stream.Seek(offset = offset + 0x18, SeekOrigin.Begin);  //Optional hdr
                bool pe32 = (rdr.ReadUInt16() == 0x010b);
                csOffset = offset + 0x40;
                stream.Seek(offset = offset + (pe32 ? 0xE0U : 0xF0U), SeekOrigin.Begin);   //sections

                stream.Seek(offset - 16, SeekOrigin.Begin);
                uint mdDir = accessor.ResolveVirtualAddress(rdr.ReadUInt32());
                stream.Seek(mdDir + 0x20, SeekOrigin.Begin);
                sn = accessor.ResolveVirtualAddress(rdr.ReadUInt32());
                snLen = rdr.ReadUInt32();
            }
 public void Phase4(MetadataProcessor.ImageAccessor accessor)
 {
     uint size = (((uint)finalDat.Length + 2 + 0x7f) & ~0x7fu) + 0x28;
     Section prev = accessor.Sections[accessor.Sections.Count - 1];
     Section sect = accessor.CreateSection(sectName, size, 0x40000040, prev);
     accessor.Sections.Add(sect);
 }
            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]);
            }
Exemple #18
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;
            }
Exemple #19
0
        protected string[] ProtectStub(AssemblyDefinition asm)
        {
            string tmp = Path.GetTempPath() + "\\" + Path.GetRandomFileName() + "\\";
            Directory.CreateDirectory(tmp);
            ModuleDefinition modDef = this.cr.settings.Single(_ => _.IsMain).Assembly.MainModule;
            asm.MainModule.TimeStamp = modDef.TimeStamp;
            byte[] mvid = new byte[0x10];
            Random.NextBytes(mvid);
            asm.MainModule.Mvid = new Guid(mvid);
            MetadataProcessor psr = new MetadataProcessor();
            Section oldRsrc = null;
            foreach (Section s in modDef.GetSections())
                if (s.Name == ".rsrc") { oldRsrc = s; break; }
            if (oldRsrc != null)
            {
                psr.ProcessImage += accessor =>
                {
                    Section sect = null;
                    foreach (Section s in accessor.Sections)
                        if (s.Name == ".rsrc") { sect = s; break; }
                    if (sect == null)
                    {
                        sect = new Section()
                        {
                            Name = ".rsrc",
                            Characteristics = 0x40000040
                        };
                        foreach (Section s in accessor.Sections)
                            if (s.Name == ".text") { accessor.Sections.Insert(accessor.Sections.IndexOf(s) + 1, sect); break; }
                    }
                    sect.VirtualSize = oldRsrc.VirtualSize;
                    sect.SizeOfRawData = oldRsrc.SizeOfRawData;
                    int idx = accessor.Sections.IndexOf(sect);
                    sect.VirtualAddress = accessor.Sections[idx - 1].VirtualAddress + ((accessor.Sections[idx - 1].VirtualSize + 0x2000U - 1) & ~(0x2000U - 1));
                    sect.PointerToRawData = accessor.Sections[idx - 1].PointerToRawData + accessor.Sections[idx - 1].SizeOfRawData;
                    for (int i = idx + 1; i < accessor.Sections.Count; i++)
                    {
                        accessor.Sections[i].VirtualAddress = accessor.Sections[i - 1].VirtualAddress + ((accessor.Sections[i - 1].VirtualSize + 0x2000U - 1) & ~(0x2000U - 1));
                        accessor.Sections[i].PointerToRawData = accessor.Sections[i - 1].PointerToRawData + accessor.Sections[i - 1].SizeOfRawData;
                    }
                    ByteBuffer buff = new ByteBuffer(oldRsrc.Data);
                    PatchResourceDirectoryTable(buff, oldRsrc, sect);
                    sect.Data = buff.GetBuffer();
                };
            }
            psr.Process(asm.MainModule, tmp + Path.GetFileName(modDef.FullyQualifiedName), new WriterParameters()
            {
                StrongNameKeyPair = this.cr.sn,
                WriteSymbols = this.cr.param.Project.Debug
            });

            Confuser cr = new Confuser();

            ConfuserProject proj = new ConfuserProject();
            proj.Seed = Random.Next().ToString();
            proj.Debug = this.cr.param.Project.Debug;
            foreach (var i in this.cr.param.Project.Rules)
                proj.Rules.Add(i);
            proj.Add(new ProjectAssembly()
            {
                Path = tmp + Path.GetFileName(modDef.FullyQualifiedName)
            });
            proj.OutputPath = tmp;
            foreach (var i in this.cr.param.Project.Plugins) proj.Plugins.Add(i);
            proj.SNKeyPath = this.cr.param.Project.SNKeyPath;

            ConfuserParameter par = new ConfuserParameter();
            par.Project = proj;
            par.ProcessMetadata = PostProcessMetadata;
            par.ProcessImage = PostProcessImage;
            cr.Confuse(par);

            return Directory.GetFiles(tmp);
        }
Exemple #20
0
            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 #21
0
 protected internal virtual void PostProcessImage(MetadataProcessor.ImageAccessor accessor)
 {
 }
Exemple #22
0
        protected string[] ProtectStub(AssemblyDefinition asm)
        {
            string tmp = Path.GetTempPath() + "\\" + Path.GetRandomFileName() + "\\";

            Directory.CreateDirectory(tmp);
            ModuleDefinition modDef = this.cr.settings.Single(_ => _.IsMain).Assembly.MainModule;

            asm.MainModule.TimeStamp = modDef.TimeStamp;
            byte[] mvid = new byte[0x10];
            Random.NextBytes(mvid);
            asm.MainModule.Mvid = new Guid(mvid);
            MetadataProcessor psr     = new MetadataProcessor();
            Section           oldRsrc = null;

            foreach (Section s in modDef.GetSections())
            {
                if (s.Name == ".rsrc")
                {
                    oldRsrc = s; break;
                }
            }
            if (oldRsrc != null)
            {
                psr.ProcessImage += accessor =>
                {
                    Section sect = null;
                    foreach (Section s in accessor.Sections)
                    {
                        if (s.Name == ".rsrc")
                        {
                            sect = s; break;
                        }
                    }
                    if (sect == null)
                    {
                        sect = new Section()
                        {
                            Name            = ".rsrc",
                            Characteristics = 0x40000040
                        };
                        foreach (Section s in accessor.Sections)
                        {
                            if (s.Name == ".text")
                            {
                                accessor.Sections.Insert(accessor.Sections.IndexOf(s) + 1, sect); break;
                            }
                        }
                    }
                    sect.VirtualSize   = oldRsrc.VirtualSize;
                    sect.SizeOfRawData = oldRsrc.SizeOfRawData;
                    int idx = accessor.Sections.IndexOf(sect);
                    sect.VirtualAddress   = accessor.Sections[idx - 1].VirtualAddress + ((accessor.Sections[idx - 1].VirtualSize + 0x2000U - 1) & ~(0x2000U - 1));
                    sect.PointerToRawData = accessor.Sections[idx - 1].PointerToRawData + accessor.Sections[idx - 1].SizeOfRawData;
                    for (int i = idx + 1; i < accessor.Sections.Count; i++)
                    {
                        accessor.Sections[i].VirtualAddress   = accessor.Sections[i - 1].VirtualAddress + ((accessor.Sections[i - 1].VirtualSize + 0x2000U - 1) & ~(0x2000U - 1));
                        accessor.Sections[i].PointerToRawData = accessor.Sections[i - 1].PointerToRawData + accessor.Sections[i - 1].SizeOfRawData;
                    }
                    ByteBuffer buff = new ByteBuffer(oldRsrc.Data);
                    PatchResourceDirectoryTable(buff, oldRsrc, sect);
                    sect.Data = buff.GetBuffer();
                };
            }
            psr.Process(asm.MainModule, tmp + Path.GetFileName(modDef.FullyQualifiedName), new WriterParameters()
            {
                StrongNameKeyPair = this.cr.sn,
                WriteSymbols      = this.cr.param.Project.Debug
            });

            Confuser cr = new Confuser();

            ConfuserProject proj = new ConfuserProject();

            proj.Seed  = Random.Next().ToString();
            proj.Debug = this.cr.param.Project.Debug;
            foreach (var i in this.cr.param.Project.Rules)
            {
                proj.Rules.Add(i);
            }
            proj.Add(new ProjectAssembly()
            {
                Path = tmp + Path.GetFileName(modDef.FullyQualifiedName)
            });
            proj.OutputPath = tmp;
            foreach (var i in this.cr.param.Project.Plugins)
            {
                proj.Plugins.Add(i);
            }
            proj.SNKeyPath = this.cr.param.Project.SNKeyPath;

            ConfuserParameter par = new ConfuserParameter();

            par.Project         = proj;
            par.ProcessMetadata = PostProcessMetadata;
            par.ProcessImage    = PostProcessImage;
            cr.Confuse(par);

            return(Directory.GetFiles(tmp));
        }
Exemple #23
0
 protected internal virtual void PostProcessMetadata(MetadataProcessor.MetadataAccessor accessor)
 {
 }
 public void Phase4(MetadataProcessor.ImageAccessor accessor)
 {
     uint size = 2 + 4 + codeLen;
     for (int i = 0; i < codes.Length; i++)
     {
         size += 4;
         if (rvas[i] == 0) continue;
         size += 8;
     }
     size = (((uint)size + 0x7f) & ~0x7fu) + 0x28;
     Section prev = accessor.Sections[accessor.Sections.Count - 1];
     accessor.Sections[0].Characteristics = 0x60000020;
     Section sect = accessor.CreateSection(sectName, size, 0x40000040, prev);
     accessor.Sections.Add(sect);
 }
Exemple #25
0
 protected internal virtual void ProcessImage(MetadataProcessor.ImageAccessor accessor, bool isMain)
 {
 }
            void ExtractCodes(Stream stream, MetadataProcessor.ImageAccessor accessor, out uint csOffset, out uint sn, out uint snLen)
            {
                BinaryReader rdr = new BinaryReader(stream);
                stream.Seek(0x3c, SeekOrigin.Begin);
                uint offset = rdr.ReadUInt32();
                stream.Seek(offset, SeekOrigin.Begin);
                stream.Seek(0x6, SeekOrigin.Current);
                uint sections = rdr.ReadUInt16();
                stream.Seek(offset = offset + 0x18, SeekOrigin.Begin);  //Optional hdr
                bool pe32 = (rdr.ReadUInt16() == 0x010b);
                csOffset = offset + 0x40;
                stream.Seek(offset = offset + (pe32 ? 0xE0U : 0xF0U), SeekOrigin.Begin);   //sections

                for (int i = 0; i < rvas.Length; i++)
                {
                    if (rvas[i] == 0) continue;
                    ptrs[i] = accessor.ResolveVirtualAddress(rvas[i]);
                    stream.Seek(ptrs[i], SeekOrigin.Begin);
                    byte b = rdr.ReadByte();
                    if ((b & 0x3) == 0x2)
                    {
                        stream.Seek((uint)b >> 2, SeekOrigin.Current);
                    }
                    else
                    {
                        stream.Seek(-1, SeekOrigin.Current);
                        ushort f = rdr.ReadUInt16();
                        stream.Seek(2, SeekOrigin.Current);
                        uint size = rdr.ReadUInt32();
                        stream.Seek(4 + size, SeekOrigin.Current);
                        if ((f & 0x80) != 0)
                        {
                            stream.Seek((stream.Position + 3) & ~3, SeekOrigin.Begin);
                            bool more;
                            do
                            {
                                byte fl = rdr.ReadByte();
                                more = ((fl & 0x80) != 0);
                                if ((fl & 0x40) != 0)
                                {
                                    stream.Seek(-1, SeekOrigin.Current);
                                    uint sectLen = rdr.ReadUInt32() >> 8;
                                    stream.Seek(-4 + sectLen, SeekOrigin.Current);
                                }
                                else
                                {
                                    byte sectLen = rdr.ReadByte();
                                    stream.Seek(-1 + sectLen, SeekOrigin.Current);
                                }
                            } while (more);
                        }
                    }
                    long len = stream.Position - ptrs[i];
                    stream.Seek(ptrs[i], SeekOrigin.Begin);
                    codes[i] = rdr.ReadBytes((int)len);
                    stream.Seek(ptrs[i], SeekOrigin.Begin);
                    byte[] bs = new byte[len];
                    stream.Write(bs, 0, (int)len);
                }

                stream.Seek(offset - 16, SeekOrigin.Begin);
                uint mdDir = accessor.ResolveVirtualAddress(rdr.ReadUInt32());
                stream.Seek(mdDir + 0x20, SeekOrigin.Begin);
                sn = accessor.ResolveVirtualAddress(rdr.ReadUInt32());
                snLen = rdr.ReadUInt32();
            }
Exemple #27
0
 public abstract void Process(NameValueCollection parameters, Stream stream, MetadataProcessor.ImageAccessor accessor);
Exemple #28
0
 protected internal virtual void ProcessMetadataPhase2(MetadataProcessor.MetadataAccessor accessor, bool isMain)
 {
 }
Exemple #29
0
 public override void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor)
 {
     cion.vers[accessor.Module].Phase3(accessor);
 }
Exemple #30
0
        void ProcessMdPePhases(ModuleDefinition mod, IDictionary <IConfusion, NameValueCollection> globalParams, IEnumerable <Phase> phases, Stream stream, WriterParameters parameters)
        {
            MetadataProcessor psr    = new MetadataProcessor();
            double            total1 = (from i in phases where (i is MetadataPhase) select i).Count();
            int now1 = 1;

            psr.BeforeBuildModule += new MetadataProcessor.MetadataProcess(delegate(MetadataProcessor.MetadataAccessor accessor)
            {
                foreach (MetadataPhase i in from i in phases where (i is MetadataPhase) && i.PhaseID == 1 orderby i.Priority ascending select i)
                {
                    if (GetTargets(mod, i.Confusion).Count == 0)
                    {
                        continue;
                    }
                    param.Logger.Log("Executing " + i.Confusion.Name + " Phase 1...");
                    i.Confuser = this;
                    NameValueCollection globalParam;
                    if (globalParams.ContainsKey(i.Confusion))
                    {
                        globalParam = globalParams[i.Confusion];
                    }
                    else
                    {
                        globalParam = new NameValueCollection();
                    }
                    i.Process(globalParam, accessor);
                    param.Logger.Progress(now1 / total1); now1++;
                }
            });
            psr.BeforeWriteTables += new MetadataProcessor.MetadataProcess(delegate(MetadataProcessor.MetadataAccessor accessor)
            {
                foreach (MetadataPhase i in from i in phases where (i is MetadataPhase) && i.PhaseID == 2 orderby i.Priority ascending select i)
                {
                    if (GetTargets(mod, i.Confusion).Count == 0)
                    {
                        continue;
                    }
                    param.Logger.Log("Executing " + i.Confusion.Name + " Phase 2...");
                    i.Confuser = this;
                    NameValueCollection globalParam;
                    if (globalParams.ContainsKey(i.Confusion))
                    {
                        globalParam = globalParams[i.Confusion];
                    }
                    else
                    {
                        globalParam = new NameValueCollection();
                    }
                    i.Process(globalParam, accessor);
                    param.Logger.Progress(now1 / total1); now1++;
                }
            });
            psr.AfterWriteTables += new MetadataProcessor.MetadataProcess(delegate(MetadataProcessor.MetadataAccessor accessor)
            {
                foreach (MetadataPhase i in from i in phases where (i is MetadataPhase) && i.PhaseID == 3 orderby i.Priority ascending select i)
                {
                    if (GetTargets(mod, i.Confusion).Count == 0)
                    {
                        continue;
                    }
                    param.Logger.Log("Executing " + i.Confusion.Name + " Phase 3...");
                    i.Confuser = this;
                    NameValueCollection globalParam;
                    if (globalParams.ContainsKey(i.Confusion))
                    {
                        globalParam = globalParams[i.Confusion];
                    }
                    else
                    {
                        globalParam = new NameValueCollection();
                    }
                    i.Process(globalParam, accessor);
                    param.Logger.Progress(now1 / total1); now1++;
                }
            });
            psr.ProcessImage += new MetadataProcessor.ImageProcess(delegate(MetadataProcessor.ImageAccessor accessor)
            {
                param.Logger.StartPhase(4);
                param.Logger.Log(string.Format("Obfuscating Image of module {0}...", mod.Name));
                ImagePhase[] imgPhases = (from i in phases where (i is ImagePhase)orderby(int) i.Priority + i.PhaseID * 10 ascending select(ImagePhase) i).ToArray();
                for (int i = 0; i < imgPhases.Length; i++)
                {
                    if (GetTargets(mod, imgPhases[i].Confusion).Count == 0)
                    {
                        continue;
                    }
                    param.Logger.Log("Executing " + imgPhases[i].Confusion.Name + " Phase " + imgPhases[i].PhaseID + "...");
                    imgPhases[i].Confuser = this;
                    NameValueCollection globalParam;
                    if (globalParams.ContainsKey(imgPhases[i].Confusion))
                    {
                        globalParam = globalParams[imgPhases[i].Confusion];
                    }
                    else
                    {
                        globalParam = new NameValueCollection();
                    }
                    imgPhases[i].Process(globalParam, accessor);
                    param.Logger.Progress((double)i / imgPhases.Length);
                }
            });
            psr.ProcessPe += new MetadataProcessor.PeProcess(delegate(Stream str)
            {
                param.Logger.Log(string.Format("Obfuscating PE of module {0}...", mod.Name));
                PePhase[] pePhases = (from i in phases where (i is PePhase)orderby(int) i.Priority + i.PhaseID * 10 ascending select(PePhase) i).ToArray();
                for (int i = 0; i < pePhases.Length; i++)
                {
                    if (GetTargets(mod, pePhases[i].Confusion).Count == 0)
                    {
                        continue;
                    }
                    param.Logger.Log("Executing " + pePhases[i].Confusion.Name + " Phase " + pePhases[i].PhaseID + "...");
                    pePhases[i].Confuser = this;
                    NameValueCollection globalParam;
                    if (globalParams.ContainsKey(pePhases[i].Confusion))
                    {
                        globalParam = globalParams[pePhases[i].Confusion];
                    }
                    else
                    {
                        globalParam = new NameValueCollection();
                    }
                    pePhases[i].Process(globalParam, str);
                    param.Logger.Progress((double)i / pePhases.Length);
                }
            });
            param.Logger.Log(string.Format("Obfuscating metadata of module {0}...", mod.Name));
            psr.Process(mod, stream, parameters);
        }
Exemple #31
0
 public abstract void Process(NameValueCollection parameters, MetadataProcessor.MetadataAccessor accessor);