summaryrefslogtreecommitdiff
path: root/general/registry/regfltr/exe/util.c
blob: 34d24c38b7a0c5579e99c91f1d3795b3737a3f4f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
/*++
Copyright (c) Microsoft Corporation.  All rights reserved.

    THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
    KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
    PURPOSE.

Module Name:

    util.c

Abstract: 

    Utility routines to dynamically load and unload a Windows NT kernel-mode
    driver using the Service Control Manager APIs.

Environment:

    User mode only

--*/



#include "regctrl.h"


BOOL 
UtilCreateService(
    _In_ SC_HANDLE hSCM, 
    _In_ LPTSTR szDriverName, 
    _In_ LPTSTR szDriverPath
);

BOOL 
UtilStartService(
    _In_ SC_HANDLE hSCM, 
    _In_ LPTSTR szDriverName
);

BOOL 
UtilStopService(
    _In_ SC_HANDLE hSCM, 
    _In_ LPTSTR szDriverName
);

BOOL 
UtilDeleteService(
    _In_ SC_HANDLE hSCM, 
    _In_ LPTSTR szDriverName
);

BOOL 
UtilOpenDevice(
    _In_ LPTSTR szWin32DeviceName, 
    _Out_ HANDLE * phDevice);

BOOL 
UtilGetServiceState(
    _In_ SC_HANDLE hService, 
    _Out_ DWORD * State);

BOOL 
UtilWaitForServiceState(
    _In_ SC_HANDLE hService, 
    _In_ DWORD State);


BOOL 
UtilLoadDriver(
    _In_ LPTSTR szDriverName,
    _In_ LPTSTR szDriverFileName,
    _In_ LPTSTR szWin32DeviceName,
    _Out_ HANDLE *pDriver
    )
/*++

Routine Description:

    This routine uses the Service Control Manager APIs to create an entry 
    for a standalone driver. It then opens a handle to the driver. 
    The driver is assumed to be in the current directory.

    NOTE: This routine creates an entry for a standalone driver. If this
    is modified for use with a driver that requires a Tag, Group, and/or 
    Dependencies, it may be necessary to query the registry for existing 
    driver information (in order to determine a unique Tag, etc.).
    
Arguments:

    szDriverName - name of the driver (no extension)

    szDriverFileName - name of driver (with extension)

    szWin32DeviceName - Name of driver (no extension) prefixed with \\.\

    pDriver - pointer to a variable that receives the handle to the driver

Return Value:

    TRUE if driver is loaded successfully.

--*/
{
    BOOL ReturnValue = FALSE;
    TCHAR* pPathSeparator;
    TCHAR szDriverPath[MAX_PATH] = _T("");
    DWORD dwSize;
    SC_HANDLE hSCM = NULL;
    HANDLE hDriver = NULL;

    *pDriver = NULL;

    //
    // Construct driver path.
    //

    dwSize = GetModuleFileName(NULL, szDriverPath, ARRAY_LENGTH(szDriverPath));
    
    if (dwSize == 0) {
        ErrorPrint("GetModuleFileName failed, last error 0x%u", GetLastError());
        goto Exit;
    }

    pPathSeparator = _tcsrchr(szDriverPath, _T('\\'));

    if (pPathSeparator != NULL) {
        pPathSeparator[1] = _T('\0');
        _tcscat_s(szDriverPath, MAX_PATH, szDriverFileName);
    } else {
        ErrorPrint("_tcsrchr failed to file \\ in driver path.");
        goto Exit;
    }

    //
    // Get a handle to SCM
    //

    hSCM = OpenSCManager ( NULL, NULL, SC_MANAGER_ALL_ACCESS );

    if (hSCM == NULL) {
        ErrorPrint("OpenSCManager failed, last error 0x%x", GetLastError());
        goto Exit;
    }

    //
    // First, uninstall and unload the driver. 
    //

    ReturnValue = UtilUnloadDriver( INVALID_HANDLE_VALUE, hSCM, szDriverName);

    if (ReturnValue != TRUE) {
        ErrorPrint("UnloadDriver failed");
        goto Exit;
    }

    //
    // Install the driver.
    //

    ReturnValue = UtilCreateService(hSCM, szDriverName, szDriverPath);

    if (ReturnValue == FALSE) {
        ErrorPrint("UtilCreateService failed");
        goto Exit;
    }

    //
    // Load the driver.
    //

    ReturnValue = UtilStartService(hSCM, szDriverName);

    if (ReturnValue == FALSE) {
        ErrorPrint("UtilStartService failed");
        goto Exit;
    }

    //
    // Open a handle to the device.
    //

    ReturnValue = UtilOpenDevice(szWin32DeviceName, &hDriver);

    if (ReturnValue == FALSE) {
        ErrorPrint("UtilOpenDevice failed");
        goto Exit;
    }

    *pDriver = hDriver;
    ReturnValue = TRUE;

Exit:

    if (hSCM != NULL) {
        CloseServiceHandle(hSCM);
    }
    
    return ReturnValue;
}


BOOL 
UtilUnloadDriver(
    _In_ HANDLE hDriver,
    _In_opt_ SC_HANDLE hPassedSCM,
    _In_ LPTSTR szDriverName
    )
