Exemplo n.º 1
0
        [System.Security.SecurityCritical]  // auto-generated
        internal static void SetKeySetSecurityInfo (SafeProvHandle hProv, CryptoKeySecurity cryptoKeySecurity, AccessControlSections accessControlSections) {
            SecurityInfos securityInfo = 0;
            Privilege privilege = null;

            if ((accessControlSections & AccessControlSections.Owner) != 0 && cryptoKeySecurity._securityDescriptor.Owner != null)
                securityInfo |= SecurityInfos.Owner;
            if ((accessControlSections & AccessControlSections.Group) != 0 && cryptoKeySecurity._securityDescriptor.Group != null)
                securityInfo |= SecurityInfos.Group;
            if ((accessControlSections & AccessControlSections.Audit) != 0)
                securityInfo |= SecurityInfos.SystemAcl;
            if ((accessControlSections & AccessControlSections.Access) != 0 && cryptoKeySecurity._securityDescriptor.IsDiscretionaryAclPresent)
                securityInfo |= SecurityInfos.DiscretionaryAcl;

            if (securityInfo == 0) {
                // Nothing to persist
                return;
            }

            int error = 0;

            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                if ((securityInfo & SecurityInfos.SystemAcl) != 0) {
                    privilege = new Privilege("SeSecurityPrivilege");
                    privilege.Enable();
                }

                byte[] sd = cryptoKeySecurity.GetSecurityDescriptorBinaryForm();
                if (sd != null && sd.Length > 0)
                    error = SetKeySetSecurityInfo (hProv, securityInfo, sd);
            }
            finally {
                if (privilege != null)
                    privilege.Revert();
            }

            if (error == Win32Native.ERROR_ACCESS_DENIED || error == Win32Native.ERROR_INVALID_OWNER || error == Win32Native.ERROR_INVALID_PRIMARY_GROUP)
                throw new UnauthorizedAccessException();
            else if (error == Win32Native.ERROR_PRIVILEGE_NOT_HELD)
                throw new PrivilegeNotHeldException("SeSecurityPrivilege");
            else if (error == Win32Native.ERROR_INVALID_HANDLE)
                throw new NotSupportedException(Environment.GetResourceString("AccessControl_InvalidHandle"));
            else if (error != Win32Native.ERROR_SUCCESS)
                throw new CryptographicException(error);
        }
Exemplo n.º 2
0
        //
        // Wrapper around advapi32.GetSecurityInfo
        //

        internal static int GetSecurityInfo(
            ResourceType resourceType,
            string name,
            SafeHandle handle,
            AccessControlSections accessControlSections,
            out RawSecurityDescriptor resultSd
            )
        {
            resultSd = null;

            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);
            }

            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)Interop.mincore.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(
                                  SR.Argument_InvalidSafeHandle,
                                  nameof(handle));
                    }
                    else
                    {
                        errorCode = (int)Interop.mincore.GetSecurityInfoByHandle(handle, (uint)resourceType, (uint)SecurityInfos, out SidOwner, out SidGroup, out Dacl, out Sacl, out ByteArray);
                    }
                }
                else
                {
                    // both are null, shouldn't happen
                    // Changing from SystemException to ArgumentException as this code path is indicative of a null name argument
                    // as well as an accessControlSections argument with an audit flag
                    throw new ArgumentException();
                }

                if (errorCode == Interop.mincore.Errors.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(SR.InvalidOperation_NoSecurityDescriptor);
                }
                else if (errorCode == Interop.mincore.Errors.ERROR_NOT_ALL_ASSIGNED ||
                         errorCode == Interop.mincore.Errors.ERROR_PRIVILEGE_NOT_HELD)
                {
                    throw new PrivilegeNotHeldException(Privilege.Security);
                }
                else if (errorCode == Interop.mincore.Errors.ERROR_ACCESS_DENIED ||
                         errorCode == Interop.mincore.Errors.ERROR_CANT_OPEN_ANONYMOUS)
                {
                    throw new UnauthorizedAccessException();
                }

                if (errorCode != Interop.mincore.Errors.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 = Interop.mincore.GetSecurityDescriptorLength(ByteArray);

            byte[] BinaryForm = new byte[Length];

            Marshal.Copy(ByteArray, BinaryForm, 0, (int)Length);

            Interop.mincore_obsolete.LocalFree(ByteArray);

            resultSd = new RawSecurityDescriptor(BinaryForm, 0);

            return(Interop.mincore.Errors.ERROR_SUCCESS);

Error:

            if (errorCode == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY)
            {
                throw new OutOfMemoryException();
            }

            return(errorCode);
        }
