Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

C++ - OSR Driver Loader와 같은 Legacy 커널 드라이버 설치 프로그램 제작

OSR Driver Loader는,

Loading the Windows Kernel Driver
; https://resources.infosecinstitute.com/loading-the-windows-kernel-driver/

GUI 환경을 제공해 편리하긴 해도 명령행으로 쓸 수 없다는 불편함이 있습니다. (혹시 명령행을 제공하나요? ^^)

사실 명령행이 크게 필요하지 않은 이유가 있긴 한데, 이미 sc.exe를 이용해서 그런 역할을 수행할 수 있기 때문입니다. 이에 대해서는 다음의 글에서 코드를 통한 방법과 함께 자세하게 설명하고 있습니다.

Loading the Windows Kernel Driver
; https://resources.infosecinstitute.com/loading-the-windows-kernel-driver/

예를 들어, 지난 글에 소개한 KernelMemoryIO 드라이버를 명령행으로 다음과 같이 등록할 수 있습니다.

c:\temp> sc create "KernelMemoryIO" binPath= "D:\wdk\KernelMemoryIO\x64\Debug\KernelMemoryIO.sys" type= kernel start= demand
[SC] CreateService SUCCESS

사실 이 작업도 그리 복잡한 시스템 변경을 수행하진 않습니다. 단순히 다음과 같이 "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services" 경로에 적절한 정보를 설정하는 것에 불과합니다.

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\KernelMemoryIO]
"Type"=dword:00000001
"Start"=dword:00000003
"ErrorControl"=dword:00000001
"ImagePath"=hex(2):5c,00,3f,00,3f,00,5c,00,44,00,3a,00,5c,00,77,00,64,00,6b,00,\
  5c,00,4b,00,65,00,72,00,6e,00,65,00,6c,00,4d,00,65,00,6d,00,6f,00,72,00,79,\
  00,49,00,4f,00,5c,00,78,00,36,00,34,00,5c,00,44,00,65,00,62,00,75,00,67,00,\
  5c,00,4b,00,65,00,72,00,6e,00,65,00,6c,00,4d,00,65,00,6d,00,6f,00,72,00,79,\
  00,49,00,4f,00,2e,00,73,00,79,00,73,00,00,00

등록된 드라이버를 제거하는 방법은 sc.exe로 해도 되지만,

c:\temp> sc delete "KernelMemoryIO"
[SC] DeleteService SUCCESS

마찬가지로 그냥 레지스트리 키(HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\KernelMemoryIO)를 삭제해도 무방합니다. 게다가 커널 드라이버를 시작 및 중지하는 방법은 일반적인 NT 서비스를 다루는 방법과 동일합니다.

[시작]
c:\temp> net start KernelMemoryIO

The KernelMemoryIO service was started successfully.

[중지]
c:\temp> net stop KernelMemoryIO

The KernelMemoryIO service was stopped successfully.

당연하지만, 위의 모든 작업은 "관리자 권한"을 요구합니다.




명령행이 아닌, 직접 코드를 작성하는 것도 그리 어렵지 않습니다. Service Control Manager를 다루는 Win32 API만 적절하게 호출하면 되는데 아래는 그렇게 해서 만든 간단한 프로그램입니다.

#include "stdafx.h"

int InstallDriver(wchar_t *pDriverFilePath, wchar_t *pDriverName);
int UninstallDriver(wchar_t *pDriverName);
int StartDeviceDriver(wchar_t *pDriverName);
int StopDeviceDriver(wchar_t *pDriverName);

// HKLM\SYSTEM\CurrentControlSet\Services\[DriverName]

// [install]
//  InstallDriver 1 "[경로]" "[DriverName]"
//  or
//  sc create "[DriverName]" binPath= "[경로]" type= kernel start= demand
//
// [uninstall]
//  InstallDriver 0 "[DriverName]"
//
// [start_service]
//  InstallDriver 2 "[DriverName]"
//  or
//  net start "[DriverName]"
//  or
//  sc start "[DriverName]"
//
// [stop_service]
//  InstallDriver 3 "[DriverName]"
//  or
//  net stop "[DriverName]"
//  or
//  sc stop "[DriverName]"

