一个驱动加载器代码

//原作者:不明(来源于网络)

/*
使用方法:
修改DRV_NAME和DRV_FILENAME定义
HANDLE openDriver(void):打开驱动建立的符号链接的句柄
void uninstallDriver(void):卸载驱动(只有把openDriver打开的句柄关闭才可以成功卸载)
*/

#pragma comment(lib,"user32.lib")
#pragma comment(lib,"Advapi32.lib")

#define DRV_NAME		"myDriver"//驱动名
#define DRV_FILENAME	"myDriver.sys"//驱动文件
#define DRV_SYMBOL_LINK  "\\\\.\\LenfSys"              // \??\LenfSys

#define STATUS_SUCCESS     ((NTSTATUS)0x00000000L)

typedef LONG NTSTATUS;

typedef struct _STRING
{
    USHORT  Length;
    USHORT  MaximumLength;
    PCHAR  Buffer;
} ANSI_STRING, *PANSI_STRING;

typedef struct _UNICODE_STRING
{
    USHORT  Length;
    USHORT  MaximumLength;
    PWSTR  Buffer;
} UNICODE_STRING, *PUNICODE_STRING;

VOID AfxMessageBox(char *sz)
{
	LoadLibraryA("user32.dll");
    MessageBoxA(0,sz,DRV_NAME,0);
}

//*********************************************************************************************
// Assign loaddriver priviledge to our process, so we can load our support driver.
//*********************************************************************************************

BOOL getLoadDriverPriv()
{
    HANDLE hToken;

    if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, &hToken))
    {
        LUID huid;
        if(LookupPrivilegeValueA(NULL, "SeLoadDriverPrivilege", &huid))
        {
            LUID_AND_ATTRIBUTES priv;
            priv.Attributes = SE_PRIVILEGE_ENABLED;
            priv.Luid = huid;

            TOKEN_PRIVILEGES tp;
            tp.PrivilegeCount = 1;
            tp.Privileges[0] = priv;

            if(AdjustTokenPrivileges(hToken, FALSE, &tp, 0, NULL, NULL))
            {
                return TRUE;
            }
         }
     }
    return FALSE;
}


