Imported Upstream version 4.0.0~alpha1

Former-commit-id: 806294f5ded97629b74c85c09952f2a74fe182d9
This commit is contained in:
Jo Shields
2015-04-07 09:35:12 +01:00
parent 283343f570
commit 3c1f479b9d
22469 changed files with 2931443 additions and 869343 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1 @@
16df8b1e453f752136d149af4f886d022e26981b

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,269 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// CryptoKeySecurity.cs
//
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Security.Principal;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Security.AccessControl {
[Flags]
public enum CryptoKeyRights {
ReadData = 0x00000001,
WriteData = 0x00000002,
ReadExtendedAttributes = 0x00000008,
WriteExtendedAttributes = 0x00000010,
ReadAttributes = 0x00000080,
WriteAttributes = 0x00000100,
Delete = 0x00010000,
ReadPermissions = 0x00020000,
ChangePermissions = 0x00040000,
TakeOwnership = 0x00080000,
Synchronize = 0x00100000,
FullControl = 0x001F019B,
GenericAll = 0x10000000,
GenericExecute = 0x20000000,
GenericWrite = 0x40000000,
GenericRead = unchecked((int) 0x80000000)
}
public sealed class CryptoKeyAccessRule : AccessRule {
public CryptoKeyAccessRule (IdentityReference identity, CryptoKeyRights cryptoKeyRights, AccessControlType type)
: this (identity,
AccessMaskFromRights(cryptoKeyRights, type),
false,
InheritanceFlags.None,
PropagationFlags.None,
type) {
}
public CryptoKeyAccessRule (string identity, CryptoKeyRights cryptoKeyRights, AccessControlType type)
: this (new NTAccount(identity),
AccessMaskFromRights(cryptoKeyRights, type),
false,
InheritanceFlags.None,
PropagationFlags.None,
type) {
}
private CryptoKeyAccessRule (IdentityReference identity, int accessMask, bool isInherited,
InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
: base (identity,
accessMask,
isInherited,
inheritanceFlags,
propagationFlags,
type) {
}
public CryptoKeyRights CryptoKeyRights {
get { return RightsFromAccessMask(base.AccessMask); }
}
// Acl's on files have a Synchronize bit, and CreateFile always
// asks for it. So for allows, let's always include this bit,
// and for denies, let's never include this bit unless we're denying
// full control. This is the right thing for users, even if it does
// make the model look asymmetrical from a purist point of view.
// Also, crypto key containers are just files in the end, so
// this tweak to the access rights for files makes sense here.
private static int AccessMaskFromRights (CryptoKeyRights cryptoKeyRights, AccessControlType controlType) {
if (controlType == AccessControlType.Allow) {
cryptoKeyRights |= CryptoKeyRights.Synchronize;
}
else if (controlType == AccessControlType.Deny) {
if (cryptoKeyRights != CryptoKeyRights.FullControl)
cryptoKeyRights &= ~CryptoKeyRights.Synchronize;
}
else {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidEnumValue", controlType, "controlType"), "controlType");
}
return (int) cryptoKeyRights;
}
internal static CryptoKeyRights RightsFromAccessMask(int accessMask) {
return (CryptoKeyRights) accessMask;
}
}
public sealed class CryptoKeyAuditRule : AuditRule {
public CryptoKeyAuditRule (IdentityReference identity, CryptoKeyRights cryptoKeyRights, AuditFlags flags)
: this (identity,
AccessMaskFromRights(cryptoKeyRights),
false,
InheritanceFlags.None,
PropagationFlags.None,
flags) {
}
public CryptoKeyAuditRule (string identity, CryptoKeyRights cryptoKeyRights, AuditFlags flags)
: this (new NTAccount(identity),
AccessMaskFromRights(cryptoKeyRights),
false,
InheritanceFlags.None,
PropagationFlags.None,
flags) {
}
private CryptoKeyAuditRule (IdentityReference identity, int accessMask, bool isInherited,
InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
: base (identity,
accessMask,
isInherited,
inheritanceFlags,
propagationFlags,
flags) {
}
public CryptoKeyRights CryptoKeyRights {
get { return RightsFromAccessMask(base.AccessMask); }
}
private static int AccessMaskFromRights (CryptoKeyRights cryptoKeyRights) {
return (int) cryptoKeyRights;
}
internal static CryptoKeyRights RightsFromAccessMask(int accessMask) {
return (CryptoKeyRights) accessMask;
}
}
public sealed class CryptoKeySecurity : NativeObjectSecurity {
private const ResourceType s_ResourceType = ResourceType.FileObject;
public CryptoKeySecurity () : base(false, s_ResourceType) {}
[System.Security.SecuritySafeCritical] // auto-generated
public CryptoKeySecurity (CommonSecurityDescriptor securityDescriptor) : base(s_ResourceType, securityDescriptor) {}
public sealed override AccessRule AccessRuleFactory (IdentityReference identityReference,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type) {
return new CryptoKeyAccessRule(
identityReference,
CryptoKeyAccessRule.RightsFromAccessMask(accessMask),
type);
}
public sealed override AuditRule AuditRuleFactory (IdentityReference identityReference,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AuditFlags flags) {
return new CryptoKeyAuditRule(
identityReference,
CryptoKeyAuditRule.RightsFromAccessMask(accessMask),
flags);
}
public void AddAccessRule (CryptoKeyAccessRule rule) {
base.AddAccessRule(rule);
}
public void SetAccessRule (CryptoKeyAccessRule rule) {
base.SetAccessRule(rule);
}
public void ResetAccessRule (CryptoKeyAccessRule rule) {
base.ResetAccessRule(rule);
}
public bool RemoveAccessRule (CryptoKeyAccessRule rule) {
return base.RemoveAccessRule(rule);
}
public void RemoveAccessRuleAll (CryptoKeyAccessRule rule) {
base.RemoveAccessRuleAll(rule);
}
public void RemoveAccessRuleSpecific (CryptoKeyAccessRule rule) {
base.RemoveAccessRuleSpecific(rule);
}
public void AddAuditRule (CryptoKeyAuditRule rule) {
base.AddAuditRule(rule);
}
public void SetAuditRule (CryptoKeyAuditRule rule) {
base.SetAuditRule(rule);
}
public bool RemoveAuditRule (CryptoKeyAuditRule rule) {
return base.RemoveAuditRule(rule);
}
public void RemoveAuditRuleAll (CryptoKeyAuditRule rule) {
base.RemoveAuditRuleAll(rule);
}
public void RemoveAuditRuleSpecific (CryptoKeyAuditRule rule) {
base.RemoveAuditRuleSpecific(rule);
}
#region some overrides
public override Type AccessRightType
{
get { return typeof(System.Security.AccessControl.CryptoKeyRights); }
}
public override Type AccessRuleType
{
get { return typeof(System.Security.AccessControl.CryptoKeyAccessRule); }
}
public override Type AuditRuleType
{
get { return typeof(System.Security.AccessControl.CryptoKeyAuditRule); }
}
#endregion
internal AccessControlSections ChangedAccessControlSections {
[System.Security.SecurityCritical] // auto-generated
get {
AccessControlSections changedSections = AccessControlSections.None;
bool readLockAcquired = false;
RuntimeHelpers.PrepareConstrainedRegions();
try {
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally {
ReadLock();
readLockAcquired = true;
}
if (AccessRulesModified)
changedSections |= AccessControlSections.Access;
if (AuditRulesModified)
changedSections |= AccessControlSections.Audit;
if (GroupModified)
changedSections |= AccessControlSections.Group;
if (OwnerModified)
changedSections |= AccessControlSections.Owner;
}
finally {
if (readLockAcquired) {
ReadUnlock();
}
}
return changedSections;
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,82 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
using System.Runtime.InteropServices;
namespace System.Security.AccessControl
{
[Flags]
public enum InheritanceFlags
{
None = 0x00,
ContainerInherit = 0x01,
ObjectInherit = 0x02,
}
[Flags]
public enum PropagationFlags
{
None = 0x00,
NoPropagateInherit = 0x01,
InheritOnly = 0x02,
}
[Flags]
public enum AuditFlags
{
None = 0x00,
Success = 0x01,
Failure = 0x02,
}
[Flags]
public enum SecurityInfos
{
Owner = 0x00000001,
Group = 0x00000002,
DiscretionaryAcl = 0x00000004,
SystemAcl = 0x00000008,
}
public enum ResourceType
{
Unknown = 0x00,
FileObject = 0x01,
Service = 0x02,
Printer = 0x03,
RegistryKey = 0x04,
LMShare = 0x05,
KernelObject = 0x06,
WindowObject = 0x07,
DSObject = 0x08,
DSObjectAll = 0x09,
ProviderDefined = 0x0A,
WmiGuidObject = 0x0B,
RegistryWow6432Key = 0x0C,
}
[Flags]
public enum AccessControlSections {
None = 0,
Audit = 0x1,
Access = 0x2,
Owner = 0x4,
Group = 0x8,
All = 0xF
}
[Flags]
public enum AccessControlActions {
#if FEATURE_MACL
None = 0,
View = 1,
Change = 2
#else
None = 0
#endif
}
}

View File

@@ -0,0 +1,277 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: EventWaitHandleSecurity
**
**
** Purpose: Managed ACL wrapper for Win32 events.
**
**
===========================================================*/
using System;
using System.Collections;
using System.Security.Permissions;
using System.Security.Principal;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
namespace System.Security.AccessControl
{
// Derive this list of values from winnt.h and MSDN docs:
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/synchronization_object_security_and_access_rights.asp
// Win32's interesting values are EVENT_MODIFY_STATE (0x0002) and
// EVENT_ALL_ACCESS (0x1F0003). I don't know what 0x1 is, but Windows
// includes it in EVENT_ALL_ACCESS.
[Flags]
public enum EventWaitHandleRights
{
Modify = 0x000002,
Delete = 0x010000,
ReadPermissions = 0x020000,
ChangePermissions = 0x040000,
TakeOwnership = 0x080000,
Synchronize = 0x100000, // SYNCHRONIZE
FullControl = 0x1F0003
}
public sealed class EventWaitHandleAccessRule : AccessRule
{
// Constructor for creating access rules for registry objects
public EventWaitHandleAccessRule(IdentityReference identity, EventWaitHandleRights eventRights, AccessControlType type)
: this(identity, (int) eventRights, false, InheritanceFlags.None, PropagationFlags.None, type)
{
}
public EventWaitHandleAccessRule(String identity, EventWaitHandleRights eventRights, AccessControlType type)
: this(new NTAccount(identity), (int) eventRights, false, InheritanceFlags.None, PropagationFlags.None, type)
{
}
//
// Internal constructor to be called by public constructors
// and the access rule factory methods of {File|Folder}Security
//
internal EventWaitHandleAccessRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type )
: base(
identity,
accessMask,
isInherited,
inheritanceFlags,
propagationFlags,
type )
{
}
public EventWaitHandleRights EventWaitHandleRights {
get { return (EventWaitHandleRights) base.AccessMask; }
}
}
public sealed class EventWaitHandleAuditRule : AuditRule
{
public EventWaitHandleAuditRule(IdentityReference identity, EventWaitHandleRights eventRights, AuditFlags flags)
: this(identity, (int) eventRights, false, InheritanceFlags.None, PropagationFlags.None, flags)
{
}
/* // Not in the spec
public EventWaitHandleAuditRule(string identity, EventWaitHandleRights eventRights, AuditFlags flags)
: this(new NTAccount(identity), (int) eventRights, false, InheritanceFlags.None, PropagationFlags.None, flags)
{
}
*/
internal EventWaitHandleAuditRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
: base(identity, accessMask, isInherited, inheritanceFlags, propagationFlags, flags)
{
}
public EventWaitHandleRights EventWaitHandleRights {
get { return (EventWaitHandleRights) base.AccessMask; }
}
}
public sealed class EventWaitHandleSecurity : NativeObjectSecurity
{
public EventWaitHandleSecurity()
: base(true, ResourceType.KernelObject)
{
}
[System.Security.SecurityCritical] // auto-generated
internal EventWaitHandleSecurity(String name, AccessControlSections includeSections)
: base(true, ResourceType.KernelObject, name, includeSections, _HandleErrorCode, null)
{
// Let the underlying ACL API's demand unmanaged code permission.
}
[System.Security.SecurityCritical] // auto-generated
internal EventWaitHandleSecurity(SafeWaitHandle handle, AccessControlSections includeSections)
: base(true, ResourceType.KernelObject, handle, includeSections, _HandleErrorCode, null)
{
// Let the underlying ACL API's demand unmanaged code permission.
}
[System.Security.SecurityCritical] // auto-generated
private static Exception _HandleErrorCode(int errorCode, string name, SafeHandle handle, object context)
{
System.Exception exception = null;
switch (errorCode) {
case Win32Native.ERROR_INVALID_NAME:
case Win32Native.ERROR_INVALID_HANDLE:
case Win32Native.ERROR_FILE_NOT_FOUND:
if ((name != null) && (name.Length != 0))
exception = new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name));
else
exception = new WaitHandleCannotBeOpenedException();
break;
default:
break;
}
return exception;
}
public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
{
return new EventWaitHandleAccessRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type);
}
public override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
{
return new EventWaitHandleAuditRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags);
}
internal AccessControlSections GetAccessControlSectionsFromChanges()
{
AccessControlSections persistRules = AccessControlSections.None;
if (AccessRulesModified)
persistRules = AccessControlSections.Access;
if (AuditRulesModified)
persistRules |= AccessControlSections.Audit;
if (OwnerModified)
persistRules |= AccessControlSections.Owner;
if (GroupModified)
persistRules |= AccessControlSections.Group;
return persistRules;
}
[System.Security.SecurityCritical] // auto-generated
internal void Persist(SafeWaitHandle handle)
{
//
// Let the underlying ACL API's demand unmanaged code.
//
WriteLock();
try
{
AccessControlSections persistSections = GetAccessControlSectionsFromChanges();
if (persistSections == AccessControlSections.None)
return; // Don't need to persist anything.
base.Persist(handle, persistSections);
OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false;
}
finally
{
WriteUnlock();
}
}
public void AddAccessRule(EventWaitHandleAccessRule rule)
{
base.AddAccessRule(rule);
}
public void SetAccessRule(EventWaitHandleAccessRule rule)
{
base.SetAccessRule(rule);
}
public void ResetAccessRule(EventWaitHandleAccessRule rule)
{
base.ResetAccessRule(rule);
}
public bool RemoveAccessRule(EventWaitHandleAccessRule rule)
{
return base.RemoveAccessRule(rule);
}
public void RemoveAccessRuleAll(EventWaitHandleAccessRule rule)
{
base.RemoveAccessRuleAll(rule);
}
public void RemoveAccessRuleSpecific(EventWaitHandleAccessRule rule)
{
base.RemoveAccessRuleSpecific(rule);
}
public void AddAuditRule(EventWaitHandleAuditRule rule)
{
base.AddAuditRule(rule);
}
public void SetAuditRule(EventWaitHandleAuditRule rule)
{
base.SetAuditRule(rule);
}
public bool RemoveAuditRule(EventWaitHandleAuditRule rule)
{
return base.RemoveAuditRule(rule);
}
public void RemoveAuditRuleAll(EventWaitHandleAuditRule rule)
{
base.RemoveAuditRuleAll(rule);
}
public void RemoveAuditRuleSpecific(EventWaitHandleAuditRule rule)
{
base.RemoveAuditRuleSpecific(rule);
}
public override Type AccessRightType
{
get { return typeof(EventWaitHandleRights); }
}
public override Type AccessRuleType
{
get { return typeof(EventWaitHandleAccessRule); }
}
public override Type AuditRuleType
{
get { return typeof(EventWaitHandleAuditRule); }
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,273 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: MutexSecurity
**
**
** Purpose: Managed ACL wrapper for Win32 mutexes.
**
**
===========================================================*/
using System;
using System.Collections;
using System.Security.Permissions;
using System.Security.Principal;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
namespace System.Security.AccessControl
{
// Derive this list of values from winnt.h and MSDN docs:
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/synchronization_object_security_and_access_rights.asp
// In order to call ReleaseMutex, you must have an ACL granting you
// MUTEX_MODIFY_STATE rights (0x0001). The other interesting value
// in a Mutex's ACL is MUTEX_ALL_ACCESS (0x1F0001).
// You need SYNCHRONIZE to be able to open a handle to a mutex.
[Flags]
public enum MutexRights
{
Modify = 0x000001,
Delete = 0x010000,
ReadPermissions = 0x020000,
ChangePermissions = 0x040000,
TakeOwnership = 0x080000,
Synchronize = 0x100000, // SYNCHRONIZE
FullControl = 0x1F0001
}
public sealed class MutexAccessRule : AccessRule
{
// Constructor for creating access rules for registry objects
public MutexAccessRule(IdentityReference identity, MutexRights eventRights, AccessControlType type)
: this(identity, (int) eventRights, false, InheritanceFlags.None, PropagationFlags.None, type)
{
}
public MutexAccessRule(String identity, MutexRights eventRights, AccessControlType type)
: this(new NTAccount(identity), (int) eventRights, false, InheritanceFlags.None, PropagationFlags.None, type)
{
}
//
// Internal constructor to be called by public constructors
// and the access rule factory methods of {File|Folder}Security
//
internal MutexAccessRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type )
: base(
identity,
accessMask,
isInherited,
inheritanceFlags,
propagationFlags,
type )
{
}
public MutexRights MutexRights {
get { return (MutexRights) base.AccessMask; }
}
}
public sealed class MutexAuditRule : AuditRule
{
public MutexAuditRule(IdentityReference identity, MutexRights eventRights, AuditFlags flags)
: this(identity, (int) eventRights, false, InheritanceFlags.None, PropagationFlags.None, flags)
{
}
/* // Not in the spec
public MutexAuditRule(string identity, MutexRights eventRights, AuditFlags flags)
: this(new NTAccount(identity), (int) eventRights, false, InheritanceFlags.None, PropagationFlags.None, flags)
{
}
*/
internal MutexAuditRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
: base(identity, accessMask, isInherited, inheritanceFlags, propagationFlags, flags)
{
}
public MutexRights MutexRights {
get { return (MutexRights) base.AccessMask; }
}
}
public sealed class MutexSecurity : NativeObjectSecurity
{
public MutexSecurity()
: base(true, ResourceType.KernelObject)
{
}
[System.Security.SecuritySafeCritical] // auto-generated
public MutexSecurity(String name, AccessControlSections includeSections)
: base(true, ResourceType.KernelObject, name, includeSections, _HandleErrorCode, null)
{
// Let the underlying ACL API's demand unmanaged code permission.
}
[System.Security.SecurityCritical] // auto-generated
internal MutexSecurity(SafeWaitHandle handle, AccessControlSections includeSections)
: base(true, ResourceType.KernelObject, handle, includeSections, _HandleErrorCode, null)
{
// Let the underlying ACL API's demand unmanaged code permission.
}
[System.Security.SecurityCritical] // auto-generated
private static Exception _HandleErrorCode(int errorCode, string name, SafeHandle handle, object context)
{
System.Exception exception = null;
switch (errorCode) {
case Win32Native.ERROR_INVALID_NAME:
case Win32Native.ERROR_INVALID_HANDLE:
case Win32Native.ERROR_FILE_NOT_FOUND:
if ((name != null) && (name.Length != 0))
exception = new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name));
else
exception = new WaitHandleCannotBeOpenedException();
break;
default:
break;
}
return exception;
}
public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
{
return new MutexAccessRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type);
}
public override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
{
return new MutexAuditRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags);
}
internal AccessControlSections GetAccessControlSectionsFromChanges()
{
AccessControlSections persistRules = AccessControlSections.None;
if (AccessRulesModified)
persistRules = AccessControlSections.Access;
if (AuditRulesModified)
persistRules |= AccessControlSections.Audit;
if (OwnerModified)
persistRules |= AccessControlSections.Owner;
if (GroupModified)
persistRules |= AccessControlSections.Group;
return persistRules;
}
[System.Security.SecurityCritical] // auto-generated
internal void Persist(SafeWaitHandle handle)
{
// Let the underlying ACL API's demand unmanaged code.
WriteLock();
try
{
AccessControlSections persistSections = GetAccessControlSectionsFromChanges();
if (persistSections == AccessControlSections.None)
return; // Don't need to persist anything.
base.Persist(handle, persistSections);
OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false;
}
finally
{
WriteUnlock();
}
}
public void AddAccessRule(MutexAccessRule rule)
{
base.AddAccessRule(rule);
}
public void SetAccessRule(MutexAccessRule rule)
{
base.SetAccessRule(rule);
}
public void ResetAccessRule(MutexAccessRule rule)
{
base.ResetAccessRule(rule);
}
public bool RemoveAccessRule(MutexAccessRule rule)
{
return base.RemoveAccessRule(rule);
}
public void RemoveAccessRuleAll(MutexAccessRule rule)
{
base.RemoveAccessRuleAll(rule);
}
public void RemoveAccessRuleSpecific(MutexAccessRule rule)
{
base.RemoveAccessRuleSpecific(rule);
}
public void AddAuditRule(MutexAuditRule rule)
{
base.AddAuditRule(rule);
}
public void SetAuditRule(MutexAuditRule rule)
{
base.SetAuditRule(rule);
}
public bool RemoveAuditRule(MutexAuditRule rule)
{
return base.RemoveAuditRule(rule);
}
public void RemoveAuditRuleAll(MutexAuditRule rule)
{
base.RemoveAuditRuleAll(rule);
}
public void RemoveAuditRuleSpecific(MutexAuditRule rule)
{
base.RemoveAuditRuleSpecific(rule);
}
public override Type AccessRightType
{
get { return typeof(MutexRights); }
}
public override Type AccessRuleType
{
get { return typeof(MutexAccessRule); }
}
public override Type AuditRuleType
{
get { return typeof(MutexAuditRule); }
}
}
}

