summaryrefslogtreecommitdiffstats
path: root/private/rpcutil/server.c
blob: f20a48227ac4f38eeb831ba78a1cb467eac04384 (plain) (blame)
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
/*++

Copyright (c) 1990,91  Microsoft Corporation

Module Name:

    RpcServ.c

Abstract:

    This file contains commonly used server-side RPC functions,
    such as starting and stoping RPC servers.

Author:

    Dan Lafferty    danl    09-May-1991

Environment:

    User Mode - Win32

Revision History:

    09-May-1991     Danl
        Created

    03-July-1991    JimK
        Copied from a net-specific file.

    18-Feb-1992     Danl
        Added support for multiple endpoints & interfaces per server.

    10-Nov-1993     Danl
        Wait for RPC calls to complete before returning from
        RpcServerUnregisterIf.  Also, do a WaitServerListen after
        calling StopServerListen (when the last server shuts down).
        Now this is similar to RpcServer functions in netlib.

    29-Jun-1995     RichardW
        Read an alternative ACL from a key in the registry, if one exists.
        This ACL is used to protect the named pipe.

--*/

//
// INCLUDES
//

// These must be included first:
#include <nt.h>              // DbgPrint
#include <ntrtl.h>              // DbgPrint
#include <windef.h>             // win32 typedefs
#include <rpc.h>                // rpc prototypes
#include <ntrpcp.h>
#include <nturtl.h>             // needed for winbase.h
#include <winbase.h>            // LocalAlloc

// These may be included in any order:
#include <stdlib.h>      // for wcscpy wcscat
#include <tstr.h>       // WCSSIZE

#define     NT_PIPE_PREFIX_W        L"\\PIPE\\"
#define     NT_PIPE_SD_PREFIX_W     L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\SecurePipeServers\\"

static
PWSTR   RpcpSecurablePipes[] = {
                L"eventlog"         // Eventlog server
                };

//
// GLOBALS
//

    static CRITICAL_SECTION RpcpCriticalSection;
    static DWORD            RpcpNumInstances;



DWORD
RpcpInitRpcServer(
    VOID
    )

/*++

Routine Description:

    This function initializes the critical section used to protect the
    global server handle and instance count.

Arguments:

    none

Return Value:

    none

--*/
{
    InitializeCriticalSection(&RpcpCriticalSection);
    RpcpNumInstances = 0;

    return(0);
}

NTSTATUS
RpcpReadSDFromRegistry(
    IN  LPWSTR                  InterfaceName,
    OUT PSECURITY_DESCRIPTOR *  pSDToUse)