Exemplo n.º 3
0
        [System.Security.SecurityCritical]  // auto-generated
        internal static CryptoKeySecurity GetKeySetSecurityInfo (SafeProvHandle hProv, AccessControlSections accessControlSections) {
            SecurityInfos securityInfo = 0;
            Privilege privilege = null;

            if ((accessControlSections & AccessControlSections.Owner) != 0)
                securityInfo |= SecurityInfos.Owner;
            if ((accessControlSections & AccessControlSections.Group) != 0)
                securityInfo |= SecurityInfos.Group;
            if ((accessControlSections & AccessControlSections.Access) != 0)
                securityInfo |= SecurityInfos.DiscretionaryAcl;

            byte[] rawSecurityDescriptor = null;
            int error;

            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                if ((accessControlSections & AccessControlSections.Audit) != 0) {
                    securityInfo |= SecurityInfos.SystemAcl;
                    privilege = new Privilege("SeSecurityPrivilege");
                    privilege.Enable();
                }
                rawSecurityDescriptor = _GetKeySetSecurityInfo(hProv, securityInfo, out error);
            }
            finally {
                if (privilege != null)
                    privilege.Revert();
            }

            // 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.
            if (error == Win32Native.ERROR_SUCCESS && (rawSecurityDescriptor == null || rawSecurityDescriptor.Length == 0))
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoSecurityDescriptor"));
            if (error == Win32Native.ERROR_NOT_ENOUGH_MEMORY)
                throw new OutOfMemoryException();
            if (error == Win32Native.ERROR_ACCESS_DENIED)
                throw new UnauthorizedAccessException();
            if (error == Win32Native.ERROR_PRIVILEGE_NOT_HELD)
                throw new PrivilegeNotHeldException( "SeSecurityPrivilege" );
            if (error != Win32Native.ERROR_SUCCESS)
                throw new CryptographicException(error);

            CommonSecurityDescriptor sd = new CommonSecurityDescriptor(false /* isContainer */,
                                                                       false /* isDS */,
                                                                       new RawSecurityDescriptor(rawSecurityDescriptor, 0),
                                                                       true);
            return new CryptoKeySecurity(sd);
        }
Exemplo n.º 4
0
        [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;
        }
Exemplo n.º 5
0
        //
        // Wrapper around advapi32.SetNamedSecurityInfoW and advapi32.SetSecurityInfo
        //

        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;

            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);
            }

            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)Interop.mincore.SetSecurityInfoByName(name, (uint)type, (uint)securityInformation, OwnerBinary, GroupBinary, DaclBinary, SaclBinary);
                }
                else if (handle != null)
                {
                    if (handle.IsInvalid)
                    {
                        throw new ArgumentException(
                                  SR.Argument_InvalidSafeHandle,
                                  nameof(handle));
                    }
                    else
                    {
                        errorCode = (int)Interop.mincore.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 ArgumentException();
                }

                if (errorCode == Interop.mincore.Errors.ERROR_NOT_ALL_ASSIGNED ||
                    errorCode == Interop.mincore.Errors.ERROR_PRIVILEGE_NOT_HELD)
                {
                    throw new PrivilegeNotHeldException(Privilege.Security);
                }
                else if (errorCode == Interop.mincore.Errors.ERROR_ACCESS_DENIED ||
                         errorCode == Interop.mincore.Errors.ERROR_CANT_OPEN_ANONYMOUS)
                {
                    throw new UnauthorizedAccessException();
                }
                else if (errorCode != Interop.mincore.Errors.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 == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY)
            {
                throw new OutOfMemoryException();
            }

            return(errorCode);
        }