View File

@@ -0,0 +1,395 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Classes: NativeObjectSecurity class
**
**
===========================================================*/
using Microsoft.Win32;
using System;
using System.Collections;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace System.Security.AccessControl
{
using FileNotFoundException = System.IO.FileNotFoundException;
using System.Globalization;
using System.Diagnostics.Contracts;
public abstract class NativeObjectSecurity : CommonObjectSecurity
{
#region Private Members
private readonly ResourceType _resourceType;
private ExceptionFromErrorCode _exceptionFromErrorCode = null;
private object _exceptionContext = null;
private readonly uint ProtectedDiscretionaryAcl = 0x80000000;
private readonly uint ProtectedSystemAcl = 0x40000000;
private readonly uint UnprotectedDiscretionaryAcl = 0x20000000;
private readonly uint UnprotectedSystemAcl = 0x10000000;
#endregion
#region Delegates
[System.Security.SecuritySafeCritical] // auto-generated
internal protected delegate System.Exception ExceptionFromErrorCode( int errorCode, string name, SafeHandle handle, object context );
#endregion
#region Constructors
protected NativeObjectSecurity( bool isContainer, ResourceType resourceType )
: base( isContainer )
{
_resourceType = resourceType;
}
protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext)
: this(isContainer, resourceType)
{
_exceptionContext = exceptionContext;
_exceptionFromErrorCode = exceptionFromErrorCode;
}
[System.Security.SecurityCritical] // auto-generated
internal NativeObjectSecurity( ResourceType resourceType, CommonSecurityDescriptor securityDescriptor )
: this( resourceType, securityDescriptor, null )
{
}
[System.Security.SecurityCritical] // auto-generated
internal NativeObjectSecurity( ResourceType resourceType, CommonSecurityDescriptor securityDescriptor, ExceptionFromErrorCode exceptionFromErrorCode )
: base( securityDescriptor )
{
_resourceType = resourceType;
_exceptionFromErrorCode = exceptionFromErrorCode;
}
[System.Security.SecuritySafeCritical] // auto-generated
protected NativeObjectSecurity( bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext )
: this( resourceType, CreateInternal( resourceType, isContainer, name, null, includeSections, true, exceptionFromErrorCode, exceptionContext ), exceptionFromErrorCode)
{
}
protected NativeObjectSecurity( bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections )
: this( isContainer, resourceType, name, includeSections, null, null )
{
}
[System.Security.SecuritySafeCritical] // auto-generated
protected NativeObjectSecurity( bool isContainer, ResourceType resourceType, SafeHandle handle, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext )
: this( resourceType, CreateInternal( resourceType, isContainer, null, handle, includeSections, false, exceptionFromErrorCode, exceptionContext ), exceptionFromErrorCode)
{
}
[System.Security.SecuritySafeCritical] // auto-generated
protected NativeObjectSecurity( bool isContainer, ResourceType resourceType, SafeHandle handle, AccessControlSections includeSections )
: this( isContainer, resourceType, handle, includeSections, null, null )
{
}
#endregion
#region Private Methods
[System.Security.SecurityCritical] // auto-generated
private static CommonSecurityDescriptor CreateInternal( ResourceType resourceType, bool isContainer, string name, SafeHandle handle, AccessControlSections includeSections, bool createByName, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext )
{
int error;
RawSecurityDescriptor rawSD;
if ( createByName && name == null )
{
throw new ArgumentNullException( "name" );
}
else if ( !createByName && handle == null )
{
throw new ArgumentNullException( "handle" );
}
error = Win32.GetSecurityInfo( resourceType, name, handle, includeSections, out rawSD );
if ( error != Win32Native.ERROR_SUCCESS )
{
System.Exception exception = null;
if ( exceptionFromErrorCode != null )
{
exception = exceptionFromErrorCode( error, name, handle, exceptionContext );
}
if ( exception == null )
{
if ( error == Win32Native.ERROR_ACCESS_DENIED )
{
exception = new UnauthorizedAccessException();
}
else if ( error == Win32Native.ERROR_INVALID_OWNER )
{
exception = new InvalidOperationException( Environment.GetResourceString( "AccessControl_InvalidOwner" ) );
}
else if ( error == Win32Native.ERROR_INVALID_PRIMARY_GROUP )
{
exception = new InvalidOperationException( Environment.GetResourceString( "AccessControl_InvalidGroup" ));
}
else if ( error == Win32Native.ERROR_INVALID_PARAMETER )
{
exception = new InvalidOperationException( Environment.GetResourceString( "AccessControl_UnexpectedError", error ));
}
else if ( error == Win32Native.ERROR_INVALID_NAME )
{
exception = new ArgumentException(
Environment.GetResourceString( "Argument_InvalidName" ),
"name" );
}
else if ( error == Win32Native.ERROR_FILE_NOT_FOUND )
{
exception = ( name == null ? new FileNotFoundException() : new FileNotFoundException( name ));
}
else if ( error == Win32Native.ERROR_NO_SECURITY_ON_OBJECT )
{
exception = new NotSupportedException( Environment.GetResourceString( "AccessControl_NoAssociatedSecurity" ));
}
else
{
Contract.Assert( false, string.Format( CultureInfo.InvariantCulture, "Win32GetSecurityInfo() failed with unexpected error code {0}", error ));
exception = new InvalidOperationException( Environment.GetResourceString( "AccessControl_UnexpectedError", error ));
}
}
throw exception;
}
return new CommonSecurityDescriptor( isContainer, false /* isDS */, rawSD, true );
}
//
// Attempts to persist the security descriptor onto the object
//
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private void Persist( string name, SafeHandle handle, AccessControlSections includeSections, object exceptionContext )
{
WriteLock();
try
{
int error;
SecurityInfos securityInfo = 0;
SecurityIdentifier owner = null, group = null;
SystemAcl sacl = null;
DiscretionaryAcl dacl = null;
if (( includeSections & AccessControlSections.Owner ) != 0 && _securityDescriptor.Owner != null )
{
securityInfo |= SecurityInfos.Owner;
owner = _securityDescriptor.Owner;
}
if (( includeSections & AccessControlSections.Group ) != 0 && _securityDescriptor.Group != null )
{
securityInfo |= SecurityInfos.Group;
group = _securityDescriptor.Group;
}
if (( includeSections & AccessControlSections.Audit ) != 0 )
{
securityInfo |= SecurityInfos.SystemAcl;
if ( _securityDescriptor.IsSystemAclPresent &&
_securityDescriptor.SystemAcl != null &&
_securityDescriptor.SystemAcl.Count > 0 )
{
sacl = _securityDescriptor.SystemAcl;
}
else
{
sacl = null;
}
if (( _securityDescriptor.ControlFlags & ControlFlags.SystemAclProtected ) != 0 )
{
securityInfo = (SecurityInfos)((uint)securityInfo | ProtectedSystemAcl);
}
else
{
securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedSystemAcl);
}
}
if (( includeSections & AccessControlSections.Access ) != 0 && _securityDescriptor.IsDiscretionaryAclPresent )
{
securityInfo |= SecurityInfos.DiscretionaryAcl;
// if the DACL is in fact a crafted replaced for NULL replacement, then we will persist it as NULL
if (_securityDescriptor.DiscretionaryAcl.EveryOneFullAccessForNullDacl)
{
dacl = null;
}
else
{
dacl = _securityDescriptor.DiscretionaryAcl;
}
if (( _securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected ) != 0 )
{
securityInfo = (SecurityInfos)((uint)securityInfo | ProtectedDiscretionaryAcl);
}
else
{
securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedDiscretionaryAcl);
}
}
if ( securityInfo == 0 )
{
//
// Nothing to persist
//
return;
}
error = Win32.SetSecurityInfo( _resourceType, name, handle, securityInfo, owner, group, sacl, dacl );
if ( error != Win32Native.ERROR_SUCCESS )
{
System.Exception exception = null;
if ( _exceptionFromErrorCode != null )
{
exception = _exceptionFromErrorCode( error, name, handle, exceptionContext );
}
if ( exception == null )
{
if ( error == Win32Native.ERROR_ACCESS_DENIED )
{
exception = new UnauthorizedAccessException();
}
else if ( error == Win32Native.ERROR_INVALID_OWNER )
{
exception = new InvalidOperationException( Environment.GetResourceString( "AccessControl_InvalidOwner" ) );
}
else if ( error == Win32Native.ERROR_INVALID_PRIMARY_GROUP )
{
exception = new InvalidOperationException( Environment.GetResourceString( "AccessControl_InvalidGroup" ) );
}
else if ( error == Win32Native.ERROR_INVALID_NAME )
{
exception = new ArgumentException(
Environment.GetResourceString( "Argument_InvalidName" ),
"name" );
}
else if ( error == Win32Native.ERROR_INVALID_HANDLE )
{
exception = new NotSupportedException( Environment.GetResourceString( "AccessControl_InvalidHandle" ));
}
else if ( error == Win32Native.ERROR_FILE_NOT_FOUND )
{
exception = new FileNotFoundException();
}
else if (error == Win32Native.ERROR_NO_SECURITY_ON_OBJECT)
{
exception = new NotSupportedException(Environment.GetResourceString("AccessControl_NoAssociatedSecurity"));
}
else
{
Contract.Assert( false, string.Format( CultureInfo.InvariantCulture, "Unexpected error code {0}", error ));
exception = new InvalidOperationException( Environment.GetResourceString( "AccessControl_UnexpectedError", error ));
}
}
throw exception;
}
//
// Everything goes well, let us clean the modified flags.
// We are in proper write lock, so just go ahead
//
this.OwnerModified = false;
this.GroupModified = false;
this.AccessRulesModified = false;
this.AuditRulesModified = false;
}
finally
{
WriteUnlock();
}
}
#endregion
#region Protected Methods
//
// Persists the changes made to the object
// by calling the underlying Windows API
//
// This overloaded method takes a name of an existing object
//
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
protected sealed override void Persist( string name, AccessControlSections includeSections )
{
Persist(name, includeSections, _exceptionContext);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
protected void Persist( string name, AccessControlSections includeSections, object exceptionContext )
{
if (name == null)
{
throw new ArgumentNullException( "name" );
}
Contract.EndContractBlock();
Persist( name, null, includeSections, exceptionContext );
}
//
// Persists the changes made to the object
// by calling the underlying Windows API
//
// This overloaded method takes a handle to an existing object
//
[System.Security.SecuritySafeCritical] // auto-generated
protected sealed override void Persist( SafeHandle handle, AccessControlSections includeSections )
{
Persist(handle, includeSections, _exceptionContext);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
protected void Persist( SafeHandle handle, AccessControlSections includeSections, object exceptionContext )
{
if (handle == null)
{
throw new ArgumentNullException( "handle" );
}
Contract.EndContractBlock();
Persist( null, handle, includeSections, exceptionContext );
}
#endregion
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,384 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: ObjectSecurity
**
** Purpose: Generic Managed ACL wrapper
**
** Date: February 7, 2007
**
===========================================================*/
using System;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Permissions;
using System.Security.Principal;
using Microsoft.Win32.SafeHandles;
namespace System.Security.AccessControl {
public class AccessRule<T> : AccessRule where T : struct {
#region Constructors
//
// Constructors for creating access rules for file objects
//
public AccessRule(
IdentityReference identity,
T rights,
AccessControlType type)
: this(
identity,
(int)(object)rights,
false,
InheritanceFlags.None,
PropagationFlags.None,
type) { }
public AccessRule(
String identity,
T rights,
AccessControlType type)
: this(
new NTAccount(identity),
(int)(object)rights,
false,
InheritanceFlags.None,
PropagationFlags.None,
type) { }
//
// Constructor for creating access rules for folder objects
//
public AccessRule(
IdentityReference identity,
T rights,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type)
: this(
identity,
(int)(object)rights,
false,
inheritanceFlags,
propagationFlags,
type) { }
public AccessRule(
String identity,
T rights,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type)
: this(
new NTAccount(identity),
(int)(object)rights,
false,
inheritanceFlags,
propagationFlags,
type) { }
//
// Internal constructor to be called by public constructors
// and the access rule factory methods of ObjectSecurity
//
internal AccessRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type)
: base(
identity,
accessMask,
isInherited,
inheritanceFlags,
propagationFlags,
type) { }
#endregion
#region Public properties
public T Rights {
get { return (T)(object)base.AccessMask; }
}
#endregion
}
public class AuditRule<T> : AuditRule where T : struct {
#region Constructors
public AuditRule(
IdentityReference identity,
T rights,
AuditFlags flags)
: this(
identity,
rights,
InheritanceFlags.None,
PropagationFlags.None,
flags) {
}
public AuditRule(
IdentityReference identity,
T rights,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AuditFlags flags)
: this(
identity,
(int)(object)rights,
false,
inheritanceFlags,
propagationFlags,
flags) {
}
public AuditRule(
String identity,
T rights,
AuditFlags flags)
: this(
new NTAccount(identity),
rights,
InheritanceFlags.None,
PropagationFlags.None,
flags) {
}
public AuditRule(
String identity,
T rights,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AuditFlags flags)
: this(
new NTAccount(identity),
(int)(object)rights,
false,
inheritanceFlags,
propagationFlags,
flags) {
}
internal AuditRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AuditFlags flags)
: base(
identity,
accessMask,
isInherited,
inheritanceFlags,
propagationFlags,
flags) {
}
#endregion
#region Public properties
public T Rights {
get { return (T)(object)base.AccessMask; }
}
#endregion
}
public abstract class ObjectSecurity<T> : NativeObjectSecurity where T : struct {
#region Constructors
protected ObjectSecurity(bool isContainer, ResourceType resourceType)
: base(isContainer, resourceType, null, null) { }
protected ObjectSecurity(bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections)
: base(isContainer, resourceType, name, includeSections, null, null) { }
protected ObjectSecurity(bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext)
: base(isContainer, resourceType, name, includeSections, exceptionFromErrorCode, exceptionContext) { }
[System.Security.SecuritySafeCritical] // auto-generated
protected ObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle safeHandle, AccessControlSections includeSections)
: base(isContainer, resourceType, safeHandle, includeSections, null, null) { }
[System.Security.SecuritySafeCritical] // auto-generated
protected ObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle safeHandle, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext)
: base(isContainer, resourceType, safeHandle, includeSections, exceptionFromErrorCode, exceptionContext) { }
#endregion
#region Factories
public override AccessRule AccessRuleFactory(
IdentityReference identityReference,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type) {
return new AccessRule<T>(
identityReference,
accessMask,
isInherited,
inheritanceFlags,
propagationFlags,
type);
}
public override AuditRule AuditRuleFactory(
IdentityReference identityReference,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AuditFlags flags) {
return new AuditRule<T>(
identityReference,
accessMask,
isInherited,
inheritanceFlags,
propagationFlags,
flags);
}
#endregion
#region Private Methods
private AccessControlSections GetAccessControlSectionsFromChanges() {
AccessControlSections persistRules = AccessControlSections.None;
if (AccessRulesModified) {
persistRules = AccessControlSections.Access;
}
if (AuditRulesModified) {
persistRules |= AccessControlSections.Audit;
}
if (OwnerModified) {
persistRules |= AccessControlSections.Owner;
}
if (GroupModified) {
persistRules |= AccessControlSections.Group;
}
return persistRules;
}
#endregion
#region Protected Methods
// Use this in your own Persist after you have demanded any appropriate CAS permissions.
// Note that you will want your version to be internal and use a specialized Safe Handle.
// <SecurityKernel Critical="True" Ring="0">
// <Asserts Name="Declarative: [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)]" />
// </SecurityKernel>
[System.Security.SecuritySafeCritical] // auto-generated
[SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)]
protected internal void Persist(SafeHandle handle) {
WriteLock();
try {
AccessControlSections persistRules = GetAccessControlSectionsFromChanges();
base.Persist(handle, persistRules);
OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false;
}
finally {
WriteUnlock();
}
}
// Use this in your own Persist after you have demanded any appropriate CAS permissions.
// Note that you will want your version to be internal.
[System.Security.SecuritySafeCritical] // auto-generated
[SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)]
protected internal void Persist(String name) {
WriteLock();
try {
AccessControlSections persistRules = GetAccessControlSectionsFromChanges();
base.Persist(name, persistRules);
OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false;
}
finally {
WriteUnlock();
}
}
#endregion
#region Public Methods
// Override these if you need to do some custom bit remapping to hide any
// complexity from the user.
public virtual void AddAccessRule(AccessRule<T> rule) {
base.AddAccessRule(rule);
}
public virtual void SetAccessRule(AccessRule<T> rule) {
base.SetAccessRule(rule);
}
public virtual void ResetAccessRule(AccessRule<T> rule) {
base.ResetAccessRule(rule);
}
public virtual bool RemoveAccessRule(AccessRule<T> rule) {
return base.RemoveAccessRule(rule);
}
public virtual void RemoveAccessRuleAll(AccessRule<T> rule) {
base.RemoveAccessRuleAll(rule);
}
public virtual void RemoveAccessRuleSpecific(AccessRule<T> rule) {
base.RemoveAccessRuleSpecific(rule);
}
public virtual void AddAuditRule(AuditRule<T> rule) {
base.AddAuditRule(rule);
}
public virtual void SetAuditRule(AuditRule<T> rule) {
base.SetAuditRule(rule);
}
public virtual bool RemoveAuditRule(AuditRule<T> rule) {
return base.RemoveAuditRule(rule);
}
public virtual void RemoveAuditRuleAll(AuditRule<T> rule) {
base.RemoveAuditRuleAll(rule);
}
public virtual void RemoveAuditRuleSpecific(AuditRule<T> rule) {
base.RemoveAuditRuleSpecific(rule);
}
#endregion
#region some overrides
public override Type AccessRightType {
get { return typeof(T); }
}
public override Type AccessRuleType {
get { return typeof(AccessRule<T>); }
}
public override Type AuditRuleType {
get { return typeof(AuditRule<T>); }
}
#endregion
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,59 @@
using Microsoft.Win32;
using System;
using System.Runtime.Serialization;
using System.Text;
using System.Globalization;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
namespace System.Security.AccessControl
{
[Serializable]
public sealed class PrivilegeNotHeldException : UnauthorizedAccessException, ISerializable
{
private readonly string _privilegeName = null;
public PrivilegeNotHeldException()
: base( Environment.GetResourceString( "PrivilegeNotHeld_Default" ))
{
}
public PrivilegeNotHeldException( string privilege )
: base( string.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "PrivilegeNotHeld_Named" ), privilege ))
{
_privilegeName = privilege;
}
public PrivilegeNotHeldException( string privilege, Exception inner )
: base( string.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "PrivilegeNotHeld_Named" ), privilege ), inner )
{
_privilegeName = privilege;
}
internal PrivilegeNotHeldException( SerializationInfo info, StreamingContext context )
: base( info, context )
{
_privilegeName = info.GetString("PrivilegeName");
}
public string PrivilegeName
{
get { return _privilegeName; }
}
[System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData( SerializationInfo info, StreamingContext context )
{
if ( info == null )
{
throw new ArgumentNullException( "info" );
}
Contract.EndContractBlock();
base.GetObjectData(info, context);
info.AddValue("PrivilegeName", _privilegeName, typeof( string ));
}
}
}

