c# - 使用 VirtualAlloc 从字节数组运行程序?

标签 c# runtime .net virtualalloc

我正在使用 C# 开发应用程序 SFX/Protector,我希望 protected 程序集从字节数组执行,而不是将其写入硬盘,以便逆向工程更加困难。

我在一个字节数组中有一个程序(它有一个有效的入口点),我想执行它。 我在这个网站上发现了一个类似的问题,关于我该怎么做,我知道这可以使用下面的代码片段来完成,但是有人可以指导我如何使用它从字节数组运行程序吗?

技术上他下面的代码让我这样做:

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#?

任何帮助将不胜感激。

最佳答案

什么是有效的入口点,它的签名是什么?你如何从中获取这些字节?你生成 IL 吗?如果你这样做,也许简单地做 this 可能会更容易.

上面的代码试图做的是分配非托管内存,用 x86 指令填充它,然后让 .NET 从这个“函数指针”创建一个委托(delegate)并执行它——这与你想要的不同。

关于c# - 使用 VirtualAlloc 从字节数组运行程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10388244/

相关文章:

c# - 检查测试结束时是否还有任何线程残留

c# - 当 DropDownList Filter 的值不是 ALL 时,如何删除 GridView 中的整个第一列?

c++ - 添加无符号偏移量

c# - MySQL 查询中的输入字符串格式不正确

c# - 是否可以模拟 .NET HttpWebResponse?

c# - 改进语音识别,C#

c# - Entity Framework 中的 POCO 支持

java - Ideone Java 程序运行时错误

unity3d - 如何在运行时存储或读取动画剪辑数据?

c# - ICorProfiler : Why do I get the wrong type token for a jitted function?