Exemplo n.º 6
0
        //
        // Wrapper around advapi32.GetSecurityInfo
        //

        internal static int GetSecurityInfo(
            ResourceType resourceType,
            string name,
            SafeHandle handle,
            AccessControlSections accessControlSections,
            out RawSecurityDescriptor resultSd
            )
        {
            resultSd = null;

            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);
            }

            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)Interop.mincore.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(
                            SR.Argument_InvalidSafeHandle,
nameof(handle));
                    }
                    else
                    {
                        errorCode = (int)Interop.mincore.GetSecurityInfoByHandle(handle, (uint)resourceType, (uint)SecurityInfos, out SidOwner, out SidGroup, out Dacl, out Sacl, out ByteArray);
                    }
                }
                else
                {
                    // both are null, shouldn't happen
                    // Changing from SystemException to ArgumentException as this code path is indicative of a null name argument
                    // as well as an accessControlSections argument with an audit flag
                    throw new ArgumentException();
                }

                if (errorCode == Interop.mincore.Errors.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(SR.InvalidOperation_NoSecurityDescriptor);
                }
                else if (errorCode == Interop.mincore.Errors.ERROR_NOT_ALL_ASSIGNED ||
                         errorCode == Interop.mincore.Errors.ERROR_PRIVILEGE_NOT_HELD)
                {
                    throw new PrivilegeNotHeldException(Privilege.Security);
                }
                else if (errorCode == Interop.mincore.Errors.ERROR_ACCESS_DENIED ||
                    errorCode == Interop.mincore.Errors.ERROR_CANT_OPEN_ANONYMOUS)
                {
                    throw new UnauthorizedAccessException();
                }

                if (errorCode != Interop.mincore.Errors.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 = Interop.mincore.GetSecurityDescriptorLength(ByteArray);

            byte[] BinaryForm = new byte[Length];

            Marshal.Copy(ByteArray, BinaryForm, 0, (int)Length);

            Interop.mincore_obsolete.LocalFree(ByteArray);

            resultSd = new RawSecurityDescriptor(BinaryForm, 0);

            return Interop.mincore.Errors.ERROR_SUCCESS;

        Error:

            if (errorCode == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY)
            {
                throw new OutOfMemoryException();
            }

            return errorCode;
        }
        internal static void SetKeySetSecurityInfo(SafeProvHandle hProv, CryptoKeySecurity cryptoKeySecurity, AccessControlSections accessControlSections)
        {
            SecurityInfos securityInfo = 0;
            Privilege privilege = null;
            if (((accessControlSections & AccessControlSections.Owner) != AccessControlSections.None) && (cryptoKeySecurity._securityDescriptor.Owner != null))
            {
                securityInfo |= SecurityInfos.Owner;
            }
            if (((accessControlSections & AccessControlSections.Group) != AccessControlSections.None) && (cryptoKeySecurity._securityDescriptor.Group != null))
            {
                securityInfo |= SecurityInfos.Group;
            }
            if ((accessControlSections & AccessControlSections.Audit) != AccessControlSections.None)
            {
                securityInfo |= SecurityInfos.SystemAcl;
            }
            if (((accessControlSections & AccessControlSections.Access) != AccessControlSections.None) && cryptoKeySecurity._securityDescriptor.IsDiscretionaryAclPresent)
            {
                securityInfo |= SecurityInfos.DiscretionaryAcl;
            }
            if (securityInfo != 0)
            {
                int hr = 0;
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    if ((securityInfo & SecurityInfos.SystemAcl) != 0)
                    {
                        privilege = new Privilege("SeSecurityPrivilege");
                        privilege.Enable();
                    }
                    byte[] securityDescriptorBinaryForm = cryptoKeySecurity.GetSecurityDescriptorBinaryForm();
                    if ((securityDescriptorBinaryForm != null) && (securityDescriptorBinaryForm.Length > 0))
                    {
                        hr = SetKeySetSecurityInfo(hProv, securityInfo, securityDescriptorBinaryForm);
                    }
                }
                finally
                {
                    if (privilege != null)
                    {
                        privilege.Revert();
                    }
                }
                switch (hr)
                {
                    case 5:
                    case 0x51b:
                    case 0x51c:
                        throw new UnauthorizedAccessException();

                    case 0x522:
                        throw new PrivilegeNotHeldException("SeSecurityPrivilege");

                    case 6:
                        throw new NotSupportedException(Environment.GetResourceString("AccessControl_InvalidHandle"));
                }
                if (hr != 0)
                {
                    throw new CryptographicException(hr);
                }
            }
        }