/*++

Routine Description:

    This function checks the registry in the magic place to see if an extra
    ACL has been defined for the pipe being passed in.  If there is one, it
    is translated to a NP acl, then returned.  If there isn't one, or if
    something goes wrong, an NULL acl is returned.

Arguments:

    InterfaceName   name of the pipe to check for, e.g. winreg, etc.

    pSDToUse        returned a pointer to the security decriptor to use.

Return Value:

    STATUS_SUCCESS,
    STATUS_NO_MEMORY,
    Possible other errors from registry apis.


--*/
{
    HANDLE                  hKey;
    OBJECT_ATTRIBUTES       ObjAttr;
    UNICODE_STRING          UniString;
    PWSTR                   PipeKey;
    NTSTATUS                Status;
    PSECURITY_DESCRIPTOR    pSD;
    ULONG                   cbNeeded;
    ACL_SIZE_INFORMATION    AclSize;
    ULONG                   AceIndex;
    ACCESS_MASK             NewMask;
    PACCESS_ALLOWED_ACE     pAce;
    PACL                    pAcl;
    BOOLEAN                 DaclPresent;
    BOOLEAN                 DaclDefaulted;
    UNICODE_STRING          Interface;
    UNICODE_STRING          Allowed;
    ULONG                   i;
    BOOLEAN                 PipeNameOk;
    PSECURITY_DESCRIPTOR    pNewSD;
    PACL                    pNewAcl;

    *pSDToUse = NULL;

    RtlInitUnicodeString( &Interface, InterfaceName );

    PipeNameOk = FALSE;

    for ( i = 0 ; i < sizeof( RpcpSecurablePipes ) / sizeof(PWSTR) ; i++ )
    {
        RtlInitUnicodeString( &Allowed, RpcpSecurablePipes[i] );

        if ( RtlCompareUnicodeString( &Allowed, &Interface, TRUE ) == 0 )
        {
            PipeNameOk = TRUE;
            break;
        }
    }

    if ( PipeNameOk )
    {

        PipeKey = RtlAllocateHeap(RtlProcessHeap(), 0,
                        sizeof(NT_PIPE_SD_PREFIX_W) + WCSSIZE(InterfaceName) );

        if (!PipeKey)
        {
            return(STATUS_NO_MEMORY);
        }

        wcscpy(PipeKey, NT_PIPE_SD_PREFIX_W);
        wcscat(PipeKey, InterfaceName);

        RtlInitUnicodeString(&UniString, PipeKey);

        InitializeObjectAttributes( &ObjAttr,
                                    &UniString,
                                    OBJ_CASE_INSENSITIVE,
                                    NULL, NULL);

        Status = NtOpenKey( &hKey,
                            KEY_READ,
                            &ObjAttr);

        RtlFreeHeap(RtlProcessHeap(), 0, PipeKey);

    }
    else
    {
        //
        // This is not one of the interfaces that we allow to be secured
        // in this fashion.  Fake and error,
        //

        Status = STATUS_OBJECT_NAME_NOT_FOUND ;
    }

    //
    // In general, most times we won't find this key
    //

    if (!NT_SUCCESS(Status))
    {
        if ((Status == STATUS_OBJECT_NAME_NOT_FOUND) ||
            (Status == STATUS_OBJECT_PATH_NOT_FOUND) )
        {
            pSD = RtlAllocateHeap(RtlProcessHeap(), 0,
                                    sizeof(SECURITY_DESCRIPTOR) );
            if (pSD)
            {
                InitializeSecurityDescriptor( pSD,
                                              SECURITY_DESCRIPTOR_REVISION );

                if (SetSecurityDescriptorDacl (
                        pSD,
                        TRUE,                           // Dacl present
                        NULL,                           // NULL Dacl
                        FALSE                           // Not defaulted
                        ) )
                {
                    *pSDToUse = pSD;
                    return(STATUS_SUCCESS);
                }

                RtlFreeHeap(RtlProcessHeap(), 0, pSD);

            }
            return(STATUS_NO_MEMORY);
        }

        return(Status);

    }

    //
    // Son of a gun, someone has established security for this pipe.
    //

    pSD = NULL;

    cbNeeded = 0;
    Status = NtQuerySecurityObject(
                    hKey,
                    DACL_SECURITY_INFORMATION,
                    NULL,
                    0,
                    &cbNeeded );

    if (Status == STATUS_BUFFER_TOO_SMALL)
    {
        pSD = RtlAllocateHeap(RtlProcessHeap(), 0, cbNeeded);
        if (pSD)
        {
            Status = NtQuerySecurityObject(
                        hKey,
                        DACL_SECURITY_INFORMATION,
                        pSD,
                        cbNeeded,
                        &cbNeeded );

            //
            // One way or the other, we are done with the key handle
            //

            NtClose(hKey);

            if (NT_SUCCESS(Status))
            {
                //
                // Now, the tricky part.  There is no 1-1 mapping of Key
                // permissions to Pipe permissions.  So, we do it here.
                // We walk the DACL, and examine each ACE.  We build a new
                // access mask for each ACE, and set the flags as follows:
                //
                //  if (KEY_READ) GENERIC_READ
                //  if (KEY_WRITE) GENERIC_WRITE
                //

                Status = RtlGetDaclSecurityDescriptor(
                                        pSD,
                                        &DaclPresent,
                                        &pAcl,
                                        &DaclDefaulted);


                //
                // If this failed, or there is no DACL present, then
                // we're in trouble.
                //

                if (!NT_SUCCESS(Status) || !DaclPresent)
                {
                    goto GetSDFromKey_BadAcl;
                }


                Status = RtlQueryInformationAcl(pAcl,
                                                &AclSize,
                                                sizeof(AclSize),
                                                AclSizeInformation);

                if (!NT_SUCCESS(Status))
                {
                    goto GetSDFromKey_BadAcl;
                }

                for (AceIndex = 0; AceIndex < AclSize.AceCount ; AceIndex++ )
                {
                    NewMask = 0;
                    Status = RtlGetAce( pAcl,
                                        AceIndex,
                                        & pAce);

                    //
                    // We don't care what kind of ACE it is, since we
                    // are just mapping the access types, and the access
                    // mask is always at a constant position.
                    //

                    if (NT_SUCCESS(Status))
                    {
                        if ((pAce->Header.AceType != ACCESS_ALLOWED_ACE_TYPE) &&
                            (pAce->Header.AceType != ACCESS_DENIED_ACE_TYPE))
                        {
                            //
                            // Must be an audit or random ACE type.  Skip it.
                            //

                            continue;

                        }


                        if (pAce->Mask & KEY_READ)
                        {
                            NewMask |= GENERIC_READ;
                        }

                        if (pAce->Mask & KEY_WRITE)
                        {
                            NewMask |= GENERIC_WRITE;
                        }

                        pAce->Mask = NewMask;
                    }
                    else
                    {
                        //
                        // Panic:  Bad ACL?
                        //

                        goto GetSDFromKey_BadAcl;
                    }

                }

                //
                // BUGBUG:  RPC does not understand self-relative SDs, so
                // we have to turn this into an absolute for them to turn
                // back into a self relative.
                //

                pNewSD = RtlAllocateHeap(RtlProcessHeap(), 0, cbNeeded);
                if (!pNewSD)
                {
                    goto GetSDFromKey_BadAcl;
                }

                InitializeSecurityDescriptor(   pNewSD,
                                                SECURITY_DESCRIPTOR_REVISION);

                pNewAcl = (PACL) (((PUCHAR) pNewSD) +
                                    sizeof(SECURITY_DESCRIPTOR) );

                RtlCopyMemory(pNewAcl, pAcl, AclSize.AclBytesInUse);

                SetSecurityDescriptorDacl(pNewSD, TRUE, pNewAcl, FALSE);

                RtlFreeHeap(RtlProcessHeap(), 0, pSD);

                *pSDToUse = pNewSD;
                return(Status);
            }
        }
        return(STATUS_NO_MEMORY);
    }
    else
    {
        //
        // Failed to read SD:
        //

        NtClose(hKey);


GetSDFromKey_BadAcl:

        //
        // Free the SD that we have allocated
        //

        if (pSD)
        {
            RtlFreeHeap(RtlProcessHeap(), 0, pSD);
        }

        //
        // Key exists, but there is no security descriptor, or it is unreadable
        // for whatever reason.
        //

        pSD = RtlAllocateHeap(RtlProcessHeap(), 0,
                                sizeof(SECURITY_DESCRIPTOR) );
        if (pSD)
        {
            InitializeSecurityDescriptor( pSD,
                                          SECURITY_DESCRIPTOR_REVISION );

            if (SetSecurityDescriptorDacl (
                    pSD,
                    TRUE,                           // Dacl present
                    NULL,                           // NULL Dacl
                    FALSE                           // Not defaulted
                    ) )
            {
                *pSDToUse = pSD;
                return(STATUS_SUCCESS);
            }

        }
        return(STATUS_NO_MEMORY);

    }


}


