File: ComPlusAuthorization.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (618 lines) | stat: -rw-r--r-- 23,808 bytes parent folder | download | duplicates (9)
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
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.ComIntegration
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Runtime;
    using System.Runtime.InteropServices;
    using System.Security;
    using System.Security.AccessControl;
    using System.Security.Permissions;
    using System.Security.Principal;
    using System.ServiceModel;
    using System.ServiceModel.Diagnostics;
    using SafeCloseHandle = System.IdentityModel.SafeCloseHandle;
    using SafeHGlobalHandle = System.IdentityModel.SafeHGlobalHandle;

    static class SecurityUtils
    {
        static WindowsIdentity anonymousIdentity;
        static WindowsIdentity processIdentity;
        static object lockObject = new object();

        [Fx.Tag.SecurityNote(Critical = "Uses critical type SafeHGlobalHandle.",
            Safe = "Performs a Demand for full trust.")]
        [SecuritySafeCritical]
        [SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
        public static SafeHandle GetTokenInformation(SafeCloseHandle token, TOKEN_INFORMATION_CLASS infoClass)
        {
            uint length;
            if (!SafeNativeMethods.GetTokenInformation(token, infoClass, SafeHGlobalHandle.InvalidHandle, 0, out length))
            {
                int error = Marshal.GetLastWin32Error();
                if (error != (int)Win32Error.ERROR_INSUFFICIENT_BUFFER)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.GetTokenInfoFailed, error)));
                }
            }
            SafeHandle buffer = SafeHGlobalHandle.AllocHGlobal(length);
            try
            {
                if (!SafeNativeMethods.GetTokenInformation(token, infoClass, buffer, length, out length))
                {
                    int error = Marshal.GetLastWin32Error();
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.GetTokenInfoFailed, error)));
                }
            }
            catch
            {
                buffer.Dispose();
                throw;
            }
            return buffer;
        }

        internal static bool IsAtleastImpersonationToken(SafeCloseHandle token)
        {
            using (SafeHandle buffer =
                GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenImpersonationLevel))
            {
                int level = Marshal.ReadInt32(buffer.DangerousGetHandle());
                if (level < (int)SecurityImpersonationLevel.Impersonation)
                    return false;
                else
                    return true;
            }
        }

        internal static bool IsPrimaryToken(SafeCloseHandle token)
        {
            using (SafeHandle buffer =
                GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenType))
            {
                int level = Marshal.ReadInt32(buffer.DangerousGetHandle());
                return (level == (int)TokenType.TokenPrimary);
            }
        }

        internal static LUID GetModifiedIDLUID(SafeCloseHandle token)
        {
            using (SafeHandle buffer =
                GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenStatistics))
            {
                TOKEN_STATISTICS tokenStats = (TOKEN_STATISTICS)
                    Marshal.PtrToStructure(buffer.DangerousGetHandle(), typeof(TOKEN_STATISTICS));
                return tokenStats.ModifiedId;
            }
        }

        public static WindowsIdentity GetAnonymousIdentity()
        {
            SafeCloseHandle tokenHandle = null;
            bool isImpersonating = false;

            lock (lockObject)
            {
                if (anonymousIdentity == null)
                {
                    try
                    {
                        try
                        {
                            if (!SafeNativeMethods.ImpersonateAnonymousUserOnCurrentThread(SafeNativeMethods.GetCurrentThread()))
                            {
                                int error = Marshal.GetLastWin32Error();
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.ImpersonateAnonymousTokenFailed, error)));
                            }
                            isImpersonating = true;
                            bool revertSuccess;
                            bool isSuccess = SafeNativeMethods.OpenCurrentThreadToken(SafeNativeMethods.GetCurrentThread(), TokenAccessLevels.Query, true, out tokenHandle);
                            if (!isSuccess)
                            {
                                int error = Marshal.GetLastWin32Error();

                                revertSuccess = SafeNativeMethods.RevertToSelf();
                                if (false == revertSuccess)
                                {
                                    error = Marshal.GetLastWin32Error();

                                    //this requires a failfast since failure to revert impersonation compromises security
                                    DiagnosticUtility.FailFast("RevertToSelf() failed with " + error);
                                }
                                isImpersonating = false;

                                Utility.CloseInvalidOutSafeHandle(tokenHandle);
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.OpenThreadTokenFailed, error)));
                            }

                            revertSuccess = SafeNativeMethods.RevertToSelf();
                            if (false == revertSuccess)
                            {
                                int error = Marshal.GetLastWin32Error();

                                //this requires a failfast since failure to revert impersonation compromises security
                                DiagnosticUtility.FailFast("RevertToSelf() failed with " + error);
                            }
                            isImpersonating = false;

                            using (tokenHandle)
                            {
                                anonymousIdentity = new WindowsIdentity(tokenHandle.DangerousGetHandle());
                            }
                        }
                        finally
                        {
                            if (isImpersonating)
                            {
                                bool revertSuccess = SafeNativeMethods.RevertToSelf();
                                if (false == revertSuccess)
                                {
                                    int error = Marshal.GetLastWin32Error();

                                    //this requires a failfast since failure to revert impersonation compromises security
                                    DiagnosticUtility.FailFast("RevertToSelf() failed with " + error);
                                }
                            }
                        }
                    }
                    catch
                    {
                        // Force the finally to run before leaving the method.
                        throw;
                    }
                }
            }
            return anonymousIdentity;
        }

        public static WindowsIdentity GetProcessIdentity()
        {

            SafeCloseHandle tokenHandle = null;
            lock (lockObject)
            {

                try
                {
                    bool isSuccess = SafeNativeMethods.GetCurrentProcessToken(SafeNativeMethods.GetCurrentProcess(), TokenAccessLevels.Query, out tokenHandle);
                    if (!isSuccess)
                    {
                        int error = Marshal.GetLastWin32Error();
                        Utility.CloseInvalidOutSafeHandle(tokenHandle);
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.OpenProcessTokenFailed, error)));
                    }
                    processIdentity = new WindowsIdentity(tokenHandle.DangerousGetHandle());
                }
                finally
                {
                    if (tokenHandle != null)
                        tokenHandle.Dispose();
                }
            }
            return processIdentity;
        }
    }

    internal sealed class ComPlusAuthorization
    {

        string[] serviceRoleMembers = null;
        string[] contractRoleMembers = null;
        string[] operationRoleMembers = null;
        CommonSecurityDescriptor securityDescriptor = null;
        static SecurityIdentifier sidAdministrators = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
        Dictionary<LUID, bool> accessCheckCache = new Dictionary<LUID, bool>();

        public ComPlusAuthorization(string[] serviceRoleMembers, string[] contractRoleMembers, string[] operationRoleMembers)
        {
            this.serviceRoleMembers = serviceRoleMembers;
            this.contractRoleMembers = contractRoleMembers;
            this.operationRoleMembers = operationRoleMembers;
        }

        private void BuildSecurityDescriptor()
        {
            Fx.Assert((null == securityDescriptor), "SecurityDescriptor must be NULL");

            NTAccount name;
            SecurityIdentifier sid;
            CommonAce ace;
            RawAcl acl = new RawAcl(GenericAcl.AclRevision, 1);
            int index = 0;
            if (operationRoleMembers != null)
            {
                foreach (string userName in operationRoleMembers)
                {
                    name = new NTAccount(userName);
                    sid = (SecurityIdentifier)name.Translate(typeof(SecurityIdentifier));
                    ace = new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, (int)ComRights.EXECUTE, sid, false, null);
                    acl.InsertAce(index, ace);
                    index++;
                }
            }
            if (contractRoleMembers != null)
            {
                foreach (string userName in contractRoleMembers)
                {
                    name = new NTAccount(userName);
                    sid = (SecurityIdentifier)name.Translate(typeof(SecurityIdentifier));
                    ace = new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, (int)ComRights.EXECUTE, sid, false, null);
                    acl.InsertAce(index, ace);
                    index++;
                }
            }
            if (serviceRoleMembers != null)
            {
                foreach (string userName in serviceRoleMembers)
                {
                    name = new NTAccount(userName);
                    sid = (SecurityIdentifier)name.Translate(typeof(SecurityIdentifier));
                    ace = new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, (int)ComRights.EXECUTE, sid, false, null);
                    acl.InsertAce(index, ace);
                    index++;
                }
            }
            DiscretionaryAcl dacl = new DiscretionaryAcl(true, false, acl);
            securityDescriptor = new CommonSecurityDescriptor(true, false, ControlFlags.DiscretionaryAclPresent, sidAdministrators, sidAdministrators, null, dacl);

        }

        private bool IsAccessCached(LUID luidModifiedID, out bool isAccessAllowed)
        {
            if (null == accessCheckCache)
            {
                throw Fx.AssertAndThrowFatal("AcessCheckCache must not be NULL");
            }

            bool retValue = false;

            lock (this)
            {
                retValue = accessCheckCache.TryGetValue(luidModifiedID, out isAccessAllowed);
            }

            return retValue;
        }

        private void CacheAccessCheck(LUID luidModifiedID, bool isAccessAllowed)
        {
            if (null == accessCheckCache)
            {
                throw Fx.AssertAndThrowFatal("AcessCheckCache must not be NULL");
            }

            lock (this)
            {
                accessCheckCache[luidModifiedID] = isAccessAllowed;
            }
        }
        private void CheckAccess(WindowsIdentity clientIdentity, out bool IsAccessAllowed)
        {
            if (null == securityDescriptor)
            {
                throw Fx.AssertAndThrowFatal("Security Descriptor must not be NULL");
            }

            IsAccessAllowed = false;
            byte[] BinaryForm = new byte[securityDescriptor.BinaryLength];
            securityDescriptor.GetBinaryForm(BinaryForm, 0);
            SafeCloseHandle ImpersonationToken = null;
            SafeCloseHandle clientIdentityToken = new SafeCloseHandle(clientIdentity.Token, false);
            try
            {
                if (SecurityUtils.IsPrimaryToken(clientIdentityToken))
                {
                    if (!SafeNativeMethods.DuplicateTokenEx(clientIdentityToken,
                                                                        TokenAccessLevels.Query,
                                                                        IntPtr.Zero,
                                                                        SecurityImpersonationLevel.Identification,
                                                                        TokenType.TokenImpersonation,
                                                                        out ImpersonationToken))
                    {
                        int error = Marshal.GetLastWin32Error();
                        Utility.CloseInvalidOutSafeHandle(ImpersonationToken);
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.DuplicateTokenExFailed, error)));
                    }
                }
                GENERIC_MAPPING GenericMapping = new GENERIC_MAPPING();
                PRIVILEGE_SET PrivilegeSet = new PRIVILEGE_SET();
                uint PrivilegeSetLength = (uint)Marshal.SizeOf(PrivilegeSet);
                uint GrantedAccess = 0;
                if (!SafeNativeMethods.AccessCheck(BinaryForm, (ImpersonationToken != null) ? ImpersonationToken : clientIdentityToken,
                    (int)ComRights.EXECUTE, GenericMapping, out PrivilegeSet,
                    ref PrivilegeSetLength, out GrantedAccess, out IsAccessAllowed))
                {
                    int error = Marshal.GetLastWin32Error();
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.AccessCheckFailed, error)));
                }

            }
            finally
            {
                if (ImpersonationToken != null)
                    ImpersonationToken.Dispose();
            }
        }

        public string[] ServiceRoleMembers
        {
            get
            {
                return serviceRoleMembers;
            }
        }
        public string[] ContractRoleMembers
        {
            get
            {
                return contractRoleMembers;
            }
        }
        public string[] OperationRoleMembers
        {
            get
            {
                return operationRoleMembers;
            }
        }
        public CommonSecurityDescriptor SecurityDescriptor
        {
            get
            {
                return securityDescriptor;
            }
        }
        public bool IsAuthorizedForOperation(WindowsIdentity clientIdentity)
        {

            bool IsAccessAllowed = false;

            if (null == clientIdentity)
            {
                throw Fx.AssertAndThrow("NULL Identity");
            }
            if (IntPtr.Zero == clientIdentity.Token)
            {
                throw Fx.AssertAndThrow("Token handle cannot be zero");
            }

            lock (this)
            {
                if (securityDescriptor == null)
                {
                    BuildSecurityDescriptor();
                }
            }

            LUID luidModified = SecurityUtils.GetModifiedIDLUID(new SafeCloseHandle(clientIdentity.Token, false));

            if (IsAccessCached(luidModified, out IsAccessAllowed))
                return IsAccessAllowed;

            CheckAccess(clientIdentity, out IsAccessAllowed);

            CacheAccessCheck(luidModified, IsAccessAllowed);

            return IsAccessAllowed;
        }

    }

    internal sealed class ComPlusServerSecurity : IContextSecurityPerimeter, IServerSecurity, IDisposable
    {
        WindowsIdentity clientIdentity = null;
        IntPtr oldSecurityObject = IntPtr.Zero;
        WindowsImpersonationContext impersonateContext = null;
        bool isImpersonating = false;
        bool shouldUseCallContext = false;

        const uint RPC_C_AUTHN_GSS_NEGOTIATE = 9;
        const uint RPC_C_AUTHN_WINNT = 10;
        const uint RPC_C_AUTHN_GSS_KERBEROS = 16;
        const uint RPC_C_AUTHN_DEFAULT = unchecked((uint)0xFFFFFFFF);

        const uint RPC_C_AUTHZ_NONE = 0;

        const uint RPC_C_AUTHN_LEVEL_DEFAULT = 0;
        const uint RPC_C_AUTHN_LEVEL_NONE = 1;
        const uint RPC_C_AUTHN_LEVEL_CONNECT = 2;
        const uint RPC_C_AUTHN_LEVEL_CALL = 3;
        const uint RPC_C_AUTHN_LEVEL_PKT = 4;
        const uint RPC_C_AUTHN_LEVEL_PKT_INTEGRITY = 5;
        const uint RPC_C_AUTHN_LEVEL_PKT_PRIVACY = 6;

        public ComPlusServerSecurity(WindowsIdentity clientIdentity, bool shouldUseCallContext)
        {
            if (null == clientIdentity)
            {
                throw Fx.AssertAndThrow("NULL Identity");
            }
            if (IntPtr.Zero == clientIdentity.Token)
            {
                throw Fx.AssertAndThrow("Token handle cannot be zero");
            }

            this.shouldUseCallContext = shouldUseCallContext;
            this.clientIdentity = clientIdentity;
            IntPtr secCtx = Marshal.GetIUnknownForObject(this);
            try
            {
                oldSecurityObject = SafeNativeMethods.CoSwitchCallContext(secCtx);
            }
            catch
            {
                Marshal.Release(secCtx);

                throw;
            }
        }
        ~ComPlusServerSecurity()
        {
            Dispose(false);
        }
        public bool GetPerimeterFlag()
        {
            return shouldUseCallContext;
        }

        public void SetPerimeterFlag(bool flag)
        {
            shouldUseCallContext = flag;
        }

        public void QueryBlanket
        (
            IntPtr authnSvc,
            IntPtr authzSvc,
            IntPtr serverPrincipalName,
            IntPtr authnLevel,
            IntPtr impLevel,
            IntPtr clientPrincipalName,
            IntPtr Capabilities
        )
        {
            // Convert to RPC'isms.

            if (authnSvc != IntPtr.Zero)
            {
                uint tempAuthnSvc = RPC_C_AUTHN_DEFAULT;

                // Try to convert the clientIdentity.AuthenticationType to an RPC constant.
                // This is a best case attempt.
                string authenticationType = clientIdentity.AuthenticationType;
                if (authenticationType.ToUpperInvariant() == "NTLM")
                    tempAuthnSvc = RPC_C_AUTHN_WINNT;
                else if (authenticationType.ToUpperInvariant() == "KERBEROS")
                    tempAuthnSvc = RPC_C_AUTHN_GSS_KERBEROS;
                else if (authenticationType.ToUpperInvariant() == "NEGOTIATE")
                    tempAuthnSvc = RPC_C_AUTHN_GSS_NEGOTIATE;

                Marshal.WriteInt32(authnSvc, (int)tempAuthnSvc);
            }

            if (authzSvc != IntPtr.Zero)
            {
                Marshal.WriteInt32(authzSvc, (int)RPC_C_AUTHZ_NONE);
            }

            if (serverPrincipalName != IntPtr.Zero)
            {
                IntPtr str = Marshal.StringToCoTaskMemUni(SecurityUtils.GetProcessIdentity().Name);

                Marshal.WriteIntPtr(serverPrincipalName, str);
            }

            // There is no equivalent for the RPC authn level. It can only be
            // approximated, in the best case. Use default.

            if (authnLevel != IntPtr.Zero)
            {
                Marshal.WriteInt32(authnLevel, (int)RPC_C_AUTHN_LEVEL_DEFAULT);
            }

            if (impLevel != IntPtr.Zero)
            {
                Marshal.WriteInt32(impLevel, 0);
            }

            if (clientPrincipalName != IntPtr.Zero)
            {
                IntPtr str = Marshal.StringToCoTaskMemUni(clientIdentity.Name);

                Marshal.WriteIntPtr(clientPrincipalName, str);
            }

            if (Capabilities != IntPtr.Zero)
            {
                Marshal.WriteInt32(Capabilities, 0);
            }
        }

        public int ImpersonateClient()
        {
            // We want to return known COM hresults here rather than random CLR-Exception mapped HRESULTS.  Also, 
            // we don't want CLR to set the ErrorInfo object.

            int hresult = HR.E_FAIL;
            try
            {
                impersonateContext = WindowsIdentity.Impersonate(clientIdentity.Token);
                isImpersonating = true;
                hresult = HR.S_OK;
            }
            catch (SecurityException)
            {
                // Special case anonymous impersonation failure. 
                // Unmanaged callers to ImpersonateClient expect this hresult.
                hresult = HR.RPC_NT_BINDING_HAS_NO_AUTH;
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                    throw;
            }
            return hresult;
        }
        public int RevertToSelf()
        {
            // We want to return known COM hresults here rather than random CLR-Exception mapped HRESULTS.  Also, 
            // we don't want CLR to set the ErrorInfo object.

            int hresult = HR.E_FAIL;
            if (isImpersonating)
            {
                try
                {
                    impersonateContext.Undo();
                    isImpersonating = false;
                    hresult = HR.S_OK;
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                        throw;
                }
            }
            return hresult;
        }
        public bool IsImpersonating()
        {
            return isImpersonating;
        }
        void IDisposable.Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public void Dispose(bool disposing)
        {
            RevertToSelf();
            IntPtr secCtx = SafeNativeMethods.CoSwitchCallContext(oldSecurityObject);

            if (IntPtr.Zero == secCtx)
            {
                // this has to be a failfast since not having a security context can compromise security
                DiagnosticUtility.FailFast("Security Context was should not be null");
            }

            if (Marshal.GetObjectForIUnknown(secCtx) != this)
            {
                // this has to be a failfast since being in the wrong security context can compromise security
                DiagnosticUtility.FailFast("Security Context was modified from underneath us");
            }
            Marshal.Release(secCtx);
            if (disposing)
            {
                clientIdentity = null;
                if (impersonateContext != null)
                    impersonateContext.Dispose();
            }
        }

    }

}