Exemplo n.º 8
0
 public static string GetPrivilegeName(Privilege privilege)
 {
     switch (privilege) {
         case Privilege.AssignPrimaryToken:
             return "SeAssignPrimaryTokenPrivilege";
         case Privilege.Audit:
             return "SeAuditPrivilege";
         case Privilege.Backup:
             return "SeBackupPrivilege";
         case Privilege.ChangeNotify:
             return "SeChangeNotifyPrivilege";
         case Privilege.CreateGlobal:
             return "SeCreateGlobalPrivilege";
         case Privilege.CreatePagefile:
             return "SeCreatePagefilePrivilege";
         case Privilege.CreatePermanent:
             return "SeCreatePermanentPrivilege";
         case Privilege.CreateSymbolicLink:
             return "SeCreateSymbolicLinkPrivilege";
         case Privilege.CreateToken:
             return "SeCreateTokenPrivilege";
         case Privilege.Debug:
             return "SeDebugPrivilege";
         case Privilege.EnableDelegation:
             return "SeEnableDelegationPrivilege";
         case Privilege.Impersonate:
             return "SeImpersonatePrivilege";
         case Privilege.IncreaseBasePriority:
             return "SeIncreaseBasePriorityPrivilege";
         case Privilege.IncreaseQuota:
             return "SeIncreaseQuotaPrivilege";
         case Privilege.IncreaseWorkingSet:
             return "SeIncreaseWorkingSetPrivilege";
         case Privilege.LoadDriver:
             return "SeLoadDriverPrivilege";
         case Privilege.LockMemory:
             return "SeLockMemoryPrivilege";
         case Privilege.MachineAccount:
             return "SeMachineAccountPrivilege";
         case Privilege.ManageVolume:
             return "SeManageVolumePrivilege";
         case Privilege.ProfileSingleProcess:
             return "SeProfileSingleProcessPrivilege";
         case Privilege.Relabel:
             return "SeRelabelPrivilege";
         case Privilege.RemoteShutdown:
             return "SeRemoteShutdownPrivilege";
         case Privilege.Restore:
             return "SeRestorePrivilege";
         case Privilege.Security:
             return "SeSecurityPrivilege";
         case Privilege.Shutdown:
             return "SeShutdownPrivilege";
         case Privilege.SyncAgent:
             return "SeSyncAgentPrivilege";
         case Privilege.SystemEnvironment:
             return "SeSystemEnvironmentPrivilege";
         case Privilege.SystemProfile:
             return "SeSystemProfilePrivilege";
         case Privilege.Systemtime:
             return "SeSystemtimePrivilege";
         case Privilege.TakeOwnership:
             return "SeTakeOwnershipPrivilege";
         case Privilege.Tcb:
             return "SeTcbPrivilege";
         case Privilege.TimeZone:
             return "SeTimeZonePrivilege";
         case Privilege.TrustedCredManAccess:
             return "SeTrustedCredManAccessPrivilege";
         case Privilege.Undock:
             return "SeUndockPrivilege";
         case Privilege.UnsolicitedInput:
             return "SeUnsolicitedInputPrivilege";
         default:
             throw new ArgumentException("Unknown parameter privilege value");
     }
 }
Exemplo n.º 9
0
        internal static int SetSecurityInfo(ResourceType type, string name, SafeHandle handle, SecurityInfos securityInformation, SecurityIdentifier owner, SecurityIdentifier group, GenericAcl sacl, GenericAcl dacl)
        {
            byte[]    array     = null;
            byte[]    array2    = null;
            byte[]    array3    = null;
            byte[]    array4    = null;
            Privilege privilege = null;

            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
            if (owner != null)
            {
                int binaryLength = owner.BinaryLength;
                array = new byte[binaryLength];
                owner.GetBinaryForm(array, 0);
            }
            if (group != null)
            {
                int binaryLength = group.BinaryLength;
                array2 = new byte[binaryLength];
                group.GetBinaryForm(array2, 0);
            }
            if (dacl != null)
            {
                int binaryLength = dacl.BinaryLength;
                array4 = new byte[binaryLength];
                dacl.GetBinaryForm(array4, 0);
            }
            if (sacl != null)
            {
                int binaryLength = sacl.BinaryLength;
                array3 = new byte[binaryLength];
                sacl.GetBinaryForm(array3, 0);
            }
            if ((securityInformation & SecurityInfos.SystemAcl) != (SecurityInfos)0)
            {
                privilege = new Privilege("SeSecurityPrivilege");
            }
            RuntimeHelpers.PrepareConstrainedRegions();
            int num;

            try
            {
                if (privilege != null)
                {
                    try
                    {
                        privilege.Enable();
                    }
                    catch (PrivilegeNotHeldException)
                    {
                    }
                }
                if (name != null)
                {
                    num = (int)Win32Native.SetSecurityInfoByName(name, (uint)type, (uint)securityInformation, array, array2, array4, array3);
                }
                else
                {
                    if (handle == null)
                    {
                        throw new InvalidProgramException();
                    }
                    if (handle.IsInvalid)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSafeHandle"), "handle");
                    }
                    num = (int)Win32Native.SetSecurityInfoByHandle(handle, (uint)type, (uint)securityInformation, array, array2, array4, array3);
                }
                if (num == 1300 || num == 1314)
                {
                    throw new PrivilegeNotHeldException("SeSecurityPrivilege");
                }
                if (num == 5 || num == 1347)
                {
                    throw new UnauthorizedAccessException();
                }
                if (num != 0)
                {
                    goto IL_159;
                }
            }
            catch
            {
                if (privilege != null)
                {
                    privilege.Revert();
                }
                throw;
            }
            finally
            {
                if (privilege != null)
                {
                    privilege.Revert();
                }
            }
            return(0);

