void EncodeField(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriterBase)sender; if (e.WriterEvent == ModuleWriterEvent.MDMemberDefRidsAllocated && keyAttrs != null) { var keyFuncs = keyAttrs .Where(entry => entry != null) .ToDictionary(entry => entry.Item1, entry => entry.Item2); foreach (var desc in fieldDescs) { var token = writer.MetaData.GetToken(desc.Method).Raw; var key = encodeCtx.Random.NextUInt32() | 1; // CA var ca = desc.Field.CustomAttributes[0]; var encodedKey = keyFuncs[(TypeDef)ca.AttributeType]((int)MathsUtils.modInv(key)); ca.ConstructorArguments.Add(new CAArgument(encodeCtx.Module.CorLibTypes.Int32, encodedKey)); token *= key; // Encoding token = (uint)desc.InitDesc.Encoding.Encode(desc.InitDesc.Method, encodeCtx, (int)token); // Field name var name = new char[5]; name[desc.InitDesc.OpCodeIndex] = (char)((byte)desc.OpCode ^ desc.OpKey); var nameKey = encodeCtx.Random.NextBytes(4); uint encodedNameKey = 0; for (var i = 0; i < 4; i++) { // No zero bytes while (nameKey[i] == 0) { nameKey[i] = encodeCtx.Random.NextByte(); } name[desc.InitDesc.TokenNameOrder[i]] = (char)nameKey[i]; encodedNameKey |= (uint)nameKey[i] << desc.InitDesc.TokenByteOrder[i]; } desc.Field.Name = new string(name); // Field sig var sig = desc.Field.FieldSig; var encodedToken = (token - writer.MetaData.GetToken(((CModOptSig)sig.Type).Modifier).Raw) ^ encodedNameKey; var extra = new byte[8]; extra[0] = 0xc0; extra[3] = (byte)(encodedToken >> desc.InitDesc.TokenByteOrder[3]); extra[4] = 0xc0; extra[5] = (byte)(encodedToken >> desc.InitDesc.TokenByteOrder[2]); extra[6] = (byte)(encodedToken >> desc.InitDesc.TokenByteOrder[1]); extra[7] = (byte)(encodedToken >> desc.InitDesc.TokenByteOrder[0]); sig.ExtraData = extra; } } }
private void CurrentModuleWriterListener_OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriterBase)sender; if (e.WriterEvent == dnlib.DotNet.Writer.ModuleWriterEvent.End) { HashFile(writer); } }
private void EncodeField(object sender, ModuleWriterListenerEventArgs e) { ModuleWriterBase base2 = (ModuleWriterBase)sender; if (e.WriterEvent == ModuleWriterEvent.MDMemberDefRidsAllocated) { Dictionary <TypeDef, Func <int, int> > dictionary = (from entry in this.keyAttrs where entry != null select entry).ToDictionary <Tuple <TypeDef, Func <int, int> >, TypeDef, Func <int, int> >(entry => entry.Item1, entry => entry.Item2); foreach (FieldDesc desc in this.fieldDescs) { uint raw = base2.MetaData.GetToken(desc.Method).Raw; uint num = this.encodeCtx.Random.NextUInt32() | 1; CustomAttribute attribute = desc.Field.CustomAttributes[0]; int num3 = dictionary[(TypeDef)attribute.AttributeType]((int)MathsUtils.modInv(num)); attribute.ConstructorArguments.Add(new CAArgument(this.encodeCtx.Module.CorLibTypes.Int32, num3)); raw *= num; raw = (uint)desc.InitDesc.Encoding.Encode(desc.InitDesc.Method, this.encodeCtx, (int)raw); char[] chArray = new char[5]; chArray[desc.InitDesc.OpCodeIndex] = (char)(((byte)desc.OpCode) ^ desc.OpKey); byte[] buffer = this.encodeCtx.Random.NextBytes(4); uint num4 = 0; int index = 0; goto Label_01E1; Label_018D: buffer[index] = this.encodeCtx.Random.NextByte(); Label_01A2: if (buffer[index] == 0) { goto Label_018D; } chArray[desc.InitDesc.TokenNameOrder[index]] = (char)buffer[index]; num4 |= (uint)(buffer[index] << desc.InitDesc.TokenByteOrder[index]); index++; Label_01E1: if (index < 4) { goto Label_01A2; } desc.Field.Name = new string(chArray); FieldSig fieldSig = desc.Field.FieldSig; uint num6 = (raw - base2.MetaData.GetToken(((CModOptSig)fieldSig.Type).Modifier).Raw) ^ num4; byte[] buffer2 = new byte[8]; buffer2[0] = 0xc0; buffer2[3] = (byte)(num6 >> desc.InitDesc.TokenByteOrder[3]); buffer2[4] = 0xc0; buffer2[5] = (byte)(num6 >> desc.InitDesc.TokenByteOrder[2]); buffer2[6] = (byte)(num6 >> desc.InitDesc.TokenByteOrder[1]); buffer2[7] = (byte)(num6 >> desc.InitDesc.TokenByteOrder[0]); fieldSig.ExtraData = buffer2; } } }
void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriterBase)sender; if (e.WriterEvent == ModuleWriterEvent.MDEndCreateTables) { CreateSections(writer); } else if (e.WriterEvent == ModuleWriterEvent.BeginStrongNameSign) { EncryptSection(writer); } }
void InjectNativeCode(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriterBase)sender; if (e.WriterEvent == ModuleWriterEvent.MDEndWriteMethodBodies) { codeChunk = writer.MethodBodies.Add(new MethodBody(code)); } else if (e.WriterEvent == ModuleWriterEvent.EndCalculateRvasAndFileOffsets) { var rid = writer.MetaData.GetRid(native); writer.MetaData.TablesHeap.MethodTable[rid].RVA = (uint)codeChunk.RVA; } }
public void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { if (e.WriterEvent == ModuleWriterEvent.MDEndAddResources) { var writer = (ModuleWriterBase)sender; ctx.ManifestResources = new List <Tuple <uint, uint, string> >(); Dictionary <uint, byte[]> stringDict = writer.MetaData.StringsHeap.GetAllRawData().ToDictionary(pair => pair.Key, pair => pair.Value); foreach (RawManifestResourceRow resource in writer.MetaData.TablesHeap.ManifestResourceTable) { ctx.ManifestResources.Add(Tuple.Create(resource.Offset, resource.Flags, Encoding.UTF8.GetString(stringDict[resource.Name]))); } ctx.EntryPointToken = writer.MetaData.GetToken(ctx.EntryPoint).Raw; } }
void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriterBase)sender; if (e.WriterEvent == ModuleWriterEvent.MDBeginWriteMethodBodies) { context.Logger.Debug("Extracting method bodies..."); CreateSection(writer); } else if (e.WriterEvent == ModuleWriterEvent.BeginStrongNameSign) { context.Logger.Debug("Encrypting method section..."); EncryptSection(writer); } }
void InjectHash(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriterBase)sender; if (e.WriterEvent == ModuleWriterEvent.End) { var st = new StreamReader(writer.DestinationStream); var a = new BinaryReader(st.BaseStream); a.BaseStream.Position = 0; var data = a.ReadBytes((int)(st.BaseStream.Length - 32)); var enc = Encoding.Default.GetBytes(Hash(data)); writer.DestinationStream.Position = writer.DestinationStream.Length - enc.Length; writer.DestinationStream.Write(enc, 0, enc.Length); } }
static void InsertVMBodies(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriterBase)sender; if (e.WriterEvent != ModuleWriterEvent.MDMemberDefRidsAllocated) { return; } TokenGetter.Writer = writer; var body = Context.Bodies[writer.Module]; var data = body.Serialize(); writer.Module.Resources.Add(new EmbeddedResource(" ", Compress(data))); }
private void InjectNativeCode(object sender, ModuleWriterListenerEventArgs e) { ModuleWriterBase base2 = (ModuleWriterBase)sender; if (e.WriterEvent == ModuleWriterEvent.MDEndWriteMethodBodies) { for (int i = 0; i < this.nativeCodes.Count; i++) { this.nativeCodes[i] = new Tuple <MethodDef, byte[], dnlib.DotNet.Writer.MethodBody>(this.nativeCodes[i].Item1, this.nativeCodes[i].Item2, base2.MethodBodies.Add(new dnlib.DotNet.Writer.MethodBody(this.nativeCodes[i].Item2))); } } else if (e.WriterEvent == ModuleWriterEvent.EndCalculateRvasAndFileOffsets) { foreach (Tuple <MethodDef, byte[], dnlib.DotNet.Writer.MethodBody> tuple in this.nativeCodes) { uint rid = base2.MetaData.GetRid(tuple.Item1); base2.MetaData.TablesHeap.MethodTable[rid].RVA = (uint)tuple.Item3.RVA; } } }
public void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriter)sender; if (this.commitListener != null) { this.commitListener.OnWriterEvent(writer, e.WriterEvent); } if (e.WriterEvent != ModuleWriterEvent.MDBeginWriteMethodBodies || !this.methods.ContainsKey(writer.Module)) { if (this.commitListener != null && e.WriterEvent == ModuleWriterEvent.End && this.vr.ExportDbgInfo) { string mapName = Path.ChangeExtension(writer.Module.Name, "map"); string mapPath = Path.GetFullPath(Path.Combine(this.ctx.OutputDirectory, mapName)); Directory.CreateDirectory(this.ctx.OutputDirectory); File.WriteAllBytes(mapPath, this.vr.Runtime.DebugInfo); } } else { this.vr.ProcessMethods(writer.Module, (num, total) => { this.ctx.Logger.Progress(num, total); this.ctx.CheckCancellation(); }); this.ctx.Logger.EndProgress(); foreach (KeyValuePair <IMemberRef, IMemberRef> repl in this.refRepl) { this.vr.Runtime.Descriptor.Data.ReplaceReference(repl.Key, repl.Value); } this.commitListener = this.vr.CommitModule(this.ctx.CurrentModule, (num, total) => { this.ctx.Logger.Progress(num, total); this.ctx.CheckCancellation(); }); } }
public void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriter)sender; if (commitListener != null) { commitListener.OnWriterEvent(writer, e.WriterEvent); } if (e.WriterEvent == ModuleWriterEvent.MDBeginWriteMethodBodies && methods.ContainsKey(writer.Module)) { ctx.Logger.Debug("Virtualizing methods..."); vr.ProcessMethods(writer.Module, (num, total) => { ctx.Logger.Progress(num, total); ctx.CheckCancellation(); }); ctx.Logger.EndProgress(); foreach (var repl in refRepl) { vr.Runtime.Descriptor.Data.ReplaceReference(repl.Key, repl.Value); } commitListener = vr.CommitModule(ctx.CurrentModule, (num, total) => { ctx.Logger.Progress(num, total); ctx.CheckCancellation(); }); } else if (commitListener != null && e.WriterEvent == ModuleWriterEvent.End && vr.ExportDbgInfo) { var mapName = Path.ChangeExtension(writer.Module.Name, "map"); var mapPath = Path.GetFullPath(Path.Combine(ctx.OutputDirectory, mapName)); Directory.CreateDirectory(ctx.OutputDirectory); File.WriteAllBytes(mapPath, vr.Runtime.DebugInfo); } }
void InjectNativeCode(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriterBase)sender; if (e.WriterEvent == ModuleWriterEvent.MDEndWriteMethodBodies) { for (int n = 0; n < nativeCodes.Count; n++) { nativeCodes[n] = new Tuple <MethodDef, byte[], MethodBody>( nativeCodes[n].Item1, nativeCodes[n].Item2, writer.MethodBodies.Add(new MethodBody(nativeCodes[n].Item2))); } } else if (e.WriterEvent == ModuleWriterEvent.EndCalculateRvasAndFileOffsets) { foreach (var native in nativeCodes) { uint rid = writer.MetaData.GetRid(native.Item1); writer.MetaData.TablesHeap.MethodTable[rid].RVA = (uint)native.Item3.RVA; } } }
void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriterBase)sender; if (e.WriterEvent == ModuleWriterEvent.MDEndCreateTables) { writer.MetaData.TablesHeap.ModuleTable.Add(new RawModuleRow(0, 0x7fff7fff, 0, 0, 0)); writer.MetaData.TablesHeap.AssemblyTable.Add(new RawAssemblyRow(0, 0, 0, 0, 0, 0, 0, 0x7fff7fff, 0)); int r = random.NextInt32(8, 16); for (int i = 0; i < r; i++) { writer.MetaData.TablesHeap.ENCLogTable.Add(new RawENCLogRow(random.NextUInt32(), random.NextUInt32())); } r = random.NextInt32(8, 16); for (int i = 0; i < r; i++) { writer.MetaData.TablesHeap.ENCMapTable.Add(new RawENCMapRow(random.NextUInt32())); } Randomize(writer.MetaData.TablesHeap.ManifestResourceTable); writer.TheOptions.MetaDataOptions.TablesHeapOptions.ExtraData = random.NextUInt32(); writer.TheOptions.MetaDataOptions.TablesHeapOptions.UseENC = false; writer.TheOptions.MetaDataOptions.MetaDataHeaderOptions.VersionString += "\0\0\0\0"; writer.TheOptions.MetaDataOptions.OtherHeapsEnd.Add(new RawHeap("#GUID", Guid.NewGuid().ToByteArray())); writer.TheOptions.MetaDataOptions.OtherHeapsEnd.Add(new RawHeap("#Strings", new byte[1])); writer.TheOptions.MetaDataOptions.OtherHeapsEnd.Add(new RawHeap("#Blob", new byte[1])); writer.TheOptions.MetaDataOptions.OtherHeapsEnd.Add(new RawHeap("#Schema", new byte[1])); writer.TheOptions.MetaDataOptions.OtherHeapsEnd.Add(new RawHeap("#DarksProtector", new byte[1])); } else if (e.WriterEvent == ModuleWriterEvent.MDOnAllTablesSorted) { writer.MetaData.TablesHeap.DeclSecurityTable.Add(new RawDeclSecurityRow( unchecked (0x7fff), 0xffff7fff, 0xffff7fff)); } }
private void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { ModuleWriterBase moduleWriterBase = (ModuleWriterBase)sender; if (e.WriterEvent == ModuleWriterEvent.MDEndCreateTables) { PESection pESection = new PESection("Rzy", 1073741888u); moduleWriterBase.Sections.Add(pESection); pESection.Add(new ByteArrayChunk(new byte[123]), 4u); pESection.Add(new ByteArrayChunk(new byte[10]), 4u); string text = ".Rzy"; string s = null; for (int i = 0; i < 80; i++) { text += FakeNative.FakeNativePhase.GetRandomString(); } for (int j = 0; j < 80; j++) { byte[] bytes = Encoding.ASCII.GetBytes(text); s = Utils.EncodeString(bytes, FakeNative.FakeNativePhase.asciiCharset); } byte[] bytes2 = Encoding.ASCII.GetBytes(s); moduleWriterBase.TheOptions.MetaDataOptions.OtherHeapsEnd.Add(new FakeNative.RawHeap("#Rzy-Private-Protector", bytes2)); pESection.Add(new ByteArrayChunk(bytes2), 4u); var writer = (ModuleWriterBase)sender; uint signature = (uint)(moduleWriterBase.MetaData.TablesHeap.TypeSpecTable.Rows + 1); List <uint> list = (from row in moduleWriterBase.MetaData.TablesHeap.TypeDefTable select row.Namespace).Distinct <uint>().ToList <uint>(); List <uint> list2 = (from row in moduleWriterBase.MetaData.TablesHeap.MethodTable select row.Name).Distinct <uint>().ToList <uint>(); uint num2 = Convert.ToUInt32(FakeNative.R.Next(15, 3546)); using (List <uint> .Enumerator enumerator = list.GetEnumerator()) { while (enumerator.MoveNext()) { uint current = enumerator.Current; if (current != 0u) { foreach (uint current2 in list2) { if (current2 != 0u) { moduleWriterBase.MetaData.TablesHeap.TypeSpecTable.Add(new RawTypeSpecRow(signature)); moduleWriterBase.MetaData.TablesHeap.ModuleTable.Add(new RawModuleRow(65535, 0u, 4294967295u, 4294967295u, 4294967295u)); moduleWriterBase.MetaData.TablesHeap.ParamTable.Add(new RawParamRow(254, 254, moduleWriterBase.MetaData.TablesHeap.ENCMapTable.Add(new RawENCMapRow(this.random.NextUInt32())))); moduleWriterBase.MetaData.TablesHeap.FieldTable.Add(new RawFieldRow((ushort)(num2 * 4u + 77u), 31u + num2 / 2u * 3u, this.random.NextUInt32())); moduleWriterBase.MetaData.TablesHeap.MemberRefTable.Add(new RawMemberRefRow(num2 + 18u, num2 * 4u + 77u, 31u + num2 / 2u * 3u)); moduleWriterBase.MetaData.TablesHeap.TypeSpecTable.Add(new RawTypeSpecRow(3391u + num2 / 2u * 3u)); moduleWriterBase.MetaData.TablesHeap.PropertyTable.Add(new RawPropertyRow((ushort)(num2 + 44u - 1332u), num2 / 2u + 2u, this.random.NextUInt32())); moduleWriterBase.MetaData.TablesHeap.TypeSpecTable.Add(new RawTypeSpecRow(3391u + num2 / 2u * 3u)); moduleWriterBase.MetaData.TablesHeap.PropertyPtrTable.Add(new RawPropertyPtrRow(this.random.NextUInt32())); moduleWriterBase.MetaData.TablesHeap.AssemblyRefTable.Add(new RawAssemblyRefRow(55, 44, 66, 500, this.random.NextUInt32(), this.random.NextUInt32(), moduleWriterBase.MetaData.TablesHeap.ENCMapTable.Add(new RawENCMapRow(this.random.NextUInt32())), this.random.NextUInt32(), this.random.NextUInt32())); moduleWriterBase.MetaData.TablesHeap.ENCLogTable.Add(new RawENCLogRow(this.random.NextUInt32(), moduleWriterBase.MetaData.TablesHeap.ENCMapTable.Add(new RawENCMapRow(this.random.NextUInt32())))); moduleWriterBase.MetaData.TablesHeap.ENCLogTable.Add(new RawENCLogRow(this.random.NextUInt32(), (uint)(moduleWriterBase.MetaData.TablesHeap.ENCMapTable.Rows - 1))); moduleWriterBase.MetaData.TablesHeap.ImplMapTable.Add(new RawImplMapRow(18, num2 * 4u + 77u, 31u + num2 / 2u * 3u, num2 * 4u + 77u)); } } } } } } if (e.WriterEvent == ModuleWriterEvent.MDOnAllTablesSorted) { moduleWriterBase.MetaData.TablesHeap.DeclSecurityTable.Add(new RawDeclSecurityRow(32767, 4294934527u, 4294934527u)); } }
// Token: 0x0600019A RID: 410 RVA: 0x00061B74 File Offset: 0x0005FD74 private void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { ModuleWriterBase moduleWriterBase = (ModuleWriterBase)sender; bool flag = e.WriterEvent == ModuleWriterEvent.MDBeginAddResources; if (flag) { this.ctx.Context.CheckCancellation(); this.ctx.Context.Logger.Debug("Encrypting resources..."); bool flag2 = this.ctx.Context.Packer != null; List <EmbeddedResource> list = this.ctx.Module.Resources.OfType <EmbeddedResource>().ToList <EmbeddedResource>(); bool flag3 = !flag2; if (flag3) { this.ctx.Module.Resources.RemoveWhere((Resource res) => res is EmbeddedResource); } string text = this.ctx.Name.RandomName(RenameMode.Letters); PublicKey publicKey = null; bool flag4 = moduleWriterBase.TheOptions.StrongNameKey != null; if (flag4) { publicKey = PublicKeyBase.CreatePublicKey(moduleWriterBase.TheOptions.StrongNameKey.PublicKey); } AssemblyDefUser assemblyDefUser = new AssemblyDefUser(text, new Version(0, 0), publicKey); assemblyDefUser.Modules.Add(new ModuleDefUser(text + ".dll")); ModuleDef manifestModule = assemblyDefUser.ManifestModule; assemblyDefUser.ManifestModule.Kind = ModuleKind.Dll; AssemblyRefUser asmRef = new AssemblyRefUser(manifestModule.Assembly); bool flag5 = !flag2; if (flag5) { foreach (EmbeddedResource embeddedResource in list) { embeddedResource.Attributes = ManifestResourceAttributes.Public; manifestModule.Resources.Add(embeddedResource); this.ctx.Module.Resources.Add(new AssemblyLinkedResource(embeddedResource.Name, asmRef, embeddedResource.Attributes)); } } byte[] array; using (MemoryStream memoryStream = new MemoryStream()) { manifestModule.Write(memoryStream, new ModuleWriterOptions { StrongNameKey = moduleWriterBase.TheOptions.StrongNameKey }); array = memoryStream.ToArray(); } array = this.ctx.Context.Registry.GetService <ICompressionService>().Compress(array, delegate(double progress) { this.ctx.Context.Logger.Progress((int)(progress * 10000.0), 10000); }); this.ctx.Context.Logger.EndProgress(); this.ctx.Context.CheckCancellation(); uint num = (uint)((array.Length + 3) / 4); num = (num + 15u & 4294967280u); uint[] array2 = new uint[num]; Buffer.BlockCopy(array, 0, array2, 0, array.Length); Debug.Assert(num % 16u == 0u); uint num2 = this.ctx.Random.NextUInt32() | 16u; uint[] array3 = new uint[16]; uint num3 = num2; for (int i = 0; i < 16; i++) { num3 ^= num3 >> 13; num3 ^= num3 << 25; num3 ^= num3 >> 27; array3[i] = num3; } byte[] array4 = new byte[array2.Length * 4]; int j; for (j = 0; j < array2.Length; j += 16) { uint[] src = this.ctx.ModeHandler.Encrypt(array2, j, array3); for (int k = 0; k < 16; k++) { array3[k] ^= array2[j + k]; } Buffer.BlockCopy(src, 0, array4, j * 4, 64); } Debug.Assert(j == array2.Length); uint num4 = (uint)array4.Length; TablesHeap tablesHeap = moduleWriterBase.MetaData.TablesHeap; tablesHeap.ClassLayoutTable[moduleWriterBase.MetaData.GetClassLayoutRid(this.ctx.DataType)].ClassSize = num4; RawFieldRow rawFieldRow = tablesHeap.FieldTable[moduleWriterBase.MetaData.GetRid(this.ctx.DataField)]; rawFieldRow.Flags |= 256; this.encryptedResource = moduleWriterBase.Constants.Add(new ByteArrayChunk(array4), 8u); MutationHelper.InjectKeys(this.ctx.InitMethod, new int[] { 0, 1 }, new int[] { (int)(num4 / 4u), (int)num2 }); } else { bool flag6 = e.WriterEvent == ModuleWriterEvent.EndCalculateRvasAndFileOffsets; if (flag6) { TablesHeap tablesHeap2 = moduleWriterBase.MetaData.TablesHeap; tablesHeap2.FieldRVATable[moduleWriterBase.MetaData.GetFieldRVARid(this.ctx.DataField)].RVA = (uint)this.encryptedResource.RVA; } } }
void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriterBase)sender; if (e.WriterEvent == ModuleWriterEvent.MDBeginAddResources) { ctx.Context.CheckCancellation(); ctx.Context.Logger.Debug("Encrypting resources..."); bool hasPacker = ctx.Context.Packer != null; List <EmbeddedResource> resources = ctx.Module.Resources.OfType <EmbeddedResource>().ToList(); if (!hasPacker) { ctx.Module.Resources.RemoveWhere(res => res is EmbeddedResource); } // move resources string asmName = ctx.Name.RandomName(RenameMode.Letters); PublicKey pubKey = null; if (writer.TheOptions.StrongNameKey != null) { pubKey = PublicKeyBase.CreatePublicKey(writer.TheOptions.StrongNameKey.PublicKey); } var assembly = new AssemblyDefUser(asmName, new Version(0, 0), pubKey); assembly.Modules.Add(new ModuleDefUser(asmName + ".dll")); ModuleDef module = assembly.ManifestModule; assembly.ManifestModule.Kind = ModuleKind.Dll; var asmRef = new AssemblyRefUser(module.Assembly); if (!hasPacker) { foreach (EmbeddedResource res in resources) { res.Attributes = ManifestResourceAttributes.Public; module.Resources.Add(res); ctx.Module.Resources.Add(new AssemblyLinkedResource(res.Name, asmRef, res.Attributes)); } } byte[] moduleBuff; using (var ms = new MemoryStream()) { module.Write(ms, new ModuleWriterOptions { StrongNameKey = writer.TheOptions.StrongNameKey }); moduleBuff = ms.ToArray(); } // compress moduleBuff = ctx.Context.Registry.GetService <ICompressionService>().Compress( moduleBuff, progress => ctx.Context.Logger.Progress((int)(progress * 10000), 10000)); ctx.Context.Logger.EndProgress(); ctx.Context.CheckCancellation(); uint compressedLen = (uint)(moduleBuff.Length + 3) / 4; compressedLen = (compressedLen + 0xfu) & ~0xfu; var compressedBuff = new uint[compressedLen]; Buffer.BlockCopy(moduleBuff, 0, compressedBuff, 0, moduleBuff.Length); Debug.Assert(compressedLen % 0x10 == 0); // encrypt uint keySeed = ctx.Random.NextUInt32() | 0x10; var key = new uint[0x10]; uint state = keySeed; for (int i = 0; i < 0x10; i++) { state ^= state >> 13; state ^= state << 25; state ^= state >> 27; key[i] = state; } var encryptedBuffer = new byte[compressedBuff.Length * 4]; int buffIndex = 0; while (buffIndex < compressedBuff.Length) { uint[] enc = ctx.ModeHandler.Encrypt(compressedBuff, buffIndex, key); for (int j = 0; j < 0x10; j++) { key[j] ^= compressedBuff[buffIndex + j]; } Buffer.BlockCopy(enc, 0, encryptedBuffer, buffIndex * 4, 0x40); buffIndex += 0x10; } Debug.Assert(buffIndex == compressedBuff.Length); var size = (uint)encryptedBuffer.Length; TablesHeap tblHeap = writer.MetaData.TablesHeap; tblHeap.ClassLayoutTable[writer.MetaData.GetClassLayoutRid(ctx.DataType)].ClassSize = size; tblHeap.FieldTable[writer.MetaData.GetRid(ctx.DataField)].Flags |= (ushort)FieldAttributes.HasFieldRVA; encryptedResource = writer.Constants.Add(new ByteArrayChunk(encryptedBuffer), 8); // inject key values MutationHelper.InjectKeys(ctx.InitMethod, new[] { 0, 1 }, new[] { (int)(size / 4), (int)(keySeed) }); } else if (e.WriterEvent == ModuleWriterEvent.EndCalculateRvasAndFileOffsets) { TablesHeap tblHeap = writer.MetaData.TablesHeap; tblHeap.FieldRVATable[writer.MetaData.GetFieldRVARid(ctx.DataField)].RVA = (uint)encryptedResource.RVA; } }
void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriterBase)sender; if (e.WriterEvent == ModuleWriterEvent.MDEndCreateTables) { // These hurts reflection /* * uint methodLen = (uint)writer.MetaData.TablesHeap.MethodTable.Rows + 1; * uint fieldLen = (uint)writer.MetaData.TablesHeap.FieldTable.Rows + 1; * * var root = writer.MetaData.TablesHeap.TypeDefTable.Add(new RawTypeDefRow( * 0, 0x7fff7fff, 0, 0x3FFFD, fieldLen, methodLen)); * writer.MetaData.TablesHeap.NestedClassTable.Add(new RawNestedClassRow(root, root)); * * var namespaces = writer.MetaData.TablesHeap.TypeDefTable * .Select(row => row.Namespace) * .Distinct() * .ToList(); * foreach (var ns in namespaces) * { * if (ns == 0) continue; * var type = writer.MetaData.TablesHeap.TypeDefTable.Add(new RawTypeDefRow( * 0, 0, ns, 0x3FFFD, fieldLen, methodLen)); * writer.MetaData.TablesHeap.NestedClassTable.Add(new RawNestedClassRow(root, type)); * } * * foreach (var row in writer.MetaData.TablesHeap.ParamTable) * row.Name = 0x7fff7fff; */ writer.MetaData.TablesHeap.ModuleTable.Add(new RawModuleRow(0, 0x7fff7fff, 0, 0, 0)); writer.MetaData.TablesHeap.AssemblyTable.Add(new RawAssemblyRow(0, 0, 0, 0, 0, 0, 0, 0x7fff7fff, 0)); int r = random.NextInt32(8, 16); for (int i = 0; i < r; i++) { writer.MetaData.TablesHeap.ENCLogTable.Add(new RawENCLogRow(random.NextUInt32(), random.NextUInt32())); } r = random.NextInt32(8, 16); for (int i = 0; i < r; i++) { writer.MetaData.TablesHeap.ENCMapTable.Add(new RawENCMapRow(random.NextUInt32())); } //Randomize(writer.MetaData.TablesHeap.NestedClassTable); Randomize(writer.MetaData.TablesHeap.ManifestResourceTable); //Randomize(writer.MetaData.TablesHeap.GenericParamConstraintTable); writer.TheOptions.MetaDataOptions.TablesHeapOptions.ExtraData = random.NextUInt32(); writer.TheOptions.MetaDataOptions.TablesHeapOptions.UseENC = false; writer.TheOptions.MetaDataOptions.MetaDataHeaderOptions.VersionString += "\0\0\0\0"; /* * We are going to create a new specific '#GUID' Heap to avoid UnConfuserEX to work. * <sarcasm>UnConfuserEX is so well coded, it relies on static cmp between values</sarcasm> * If you deobfuscate this tool, you can see that it check for #GUID size and compare it to * '16', so we have to create a new array of byte wich size is exactly 16 and put it into * our brand new Heap */ // writer.TheOptions.MetaDataOptions.OtherHeapsEnd.Add(new RawHeap("#GUID", Guid.NewGuid().ToByteArray())); // writer.TheOptions.MetaDataOptions.OtherHeapsEnd.Add(new RawHeap("#Strings", new byte[1])); writer.TheOptions.MetaDataOptions.OtherHeapsEnd.Add(new RawHeap("#Blob", new byte[1])); writer.TheOptions.MetaDataOptions.OtherHeapsEnd.Add(new RawHeap("#Schema", new byte[1])); } else if (e.WriterEvent == ModuleWriterEvent.MDOnAllTablesSorted) { writer.MetaData.TablesHeap.DeclSecurityTable.Add(new RawDeclSecurityRow( unchecked (0x7fff), 0xffff7fff, 0xffff7fff)); /* * writer.MetaData.TablesHeap.ManifestResourceTable.Add(new RawManifestResourceRow( * 0x7fff7fff, (uint)ManifestResourceAttributes.Private, 0x7fff7fff, 2)); */ } }
void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriterBase)sender; if (e.WriterEvent == ModuleWriterEvent.MDEndCreateTables) { // These hurts reflection /* * uint methodLen = (uint)writer.MetaData.TablesHeap.MethodTable.Rows + 1; * uint fieldLen = (uint)writer.MetaData.TablesHeap.FieldTable.Rows + 1; * * var root = writer.MetaData.TablesHeap.TypeDefTable.Add(new RawTypeDefRow( * 0, 0x7fff7fff, 0, 0x3FFFD, fieldLen, methodLen)); * writer.MetaData.TablesHeap.NestedClassTable.Add(new RawNestedClassRow(root, root)); * * var namespaces = writer.MetaData.TablesHeap.TypeDefTable * .Select(row => row.Namespace) * .Distinct() * .ToList(); * foreach (var ns in namespaces) * { * if (ns == 0) continue; * var type = writer.MetaData.TablesHeap.TypeDefTable.Add(new RawTypeDefRow( * 0, 0, ns, 0x3FFFD, fieldLen, methodLen)); * writer.MetaData.TablesHeap.NestedClassTable.Add(new RawNestedClassRow(root, type)); * } * * foreach (var row in writer.MetaData.TablesHeap.ParamTable) * row.Name = 0x7fff7fff; */ writer.MetaData.TablesHeap.ModuleTable.Add(new RawModuleRow(0, 0x7fff7fff, 0, 0, 0)); writer.MetaData.TablesHeap.AssemblyTable.Add(new RawAssemblyRow(0, 0, 0, 0, 0, 0, 0, 0x7fff7fff, 0)); int r = random.NextInt32(8, 16); for (int i = 0; i < r; i++) { writer.MetaData.TablesHeap.ENCLogTable.Add(new RawENCLogRow(random.NextUInt32(), random.NextUInt32())); } r = random.NextInt32(8, 16); for (int i = 0; i < r; i++) { writer.MetaData.TablesHeap.ENCMapTable.Add(new RawENCMapRow(random.NextUInt32())); } //Randomize(writer.MetaData.TablesHeap.NestedClassTable); Randomize(writer.MetaData.TablesHeap.ManifestResourceTable); //Randomize(writer.MetaData.TablesHeap.GenericParamConstraintTable); writer.TheOptions.MetaDataOptions.TablesHeapOptions.ExtraData = random.NextUInt32(); writer.TheOptions.MetaDataOptions.TablesHeapOptions.UseENC = false; writer.TheOptions.MetaDataOptions.MetaDataHeaderOptions.VersionString += "\0\0\0\0"; writer.TheOptions.MetaDataOptions.OtherHeapsEnd.Add(new RawHeap("#Strings", new byte[1])); writer.TheOptions.MetaDataOptions.OtherHeapsEnd.Add(new RawHeap("#Blob", new byte[1])); writer.TheOptions.MetaDataOptions.OtherHeapsEnd.Add(new RawHeap("#Schema", new byte[1])); } else if (e.WriterEvent == ModuleWriterEvent.MDOnAllTablesSorted) { writer.MetaData.TablesHeap.DeclSecurityTable.Add(new RawDeclSecurityRow( unchecked (0x7fff), 0xffff7fff, 0xffff7fff)); /* * writer.MetaData.TablesHeap.ManifestResourceTable.Add(new RawManifestResourceRow( * 0x7fff7fff, (uint)ManifestResourceAttributes.Private, 0x7fff7fff, 2)); */ } }