NTSTATUS
RpcpAddInterface(
    IN  LPWSTR              InterfaceName,
    IN  RPC_IF_HANDLE       InterfaceSpecification
    )

/*++

Routine Description:

    Starts an RPC Server, adds the address (or port/pipe), and adds the
    interface (dispatch table).

Arguments:

    InterfaceName - points to the name of the interface.

    InterfaceSpecification - Supplies the interface handle for the
        interface which we wish to add.

Return Value:

    NT_SUCCESS - Indicates the server was successfully started.

    STATUS_NO_MEMORY - An attempt to allocate memory has failed.

    Other - Status values that may be returned by:

                 RpcServerRegisterIf()
                 RpcServerUseProtseqEp()

    , or any RPC error codes, or any windows error codes that
    can be returned by LocalAlloc.

--*/
{
    RPC_STATUS          RpcStatus;
    LPWSTR              Endpoint = NULL;

    PSECURITY_DESCRIPTOR SecurityDescriptor = NULL;
    BOOL                Bool;
    NTSTATUS            Status;

    // We need to concatenate \pipe\ to the front of the interface name.

    Endpoint = (LPWSTR)LocalAlloc(LMEM_FIXED, sizeof(NT_PIPE_PREFIX_W) + WCSSIZE(InterfaceName));
    if (Endpoint == 0) {
       return(STATUS_NO_MEMORY);
    }
    wcscpy(Endpoint, NT_PIPE_PREFIX_W );
    wcscat(Endpoint,InterfaceName);

    //
    // Croft up a security descriptor that will grant everyone
    // all access to the object (basically, no security)
    //
    // We do this by putting in a NULL Dacl.
    //
    // BUGBUG: rpc should copy the security descriptor,
    // Since it currently doesn't, simply allocate it for now and
    // leave it around forever.
    //

    Status = RpcpReadSDFromRegistry(InterfaceName, &SecurityDescriptor);
    if (!NT_SUCCESS(Status))
    {
        return(Status);
    }

    // Ignore the second argument for now.

    RpcStatus = RpcServerUseProtseqEpW(L"ncacn_np", 10, Endpoint, SecurityDescriptor);

    // If RpcpStartRpcServer and then RpcpStopRpcServer have already
    // been called, the endpoint will have already been added but not
    // removed (because there is no way to do it).  If the endpoint is
    // already there, it is ok.

    if (   (RpcStatus != RPC_S_OK)
        && (RpcStatus != RPC_S_DUPLICATE_ENDPOINT)) {

#if DBG
        DbgPrint("RpcServerUseProtseqW failed! rpcstatus = %u\n",RpcStatus);
#endif
        goto CleanExit;
    }

    RpcStatus = RpcServerRegisterIf(InterfaceSpecification, 0, 0);

CleanExit:
    if ( Endpoint != NULL ) {
        LocalFree(Endpoint);
    }
    if ( SecurityDescriptor != NULL) {
        LocalFree(SecurityDescriptor);
    }

    return( I_RpcMapWin32Status(RpcStatus) );
}