IL_159:
            if (num == 8)
            {
                throw new OutOfMemoryException();
            }
            return(num);
        }
Exemplo n.º 10
0
 public static void LookupPrivilegeValue(string systemName, Privilege privilege, out Luid luid)
 {
     if (!LookupPrivilegeValue(systemName, GetPrivilegeName(privilege), out luid)) {
         WindowsApi.NativeMethods.ReportWin32Exception();
     }
 }
Exemplo n.º 11
0
        public static Luid LuidFromPrivilege(Privilege privilege)
        {
            Luid result;

            result.LowPart = 0;
            result.HighPart = 0;

            using (_LuidLock.GetUpgradeableReadLock()) {
                if (_Luid.ContainsKey(privilege)) {
                    result = _Luid[privilege];
                }
                else {
                    using (_LuidLock.GetWriteLock()) {
                        LookupPrivilegeValue(privilege, out result);

                        _Luid[privilege] = result;
                    }
                }
            }

            return result;
        }
Exemplo n.º 12
0
 public static void LookupPrivilegeValue(Privilege privilege, out Luid luid)
 {
     LookupPrivilegeValue(null, privilege, out luid);
 }
 protected virtual void Persist(bool enableOwnershipPrivilege, string name, AccessControlSections includeSections)
 {
     Privilege privilege = null;
     RuntimeHelpers.PrepareConstrainedRegions();
     try
     {
         if (enableOwnershipPrivilege)
         {
             privilege = new Privilege("SeTakeOwnershipPrivilege");
             try
             {
                 privilege.Enable();
             }
             catch (PrivilegeNotHeldException)
             {
             }
         }
         this.Persist(name, includeSections);
     }
     catch
     {
         if (privilege != null)
         {
             privilege.Revert();
         }
         throw;
     }
     finally
     {
         if (privilege != null)
         {
             privilege.Revert();
         }
     }
 }
        internal static WindowsIdentity KerberosCertificateLogon(X509Certificate2 certificate)
        {
            int status;
            SafeHGlobalHandle pSourceName = null;
            SafeHGlobalHandle pPackageName = null;
            SafeHGlobalHandle pLogonInfo = null;
            SafeLsaLogonProcessHandle logonHandle = null;
            SafeLsaReturnBufferHandle profileHandle = null;
            SafeCloseHandle tokenHandle = null;
            try
            {
                pSourceName = SafeHGlobalHandle.AllocHGlobal(NativeMethods.LsaSourceName.Length + 1);
                Marshal.Copy(NativeMethods.LsaSourceName, 0, pSourceName.DangerousGetHandle(), NativeMethods.LsaSourceName.Length);
                UNICODE_INTPTR_STRING sourceName = new UNICODE_INTPTR_STRING(NativeMethods.LsaSourceName.Length, NativeMethods.LsaSourceName.Length + 1, pSourceName.DangerousGetHandle());

                Privilege privilege = null;

                RuntimeHelpers.PrepareConstrainedRegions();
                // Try to get an impersonation token.
                try
                {
                    // Try to enable the TCB privilege if possible
                    try
                    {
                        privilege = new Privilege(Privilege.SeTcbPrivilege);
                        privilege.Enable();
                    }
                    catch (PrivilegeNotHeldException ex)
                    {
                        DiagnosticUtility.TraceHandledException(ex, TraceEventType.Information);
                    }

                    IntPtr dummy = IntPtr.Zero;
                    status = NativeMethods.LsaRegisterLogonProcess(ref sourceName, out logonHandle, out dummy);
                    if (NativeMethods.ERROR_ACCESS_DENIED == NativeMethods.LsaNtStatusToWinError(status))
                    {
                        // We don't have the Tcb privilege. The best we can hope for is to get an Identification token.
                        status = NativeMethods.LsaConnectUntrusted(out logonHandle);
                    }
                    if (status < 0) // non-negative numbers indicate success
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(NativeMethods.LsaNtStatusToWinError(status)));
                    }
                }
                finally
                {
                    // if reverting privilege fails, fail fast!
                    int revertResult = -1;
                    string message = null;
                    try
                    {
                        revertResult = privilege.Revert();
                        if (revertResult != 0)
                        {
                            message = SR.GetString(SR.RevertingPrivilegeFailed, new Win32Exception(revertResult));
                        }
                    }
                    finally
                    {
                        if (revertResult != 0)
                        {
                            DiagnosticUtility.FailFast(message);
                        }
                    }
                }

                // package name ("Kerberos")
                pPackageName = SafeHGlobalHandle.AllocHGlobal(NativeMethods.LsaKerberosName.Length + 1);
                Marshal.Copy(NativeMethods.LsaKerberosName, 0, pPackageName.DangerousGetHandle(), NativeMethods.LsaKerberosName.Length);
                UNICODE_INTPTR_STRING packageName = new UNICODE_INTPTR_STRING(NativeMethods.LsaKerberosName.Length, NativeMethods.LsaKerberosName.Length + 1, pPackageName.DangerousGetHandle());

                uint packageId = 0;
                status = NativeMethods.LsaLookupAuthenticationPackage(logonHandle, ref packageName, out packageId);
                if (status < 0) // non-negative numbers indicate success
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(NativeMethods.LsaNtStatusToWinError(status)));
                }

                // source context
                TOKEN_SOURCE sourceContext = new TOKEN_SOURCE();
                if (!NativeMethods.AllocateLocallyUniqueId(out sourceContext.SourceIdentifier))
                {
                    int dwErrorCode = Marshal.GetLastWin32Error();
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(dwErrorCode));
                }

                // SourceContext
                sourceContext.Name = new char[8];
                sourceContext.Name[0] = 'W'; sourceContext.Name[1] = 'C'; sourceContext.Name[2] = 'F';

                // LogonInfo
                byte[] certRawData = certificate.RawData;
                int logonInfoSize = KERB_CERTIFICATE_S4U_LOGON.Size + certRawData.Length;
                pLogonInfo = SafeHGlobalHandle.AllocHGlobal(logonInfoSize);
                unsafe
                {
                    KERB_CERTIFICATE_S4U_LOGON* pInfo = (KERB_CERTIFICATE_S4U_LOGON*)pLogonInfo.DangerousGetHandle().ToPointer();
                    pInfo->MessageType = KERB_LOGON_SUBMIT_TYPE.KerbCertificateS4ULogon;
                    pInfo->Flags = NativeMethods.KERB_CERTIFICATE_S4U_LOGON_FLAG_CHECK_LOGONHOURS;
                    pInfo->UserPrincipalName = new UNICODE_INTPTR_STRING(0, 0, IntPtr.Zero);
                    pInfo->DomainName = new UNICODE_INTPTR_STRING(0, 0, IntPtr.Zero);
                    pInfo->CertificateLength = (uint)certRawData.Length;
                    pInfo->Certificate = new IntPtr(pLogonInfo.DangerousGetHandle().ToInt64() + KERB_CERTIFICATE_S4U_LOGON.Size);
                    Marshal.Copy(certRawData, 0, pInfo->Certificate, certRawData.Length);
                }

                QUOTA_LIMITS quotas = new QUOTA_LIMITS();
                LUID logonId = new LUID();
                uint profileBufferLength;
                int subStatus = 0;

                // Call LsaLogonUser
                status = NativeMethods.LsaLogonUser(
                    logonHandle,
                    ref sourceName,
                    SecurityLogonType.Network,
                    packageId,
                    pLogonInfo.DangerousGetHandle(),
                    (uint)logonInfoSize,
                    IntPtr.Zero,
                    ref sourceContext,
                    out profileHandle,
                    out profileBufferLength,
                    out logonId,
                    out tokenHandle,
                    out quotas,
                    out subStatus
                    );

                // LsaLogon has restriction (eg. password expired).  SubStatus indicates the reason.
                if ((uint)status == NativeMethods.STATUS_ACCOUNT_RESTRICTION && subStatus < 0)
                {
                    status = subStatus;
                }
                if (status < 0) // non-negative numbers indicate success
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(NativeMethods.LsaNtStatusToWinError(status)));
                }
                if (subStatus < 0) // non-negative numbers indicate success
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(NativeMethods.LsaNtStatusToWinError(subStatus)));
                }

                return new WindowsIdentity(tokenHandle.DangerousGetHandle(), SecurityUtils.AuthTypeCertMap);
            }
            finally
            {
                if (tokenHandle != null)
                {
                    tokenHandle.Close();
                }
                if (pLogonInfo != null)
                {
                    pLogonInfo.Close();
                }
                if (profileHandle != null)
                {
                    profileHandle.Close();
                }
                if (pSourceName != null)
                {
                    pSourceName.Close();
                }
                if (pPackageName != null)
                {
                    pPackageName.Close();
                }
                if (logonHandle != null)
                {
                    logonHandle.Close();
                }
            }
        }
