C# 远过程外部调用 LoadLibrary、GetModuleHandle、GetProcAddress、FreeLibrary

本类可以很方便的实现“远过程外部调用”获取、卸载、导入外部对象的动态链接库

且包括特俗的获取模块函数,调用“LoadLibrary / 导入动态链接库”到外部对象,可

能会被安全软件认定为注入行为,需要注明的是本类代码在x86下编写,且在代码

中大量使用了x86 asm / auto,所以尽量以x86平台编译且需要操作的是x86 / 32bit

外部对象 当然本类只作参考与学习 在本类中代码最繁琐的部分在于

GetProcAddress && LoadLibrary两个部分

    public static class Program
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, int dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);

        [STAThread]
        private static void Main()
        {
            Process ppNotepad = Process.Start("notepad");
            IntPtr hRemoteProcess = ppNotepad.Handle;
            IntPtr hRemoteHandle = MP.GetModuleHandle(hRemoteProcess, "user32");
            IntPtr pfnRemoteMethod = MP.GetProcAddress(hRemoteProcess, hRemoteHandle, "MessageBoxW");
           
            IntPtr hRemoteThread = CreateRemoteThread(hRemoteProcess, IntPtr.Zero, 0, pfnRemoteMethod, IntPtr.Zero, 0, IntPtr.Zero);
        }
    }

上面是一串代码,它的作用很简单 运行“记事本”且获得对象的句柄在外

部对象中获取User32.dll的模块句柄 其后获取MessageBoxW的函数地

址,在调用CreateRemoteThread调用W信息框、然后可以看到效果了

using System;
using System.Runtime.InteropServices;
using System.Text;

public partial class MP
{
    private abstract class NativeMethod
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, int nSize, ref int lpNumberOfBytesWritten);

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, int dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);

        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, int dwSize, int flAllocationType, int flProtect);

        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        public static extern bool VirtualFreeEx(I
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值