【发布时间】:2012-05-10 10:07:32
【问题描述】:
我正在使用 C# 开发应用程序 SFX / Protector,我希望从字节数组执行受保护的程序集,而不是将其写入硬盘,以便更难进行逆向工程。
我在字节数组中有一个程序(它有一个有效的入口点),我想执行它。 我在这个网站上发现了一个类似的问题,关于我该怎么做,我知道这可以使用下面的代码 sn-p 来完成,但是有人可以指导我如何使用这个从字节数组运行程序吗?
从技术上讲,他下面的代码让我这样做:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace DynamicX86
{
class Program
{
const uint PAGE_EXECUTE_READWRITE = 0x40;
const uint MEM_COMMIT = 0x1000;
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
private delegate int IntReturner();
static void Main(string[] args)
{
List<byte> bodyBuilder = new List<byte>();
bodyBuilder.Add(0xb8);
bodyBuilder.AddRange(BitConverter.GetBytes(42));
bodyBuilder.Add(0xc3);
byte[] body = bodyBuilder.ToArray();
IntPtr buf = VirtualAlloc(IntPtr.Zero, (uint)body.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
Marshal.Copy(body, 0, buf, body.Length);
IntReturner ptr = (IntReturner)Marshal.GetDelegateForFunctionPointer(buf, typeof(IntReturner));
Console.WriteLine(ptr());
}
}
}
如何实现此答案以从字节数组运行程序。我无法完全理解我可以用这段代码做什么。请帮忙
这是我找到此答案的链接: Is it possible to execute an x86 assembly sequence from within C#?
任何帮助将不胜感激。
【问题讨论】:
-
这段代码显然对运行真正的程序毫无用处。您需要了解 PE32 文件格式并实现您自己的加载程序,该加载程序与 Windows 加载程序执行相同的工作。如果代码有任何依赖关系,这非常很难做到。如果它实际上是一个托管程序集,那么只需使用 Assembly.Load(byte[])。
标签: c# runtime .net virtualalloc