Exemplo n.º 15
0
        public static void RunWithPrivilege( string privilege, bool enabled, PrivilegedHelper helper )
        {
            if ( helper == null )
            {
                throw new ArgumentNullException( "helper" );
            }
            Contract.EndContractBlock();
            
            Privilege p = new Privilege( privilege );

            RuntimeHelpers.PrepareConstrainedRegions();

            try 
            {
                if (enabled)
                {
                    p.Enable();
                }
                else
                {
                    p.Disable();
                }

                helper();
            }
            finally
            {
                p.Revert();
            }
        }
Exemplo n.º 16
0
        internal static int GetSecurityInfo(ResourceType resourceType, string name, SafeHandle handle, AccessControlSections accessControlSections, out RawSecurityDescriptor resultSd)
        {
            resultSd = null;
            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
            SecurityInfos securityInfos = (SecurityInfos)0;
            Privilege     privilege     = null;

            if ((accessControlSections & AccessControlSections.Owner) != AccessControlSections.None)
            {
                securityInfos |= SecurityInfos.Owner;
            }
            if ((accessControlSections & AccessControlSections.Group) != AccessControlSections.None)
            {
                securityInfos |= SecurityInfos.Group;
            }
            if ((accessControlSections & AccessControlSections.Access) != AccessControlSections.None)
            {
                securityInfos |= SecurityInfos.DiscretionaryAcl;
            }
            if ((accessControlSections & AccessControlSections.Audit) != AccessControlSections.None)
            {
                securityInfos |= SecurityInfos.SystemAcl;
                privilege      = new Privilege("SeSecurityPrivilege");
            }
            RuntimeHelpers.PrepareConstrainedRegions();
            IntPtr intPtr5;
            int    num;

            try
            {
                if (privilege != null)
                {
                    try
                    {
                        privilege.Enable();
                    }
                    catch (PrivilegeNotHeldException)
                    {
                    }
                }
                if (name != null)
                {
                    IntPtr intPtr;
                    IntPtr intPtr2;
                    IntPtr intPtr3;
                    IntPtr intPtr4;
                    num = (int)Win32Native.GetSecurityInfoByName(name, (uint)resourceType, (uint)securityInfos, out intPtr, out intPtr2, out intPtr3, out intPtr4, out intPtr5);
                }
                else
                {
                    if (handle == null)
                    {
                        throw new SystemException();
                    }
                    if (handle.IsInvalid)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSafeHandle"), "handle");
                    }
                    IntPtr intPtr;
                    IntPtr intPtr2;
                    IntPtr intPtr3;
                    IntPtr intPtr4;
                    num = (int)Win32Native.GetSecurityInfoByHandle(handle, (uint)resourceType, (uint)securityInfos, out intPtr, out intPtr2, out intPtr3, out intPtr4, out intPtr5);
                }
                if (num == 0 && IntPtr.Zero.Equals(intPtr5))
                {
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoSecurityDescriptor"));
                }
                if (num == 1300 || num == 1314)
                {
                    throw new PrivilegeNotHeldException("SeSecurityPrivilege");
                }
                if (num == 5 || num == 1347)
                {
                    throw new UnauthorizedAccessException();
                }
                if (num != 0)
                {
                    goto IL_162;
                }
            }
            catch
            {
                if (privilege != null)
                {
                    privilege.Revert();
                }
                throw;
            }
            finally
            {
                if (privilege != null)
                {
                    privilege.Revert();
                }
            }
            uint securityDescriptorLength = Win32Native.GetSecurityDescriptorLength(intPtr5);

            byte[] array = new byte[securityDescriptorLength];
            Marshal.Copy(intPtr5, array, 0, (int)securityDescriptorLength);
            Win32Native.LocalFree(intPtr5);
            resultSd = new RawSecurityDescriptor(array, 0);
            return(0);