//*********************************************************************************************
// Sets up the necessary registry settings to load the support driver
//*********************************************************************************************
BOOL setupRegistry()
{
    HKEY hkey;
    if(RegCreateKeyA(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\"DRV_NAME, &hkey) != ERROR_SUCCESS)
        return FALSE;

    DWORD val;
    val = 1;
    if(RegSetValueExA(hkey, "Type", 0, REG_DWORD, (PBYTE)&val, sizeof(val)) != ERROR_SUCCESS)
        return FALSE;

    if(RegSetValueExA(hkey, "ErrorControl", 0, REG_DWORD, (PBYTE)&val, sizeof(val)) != ERROR_SUCCESS)
        return FALSE;

    val = 3;
    if(RegSetValueExA(hkey, "Start", 0, REG_DWORD, (PBYTE)&val, sizeof(val)) != ERROR_SUCCESS)
        return FALSE;

    char *imgName = "System32\\DRIVERS\\"DRV_FILENAME;

    if(RegSetValueExA(hkey, "ImagePath", 0, REG_EXPAND_SZ, (PBYTE)imgName, strlen(imgName)) != ERROR_SUCCESS)
        return FALSE;

    return TRUE;
}


//*********************************************************************************************
// Actual code to load our driver into memory
//
//*********************************************************************************************

BOOL loadDriver()
{
    HMODULE hntdll;

    NTSTATUS (WINAPI *_RtlAnsiStringToUnicodeString)
		(PUNICODE_STRING  DestinationString,IN PANSI_STRING  SourceString,
		IN BOOLEAN b);

    VOID (WINAPI *_RtlInitAnsiString)
    (IN OUT PANSI_STRING  DestinationString,
     IN PCHAR  SourceString);

    NTSTATUS (WINAPI * _ZwLoadDriver)
    (IN PUNICODE_STRING DriverServiceName);

    NTSTATUS (WINAPI * _ZwUnloadDriver)
    (IN PUNICODE_STRING DriverServiceName);

    VOID (WINAPI * _RtlFreeUnicodeString)
    (IN PUNICODE_STRING  UnicodeString);


    hntdll = GetModuleHandleA("ntdll.dll");

    *(FARPROC *)&_ZwLoadDriver = GetProcAddress(hntdll, "NtLoadDriver");

    *(FARPROC *)&_ZwUnloadDriver = GetProcAddress(hntdll, "NtUnloadDriver");

    *(FARPROC *)&_RtlAnsiStringToUnicodeString =
        GetProcAddress(hntdll, "RtlAnsiStringToUnicodeString");

    *(FARPROC *)&_RtlInitAnsiString =
        GetProcAddress(hntdll, "RtlInitAnsiString");

    *(FARPROC *)&_RtlFreeUnicodeString =
        GetProcAddress(hntdll, "RtlFreeUnicodeString");

    if(_ZwLoadDriver && _ZwUnloadDriver && _RtlAnsiStringToUnicodeString &&
            _RtlInitAnsiString && _RtlFreeUnicodeString)
    {
        ANSI_STRING aStr;

        _RtlInitAnsiString(&aStr,
                           "\\Registry\\Machine\\System\\CurrentControlSet\\Services\\"DRV_NAME);

        UNICODE_STRING uStr;

        if(_RtlAnsiStringToUnicodeString(&uStr, &aStr, TRUE) != STATUS_SUCCESS)
            return FALSE;
        else
        {
            if(_ZwLoadDriver(&uStr) == STATUS_SUCCESS)
            {
                _RtlFreeUnicodeString(&uStr);
                return TRUE;
            }
            _RtlFreeUnicodeString(&uStr);
        }
    }

    return FALSE;
}


//*********************************************************************************************
// Actual code to remove our driver from memory
//
//*********************************************************************************************

BOOL unloadDriver()
{
// call ntdll APIs
    HMODULE hntdll;
    NTSTATUS (WINAPI * _RtlAnsiStringToUnicodeString)
    (PUNICODE_STRING  DestinationString,
     IN PANSI_STRING  SourceString,
     IN BOOLEAN);

    VOID (WINAPI *_RtlInitAnsiString)
    (IN OUT PANSI_STRING  DestinationString,
     IN PCHAR  SourceString);

    NTSTATUS (WINAPI * _ZwLoadDriver)
    (IN PUNICODE_STRING DriverServiceName);

    NTSTATUS (WINAPI * _ZwUnloadDriver)
    (IN PUNICODE_STRING DriverServiceName);

    VOID (WINAPI * _RtlFreeUnicodeString)
    (IN PUNICODE_STRING  UnicodeString);


    hntdll = GetModuleHandleA("ntdll.dll");

    *(FARPROC *)&_ZwLoadDriver = GetProcAddress(hntdll, "NtLoadDriver");

    *(FARPROC *)&_ZwUnloadDriver = GetProcAddress(hntdll, "NtUnloadDriver");

    *(FARPROC *)&_RtlAnsiStringToUnicodeString =
        GetProcAddress(hntdll, "RtlAnsiStringToUnicodeString");

    *(FARPROC *)&_RtlInitAnsiString =
        GetProcAddress(hntdll, "RtlInitAnsiString");

    *(FARPROC *)&_RtlFreeUnicodeString =
        GetProcAddress(hntdll, "RtlFreeUnicodeString");

    if(_ZwLoadDriver && _ZwUnloadDriver && _RtlAnsiStringToUnicodeString &&
            _RtlInitAnsiString && _RtlFreeUnicodeString)
    {
        ANSI_STRING aStr;

        _RtlInitAnsiString(&aStr,
                           "\\Registry\\Machine\\System\\CurrentControlSet\\Services\\"DRV_NAME);

        UNICODE_STRING uStr;

        if(_RtlAnsiStringToUnicodeString(&uStr, &aStr, TRUE) != STATUS_SUCCESS)
            return FALSE;
        else
        {
            if(_ZwUnloadDriver(&uStr) == STATUS_SUCCESS)
            {
                _RtlFreeUnicodeString(&uStr);
                return TRUE;
            }
            _RtlFreeUnicodeString(&uStr);
        }
    }

    return FALSE;
}


//*********************************************************************************************
// Removes our driver file and registry settings
//
//*********************************************************************************************
void cleanupReg(void)
{
    char sysDir[MAX_PATH + 1];
    GetSystemDirectoryA(sysDir, MAX_PATH); //C:\Windows\system32
    strncat(sysDir, "\\drivers\\"DRV_FILENAME, MAX_PATH); //C:\Windows\system32\驱动文件名
    DeleteFileA(sysDir);//删除该文件
	//删除键值
    RegDeleteKeyA(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\"DRV_NAME"\\Enum");
    RegDeleteKeyA(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\"DRV_NAME);
}


//*********************************************************************************************
// Attempts to get a handle to our kernel driver.  If fails, try to install the driver.
//
//*********************************************************************************************
HANDLE openDriver(void)
{
    HANDLE hDevice;
	//CreateFile打开驱动建立的符号链接, 符号连接可以设为,例如:"\\\\.\\"DRV_NAME
    hDevice = CreateFileA(DRV_SYMBOL_LINK, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
                          NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if(hDevice == INVALID_HANDLE_VALUE)
    {
        char drvFullPath[MAX_PATH+1];
        char *filePart;

        ZeroMemory(drvFullPath, MAX_PATH);
        GetFullPathNameA(DRV_FILENAME, MAX_PATH, drvFullPath, &filePart);
		//打开驱动文件句柄
        HANDLE hFile = CreateFileA(drvFullPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
                                   FILE_ATTRIBUTE_NORMAL, 0);
        if(hFile == INVALID_HANDLE_VALUE)
        {
            AfxMessageBox("Cannot find required driver file");
            return INVALID_HANDLE_VALUE;
        }
        else
        {
            CloseHandle(hFile);

            char sysDir[MAX_PATH + 1];
            GetSystemDirectoryA(sysDir, MAX_PATH);
            strncat(sysDir, "\\drivers\\"DRV_FILENAME, MAX_PATH);
            CopyFileA(drvFullPath, sysDir, TRUE);

            if(!getLoadDriverPriv())//获取加载驱动权限
            {
                AfxMessageBox("Error getting load driver privilege! ");
            }
            else
            {
                if(!setupRegistry()) //写入注册表
                {
                    AfxMessageBox("Error setting driver registry keys! Make sure you are running this as Administrator. ");
                }
                else
                {
                    loadDriver(); //加载驱动
					//打开符号链接 
                    hDevice = CreateFileA(DRV_SYMBOL_LINK, GENERIC_WRITE | GENERIC_READ,FILE_SHARE_READ | FILE_SHARE_WRITE,
                                          NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
                    if(hDevice == INVALID_HANDLE_VALUE)
                    {
                        AfxMessageBox("Error loading kernel support driver! Make sure you are running this as Administrator. ");
                    }
                    else
                    {
                        AfxMessageBox("loading kernel support driver success");
                    }
                }
            }
            cleanupReg();//清除该驱动在注册表里的相关键值
        }
    }

    return hDevice;
}


//*********************************************************************************************
// Remove our kernel driver from memory
//
//*********************************************************************************************

void uninstallDriver(void)
{
    char drvFullPath[MAX_PATH+1];
    char *filePart;

    ZeroMemory(drvFullPath, MAX_PATH);
    GetFullPathNameA(DRV_FILENAME, MAX_PATH, drvFullPath, &filePart);
	//打开驱动文件句柄
    HANDLE hFile = CreateFileA(drvFullPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
                               FILE_ATTRIBUTE_NORMAL, 0);
    if(hFile == INVALID_HANDLE_VALUE)
    {
        AfxMessageBox("Cannot find required driver file ");
        return;
    }
    else
    {
        CloseHandle(hFile);

        char sysDir[MAX_PATH + 1];
        GetSystemDirectoryA(sysDir, MAX_PATH);
        strncat(sysDir, "\\drivers\\"DRV_FILENAME, MAX_PATH);//复制驱动文件到C:\Windows\System32\drivers下
        CopyFileA(drvFullPath, sysDir, TRUE);

        if(!getLoadDriverPriv()) //获取加载权限
        {
            AfxMessageBox("Error getting load driver privilege! ");
        }
        else
        {
            if(!setupRegistry())//建立注册表项
            {
                AfxMessageBox("Error setting driver registry keys! Make sure you are running this as Administrator. ");
            }
            else
            {
                if(unloadDriver())//卸载驱动
                    AfxMessageBox("Support driver successfully unloaded. ");
                else
                    AfxMessageBox("Unload support driver failed.  It is probably not loaded. ");
            }
        }
        cleanupReg(); //清理注册表项
    }
}

DWORD CTL_CODE_GEN(DWORD dwFunction)
{
    return (FILE_DEVICE_UNKNOWN * 65536) | (FILE_ANY_ACCESS * 16384) | (dwFunction * 4) | METHOD_BUFFERED;
}

BOOL IoControl(HANDLE hDrvHandle, DWORD dwIoControlCode, PVOID lpInBuffer, DWORD nInBufferSize, 
	PVOID lpOutBuffer, DWORD nOutBufferSize)
{
    DWORD dwRetSize;
    return DeviceIoControl(hDrvHandle, dwIoControlCode, lpInBuffer, nInBufferSize,
		lpOutBuffer, nOutBufferSize, &dwRetSize, 0);
}

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>软件名称:驱动加载工具(InstDrv - 中文版)软件版本:V1.0版软件类型:个人免费版(无插件)运行环境:Windows操作系统开发作者:Coderui更新日期:2008年04月08日联系邮箱:coderui@163.com作者博客:http://hi.baidu.com/coderui>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>-------------------------------------------------介绍:  该软件和网上大家常用的“InstDrv”程序功能几乎一样,只是新加入了详细的中文提示信息和拖拽打开文件等,这样可以方便用户的使用。“InstDrv”是一个比较好用的驱动安装、卸载工具。可以帮助您方便的把驱动程序安装上或卸载掉。本程序更多应用于动态调式驱动前的加载操作中。功能:1:执行加载、启动、停止、卸载驱动操作。2:支持文件拖拽打开。3:支持程序窗口总在最前显示。4:操作后有详细的中文提示信息。说明:压缩包中的“MySYS.sys”文件为测试驱动程序,支持加载、启动、停止、卸载驱动等功能,可以使用“Dbgview”工具查看驱动输出的提示信息。-------------------------------------------------详细的中文提示信息如下:状态:支持拖拽获取文件路径.状态:只能一次拖拽一个文件!状态:拖拽获取文件路径成功!状态:请输入驱动文件的路径名!状态:创建句柄失败!状态:因为不是一个有效文件,所以驱动服务安装失败!状态:因为驱动服务已经存在,所以驱动服务安装失败!状态:因为驱动服务已经启动,所以驱动服务安装失败!状态:驱动服务安装失败!状态:驱动服务安装成功!状态:打开驱动服务失败,可能该驱动服务不存在!状态:驱动服务启动成功!状态:因为驱动服务已经启动,所以驱动服务启动失败!状态:因为不是一个有效驱动,所以驱动服务启动失败!状态:因为驱动服务未被停止,所以驱动服务启动失败!状态:驱动服务启动失败!状态:驱动服务停止成功!状态:因为驱动服务没有启动,所以驱动服务停止失败!状态:驱动服务停止失败!状态:驱动服务卸栽成功!状态:因为驱动服务已经启动,所以驱动服务卸栽失败!状态:驱动服务卸栽失败!-------------------------------------------------下载说明:如果当前网页连接地址下载不了该软件,您可以发送邮件到coderui@163.com中,向程序作者所要该软件,谢谢您的支持!-------------------------------------------------解压后EXE程序全文MD5校验值为:591d784d24f5aead3a383535a4100733专用MD5校验程序下载地址为:http://hi.baidu.com/coderui/blog/item/e3a1282354c128519822ed24.html>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值