int _tmain(int argc, _TCHAR* argv[])
{
    wchar_t *mode = nullptr;
    wchar_t driverFullPath[MAX_PATH];
    wchar_t *driverName = nullptr;

    if (argc > 0)
    {
        mode = argv[1];
    }

    if (mode == nullptr)
    {
        return 1;
    }

    if (argc == 4)
    {
        wchar_t currentPath[MAX_PATH];
        ::GetCurrentDirectory(MAX_PATH, currentPath);

        ::PathCombine(driverFullPath, currentPath, argv[2]);

        driverName = argv[3];
    } 
    else if (argc == 3)
    {
        driverName = argv[2];
    }

    if (driverName == nullptr)
    {
        return 1;
    }

    if (wcscmp(mode, L"1") == 0)
    {
        return InstallDriver(driverFullPath, driverName) == 0;
    }
    else if (wcscmp(mode, L"0") == 0)
    {
        return UninstallDriver(driverName) == 0;
    }
    else if (wcscmp(mode, L"2") == 0)
    {
        return StartDeviceDriver(driverName) == 0;
    }
    else if (wcscmp(mode, L"3") == 0)
    {
        return StopDeviceDriver(driverName) == 0;
    }

    return 0;
}

int StartDeviceDriver(wchar_t *pDriverName)
{
    int result = 0;

    SC_HANDLE hSCManager = NULL;
    SC_HANDLE hService = NULL;

    do
    {
        hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
        if (hSCManager == NULL)
        {
            wprintf(L"[StartDeviceDriver] hSCManager == NULL");
            break;
        }

        hService = OpenService(hSCManager, pDriverName, SERVICE_START);
        if (hService == NULL)
        {
            wprintf(L"[StartDeviceDriver] hService == NULL");
            break;
        }

        if (::StartService(hService, 0, NULL) == TRUE)
        {
            result = 1;
        }
    } while (false);

    if (hService != NULL)
    {
        CloseServiceHandle(hService);
        hService = NULL;
    }

    if (hSCManager != NULL)
    {
        CloseServiceHandle(hSCManager);
        hSCManager = NULL;
    }

    return result;
}

int StopDeviceDriver(wchar_t *pDriverName)
{
    int result = 0;

    SC_HANDLE hSCManager = NULL;
    SC_HANDLE hService = NULL;
    DWORD dwResult;

    do
    {
        hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
        if (hSCManager == NULL)
        {
            wprintf(L"[StopDeviceDriver] hSCManager == NULL");
            break;
        }

        hService = OpenService(hSCManager, pDriverName, SERVICE_STOP | SERVICE_QUERY_STATUS);
        if (hService == NULL)
        {
            wprintf(L"[StopDeviceDriver] hService == NULL");
            break;
        }

        SERVICE_STATUS st;
        if (::ControlService(hService, SERVICE_CONTROL_STOP, &st) == TRUE)
        {
            result = 1;
        }
        else
        {
            dwResult = ::GetLastError();
            wprintf(L"[StopDeviceDriver - %s] ControlService == FALSE, LastError = %d", pDriverName, dwResult);
        }
    } while (false);

    if (hService != NULL)
    {
        CloseServiceHandle(hService);
        hService = NULL;
    }

    if (hSCManager != NULL)
    {
        CloseServiceHandle(hSCManager);
        hSCManager = NULL;
    }

    return result;
}