View File

@@ -0,0 +1,329 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: RegistrySecurity
**
**
** Purpose: Managed ACL wrapper for registry keys.
**
**
===========================================================*/
using System;
using System.Collections;
using System.Security.Permissions;
using System.Security.Principal;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.IO;
namespace System.Security.AccessControl
{
// We derived this enum from the definitions of KEY_READ and such from
// winnt.h and from MSDN, plus some experimental validation with regedit.
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/registry_key_security_and_access_rights.asp
[Flags]
public enum RegistryRights
{
// No None field - An ACE with the value 0 cannot grant nor deny.
QueryValues = Win32Native.KEY_QUERY_VALUE, // 0x0001 query the values of a registry key
SetValue = Win32Native.KEY_SET_VALUE, // 0x0002 create, delete, or set a registry value
CreateSubKey = Win32Native.KEY_CREATE_SUB_KEY, // 0x0004 required to create a subkey of a specific key
EnumerateSubKeys = Win32Native.KEY_ENUMERATE_SUB_KEYS, // 0x0008 required to enumerate sub keys of a key
Notify = Win32Native.KEY_NOTIFY, // 0x0010 needed to request change notifications
CreateLink = Win32Native.KEY_CREATE_LINK, // 0x0020 reserved for system use
///
/// The Windows Kernel team agrees that it was a bad design to expose the WOW64_n options as permissions.
/// in the .NET Framework these options are exposed via the RegistryView enum
///
/// Reg64 = Win32Native.KEY_WOW64_64KEY, // 0x0100 operate on the 64-bit registry view
/// Reg32 = Win32Native.KEY_WOW64_32KEY, // 0x0200 operate on the 32-bit registry view
ExecuteKey = ReadKey,
ReadKey = Win32Native.STANDARD_RIGHTS_READ | QueryValues | EnumerateSubKeys | Notify,
WriteKey = Win32Native.STANDARD_RIGHTS_WRITE | SetValue | CreateSubKey,
Delete = 0x10000,
ReadPermissions = 0x20000,
ChangePermissions = 0x40000,
TakeOwnership = 0x80000,
FullControl = 0xF003F | Win32Native.STANDARD_RIGHTS_READ | Win32Native.STANDARD_RIGHTS_WRITE
}
public sealed class RegistryAccessRule : AccessRule
{
// Constructor for creating access rules for registry objects
public RegistryAccessRule(IdentityReference identity, RegistryRights registryRights, AccessControlType type)
: this(identity, (int) registryRights, false, InheritanceFlags.None, PropagationFlags.None, type)
{
}
public RegistryAccessRule(String identity, RegistryRights registryRights, AccessControlType type)
: this(new NTAccount(identity), (int) registryRights, false, InheritanceFlags.None, PropagationFlags.None, type)
{
}
public RegistryAccessRule(IdentityReference identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
: this(identity, (int) registryRights, false, inheritanceFlags, propagationFlags, type)
{
}
public RegistryAccessRule(string identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
: this(new NTAccount(identity), (int) registryRights, false, inheritanceFlags, propagationFlags, type)
{
}
//
// Internal constructor to be called by public constructors
// and the access rule factory methods of {File|Folder}Security
//
internal RegistryAccessRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type )
: base(
identity,
accessMask,
isInherited,
inheritanceFlags,
propagationFlags,
type )
{
}
public RegistryRights RegistryRights {
get { return (RegistryRights) base.AccessMask; }
}
}
public sealed class RegistryAuditRule : AuditRule
{
public RegistryAuditRule(IdentityReference identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
: this(identity, (int) registryRights, false, inheritanceFlags, propagationFlags, flags)
{
}
public RegistryAuditRule(string identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
: this(new NTAccount(identity), (int) registryRights, false, inheritanceFlags, propagationFlags, flags)
{
}
internal RegistryAuditRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
: base(identity, accessMask, isInherited, inheritanceFlags, propagationFlags, flags)
{
}
public RegistryRights RegistryRights {
get { return (RegistryRights) base.AccessMask; }
}
}
public sealed class RegistrySecurity : NativeObjectSecurity
{
public RegistrySecurity()
: base(true, ResourceType.RegistryKey)
{
}
/*
// The name of registry key must start with a predefined string,
// like CLASSES_ROOT, CURRENT_USER, MACHINE, and USERS. See
// MSDN's help for SetNamedSecurityInfo for details.
[SecurityPermission(SecurityAction.Assert, UnmanagedCode=true)]
internal RegistrySecurity(String name, AccessControlSections includeSections)
: base(true, ResourceType.RegistryKey, HKeyNameToWindowsName(name), includeSections)
{
new RegistryPermission(RegistryPermissionAccess.NoAccess, AccessControlActions.View, name).Demand();
}
*/
[System.Security.SecurityCritical] // auto-generated
[SecurityPermission(SecurityAction.Assert, UnmanagedCode=true)]
internal RegistrySecurity(SafeRegistryHandle hKey, String name, AccessControlSections includeSections)
: base(true, ResourceType.RegistryKey, hKey, includeSections, _HandleErrorCode, null )
{
new RegistryPermission(RegistryPermissionAccess.NoAccess, AccessControlActions.View, name).Demand();
}
[System.Security.SecurityCritical] // auto-generated
private static Exception _HandleErrorCode(int errorCode, string name, SafeHandle handle, object context)
{
System.Exception exception = null;
switch (errorCode) {
case Win32Native.ERROR_FILE_NOT_FOUND:
exception = new IOException(Environment.GetResourceString("Arg_RegKeyNotFound", errorCode));
break;
case Win32Native.ERROR_INVALID_NAME:
exception = new ArgumentException(Environment.GetResourceString("Arg_RegInvalidKeyName", "name"));
break;
case Win32Native.ERROR_INVALID_HANDLE:
exception = new ArgumentException(Environment.GetResourceString("AccessControl_InvalidHandle"));
break;
default:
break;
}
return exception;
}
public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
{
return new RegistryAccessRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type);
}
public override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
{
return new RegistryAuditRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags);
}
internal AccessControlSections GetAccessControlSectionsFromChanges()
{
AccessControlSections persistRules = AccessControlSections.None;
if (AccessRulesModified)
persistRules = AccessControlSections.Access;
if (AuditRulesModified)
persistRules |= AccessControlSections.Audit;
if (OwnerModified)
persistRules |= AccessControlSections.Owner;
if (GroupModified)
persistRules |= AccessControlSections.Group;
return persistRules;
}
/*
// See SetNamedSecurityInfo docs - we must start strings
// with names like CURRENT_USER, MACHINE, CLASSES_ROOT, etc.
// (Look at SE_OBJECT_TYPE, then the docs for SE_REGISTRY_KEY)
internal static String HKeyNameToWindowsName(String keyName)
{
if (keyName.StartsWith("HKEY_")) {
if (keyName.Equals("HKEY_LOCAL_MACHINE"))
return "MACHINE";
return keyName.Substring(5);
}
return keyName;
}
[SecurityPermission(SecurityAction.Assert, UnmanagedCode=true)]
internal void Persist(String keyName)
{
new RegistryPermission(RegistryPermissionAccess.NoAccess, AccessControlActions.Change, keyName).Demand();
AccessControlSections persistRules = GetAccessControlSectionsFromChanges();
if (persistRules == AccessControlSections.None)
return; // Don't need to persist anything.
String windowsKeyName = HKeyNameToWindowsName(keyName);
base.Persist(windowsKeyName, persistRules);
OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false;
}
*/
[System.Security.SecurityCritical] // auto-generated
[SecurityPermission(SecurityAction.Assert, UnmanagedCode=true)]
internal void Persist(SafeRegistryHandle hKey, String keyName)
{
new RegistryPermission(RegistryPermissionAccess.NoAccess, AccessControlActions.Change, keyName).Demand();
WriteLock();
try
{
AccessControlSections persistRules = GetAccessControlSectionsFromChanges();
if (persistRules == AccessControlSections.None)
return; // Don't need to persist anything.
base.Persist(hKey, persistRules);
OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false;
}
finally
{
WriteUnlock();
}
}
public void AddAccessRule(RegistryAccessRule rule)
{
base.AddAccessRule(rule);
}
public void SetAccessRule(RegistryAccessRule rule)
{
base.SetAccessRule(rule);
}
public void ResetAccessRule(RegistryAccessRule rule)
{
base.ResetAccessRule(rule);
}
public bool RemoveAccessRule(RegistryAccessRule rule)
{
return base.RemoveAccessRule(rule);
}
public void RemoveAccessRuleAll(RegistryAccessRule rule)
{
base.RemoveAccessRuleAll(rule);
}
public void RemoveAccessRuleSpecific(RegistryAccessRule rule)
{
base.RemoveAccessRuleSpecific(rule);
}
public void AddAuditRule(RegistryAuditRule rule)
{
base.AddAuditRule(rule);
}
public void SetAuditRule(RegistryAuditRule rule)
{
base.SetAuditRule(rule);
}
public bool RemoveAuditRule(RegistryAuditRule rule)
{
return base.RemoveAuditRule(rule);
}
public void RemoveAuditRuleAll(RegistryAuditRule rule)
{
base.RemoveAuditRuleAll(rule);
}
public void RemoveAuditRuleSpecific(RegistryAuditRule rule)
{
base.RemoveAuditRuleSpecific(rule);
}
public override Type AccessRightType
{
get { return typeof(RegistryRights); }
}
public override Type AccessRuleType
{
get { return typeof(RegistryAccessRule); }
}
public override Type AuditRuleType
{
get { return typeof(RegistryAuditRule); }
}
}
}

View File

@@ -0,0 +1,383 @@
using System;
using System.Collections;
using System.Security.Principal;
using System.Diagnostics.Contracts;
namespace System.Security.AccessControl
{
public enum AccessControlType
{
Allow = 0,
Deny = 1,
}
public abstract class AuthorizationRule
{
#region Private Members
private readonly IdentityReference _identity;
private readonly int _accessMask;
private readonly bool _isInherited;
private readonly InheritanceFlags _inheritanceFlags;
private readonly PropagationFlags _propagationFlags;
#endregion
#region Constructors
internal protected AuthorizationRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags )
{
if ( identity == null )
{
throw new ArgumentNullException( "identity" );
}
if ( accessMask == 0 )
{
throw new ArgumentException(
Environment.GetResourceString( "Argument_ArgumentZero" ),
"accessMask" );
}
if ( inheritanceFlags < InheritanceFlags.None || inheritanceFlags > (InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit) )
{
throw new ArgumentOutOfRangeException(
"inheritanceFlags",
Environment.GetResourceString( "Argument_InvalidEnumValue", inheritanceFlags, "InheritanceFlags" ));
}
if ( propagationFlags < PropagationFlags.None || propagationFlags > (PropagationFlags.NoPropagateInherit | PropagationFlags.InheritOnly) )
{
throw new ArgumentOutOfRangeException(
"propagationFlags",
Environment.GetResourceString( "Argument_InvalidEnumValue", inheritanceFlags, "PropagationFlags" ));
}
Contract.EndContractBlock();
if (identity.IsValidTargetType(typeof(SecurityIdentifier)) == false)
{
throw new ArgumentException(
Environment.GetResourceString("Arg_MustBeIdentityReferenceType"),
"identity");
}
_identity = identity;
_accessMask = accessMask;
_isInherited = isInherited;
_inheritanceFlags = inheritanceFlags;
if ( inheritanceFlags != 0 )
{
_propagationFlags = propagationFlags;
}
else
{
_propagationFlags = 0;
}
}
#endregion
#region Properties
public IdentityReference IdentityReference
{
get { return _identity; }
}
internal protected int AccessMask
{
get { return _accessMask; }
}
public bool IsInherited
{
get { return _isInherited; }
}
public InheritanceFlags InheritanceFlags
{
get { return _inheritanceFlags; }
}
public PropagationFlags PropagationFlags
{
get { return _propagationFlags; }
}
#endregion
}
public abstract class AccessRule : AuthorizationRule
{
#region Private Methods
private readonly AccessControlType _type;
#endregion
#region Constructors
protected AccessRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type )
: base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags )
{
if ( type != AccessControlType.Allow &&
type != AccessControlType.Deny )
{
throw new ArgumentOutOfRangeException(
"type",
Environment.GetResourceString( "ArgumentOutOfRange_Enum" ));
}
if ( inheritanceFlags < InheritanceFlags.None || inheritanceFlags > (InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit) )
{
throw new ArgumentOutOfRangeException(
"inheritanceFlags",
Environment.GetResourceString( "Argument_InvalidEnumValue", inheritanceFlags, "InheritanceFlags" ));
}
if ( propagationFlags < PropagationFlags.None || propagationFlags > (PropagationFlags.NoPropagateInherit | PropagationFlags.InheritOnly) )
{
throw new ArgumentOutOfRangeException(
"propagationFlags",
Environment.GetResourceString( "Argument_InvalidEnumValue", inheritanceFlags, "PropagationFlags" ));
}
Contract.EndContractBlock();
_type = type;
}
#endregion
#region Properties
public AccessControlType AccessControlType
{
get { return _type; }
}
#endregion
}
public abstract class ObjectAccessRule: AccessRule
{
#region Private Members
private readonly Guid _objectType;
private readonly Guid _inheritedObjectType;
private readonly ObjectAceFlags _objectFlags = ObjectAceFlags.None;
#endregion
#region Constructors
protected ObjectAccessRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, Guid objectType, Guid inheritedObjectType, AccessControlType type )
: base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, type )
{
if (( !objectType.Equals( Guid.Empty )) && (( accessMask & ObjectAce.AccessMaskWithObjectType ) != 0 ))
{
_objectType = objectType;
_objectFlags |= ObjectAceFlags.ObjectAceTypePresent;
}
else
{
_objectType = Guid.Empty;
}
if (( !inheritedObjectType.Equals( Guid.Empty )) && ((inheritanceFlags & InheritanceFlags.ContainerInherit ) != 0 ))
{
_inheritedObjectType = inheritedObjectType;
_objectFlags |= ObjectAceFlags.InheritedObjectAceTypePresent;
}
else
{
_inheritedObjectType = Guid.Empty;
}
}
#endregion
#region Properties
public Guid ObjectType
{
get { return _objectType; }
}
public Guid InheritedObjectType
{
get { return _inheritedObjectType; }
}
public ObjectAceFlags ObjectFlags
{
get { return _objectFlags; }
}
#endregion
}
public abstract class AuditRule : AuthorizationRule
{
#region Private Members
private readonly AuditFlags _flags;
#endregion
#region Constructors
protected AuditRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AuditFlags auditFlags )
: base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags )
{
if ( auditFlags == AuditFlags.None )
{
throw new ArgumentException(
Environment.GetResourceString( "Arg_EnumAtLeastOneFlag" ),
"auditFlags" );
}
else if (( auditFlags & ~( AuditFlags.Success | AuditFlags.Failure )) != 0 )
{
throw new ArgumentOutOfRangeException(
"auditFlags",
Environment.GetResourceString( "ArgumentOutOfRange_Enum" ));
}
_flags = auditFlags;
}
#endregion
#region Public Properties
public AuditFlags AuditFlags
{
get { return _flags; }
}
#endregion
}
public abstract class ObjectAuditRule: AuditRule
{
#region Private Members
private readonly Guid _objectType;
private readonly Guid _inheritedObjectType;
private readonly ObjectAceFlags _objectFlags = ObjectAceFlags.None;
#endregion
#region Constructors
protected ObjectAuditRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, Guid objectType, Guid inheritedObjectType, AuditFlags auditFlags )
: base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, auditFlags )
{
if (( !objectType.Equals( Guid.Empty )) && (( accessMask & ObjectAce.AccessMaskWithObjectType ) != 0 ))
{
_objectType = objectType;
_objectFlags |= ObjectAceFlags.ObjectAceTypePresent;
}
else
{
_objectType = Guid.Empty;
}
if (( !inheritedObjectType.Equals( Guid.Empty )) && ((inheritanceFlags & InheritanceFlags.ContainerInherit ) != 0 ))
{
_inheritedObjectType = inheritedObjectType;
_objectFlags |= ObjectAceFlags.InheritedObjectAceTypePresent;
}
else
{
_inheritedObjectType = Guid.Empty;
}
}
#endregion
#region Public Properties
public Guid ObjectType
{
get { return _objectType; }
}
public Guid InheritedObjectType
{
get { return _inheritedObjectType; }
}
public ObjectAceFlags ObjectFlags
{
get { return _objectFlags; }
}
#endregion
}
public sealed class AuthorizationRuleCollection : ReadOnlyCollectionBase
{
#region Constructors
internal AuthorizationRuleCollection()
: base()
{
}
#endregion
#region Internal methods
internal void AddRule( AuthorizationRule rule )
{
InnerList.Add( rule );
}
#endregion
#region ICollection Members
public void CopyTo( AuthorizationRule[] rules, int index )
{
(( ICollection )this ).CopyTo( rules, index );
}
#endregion
#region Public properties
public AuthorizationRule this[int index]
{
get { return InnerList[index] as AuthorizationRule; }
}
#endregion
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,386 @@
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if FEATURE_CORRUPTING_EXCEPTIONS
using System.Runtime.ExceptionServices;
#endif // FEATURE_CORRUPTING_EXCEPTIONS
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using System.Diagnostics.Contracts;
namespace System.Security.AccessControl
{
internal static class Win32
{
internal const System.Int32 TRUE = 1;
//
// Wrapper around advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW
//
[System.Security.SecurityCritical] // auto-generated
[SecurityPermission( SecurityAction.Assert, UnmanagedCode=true )]
internal static int ConvertSdToSddl(
byte[] binaryForm,
int requestedRevision,
SecurityInfos si,
out string resultSddl )
{
int errorCode;
IntPtr ByteArray;
uint ByteArraySize = 0;
if ( TRUE != Win32Native.ConvertSdToStringSd( binaryForm, ( uint )requestedRevision, ( uint )si, out ByteArray, ref ByteArraySize ))
{
errorCode = Marshal.GetLastWin32Error();
goto Error;
}
//
// Extract data from the returned pointer
//
resultSddl = Marshal.PtrToStringUni( ByteArray );
//
// Now is a good time to get rid of the returned pointer
//
Win32Native.LocalFree( ByteArray );
return 0;
Error:
resultSddl = null;
if ( errorCode == Win32Native.ERROR_NOT_ENOUGH_MEMORY )
{
throw new OutOfMemoryException();
}
return errorCode;
}
//
// Wrapper around advapi32.GetSecurityInfo
//
[System.Security.SecurityCritical] // auto-generated
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions] //
#endif // FEATURE_CORRUPTING_EXCEPTIONS
internal static int GetSecurityInfo(
ResourceType resourceType,
string name,
SafeHandle handle,
AccessControlSections accessControlSections,
out RawSecurityDescriptor resultSd
)
{
resultSd = null;
//
// Demand unmanaged code permission
// The integrator layer is free to assert this permission
// and, in turn, demand another permission of its caller
//
new SecurityPermission( SecurityPermissionFlag.UnmanagedCode ).Demand();
int errorCode;
IntPtr SidOwner, SidGroup, Dacl, Sacl, ByteArray;
SecurityInfos SecurityInfos = 0;
Privilege privilege = null;
if (( accessControlSections & AccessControlSections.Owner ) != 0 )
{
SecurityInfos |= SecurityInfos.Owner;
}
if (( accessControlSections & AccessControlSections.Group ) != 0 )
{
SecurityInfos |= SecurityInfos.Group;
}
if (( accessControlSections & AccessControlSections.Access ) != 0 )
{
SecurityInfos |= SecurityInfos.DiscretionaryAcl;
}
if (( accessControlSections & AccessControlSections.Audit ) != 0 )
{
SecurityInfos |= SecurityInfos.SystemAcl;
privilege = new Privilege( Privilege.Security );
}
// Ensure that the finally block will execute
RuntimeHelpers.PrepareConstrainedRegions();
try
{
if ( privilege != null )
{
try
{
privilege.Enable();
}
catch (PrivilegeNotHeldException)
{
// we will ignore this exception and press on just in case this is a remote resource
}
}
if ( name != null )
{
errorCode = ( int )Win32Native.GetSecurityInfoByName( name, ( uint )resourceType, ( uint )SecurityInfos, out SidOwner, out SidGroup, out Dacl, out Sacl, out ByteArray );
}
else if (handle != null)
{
if (handle.IsInvalid)
{
throw new ArgumentException(
Environment.GetResourceString( "Argument_InvalidSafeHandle" ),
"handle" );
}
else
{
errorCode = ( int )Win32Native.GetSecurityInfoByHandle( handle, ( uint )resourceType, ( uint )SecurityInfos, out SidOwner, out SidGroup, out Dacl, out Sacl, out ByteArray );
}
}
else
{
// both are null, shouldn't happen
throw new SystemException();
}
if ( errorCode == Win32Native.ERROR_SUCCESS && IntPtr.Zero.Equals(ByteArray) )
{
//
// This means that the object doesn't have a security descriptor. And thus we throw
// a specific exception for the caller to catch and handle properly.
//
throw new InvalidOperationException(Environment.GetResourceString( "InvalidOperation_NoSecurityDescriptor" ));
}
else if (errorCode == Win32Native.ERROR_NOT_ALL_ASSIGNED ||
errorCode == Win32Native.ERROR_PRIVILEGE_NOT_HELD)
{
throw new PrivilegeNotHeldException( Privilege.Security );
}
else if ( errorCode == Win32Native.ERROR_ACCESS_DENIED ||
errorCode == Win32Native.ERROR_CANT_OPEN_ANONYMOUS )
{
throw new UnauthorizedAccessException();
}
if ( errorCode != Win32Native.ERROR_SUCCESS )
{
goto Error;
}
}
catch
{
// protection against exception filter-based luring attacks
if ( privilege != null )
{
privilege.Revert();
}
throw;
}
finally
{
if ( privilege != null )
{
privilege.Revert();
}
}
//
// Extract data from the returned pointer
//
uint Length = Win32Native.GetSecurityDescriptorLength( ByteArray );
byte[] BinaryForm = new byte[Length];
Marshal.Copy( ByteArray, BinaryForm, 0, ( int )Length );
Win32Native.LocalFree( ByteArray );
resultSd = new RawSecurityDescriptor( BinaryForm, 0 );
return Win32Native.ERROR_SUCCESS;
Error:
if ( errorCode == Win32Native.ERROR_NOT_ENOUGH_MEMORY )
{
throw new OutOfMemoryException();
}
return errorCode;
}
//
// Wrapper around advapi32.SetNamedSecurityInfoW and advapi32.SetSecurityInfo
//
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions] //
#endif // FEATURE_CORRUPTING_EXCEPTIONS
internal static int SetSecurityInfo(
ResourceType type,
string name,
SafeHandle handle,
SecurityInfos securityInformation,
SecurityIdentifier owner,
SecurityIdentifier group,
GenericAcl sacl,
GenericAcl dacl )
{
int errorCode;
int Length;
byte[] OwnerBinary = null, GroupBinary = null, SaclBinary = null, DaclBinary = null;
Privilege securityPrivilege = null;
//
// Demand unmanaged code permission
// The integrator layer is free to assert this permission
// and, in turn, demand another permission of its caller
//
new SecurityPermission( SecurityPermissionFlag.UnmanagedCode ).Demand();
if ( owner != null )
{
Length = owner.BinaryLength;
OwnerBinary = new byte[Length];
owner.GetBinaryForm( OwnerBinary, 0 );
}
if ( group != null )
{
Length = group.BinaryLength;
GroupBinary = new byte[Length];
group.GetBinaryForm( GroupBinary, 0 );
}
if ( dacl != null )
{
Length = dacl.BinaryLength;
DaclBinary = new byte[Length];
dacl.GetBinaryForm( DaclBinary, 0 );
}
if ( sacl != null )
{
Length = sacl.BinaryLength;
SaclBinary = new byte[Length];
sacl.GetBinaryForm( SaclBinary, 0 );
}
if ( ( securityInformation & SecurityInfos.SystemAcl ) != 0 )
{
//
// Enable security privilege if trying to set a SACL.
// Note: even setting it by handle needs this privilege enabled!
//
securityPrivilege = new Privilege( Privilege.Security );
}
// Ensure that the finally block will execute
RuntimeHelpers.PrepareConstrainedRegions();
try
{
if ( securityPrivilege != null )
{
try
{
securityPrivilege.Enable();
}
catch (PrivilegeNotHeldException)
{
// we will ignore this exception and press on just in case this is a remote resource
}
}
if ( name != null )
{
errorCode = ( int )Win32Native.SetSecurityInfoByName( name, ( uint )type, ( uint )securityInformation, OwnerBinary, GroupBinary, DaclBinary, SaclBinary );
}
else if (handle != null)
{
if (handle.IsInvalid)
{
throw new ArgumentException(
Environment.GetResourceString( "Argument_InvalidSafeHandle" ),
"handle" );
}
else
{
errorCode = ( int )Win32Native.SetSecurityInfoByHandle( handle, ( uint )type, ( uint )securityInformation, OwnerBinary, GroupBinary, DaclBinary, SaclBinary );
}
}
else
{
// both are null, shouldn't happen
Contract.Assert( false, "Internal error: both name and handle are null" );
throw new InvalidProgramException();
}
if (errorCode == Win32Native.ERROR_NOT_ALL_ASSIGNED ||
errorCode == Win32Native.ERROR_PRIVILEGE_NOT_HELD)
{
throw new PrivilegeNotHeldException( Privilege.Security );
}
else if ( errorCode == Win32Native.ERROR_ACCESS_DENIED ||
errorCode == Win32Native.ERROR_CANT_OPEN_ANONYMOUS )
{
throw new UnauthorizedAccessException();
}
else if ( errorCode != Win32Native.ERROR_SUCCESS )
{
goto Error;
}
}
catch
{
// protection against exception filter-based luring attacks
if ( securityPrivilege != null )
{
securityPrivilege.Revert();
}
throw;
}
finally
{
if ( securityPrivilege != null )
{
securityPrivilege.Revert();
}
}
return 0;
Error:
if ( errorCode == Win32Native.ERROR_NOT_ENOUGH_MEMORY )
{
throw new OutOfMemoryException();
}
return errorCode;
}
}
}