NTSTATUS
RpcpStartRpcServer(
    IN  LPWSTR              InterfaceName,
    IN  RPC_IF_HANDLE       InterfaceSpecification
    )

/*++

Routine Description:

    Starts an RPC Server, adds the address (or port/pipe), and adds the
    interface (dispatch table).

Arguments:

    InterfaceName - points to the name of the interface.

    InterfaceSpecification - Supplies the interface handle for the
        interface which we wish to add.

Return Value:

    NT_SUCCESS - Indicates the server was successfully started.

    STATUS_NO_MEMORY - An attempt to allocate memory has failed.

    Other - Status values that may be returned by:

                 RpcServerRegisterIf()
                 RpcServerUseProtseqEp()

    , or any RPC error codes, or any windows error codes that
    can be returned by LocalAlloc.

--*/
{
    RPC_STATUS          RpcStatus;

    EnterCriticalSection(&RpcpCriticalSection);

    RpcStatus = RpcpAddInterface( InterfaceName,
                                  InterfaceSpecification );

    if ( RpcStatus != RPC_S_OK ) {
        LeaveCriticalSection(&RpcpCriticalSection);
        return( I_RpcMapWin32Status(RpcStatus) );
    }

    RpcpNumInstances++;

    if (RpcpNumInstances == 1) {


       // The first argument specifies the minimum number of threads to
       // be created to handle calls; the second argument specifies the
       // maximum number of concurrent calls allowed.  The last argument
       // indicates not to wait.

       RpcStatus = RpcServerListen(1,12345, 1);
       if ( RpcStatus == RPC_S_ALREADY_LISTENING ) {
           RpcStatus = RPC_S_OK;
           }
    }

    LeaveCriticalSection(&RpcpCriticalSection);
    return( I_RpcMapWin32Status(RpcStatus) );
}


NTSTATUS
RpcpDeleteInterface(
    IN  RPC_IF_HANDLE      InterfaceSpecification
    )

/*++

Routine Description:

    Deletes the interface.  This is likely
    to be caused by an invalid handle.  If an attempt to add the same
    interface or address again, then an error will be generated at that
    time.

Arguments:

    InterfaceSpecification - A handle for the interface that is to be removed.

Return Value:

    NERR_Success, or any RPC error codes that can be returned from
    RpcServerUnregisterIf.

--*/
{
    RPC_STATUS RpcStatus;

    RpcStatus = RpcServerUnregisterIf(InterfaceSpecification, 0, 1);

    return( I_RpcMapWin32Status(RpcStatus) );
}


NTSTATUS
RpcpStopRpcServer(
    IN  RPC_IF_HANDLE      InterfaceSpecification
    )

/*++

Routine Description:

    Deletes the interface.  This is likely
    to be caused by an invalid handle.  If an attempt to add the same
    interface or address again, then an error will be generated at that
    time.

Arguments:

    InterfaceSpecification - A handle for the interface that is to be removed.

Return Value:

    NERR_Success, or any RPC error codes that can be returned from
    RpcServerUnregisterIf.

--*/
{
    RPC_STATUS RpcStatus;

    RpcStatus = RpcServerUnregisterIf(InterfaceSpecification, 0, 1);
    EnterCriticalSection(&RpcpCriticalSection);

    RpcpNumInstances--;
    if (RpcpNumInstances == 0) {
       RpcMgmtStopServerListening(0);
       RpcMgmtWaitServerListen();
    }

    LeaveCriticalSection(&RpcpCriticalSection);

    return( I_RpcMapWin32Status(RpcStatus) );
}