技术宅的结界

 找回密码
 立即注册→加入我们

QQ登录

只需一步,快速开始

搜索
热搜: 下载 VB C 实现 编写
查看: 3253|回复: 2
收起左侧

【C】驱动加载/卸载/通信代码(兼容WIN32/WIN64)

[复制链接]

46

主题

242

帖子

8315

积分

用户组: 管理员

UID
77
精华
15
威望
174 点
宅币
7463 个
贡献
187 次
宅之契约
0 份
在线时间
186 小时
注册时间
2014-2-22
发表于 2014-5-2 18:51:43 | 显示全部楼层 |阅读模式

欢迎访问技术宅的结界,请注册或者登录吧。

您需要 登录 才可以下载或查看,没有帐号?立即注册→加入我们

x
[C] 纯文本查看 复制代码
//整理者:Tesla.Angela(原代码来源于网络,原作者不明)
/*
使用方法:修改DRV_NAME和DRV_FILENAME
HANDLE openDriver(void):打开驱动建立的符号链接的句柄
void uninstallDriver(void):卸载驱动(只有把openDriver打开的句柄关闭才可以成功卸载)
*/
/*
使用示例:
VOID TEST()
{
    HANDLE hMyDrv;
    hMyDrv=openDriver();
    IoControl(hMyDrv, CTL_CODE_GEN(0x802), &fn_index, 4, &ssdt_func_addr, 8);
    uninstallDriver();
    CloseHandle(hMyDrv);
}
*/

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

#define DRV_NAME                "xxxxxxxx"//驱动链接名
#define DRV_FILENAME        "xxxxxxxx.sys"//驱动文件
#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)
{
    //下面这句可以随时注释掉
    //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)        //0为boot驱动
        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 = GetModuleHandleA("ntdll.dll");
    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);
    *(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()
{
    HMODULE hntdll = GetModuleHandleA("ntdll.dll");
    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);
    *(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 cleanupDriver(void)
{
    char sysDir[MAX_PATH + 1];
    GetSystemDirectoryA(sysDir, MAX_PATH);
    strncat(sysDir, "\\drivers\\"DRV_FILENAME, MAX_PATH);
    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=NULL;
    //CreateFile打开驱动建立的符号链接,得根据驱动中建立的名字更改
    hDevice = CreateFileA("\\\\.\\"DRV_NAME, 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);//MessageBoxA(0,drvFullPath,0,0);
        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_NAME, 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");
                    }
                }
            }
            cleanupDriver();
        }
    }
    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);
        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. ");
            }
        }
        cleanupDriver();
    }
}

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

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

评分

参与人数 3威望 +15 宅币 +30 贡献 +12 收起 理由
FFFFFFFE + 5 + 5 + 5 屌!
0xAA55 + 5 + 5 + 5 支持!
KxIX + 5 + 20 + 2 例行奖励

查看全部评分

本帖被以下淘专辑推荐:

回复

使用道具 举报

7

主题

21

帖子

113

积分

用户组: 小·技术宅

UID
245
精华
0
威望
2 点
宅币
86 个
贡献
2 次
宅之契约
0 份
在线时间
6 小时
注册时间
2014-5-3
发表于 2014-8-6 10:29:57 | 显示全部楼层
你是TA?
回复

使用道具 举报

1

主题

110

帖子

114

积分

用户组: 小·技术宅

UID
7535
精华
0
威望
0 点
宅币
4 个
贡献
0 次
宅之契约
0 份
在线时间
8 小时
注册时间
2021-10-16
发表于 2022-5-13 16:40:23 | 显示全部楼层

如此好贴,必须支持~~~

本版积分规则

QQ|申请友链||Archiver|手机版|小黑屋|技术宅的结界 ( 滇ICP备16008837号 )|网站地图

GMT+8, 2022-5-21 16:30 , Processed in 0.042212 second(s), 37 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表