View File

@@ -0,0 +1,211 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
using System.Runtime.InteropServices;
namespace System.Security
{
// DynamicSecurityMethodAttribute:
// Indicates that calling the target method requires space for a security
// object to be allocated on the callers stack. This attribute is only ever
// set on certain security methods defined within mscorlib.
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false )]
sealed internal class DynamicSecurityMethodAttribute : System.Attribute
{
}
// SuppressUnmanagedCodeSecurityAttribute:
// Indicates that the target P/Invoke method(s) should skip the per-call
// security checked for unmanaged code permission.
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = true, Inherited = false )]
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class SuppressUnmanagedCodeSecurityAttribute : System.Attribute
{
}
// UnverifiableCodeAttribute:
// Indicates that the target module contains unverifiable code.
[AttributeUsage(AttributeTargets.Module, AllowMultiple = true, Inherited = false )]
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class UnverifiableCodeAttribute : System.Attribute
{
}
// AllowPartiallyTrustedCallersAttribute:
// Indicates that the Assembly is secure and can be used by untrusted
// and semitrusted clients
// For v.1, this is valid only on Assemblies, but could be expanded to
// include Module, Method, class
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false )]
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class AllowPartiallyTrustedCallersAttribute : System.Attribute
{
private PartialTrustVisibilityLevel _visibilityLevel;
public AllowPartiallyTrustedCallersAttribute () { }
public PartialTrustVisibilityLevel PartialTrustVisibilityLevel
{
get { return _visibilityLevel; }
set { _visibilityLevel = value; }
}
}
public enum PartialTrustVisibilityLevel
{
VisibleToAllHosts = 0,
NotVisibleByDefault = 1
}
#if !FEATURE_CORECLR
[Obsolete("SecurityCriticalScope is only used for .NET 2.0 transparency compatibility.")]
public enum SecurityCriticalScope
{
Explicit = 0,
Everything = 0x1
}
#endif // FEATURE_CORECLR
// SecurityCriticalAttribute
// Indicates that the decorated code or assembly performs security critical operations (e.g. Assert, "unsafe", LinkDemand, etc.)
// The attribute can be placed on most targets, except on arguments/return values.
[AttributeUsage(AttributeTargets.Assembly |
AttributeTargets.Class |
AttributeTargets.Struct |
AttributeTargets.Enum |
AttributeTargets.Constructor |
AttributeTargets.Method |
AttributeTargets.Field |
AttributeTargets.Interface |
AttributeTargets.Delegate,
AllowMultiple = false,
Inherited = false )]
sealed public class SecurityCriticalAttribute : System.Attribute
{
#pragma warning disable 618 // We still use SecurityCriticalScope for v2 compat
#if !FEATURE_CORECLR
private SecurityCriticalScope _val;
#endif // FEATURE_CORECLR
public SecurityCriticalAttribute () {}
#if !FEATURE_CORECLR
public SecurityCriticalAttribute(SecurityCriticalScope scope)
{
_val = scope;
}
[Obsolete("SecurityCriticalScope is only used for .NET 2.0 transparency compatibility.")]
public SecurityCriticalScope Scope {
get {
return _val;
}
}
#endif // FEATURE_CORECLR
#pragma warning restore 618
}
// SecurityTreatAsSafeAttribute:
// Indicates that the code may contain violations to the security critical rules (e.g. transitions from
// critical to non-public transparent, transparent to non-public critical, etc.), has been audited for
// security concerns and is considered security clean.
// At assembly-scope, all rule checks will be suppressed within the assembly and for calls made against the assembly.
// At type-scope, all rule checks will be suppressed for members within the type and for calls made against the type.
// At member level (e.g. field and method) the code will be treated as public - i.e. no rule checks for the members.
[AttributeUsage(AttributeTargets.Assembly |
AttributeTargets.Class |
AttributeTargets.Struct |
AttributeTargets.Enum |
AttributeTargets.Constructor |
AttributeTargets.Method |
AttributeTargets.Field |
AttributeTargets.Interface |
AttributeTargets.Delegate,
AllowMultiple = false,
Inherited = false )]
[Obsolete("SecurityTreatAsSafe is only used for .NET 2.0 transparency compatibility. Please use the SecuritySafeCriticalAttribute instead.")]
sealed public class SecurityTreatAsSafeAttribute : System.Attribute
{
public SecurityTreatAsSafeAttribute () { }
}
// SecuritySafeCriticalAttribute:
// Indicates that the code may contain violations to the security critical rules (e.g. transitions from
// critical to non-public transparent, transparent to non-public critical, etc.), has been audited for
// security concerns and is considered security clean. Also indicates that the code is considered SecurityCritical.
// The effect of this attribute is as if the code was marked [SecurityCritical][SecurityTreatAsSafe].
// At assembly-scope, all rule checks will be suppressed within the assembly and for calls made against the assembly.
// At type-scope, all rule checks will be suppressed for members within the type and for calls made against the type.
// At member level (e.g. field and method) the code will be treated as public - i.e. no rule checks for the members.
[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Struct |
AttributeTargets.Enum |
AttributeTargets.Constructor |
AttributeTargets.Method |
AttributeTargets.Field |
AttributeTargets.Interface |
AttributeTargets.Delegate,
AllowMultiple = false,
Inherited = false )]
sealed public class SecuritySafeCriticalAttribute : System.Attribute
{
public SecuritySafeCriticalAttribute () { }
}
// SecurityTransparentAttribute:
// Indicates the assembly contains only transparent code.
// Security critical actions will be restricted or converted into less critical actions. For example,
// Assert will be restricted, SuppressUnmanagedCode, LinkDemand, unsafe, and unverifiable code will be converted
// into Full-Demands.
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false )]
sealed public class SecurityTransparentAttribute : System.Attribute
{
public SecurityTransparentAttribute () {}
}
#if !FEATURE_CORECLR
public enum SecurityRuleSet : byte
{
None = 0,
Level1 = 1, // v2.0 transparency model
Level2 = 2, // v4.0 transparency model
}
// SecurityRulesAttribute
//
// Indicates which set of security rules an assembly was authored against, and therefore which set of
// rules the runtime should enforce on the assembly. For instance, an assembly marked with
// [SecurityRules(SecurityRuleSet.Level1)] will follow the v2.0 transparency rules, where transparent code
// can call a LinkDemand by converting it to a full demand, public critical methods are implicitly
// treat as safe, and the remainder of the v2.0 rules apply.
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class SecurityRulesAttribute : Attribute
{
private SecurityRuleSet m_ruleSet;
private bool m_skipVerificationInFullTrust = false;
public SecurityRulesAttribute(SecurityRuleSet ruleSet)
{
m_ruleSet = ruleSet;
}
// Should fully trusted transparent code skip IL verification
public bool SkipVerificationInFullTrust
{
get { return m_skipVerificationInFullTrust; }
set { m_skipVerificationInFullTrust = value; }
}
public SecurityRuleSet RuleSet
{
get { return m_ruleSet; }
}
}
#endif // !FEATURE_CORECLR
}