IL_162:
            if (num == 8)
            {
                throw new OutOfMemoryException();
            }
            return(num);
        }
Exemplo n.º 17
0
        //
        // Wrapper around advapi32.SetNamedSecurityInfoW and advapi32.SetSecurityInfo
        //

        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;

            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);
            }

            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)Interop.mincore.SetSecurityInfoByName(name, (uint)type, (uint)securityInformation, OwnerBinary, GroupBinary, DaclBinary, SaclBinary);
                }
                else if (handle != null)
                {
                    if (handle.IsInvalid)
                    {
                        throw new ArgumentException(
                            SR.Argument_InvalidSafeHandle,
nameof(handle));
                    }
                    else
                    {
                        errorCode = (int)Interop.mincore.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 ArgumentException();
                }

                if (errorCode == Interop.mincore.Errors.ERROR_NOT_ALL_ASSIGNED ||
                    errorCode == Interop.mincore.Errors.ERROR_PRIVILEGE_NOT_HELD)
                {
                    throw new PrivilegeNotHeldException(Privilege.Security);
                }
                else if (errorCode == Interop.mincore.Errors.ERROR_ACCESS_DENIED ||
                    errorCode == Interop.mincore.Errors.ERROR_CANT_OPEN_ANONYMOUS)
                {
                    throw new UnauthorizedAccessException();
                }
                else if (errorCode != Interop.mincore.Errors.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 == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY)
            {
                throw new OutOfMemoryException();
            }

            return errorCode;
        }