/*++

Routine Description:

    Unloads the driver using SCManager.

Arguments:

    hDriver - handle to the driver

    hPassedSCM - handle to the SCManager (optional)

    szDriverName - name of driver (no extension)
    
Return Value:

    TRUE if driver is successfully unloaded

--*/
{

    BOOL ReturnValue = FALSE;
    SC_HANDLE hSCM = hPassedSCM;

    //
    // Get a handle to SCM if not passed in
    //

    if (hSCM == NULL) {

        hSCM = OpenSCManager ( NULL, NULL, SC_MANAGER_ALL_ACCESS );

        if (hSCM == NULL) {
            ErrorPrint("OpenSCManager failed, last error 0x%x", GetLastError());
            goto Exit;
        }
    }


    //
    // Close our handle to the device.
    //

    if ((hDriver != NULL) && (hDriver != INVALID_HANDLE_VALUE)) {
        CloseHandle (hDriver);
        hDriver = INVALID_HANDLE_VALUE;
    }

    //
    // Unload the driver.
    //

    ReturnValue = UtilStopService(hSCM, szDriverName);

    if (ReturnValue == FALSE) {
        ErrorPrint("UtilStopService failed");
        goto Exit;
    }

    //
    // Delete the service.
    //

    ReturnValue = UtilDeleteService(hSCM, szDriverName);

    if (ReturnValue == FALSE) {
        ErrorPrint("UtilDeleteService failed");
        goto Exit;
    }

    ReturnValue = TRUE;

Exit:

    if ((hPassedSCM == NULL) && (hSCM != NULL)) {
        CloseServiceHandle(hSCM);
    }
    
    return ReturnValue;
}



BOOL 
UtilGetServiceState (
    _In_ SC_HANDLE hService,
    _Out_ DWORD* State
    )
/*++

Routine Description:

    Gets the state of the service using QueryServiceStatusEx

Arguments:

    hService - handle to the service to query

    State - pointer to a variable that receives the state

Return Value:

    TRUE if service is queried successfully.

--*/
{
    SERVICE_STATUS_PROCESS ServiceStatus;
    DWORD BytesNeeded;
    BOOL Result;
    
    *State = 0;

    Result = QueryServiceStatusEx ( hService,
                                         SC_STATUS_PROCESS_INFO,
                                         (LPBYTE)&ServiceStatus,
                                         sizeof(ServiceStatus),
                                         &BytesNeeded);

    if (Result == FALSE) {
        ErrorPrint("QueryServiceStatusEx failed, last error 0x%x", GetLastError());
        return FALSE;
    }

    *State = ServiceStatus.dwCurrentState;

    return TRUE;
}


BOOL 
UtilWaitForServiceState (
    _In_ SC_HANDLE hService,
    _In_ DWORD State
    )
/*++

Routine Description:

    This routine waits for the service to reach a certain state

Arguments:

    hService - handle to the service

    State - the desired state

Return Value:

    TRUE if service reaches the desired state or FALSE if querying the
    service returns an error.

--*/
{

    DWORD ServiceState;
    BOOL Result; 
    
    for (;;) {

        Result = UtilGetServiceState (hService, &ServiceState);

        if (Result == FALSE) {
            return FALSE;
        }

        if (ServiceState == State) {
            break;
        }

        Sleep (1000);
    }

    return TRUE;
}

//
// UtilCreateService
//

BOOL 
UtilCreateService(
    _In_ SC_HANDLE hSCM,
    _In_ LPTSTR szDriverName,
    _In_ LPTSTR szDriverPath
    )
/*++

Routine Description:

    Uses SCManager to create a service

Arguments:

    hSCM - handle to the SCManager

    szDriverName - name of driver (no extension) which will serve as the 
        created service's name

    szDriverPath - path to driver

Return Value:

    TRUE if service is created successfully, FALSE otherwise.

--*/
{
    BOOL ReturnValue = FALSE;

    //
    // Create the service
    //

    SC_HANDLE hService = CreateService (
        hSCM,                 // handle to SC manager
        szDriverName,         // name of service
        szDriverName,         // display name
        SERVICE_ALL_ACCESS,     // access mask
        SERVICE_KERNEL_DRIVER,  // service type
        SERVICE_DEMAND_START,   // start type
        SERVICE_ERROR_NORMAL,   // error control
        szDriverPath,           // full path to driver
        NULL,                   // load ordering
        NULL,                   // tag id
        NULL,                   // dependency
        NULL,                   // account name
        NULL                    // password
    );

    if ((hService == NULL) && (GetLastError() != ERROR_SERVICE_EXISTS)) {
        ErrorPrint("CreateService failed, last error 0x%x", GetLastError());
        goto Exit;
    }

    ReturnValue = TRUE;

Exit:

    if (hService) {
        CloseServiceHandle(hService);
    }

    return ReturnValue;
}


BOOL 
UtilStartService(
    _In_ SC_HANDLE hSCM,
    _In_ LPTSTR szDriverName
    )