View File

@@ -0,0 +1,344 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// <OWNER>[....]</OWNER>
//
using System;
using System.Diagnostics.Contracts;
using System.Security.Permissions;
using Microsoft.Win32;
namespace System.Security
{
internal static class BuiltInPermissionSets
{
//
// Raw PermissionSet XML - the built in permission sets are expressed in XML form since they contain
// permissions from assemblies other than mscorlib.
//
private static readonly string s_everythingXml =
@"<PermissionSet class = ""System.Security.NamedPermissionSet""
version = ""1""
Name = ""Everything""
Description = """ + Environment.GetResourceString("Policy_PS_Everything") + @"""
<IPermission class = ""System.Data.OleDb.OleDbPermission, " + AssemblyRef.SystemData + @"""
version = ""1""
Unrestricted = ""true"" />
<IPermission class = ""System.Data.SqlClient.SqlClientPermission, " + AssemblyRef.SystemData + @"""
version = ""1""
Unrestricted = ""true"" />
<IPermission class = ""System.Diagnostics.PerformanceCounterPermission, " + AssemblyRef.System + @"""
version = ""1""
Unrestricted = ""true"" />
<IPermission class = ""System.Net.DnsPermission, " + AssemblyRef.System + @"""
version = ""1""
Unrestricted = ""true"" />
<IPermission class = ""System.Net.SocketPermission, " + AssemblyRef.System + @"""
version = ""1""
Unrestricted = ""true"" />
<IPermission class = ""System.Net.WebPermission, " + AssemblyRef.System + @"""
version = ""1""
Unrestricted = ""true"" />
<IPermission class = ""System.Security.Permissions.DataProtectionPermission, " + AssemblyRef.SystemSecurity + @"""
version = ""1""
Unrestricted = ""true"" />
<IPermission class = ""System.Security.Permissions.EnvironmentPermission, " + AssemblyRef.Mscorlib + @"""
version = ""1""
Unrestricted = ""true"" />
<IPermission class = ""System.Diagnostics.EventLogPermission, " + AssemblyRef.System + @"""
version = ""1""
Unrestricted = ""true"" />
<IPermission class = ""System.Security.Permissions.FileDialogPermission, " + AssemblyRef.Mscorlib + @"""
version = ""1""
Unrestricted = ""true"" />
<IPermission class = ""System.Security.Permissions.FileIOPermission, " + AssemblyRef.Mscorlib + @"""
version = ""1""
Unrestricted = ""true"" />
<IPermission class = ""System.Security.Permissions.IsolatedStorageFilePermission, " + AssemblyRef.Mscorlib + @"""
version = ""1""
Unrestricted = ""true"" />
<IPermission class = ""System.Security.Permissions.KeyContainerPermission, " + AssemblyRef.Mscorlib + @"""
version = ""1""
Unrestricted = ""true"" />
<IPermission class = ""System.Drawing.Printing.PrintingPermission, " + AssemblyRef.SystemDrawing + @"""
version = ""1""
Unrestricted = ""true"" />
<IPermission class = ""System.Security.Permissions.ReflectionPermission, " + AssemblyRef.Mscorlib + @"""
version = ""1""
Unrestricted = ""true"" />
<IPermission class = ""System.Security.Permissions.RegistryPermission, " + AssemblyRef.Mscorlib + @"""
version = ""1""
Unrestricted = ""true"" />
<IPermission class = ""System.Security.Permissions.SecurityPermission, " + AssemblyRef.Mscorlib + @"""
version = ""1""
Flags = ""Assertion, UnmanagedCode, Execution, ControlThread, ControlEvidence, ControlPolicy, ControlAppDomain, SerializationFormatter, ControlDomainPolicy, ControlPrincipal, RemotingConfiguration, Infrastructure, BindingRedirects"" />
<IPermission class = ""System.Security.Permissions.UIPermission, " + AssemblyRef.Mscorlib + @"""
version = ""1""
Unrestricted = ""true"" />
<IPermission class = ""System.Security.Permissions.StorePermission, " + AssemblyRef.System + @"""
version = ""1""
Unrestricted = ""true"" />
<IPermission class = ""System.Security.Permissions.TypeDescriptorPermission, " + AssemblyRef.System + @"""
version = ""1""
Unrestricted = ""true"" />
</PermissionSet>";
private static readonly string s_executionXml =
@"<PermissionSet class = ""System.Security.NamedPermissionSet""
version = ""1""
Name = ""Execution""
Description = """ + Environment.GetResourceString("Policy_PS_Execution") + @""">
<IPermission class = ""System.Security.Permissions.SecurityPermission, " + AssemblyRef.Mscorlib + @"""
version = ""1""
Flags = ""Execution"" />
</PermissionSet>";
private static readonly string s_fullTrustXml =
@"<PermissionSet class = ""System.Security.NamedPermissionSet""
version = ""1""
Unrestricted = ""true""
Name = ""FullTrust""
Description = """ + Environment.GetResourceString("Policy_PS_FullTrust") + @""" />";
private static readonly string s_internetXml =
@"<PermissionSet class = ""System.Security.NamedPermissionSet""
version = ""1""
Name = ""Internet""
Description = """ + Environment.GetResourceString("Policy_PS_Internet") + @""">
<IPermission class = ""System.Drawing.Printing.PrintingPermission, " + AssemblyRef.SystemDrawing + @"""
version = ""1""
Level = ""SafePrinting"" />
<IPermission class = ""System.Security.Permissions.FileDialogPermission, " + AssemblyRef.Mscorlib + @"""
version = ""1""
Access = ""Open"" />
<IPermission class = ""System.Security.Permissions.IsolatedStorageFilePermission, " + AssemblyRef.Mscorlib + @"""
version = ""1""
UserQuota = ""1024000""
Allowed = ""ApplicationIsolationByUser"" />
<IPermission class = ""System.Security.Permissions.SecurityPermission, " + AssemblyRef.Mscorlib + @"""
version = ""1""
Flags = ""Execution"" />
<IPermission class = ""System.Security.Permissions.UIPermission, " + AssemblyRef.Mscorlib + @"""
version = ""1""
Window = ""SafeTopLevelWindows""
Clipboard = ""OwnClipboard"" />
</PermissionSet>";
private static readonly string s_localIntranetXml =
@"<PermissionSet class = ""System.Security.NamedPermissionSet""
version = ""1""
Name = ""LocalIntranet""
Description = """ + Environment.GetResourceString("Policy_PS_LocalIntranet") + @""" >
<IPermission class = ""System.Drawing.Printing.PrintingPermission, " + AssemblyRef.SystemDrawing + @"""
version = ""1""
Level = ""DefaultPrinting"" />
<IPermission class = ""System.Net.DnsPermission, " + AssemblyRef.System + @"""
version = ""1""
Unrestricted = ""true"" />
<IPermission class = ""System.Security.Permissions.EnvironmentPermission, " + AssemblyRef.Mscorlib + @"""
version = ""1""
Read = ""USERNAME"" />
<IPermission class = ""System.Security.Permissions.FileDialogPermission, " + AssemblyRef.Mscorlib + @"""
version = ""1""
Unrestricted = ""true"" />
<IPermission class = ""System.Security.Permissions.IsolatedStorageFilePermission, " + AssemblyRef.Mscorlib + @"""
version = ""1""
Allowed = ""AssemblyIsolationByUser""
UserQuota = ""9223372036854775807""
Expiry = ""9223372036854775807""
Permanent = ""true"" />
<IPermission class = ""System.Security.Permissions.ReflectionPermission, " + AssemblyRef.Mscorlib + @"""
version = ""1""
Flags = ""ReflectionEmit, RestrictedMemberAccess"" />
<IPermission class = ""System.Security.Permissions.SecurityPermission, " + AssemblyRef.Mscorlib + @"""
version = ""1""
Flags = ""Execution, Assertion, BindingRedirects "" />
<IPermission class = ""System.Security.Permissions.TypeDescriptorPermission, " + AssemblyRef.System + @"""
version = ""1""
Flags = ""RestrictedRegistrationAccess"" />
<IPermission class = ""System.Security.Permissions.UIPermission, " + AssemblyRef.Mscorlib + @"""
version = ""1""
Unrestricted = ""true"" />
</PermissionSet>";
private static readonly string s_nothingXml =
@"<PermissionSet class = ""System.Security.NamedPermissionSet""
version = ""1""
Name = ""Nothing""
Description = """ + Environment.GetResourceString("Policy_PS_Nothing") + @""" />";
private static readonly string s_skipVerificationXml =
@"<PermissionSet class = ""System.Security.NamedPermissionSet""
version = ""1""
Name = ""SkipVerification""
Description = """ + Environment.GetResourceString("Policy_PS_SkipVerification") + @""">
<IPermission class = ""System.Security.Permissions.SecurityPermission, " + AssemblyRef.Mscorlib + @"""
version = ""1""
Flags = ""SkipVerification"" />
</PermissionSet>";
#if FEATURE_CAS_POLICY
private const string s_wpfExtensionXml =
@"<PermissionSet class = ""System.Security.PermissionSet""
version = ""1"">
<IPermission class = ""System.Security.Permissions.MediaPermission, " + AssemblyRef.WindowsBase + @"""
version = ""1""
Audio=""SafeAudio"" Video=""SafeVideo"" Image=""SafeImage"" />
<IPermission class = ""System.Security.Permissions.WebBrowserPermission, " + AssemblyRef.WindowsBase + @"""
version = ""1""
Level=""Safe"" />
</PermissionSet>";
private const string s_wpfExtensionUnrestrictedXml =
@"<PermissionSet class = ""System.Security.PermissionSet""
version = ""1"">
<IPermission class = ""System.Security.Permissions.MediaPermission, " + AssemblyRef.WindowsBase + @"""
version = ""1""
Unrestricted = ""true"" />
<IPermission class = ""System.Security.Permissions.WebBrowserPermission, " + AssemblyRef.WindowsBase + @"""
version = ""1""
Unrestricted = ""true"" />
</PermissionSet>";
#endif //FEATURE_CAS_POLICY
//
// Built in permission set objects
//
private static NamedPermissionSet s_everything;
private static NamedPermissionSet s_execution;
private static NamedPermissionSet s_fullTrust;
private static NamedPermissionSet s_internet;
private static NamedPermissionSet s_localIntranet;
private static NamedPermissionSet s_nothing;
private static NamedPermissionSet s_skipVerification;
//
// Standard permission sets
//
internal static NamedPermissionSet Everything
{
get { return GetOrDeserializeExtendablePermissionSet(ref s_everything, s_everythingXml
#if FEATURE_CAS_POLICY
, s_wpfExtensionUnrestrictedXml
#endif // FEATURE_CAS_POLICY
); }
}
internal static NamedPermissionSet Execution
{
get { return GetOrDeserializePermissionSet(ref s_execution, s_executionXml); }
}
internal static NamedPermissionSet FullTrust
{
get { return GetOrDeserializePermissionSet(ref s_fullTrust, s_fullTrustXml); }
}
internal static NamedPermissionSet Internet
{
get { return GetOrDeserializeExtendablePermissionSet(ref s_internet, s_internetXml
#if FEATURE_CAS_POLICY
, s_wpfExtensionXml
#endif // FEATURE_CAS_POLICY
); }
}
internal static NamedPermissionSet LocalIntranet
{
get { return GetOrDeserializeExtendablePermissionSet(ref s_localIntranet, s_localIntranetXml
#if FEATURE_CAS_POLICY
, s_wpfExtensionXml
#endif // FEATURE_CAS_POLICY
); }
}
internal static NamedPermissionSet Nothing
{
get { return GetOrDeserializePermissionSet(ref s_nothing, s_nothingXml); }
}
internal static NamedPermissionSet SkipVerification
{
get { return GetOrDeserializePermissionSet(ref s_skipVerification, s_skipVerificationXml); }
}
//
// Utility methods to construct the permission set objects from the well known XML and any permission
// set extensions if necessary
//
private static NamedPermissionSet GetOrDeserializeExtendablePermissionSet(ref NamedPermissionSet permissionSet,
string permissionSetXml
#if FEATURE_CAS_POLICY
,string extensionXml
#endif // FEATURE_CAS_POLICY
)
{
Contract.Requires(!String.IsNullOrEmpty(permissionSetXml));
#if FEATURE_CAS_POLICY
Contract.Requires(!String.IsNullOrEmpty(extensionXml));
#endif // FEATURE_CAS_POLICY
if (permissionSet == null)
{
#if FEATURE_CAS_POLICY
SecurityElement securityElement = SecurityElement.FromString(permissionSetXml);
NamedPermissionSet deserializedPermissionSet = new NamedPermissionSet(securityElement);
PermissionSet extensions = GetPermissionSetExtensions(extensionXml);
deserializedPermissionSet.InplaceUnion(extensions);
permissionSet = deserializedPermissionSet;
#endif // FEATURE_CAS_POLICY
}
return permissionSet.Copy() as NamedPermissionSet;
}
private static NamedPermissionSet GetOrDeserializePermissionSet(ref NamedPermissionSet permissionSet,
string permissionSetXml)
{
Contract.Assert(!String.IsNullOrEmpty(permissionSetXml));
#if FEATURE_CAS_POLICY
if (permissionSet == null)
{
SecurityElement securityElement = SecurityElement.FromString(permissionSetXml);
NamedPermissionSet deserializedPermissionSet = new NamedPermissionSet(securityElement);
permissionSet = deserializedPermissionSet;
}
#endif // FEATURE_CAS_POLICY
return permissionSet.Copy() as NamedPermissionSet;
}
#if FEATURE_CAS_POLICY
private static PermissionSet GetPermissionSetExtensions(string extensionXml)
{
Contract.Requires(!String.IsNullOrEmpty(extensionXml));
SecurityElement se = SecurityElement.FromString(extensionXml);
// Return the permission set extension only if WPF is in the present framework profile.
// XMLUtil.GetClassFromElement() helps do the quickest check, with no exception thrown and
// minimal parsing.
SecurityElement firstPermission = (SecurityElement)se.Children[0];
if (System.Security.Util.XMLUtil.GetClassFromElement(firstPermission, /*ignoreTypeLoadFailures*/true) != null)
{
PermissionSet extensions = new NamedPermissionSet(se);
return extensions;
}
return null;
}
#endif // FEATURE_CAS_POLICY
}
}

Some files were not shown because too many files have changed in this diff Show More