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)
13397정성태7/23/20233639닷넷: 2134. C# - 문자열 연결 시 string.Create를 이용한 GC 할당 최소화
13396정성태7/22/20233336스크립트: 54. 파이썬 pystack 소개 - 메모리 덤프로부터 콜 스택 열거
13395정성태7/20/20233307개발 환경 구성: 685. 로컬에서 개발 중인 ASP.NET Core/5+ 웹 사이트에 대해 localhost 이외의 호스트 이름으로 접근하는 방법
13394정성태7/16/20233252오류 유형: 873. Oracle.ManagedDataAccess.Client - 쿼리 수행 시 System.InvalidOperationException
13393정성태7/16/20233417닷넷: 2133. C# - Oracle 데이터베이스의 Sleep 쿼리 실행하는 방법
13392정성태7/16/20233284오류 유형: 872. Oracle - ORA-01031: insufficient privileges
13391정성태7/14/20233367닷넷: 2132. C# - sealed 클래스의 메서드를 callback 호출했을 때 인라인 처리가 될까요?
13390정성태7/12/20233338스크립트: 53. 파이썬 - localhost 호출 시의 hang 현상
13389정성태7/5/20233322개발 환경 구성: 684. IIS Express로 호스팅하는 웹을 WSL 환경에서 접근하는 방법
13388정성태7/3/20233507오류 유형: 871. 윈도우 탐색기에서 열리지 않는 zip 파일 - The Compressed (zipped) Folder '[...].zip' is invalid. [1]파일 다운로드1
13387정성태6/28/20233531오류 유형: 870. _mysql - Commands out of sync; you can't run this command now
13386정성태6/27/20233601Linux: 61. docker - 원격 제어를 위한 TCP 바인딩 추가
13385정성태6/27/20233807Linux: 60. Linux - 외부에서의 접속을 허용하기 위한 TCP 포트 여는 방법
13384정성태6/26/20233563.NET Framework: 2131. C# - Source Generator로 해결하는 enum 박싱 문제파일 다운로드1
13383정성태6/26/20233312개발 환경 구성: 683. GPU 런타임을 사용하는 Colab 노트북 설정
13382정성태6/25/20233355.NET Framework: 2130. C# - Win32 API를 이용한 윈도우 계정 정보 (예: 마지막 로그온 시간)파일 다운로드1
13381정성태6/25/20233739오류 유형: 869. Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
13380정성태6/24/20233195스크립트: 52. 파이썬 3.x에서의 동적 함수 추가
13379정성태6/23/20233206스크립트: 51. 파이썬 2.x에서의 동적 함수 추가
13378정성태6/22/20233093오류 유형: 868. docker - build 시 "CANCELED ..." 뜨는 문제
13377정성태6/22/20236871오류 유형: 867. 파이썬 mysqlclient 2.2.x 설치 시 "Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually" 오류
13376정성태6/21/20233282.NET Framework: 2129. C# - Polly를 이용한 클라이언트 측의 요청 재시도파일 다운로드1
13375정성태6/20/20232977스크립트: 50. Transformers (신경망 언어모델 라이브러리) 강좌 - 2장 코드 실행 결과
13374정성태6/20/20233107오류 유형: 866. 파이썬 - <class 'AttributeError'> module 'flask.json' has no attribute 'JSONEncoder'
13373정성태6/19/20234397오류 유형: 865. 파이썬 - pymssql 설치 관련 오류 정리
13372정성태6/15/20233104개발 환경 구성: 682. SQL Server TLS 통신을 위해 사용되는 키 길이 확인 방법
1  2  3  4  5  6  7  8  [9]  10  11  12  13  14  15  ...