Exemplo n.º 18
0
        [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; 
        }
Exemplo n.º 19
0
        //
        // if Persist (by name) is implemented, then this function will also try to enable take ownership
        // privilege while persisting if the enableOwnershipPrivilege is true.
        // Integrators can override it if this is not desired.
        //
        protected virtual void Persist(bool enableOwnershipPrivilege, string name, AccessControlSections includeSections )
        {
            Privilege ownerPrivilege = null;

            try
            {
                if (enableOwnershipPrivilege)
                {
                    ownerPrivilege = new Privilege(Privilege.TakeOwnership);
                    try
                    {
                        ownerPrivilege.Enable();
                    }
                    catch (PrivilegeNotHeldException)
                    {
                        // we will ignore this exception and press on just in case this is a remote resource
                    }
                }
                Persist(name, includeSections);
            }
            catch
            {
                // protection against exception filter-based luring attacks
                if ( ownerPrivilege != null )
                {
                    ownerPrivilege.Revert();
                }
                throw;
            }
            finally
            {
                if (ownerPrivilege != null)
                {
                    ownerPrivilege.Revert();
                }
            }
        }
        internal static CryptoKeySecurity GetKeySetSecurityInfo(SafeProvHandle hProv, AccessControlSections accessControlSections)
        {
            int num;
            SecurityInfos securityInfo = 0;
            Privilege privilege = null;
            if ((accessControlSections & AccessControlSections.Owner) != AccessControlSections.None)
            {
                securityInfo |= SecurityInfos.Owner;
            }
            if ((accessControlSections & AccessControlSections.Group) != AccessControlSections.None)
            {
                securityInfo |= SecurityInfos.Group;
            }
            if ((accessControlSections & AccessControlSections.Access) != AccessControlSections.None)
            {
                securityInfo |= SecurityInfos.DiscretionaryAcl;
            }
            byte[] binaryForm = null;
            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                if ((accessControlSections & AccessControlSections.Audit) != AccessControlSections.None)
                {
                    securityInfo |= SecurityInfos.SystemAcl;
                    privilege = new Privilege("SeSecurityPrivilege");
                    privilege.Enable();
                }
                binaryForm = _GetKeySetSecurityInfo(hProv, securityInfo, out num);
            }
            finally
            {
                if (privilege != null)
                {
                    privilege.Revert();
                }
            }
            if ((num == 0) && ((binaryForm == null) || (binaryForm.Length == 0)))
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoSecurityDescriptor"));
            }
            switch (num)
            {
                case 8:
                    throw new OutOfMemoryException();

                case 5:
                    throw new UnauthorizedAccessException();

                case 0x522:
                    throw new PrivilegeNotHeldException("SeSecurityPrivilege");
            }
            if (num != 0)
            {
                throw new CryptographicException(num);
            }
            return new CryptoKeySecurity(new CommonSecurityDescriptor(false, false, new RawSecurityDescriptor(binaryForm, 0), true));
        }