/*++

Routine Description:

    Starts a service

Arguments:

    hSCM - handle to the SCManager

    szDriverName - name of driver (without extension), services as name of
        the service to start

Return Value:

    TRUE if service is successfully started, FALSE otherwise.

--*/
{
    BOOL ReturnValue = FALSE;

    //
    // Open the service. The function assumes that
    // UtilCreateService has been called before this one
    // and the service is already installed.
    //

    SC_HANDLE hService = OpenService ( hSCM, szDriverName, SERVICE_ALL_ACCESS );

    if (hService == NULL) {
        ErrorPrint("OpenService failed, last error 0x%x", GetLastError());
        goto Exit;
    }

    //
    // Start the service
    //

    if (! StartService (hService, 0, NULL)) {

        if (GetLastError() != ERROR_SERVICE_ALREADY_RUNNING) {
            ErrorPrint("StartService failed, last error 0x%x", GetLastError());
            goto Exit;
        }
    }

    if (FALSE == UtilWaitForServiceState (hService, SERVICE_RUNNING)) {
        goto Exit;
    }
    
    ReturnValue = TRUE;

Exit:

    if (hService) {
        CloseServiceHandle(hService);
    }

    return ReturnValue;
}


BOOL 
UtilStopService(
    _In_ SC_HANDLE hSCM,
    _In_ LPTSTR szDriverName
    )
/*++

Routine Description:

    Stops a service

Arguments:

    hSCM - handle to the SCManager

    szDriverName - name of driver (without extension), services as name of
        the service

Return Value:

    TRUE if service is successfully stopped, FALSE otherwise.

--*/
{
    BOOL ReturnValue = FALSE;
    SERVICE_STATUS ServiceStatus;
    
    //
    // Open the service so we can stop it
    //

    SC_HANDLE hService = OpenService ( hSCM, szDriverName, SERVICE_ALL_ACCESS );

    if (hService == NULL) {
        if (GetLastError() == ERROR_SERVICE_DOES_NOT_EXIST) {
            ReturnValue = TRUE;
        } else {
            ErrorPrint("OpenService failed, last error 0x%x", GetLastError());
        }
        goto Exit;
    }

    //
    // Stop the service
    //

    if (FALSE == ControlService (hService, SERVICE_CONTROL_STOP, &ServiceStatus)) {
        if (GetLastError() != ERROR_SERVICE_NOT_ACTIVE) {
            ErrorPrint("ControlService failed, last error 0x%x", GetLastError());
            goto Exit;
        }
    }

    if (FALSE == UtilWaitForServiceState (hService, SERVICE_STOPPED)) {
        goto Exit;
    }
    
    ReturnValue = TRUE;

Exit:

    if (hService) {
        CloseServiceHandle (hService);
    }

    return ReturnValue;
}


BOOL 
UtilDeleteService(
    _In_ SC_HANDLE hSCM,
    _In_ LPTSTR szDriverName
    )
/*++

Routine Description:

    Deletes a service

Arguments:

    hSCM - handle to the SCManager

    szDriverName - name of driver (without extension), services as name of
        the service

Return Value:

    TRUE if service is successfully deleted, FALSE otherwise.

--*/
{
    BOOL ReturnValue = FALSE;

    //
    // Open the service so we can delete it
    //

    SC_HANDLE hService = OpenService ( hSCM, szDriverName, SERVICE_ALL_ACCESS );

    if (hService == NULL) {
        if (GetLastError() == ERROR_SERVICE_DOES_NOT_EXIST) {
            ReturnValue = TRUE;
        } else {
            ErrorPrint("OpenService failed, last error 0x%x", GetLastError());
        }
       goto Exit;
    }

    //
    // Delete the service
    //

    if (! DeleteService (hService)) {
        if (GetLastError() != ERROR_SERVICE_MARKED_FOR_DELETE) {
            ErrorPrint("DeleteService failed, last error 0x%x", GetLastError());
            goto Exit;
        }
    }

    ReturnValue = TRUE;

Exit:

    if (hService) {
        CloseServiceHandle (hService);
    }

    return ReturnValue;
}


BOOL 

UtilOpenDevice(
    _In_ LPTSTR szWin32DeviceName,
    _Out_ HANDLE *phDevice
    )
/*++

Routine Description:

    Opens a device

Arguments:

    szWin32DeviceName - name of the device

    phDevice - pointer to a variable that receives the handle to the device

Return Value:

    TRUE if the device is successfully opened, FALSE otherwise.

--*/
{
    BOOL ReturnValue = FALSE;
    HANDLE hDevice;

    //
    // Open the device
    //

    hDevice = CreateFile ( szWin32DeviceName,
                           GENERIC_READ | GENERIC_WRITE,
                           0,
                           NULL,
                           OPEN_EXISTING,
                           FILE_ATTRIBUTE_NORMAL,
                           NULL);

    if (hDevice == INVALID_HANDLE_VALUE) {
        ErrorPrint("CreateFile(%ls) failed, last error 0x%x", 
                    szWin32DeviceName, 
                    GetLastError() );
        goto Exit;
    }

    ReturnValue = TRUE;

Exit:

    *phDevice = hDevice;
    return ReturnValue;
}