int InstallDriver(wchar_t *pDriverFilePath, wchar_t *pDriverName)
{
    int result = 0;

    SC_HANDLE hSCManager = NULL;
    SC_HANDLE hService = NULL;

    do
    {
        hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
        if (hSCManager == NULL)
        {
            wprintf(L"[InstallDriver] hSCManager == NULL");
            break;
        }
         
        /* HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\[DirverName] */
        hService = CreateService(hSCManager, pDriverName, pDriverName,        
                                    GENERIC_READ, 
                                    SERVICE_KERNEL_DRIVER,             /* service type */
                                    SERVICE_DEMAND_START,              /* start type */
                                    SERVICE_ERROR_NORMAL,              /* error control type */
                                    pDriverFilePath, /* service's binary */
                                    NULL,                              /* no load ordering group */
                                    NULL,                              /* no tag identifier*/
                                    NULL,                              /* no dependencies */
                                    NULL,                              /* LocalSystem account*/
                                    NULL                               /* no password */
                                    );      

        if (hService == NULL) 
        {
            DWORD dwResult = ::GetLastError();
            wprintf(L"[InstallDriver] hService == NULL, LastError = %d", dwResult);
            break;
        }

        result = 1;

    } while (false);

    if (hService != NULL)
    {
        CloseServiceHandle(hService);
        hService = NULL;
    }

    if (hSCManager != NULL)
    {
        CloseServiceHandle(hSCManager);
        hSCManager = NULL;
    }

    return result;
}

int UninstallDriver(wchar_t *pDriverName)
{
    int result = 0;

    SC_HANDLE hSCManager = NULL;
    SC_HANDLE hService = NULL;

    do
    {
        hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
        if (hSCManager == NULL)
        {
            wprintf(L"[UninstallDriver] hSCManager == NULL");
            break;
        }

        hService = OpenService(hSCManager, pDriverName, DELETE);
        if (hService == NULL)
        {
            wprintf(L"[UninstallDriver] hService == NULL");
            break;
        }

        if (::DeleteService(hService) == TRUE)
        {
            result = 1;
        }
    } while (false);

    if (hService != NULL)
    {
        CloseServiceHandle(hService);
        hService = NULL;
    }

    if (hSCManager != NULL)
    {
        CloseServiceHandle(hSCManager);
        hSCManager = NULL;
    }

    return result;
}

위의 소스 코드를 빌드한 결과물로 KernelMemoryIO 드라이버를 설치/제거/시작/중지하는 방법은 다음과 같습니다.

[설치]
c:\temp> InstallDriver64.exe 1 "D:\MyGit\wdk\KernelMemoryIO\x64\Debug\KernelMemoryIO.sys" KernelMemoryIO

[제거]
c:\temp> InstallDriver64.exe 0 KernelMemoryIO

[시작]
c:\temp> InstallDriver64.exe 2 KernelMemoryIO

[중지]
c:\temp> InstallDriver64.exe 3 KernelMemoryIO




이 글에서 소개한 소스 코드는 다음의 github에 등록해 두었습니다.

DotNetSamples/Cpp/InstallDriver/
; https://github.com/stjeong/DotNetSamples/tree/master/Cpp/InstallDriver




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 1/8/2020]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2020-02-03 03시51분
Kernel Driver Utility
; https://github.com/hfiref0x/KDU
정성태

1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13346정성태5/10/20233775오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/20235039.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/20236321.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/20234200디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/20234123.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/20233908닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/20233928오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/20234617닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/20234102닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/20234626Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/20234381.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/20234514.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/20234165Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/20233626Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/20233721Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/20233744오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233414Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
13329정성태4/24/20233622Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
13328정성태4/19/20233259VS.NET IDE: 184. Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트
13327정성태4/19/20233684VS.NET IDE: 183. C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법
13326정성태4/18/20235054.NET Framework: 2109. C# - 닷넷 응용 프로그램에서 SQLite 사용 (System.Data.SQLite) [1]파일 다운로드1
13325정성태4/18/20234402스크립트: 48. 파이썬 - PostgreSQL의 with 문을 사용한 경우 연결 개체 누수
13324정성태4/17/20234237.NET Framework: 2108. C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석파일 다운로드1
13323정성태4/16/20234134개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
13322정성태4/15/20234936VS.NET IDE: 182. Visual Studio - 32비트로만 빌드된 ActiveX와 작업해야 한다면?
13321정성태4/14/20233735개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...