Exemplo n.º 1
0
        //
        // Wrapper around advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW
        //

        internal static int ConvertSdToSddl(
            byte[] binaryForm,
            int requestedRevision,
            SecurityInfos si,
            out string resultSddl)
        {
            int errorCode;
            IntPtr ByteArray;
            uint ByteArraySize = 0;

            if (!Interop.mincore.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
            //

            Interop.mincore_obsolete.LocalFree(ByteArray);

            return 0;

        Error:

            resultSddl = null;

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

            return errorCode;
        }
Exemplo n.º 2
0
        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)NativeMethods.SetSecurityInfoByName(name, (uint)type, (uint)securityInformation, OwnerBinary, GroupBinary, DaclBinary, SaclBinary);
                }
                else if (handle != null)
                {
                    if (handle.IsInvalid)
                    {
                        throw new ArgumentException("Invalid safe handle");
                    }
                    else
                    {
                        errorCode = (int)NativeMethods.SetSecurityInfoByHandle(handle, (uint)type, (uint)securityInformation, OwnerBinary, GroupBinary, DaclBinary, SaclBinary);
                    }
                }
                else
                {
                    // both are null, shouldn't happen
                    throw new InvalidProgramException();
                }

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

            return(errorCode);
        }
Exemplo n.º 3
0
 public void SetSecurity(
     SecurityInfos securityInformation,
     IntPtr pSecurityDescriptorFromUI)
 {
     // SecurityInformation is a enumeration - we don't need to check that if being null
     // pSecurityDescriptorFromUI is the security descriptor that we receive from the UI 
     // and need to store in the registry.
     if (pSecurityDescriptorFromUI.Equals(IntPtr.Zero))
     {
         throw new ArgumentNullException(SR.GetString(SR.ACLEditorSetSecurityError));
     }
     model.SetSecurity(
         securityInformation,
         pSecurityDescriptorFromUI);
 }
        public int GetSecurity(SecurityInfos requestInformation, out IntPtr pSD, bool fDefault)
        {
            pSD = NativeMethods.GetSecurityDescriptor(this.SecurityDescriptor.GetSddlForm(AccessControlSections.All), requestInformation);

            return(S_OK);
        }
Exemplo n.º 5
0
 public string GetSecurityDescriptorSddlForm(SecurityInfos includeSections = SecurityInfos.Owner | SecurityInfos.Group | SecurityInfos.DiscretionaryAcl);
Exemplo n.º 6
0
		static extern int GetSecurityInfo (SafeHandle handle, ResourceType resourceType, SecurityInfos securityInfos,
						   out IntPtr owner, out IntPtr group, out IntPtr dacl, out IntPtr sacl,
						   out IntPtr descriptor);
Exemplo n.º 7
0
 internal static extern byte[] _GetKeySetSecurityInfo(SafeProvHandle hProv, SecurityInfos securityInfo, out int error);
Exemplo n.º 8
0
 public static extern bool QueryServiceObjectSecurity(IntPtr serviceHandle, SecurityInfos secInfo, ref SECURITY_DESCRIPTOR lpSecDesrBuf, uint bufSize, out uint bufSizeNeeded);
Exemplo n.º 9
0
        int Win32SetHelper(SetSecurityInfoNativeCall nativeCall,
                           AccessControlSections includeSections)
        {
            // SE_REGISTRY_KEY will fail UnauthorizedAccessException without this check.
            if (AccessControlSections.None == includeSections)
            {
                return(0);
            }

            SecurityInfos securityInfos = 0;

            byte[] owner = null, group = null, dacl = null, sacl = null;

            if (0 != (includeSections & AccessControlSections.Owner))
            {
                securityInfos |= SecurityInfos.Owner;
                SecurityIdentifier ownerSid = (SecurityIdentifier)GetOwner(typeof(SecurityIdentifier));
                if (null != ownerSid)
                {
                    owner = new byte[ownerSid.BinaryLength];
                    ownerSid.GetBinaryForm(owner, 0);
                }
            }

            if (0 != (includeSections & AccessControlSections.Group))
            {
                securityInfos |= SecurityInfos.Group;
                SecurityIdentifier groupSid = (SecurityIdentifier)GetGroup(typeof(SecurityIdentifier));
                if (null != groupSid)
                {
                    group = new byte[groupSid.BinaryLength];
                    groupSid.GetBinaryForm(group, 0);
                }
            }

            if (0 != (includeSections & AccessControlSections.Access))
            {
                securityInfos |= SecurityInfos.DiscretionaryAcl;
                if (AreAccessRulesProtected)
                {
                    securityInfos |= unchecked ((SecurityInfos)0x80000000);
                }
                else
                {
                    securityInfos |= (SecurityInfos)0x20000000;
                }
                dacl = new byte[descriptor.DiscretionaryAcl.BinaryLength];
                descriptor.DiscretionaryAcl.GetBinaryForm(dacl, 0);
            }

            if (0 != (includeSections & AccessControlSections.Audit))
            {
                if (null != descriptor.SystemAcl)
                {
                    securityInfos |= SecurityInfos.SystemAcl;
                    if (AreAuditRulesProtected)
                    {
                        securityInfos |= (SecurityInfos)0x40000000;
                    }
                    else
                    {
                        securityInfos |= (SecurityInfos)0x10000000;
                    }
                    sacl = new byte[descriptor.SystemAcl.BinaryLength];
                    descriptor.SystemAcl.GetBinaryForm(sacl, 0);
                }
            }

            return(nativeCall(securityInfos, owner, group, dacl, sacl));
        }
Exemplo n.º 10
0
 private static extern bool QueryServiceObjectSecurity(
     SafeHandle serviceHandle, SecurityInfos secInfo, byte[] lpSecDesrBuf, uint bufSize, out uint bufSizeNeeded);
Exemplo n.º 11
0
        internal static int GetSecurityInfo(ResourceType resourceType, string name, SafeHandle handle, AccessControlSections accessControlSections, out RawSecurityDescriptor resultSd)
        {
            resultSd = (RawSecurityDescriptor)null;
            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
            SecurityInfos securityInfos = (SecurityInfos)0;
            Privilege     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 securityDescriptor;
            int    num;

            try
            {
                if (privilege != null)
                {
                    try
                    {
                        privilege.Enable();
                    }
                    catch (PrivilegeNotHeldException ex)
                    {
                    }
                }
                IntPtr sidOwner;
                IntPtr sidGroup;
                IntPtr dacl;
                IntPtr sacl;
                if (name != null)
                {
                    num = (int)Win32Native.GetSecurityInfoByName(name, (uint)resourceType, (uint)securityInfos, out sidOwner, out sidGroup, out dacl, out sacl, out securityDescriptor);
                }
                else
                {
                    if (handle == null)
                    {
                        throw new SystemException();
                    }
                    if (handle.IsInvalid)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSafeHandle"), "handle");
                    }
                    num = (int)Win32Native.GetSecurityInfoByHandle(handle, (uint)resourceType, (uint)securityInfos, out sidOwner, out sidGroup, out dacl, out sacl, out securityDescriptor);
                }
                if (num == 0 && IntPtr.Zero.Equals((object)securityDescriptor))
                {
                    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 label_33;
                }
            }
            catch
            {
                if (privilege != null)
                {
                    privilege.Revert();
                }
                throw;
            }
            finally
            {
                if (privilege != null)
                {
                    privilege.Revert();
                }
            }
            uint descriptorLength = Win32Native.GetSecurityDescriptorLength(securityDescriptor);

            byte[] numArray = new byte[(int)descriptorLength];
            Marshal.Copy(securityDescriptor, numArray, 0, (int)descriptorLength);
            Win32Native.LocalFree(securityDescriptor);
            resultSd = new RawSecurityDescriptor(numArray, 0);
            return(0);

label_33:
            if (num == 8)
            {
                throw new OutOfMemoryException();
            }
            return(num);
        }
Exemplo n.º 12
0
        internal static int ConvertSdToSddl(byte[] binaryForm, int requestedRevision, SecurityInfos si, out string resultSddl)
        {
            uint   resultStringLength = 0;
            IntPtr resultString;

            if (1 != Win32Native.ConvertSdToStringSd(binaryForm, (uint)requestedRevision, (uint)si, out resultString, ref resultStringLength))
            {
                int lastWin32Error = Marshal.GetLastWin32Error();
                resultSddl = (string)null;
                if (lastWin32Error == 8)
                {
                    throw new OutOfMemoryException();
                }
                return(lastWin32Error);
            }
            resultSddl = Marshal.PtrToStringUni(resultString);
            Win32Native.LocalFree(resultString);
            return(0);
        }
Exemplo n.º 13
0
        internal static int SetSecurityInfo(ResourceType type, string name, SafeHandle handle, SecurityInfos securityInformation, SecurityIdentifier owner, SecurityIdentifier group, GenericAcl sacl, GenericAcl dacl)
        {
            byte[]    numArray1 = (byte[])null;
            byte[]    numArray2 = (byte[])null;
            byte[]    numArray3 = (byte[])null;
            byte[]    numArray4 = (byte[])null;
            Privilege privilege = (Privilege)null;

            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
            if (owner != (SecurityIdentifier)null)
            {
                numArray1 = new byte[owner.BinaryLength];
                owner.GetBinaryForm(numArray1, 0);
            }
            if (group != (SecurityIdentifier)null)
            {
                numArray2 = new byte[group.BinaryLength];
                group.GetBinaryForm(numArray2, 0);
            }
            if (dacl != null)
            {
                numArray4 = new byte[dacl.BinaryLength];
                dacl.GetBinaryForm(numArray4, 0);
            }
            if (sacl != null)
            {
                numArray3 = new byte[sacl.BinaryLength];
                sacl.GetBinaryForm(numArray3, 0);
            }
            if ((securityInformation & SecurityInfos.SystemAcl) != (SecurityInfos)0)
            {
                privilege = new Privilege("SeSecurityPrivilege");
            }
            RuntimeHelpers.PrepareConstrainedRegions();
            int num;

            try
            {
                if (privilege != null)
                {
                    try
                    {
                        privilege.Enable();
                    }
                    catch (PrivilegeNotHeldException ex)
                    {
                    }
                }
                if (name != null)
                {
                    num = (int)Win32Native.SetSecurityInfoByName(name, (uint)type, (uint)securityInformation, numArray1, numArray2, numArray4, numArray3);
                }
                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, numArray1, numArray2, numArray4, numArray3);
                }
                if (num == 1300 || num == 1314)
                {
                    throw new PrivilegeNotHeldException("SeSecurityPrivilege");
                }
                if (num == 5 || num == 1347)
                {
                    throw new UnauthorizedAccessException();
                }
                if (num != 0)
                {
                    goto label_33;
                }
            }
            catch
            {
                if (privilege != null)
                {
                    privilege.Revert();
                }
                throw;
            }
            finally
            {
                if (privilege != null)
                {
                    privilege.Revert();
                }
            }
            return(0);

label_33:
            if (num == 8)
            {
                throw new OutOfMemoryException();
            }
            return(num);
        }
Exemplo n.º 14
0
 public void SetSecurityDescriptor([NotNull] GenericSecurityDescriptor sd, SecurityInfos includeSections = Task.defaultSecurityInfosSections)
 {
     SetSecurityDescriptorSddlForm(sd.GetSddlForm((AccessControlSections)includeSections));
 }
Exemplo n.º 15
0
 public GenericSecurityDescriptor GetSecurityDescriptor(SecurityInfos includeSections = Task.defaultSecurityInfosSections) => new RawSecurityDescriptor(GetSecurityDescriptorSddlForm(includeSections));
Exemplo n.º 16
0
        internal static int SetSecurityInfo(ResourceType type, string name, SafeHandle handle, SecurityInfos securityInformation, SecurityIdentifier owner, SecurityIdentifier group, GenericAcl sacl, GenericAcl dacl)
        {
            byte[]    binaryForm = null;
            byte[]    buffer2    = null;
            byte[]    buffer3    = null;
            byte[]    buffer4    = null;
            Privilege privilege  = null;

            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
            if (owner != null)
            {
                binaryForm = new byte[owner.BinaryLength];
                owner.GetBinaryForm(binaryForm, 0);
            }
            if (group != null)
            {
                buffer2 = new byte[group.BinaryLength];
                group.GetBinaryForm(buffer2, 0);
            }
            if (dacl != null)
            {
                buffer4 = new byte[dacl.BinaryLength];
                dacl.GetBinaryForm(buffer4, 0);
            }
            if (sacl != null)
            {
                buffer3 = new byte[sacl.BinaryLength];
                sacl.GetBinaryForm(buffer3, 0);
            }
            if ((securityInformation & SecurityInfos.SystemAcl) != 0)
            {
                privilege = new Privilege("SeSecurityPrivilege");
            }
            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                int num;
                if (privilege != null)
                {
                    try
                    {
                        privilege.Enable();
                    }
                    catch (PrivilegeNotHeldException)
                    {
                    }
                }
                if (name != null)
                {
                    num = (int)Win32Native.SetSecurityInfoByName(name, (uint)type, (uint)securityInformation, binaryForm, buffer2, buffer4, buffer3);
                }
                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, binaryForm, buffer2, buffer4, buffer3);
                }
                if ((num == 0x514) || (num == 0x522))
                {
                    throw new PrivilegeNotHeldException("SeSecurityPrivilege");
                }
                if ((num == 5) || (num == 0x543))
                {
                    throw new UnauthorizedAccessException();
                }
                if (num != 0)
                {
                    if (num == 8)
                    {
                        throw new OutOfMemoryException();
                    }
                    return(num);
                }
            }
            catch
            {
                if (privilege != null)
                {
                    privilege.Revert();
                }
                throw;
            }
            finally
            {
                if (privilege != null)
                {
                    privilege.Revert();
                }
            }
            return(0);
        }
Exemplo n.º 17
0
        // this method is called by SecurityInfoCCW.GetSecurity  
        // its return is the SecurityDescriptor in binary format
        // it loads the data from the registry
        // [loads data from registry to UI]
        public IntPtr GetSecurity(SecurityInfos requestedInformation, bool wantDefault)
        {
            if (requestedInformation == SecurityInfos.DiscretionaryAcl)
            {
                StringBuilder securityDescriptorBuilder = new StringBuilder("D:");

                System.Collections.ArrayList kerb = new System.Collections.ArrayList(current.KerberosGlobalAcl);
                System.Collections.ArrayList indexesOfInvalidItems = new System.Collections.ArrayList();
                for (int i = 0; i < kerb.Count; i++)
                {
                    try
                    {
                        string sid = ((new NTAccount((string)kerb[i])).Translate(typeof(SecurityIdentifier))).ToString();
                        securityDescriptorBuilder.Append("(A;;LCSWRP;;;" + sid + ")");
                    }
                    catch (ArgumentException) // invalid account, do not consider it
                    {
                        indexesOfInvalidItems.Add(i);
                    }
                    catch (IdentityNotMappedException)
                    {
                        indexesOfInvalidItems.Add(i);
                    }
                }

                //remove invalid items based on indexesOfInvalidItems
                for (int i = indexesOfInvalidItems.Count - 1; i >= 0; i--)
                {
                    kerb.RemoveAt((int)indexesOfInvalidItems[i]);
                }

                // rebuild the ACL, taking care not to leave it null
                if (kerb.Count <= 0)
                {
                    current.KerberosGlobalAcl = new string[] { "" };
                }
                else
                {
                    current.KerberosGlobalAcl = (string[])kerb.ToArray(typeof(string));
                }

                IntPtr securityDescriptor;
                int size = 0;

                // call external function for transformig String SecurityDescriptors
                // into their internal representation
#pragma warning suppress 56523
                bool ret = SafeNativeMethods.ConvertStringSecurityDescriptorToSecurityDescriptor(
                    securityDescriptorBuilder.ToString(),
                    1, /* 
                        * must be SDDL_REVISION_1 == 1 always
                        */
                    out securityDescriptor,
                    out size
                );
                if (!ret)
                {
                    return IntPtr.Zero;
                }
                return securityDescriptor;
            }
            return IntPtr.Zero;
        }
Exemplo n.º 18
0
 static extern int GetSecurityInfo(SafeHandle handle, ResourceType resourceType, SecurityInfos securityInfos,
                                   out IntPtr owner, out IntPtr group, out IntPtr dacl, out IntPtr sacl,
                                   out IntPtr descriptor);
Exemplo n.º 19
0
 public static extern bool SetServiceObjectSecurity(SafeHandle serviceHandle, SecurityInfos secInfos, byte[] lpSecDesrBuf);
Exemplo n.º 20
0
 static extern int GetNamedSecurityInfo(string name, ResourceType resourceType, SecurityInfos securityInfos,
                                        out IntPtr owner, out IntPtr group, out IntPtr dacl, out IntPtr sacl,
                                        out IntPtr descriptor);
Exemplo n.º 21
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.º 22
0
 static extern int SetSecurityInfo(SafeHandle handle, ResourceType resourceType, SecurityInfos securityInfos,
                                   byte[] owner, byte[] group, byte[] dacl, byte[] sacl);
Exemplo n.º 23
0
		static extern int SetSecurityInfo (SafeHandle handle, ResourceType resourceType, SecurityInfos securityInfos,
						   byte[] owner, byte[] group, byte[] dacl, byte[] sacl);
Exemplo n.º 24
0
 static extern int SetNamedSecurityInfo(string name, ResourceType resourceType, SecurityInfos securityInfos,
                                        byte[] owner, byte[] group, byte[] dacl, byte[] sacl);
Exemplo n.º 25
0
 /// <summary>
 /// Sets a service's security descriptor as SDDL.
 /// </summary>
 public static void SetServiceSDDL(string ServiceName, SecurityInfos SecurityInfos, string SDDL)
 {
     ServiceController sc = new ServiceController(ServiceName);
     bool ok = SetServiceObjectSecurity(sc.ServiceHandle, SecurityInfos, ConvertStringSDtoSD(SDDL));
     if (!ok)
         throw new ApplicationException("error calling SetServiceObjectSecurity(); error code=" + Marshal.GetLastWin32Error());
 }
Exemplo n.º 26
0
 internal static extern bool ConvertSecurityDescriptorToStringSecurityDescriptorW(
     [In] IntPtr securityDescriptor,
     [In] int stringSDRevision,
     [In] SecurityInfos si,
     [Out] out IntPtr stringSecurityDescriptor,
     [Out] out int size);
Exemplo n.º 27
0
 public void GetSecurity(
     SecurityInfos requestedInformation,
     out IntPtr ppSecurityDescriptor,
     bool fDefault)
 {
     ppSecurityDescriptor = model.GetSecurity(requestedInformation, fDefault);
 }
Exemplo n.º 28
0
 private static extern bool SetKernelObjectSecurity(IntPtr Handle, SecurityInfos SecurityInformation, byte[] SecurityDescriptor);
Exemplo n.º 29
0
        internal static void SetAccessControlExtracted(FileSystemSecurity security, string name)
        {
            //security.WriteLock();
            AccessControlSections includeSections = AccessControlSections.Owner | AccessControlSections.Group;

            if (security.GetAccessRules(true, false, typeof(SecurityIdentifier)).Count > 0)
            {
                includeSections |= AccessControlSections.Access;
            }
            if (security.GetAuditRules(true, false, typeof(SecurityIdentifier)).Count > 0)
            {
                includeSections |= AccessControlSections.Audit;
            }

            SecurityInfos      securityInfo = (SecurityInfos)0;
            SecurityIdentifier owner        = null;
            SecurityIdentifier group        = null;
            SystemAcl          sacl         = null;
            DiscretionaryAcl   dacl         = null;

            if ((includeSections & AccessControlSections.Owner) != AccessControlSections.None)
            {
                owner = (SecurityIdentifier)security.GetOwner(typeof(SecurityIdentifier));
                if (owner != null)
                {
                    securityInfo = securityInfo | SecurityInfos.Owner;
                }
            }

            if ((includeSections & AccessControlSections.Group) != AccessControlSections.None)
            {
                @group = (SecurityIdentifier)security.GetGroup(typeof(SecurityIdentifier));
                if (@group != null)
                {
                    securityInfo = securityInfo | SecurityInfos.Group;
                }
            }
            var securityDescriptorBinaryForm            = security.GetSecurityDescriptorBinaryForm();
            RawSecurityDescriptor rawSecurityDescriptor = null;
            bool isDiscretionaryAclPresent = false;

            if (securityDescriptorBinaryForm != null)
            {
                rawSecurityDescriptor     = new RawSecurityDescriptor(securityDescriptorBinaryForm, 0);
                isDiscretionaryAclPresent = (rawSecurityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclPresent) != ControlFlags.None;
            }

            if ((includeSections & AccessControlSections.Audit) != AccessControlSections.None)
            {
                securityInfo = securityInfo | SecurityInfos.SystemAcl;
                sacl         = null;
                if (rawSecurityDescriptor != null)
                {
                    var isSystemAclPresent = (rawSecurityDescriptor.ControlFlags & ControlFlags.SystemAclPresent) != ControlFlags.None;
                    if (isSystemAclPresent && rawSecurityDescriptor.SystemAcl != null && rawSecurityDescriptor.SystemAcl.Count > 0)
                    {
                        // are all system acls on a file not a container?
                        const bool notAContainer          = false;
                        const bool notADirectoryObjectACL = false;

                        sacl = new SystemAcl(notAContainer, notADirectoryObjectACL,
                                             rawSecurityDescriptor.SystemAcl);
                    }
                    securityInfo = (SecurityInfos)(((rawSecurityDescriptor.ControlFlags & ControlFlags.SystemAclProtected) == ControlFlags.None ?
                                                    (uint)securityInfo | UnprotectedSystemAcl : (uint)securityInfo | ProtectedSystemAcl));
                }
            }
            if ((includeSections & AccessControlSections.Access) != AccessControlSections.None && isDiscretionaryAclPresent)
            {
                securityInfo = securityInfo | SecurityInfos.DiscretionaryAcl;
                dacl         = null;
                if (rawSecurityDescriptor != null)
                {
                    //if (!this._securityDescriptor.DiscretionaryAcl.EveryOneFullAccessForNullDacl)
                    {
                        dacl = new DiscretionaryAcl(false, false, rawSecurityDescriptor.DiscretionaryAcl);
                    }
                    securityInfo = (SecurityInfos)(((rawSecurityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected) == ControlFlags.None ?
                                                    (uint)securityInfo | UnprotectedDiscretionaryAcl : (uint)securityInfo | ProtectedDiscretionaryAcl));
                }
            }
            if (securityInfo == 0)
            {
                return;
            }

            int errorNum = SetSecurityInfo(ResourceType.FileObject, name, null, securityInfo, owner, @group, sacl, dacl);

            if (errorNum != 0)
            {
                Exception exception = GetExceptionFromWin32Error(errorNum, name);
                if (exception == null)
                {
                    if (errorNum == NativeMethods.ERROR_ACCESS_DENIED)
                    {
                        exception = new UnauthorizedAccessException();
                    }
                    else if (errorNum == NativeMethods.ERROR_INVALID_OWNER)
                    {
                        exception = new InvalidOperationException("Invalid owner");
                    }
                    else if (errorNum == NativeMethods.ERROR_INVALID_PRIMARY_GROUP)
                    {
                        exception = new InvalidOperationException("Invalid group");
                    }
                    else if (errorNum == NativeMethods.ERROR_INVALID_NAME)
                    {
                        exception = new ArgumentException("Invalid name", "name");
                    }
                    else if (errorNum == NativeMethods.ERROR_INVALID_HANDLE)
                    {
                        exception = new NotSupportedException("Invalid Handle");
                    }
                    else if (errorNum == NativeMethods.ERROR_FILE_NOT_FOUND)
                    {
                        exception = new FileNotFoundException();
                    }
                    else if (errorNum != NativeMethods.ERROR_NO_SECURITY_ON_OBJECT)
                    {
                        exception = new InvalidOperationException("Unexpected error");
                    }
                    else
                    {
                        exception = new NotSupportedException("No associated security");
                    }
                }
                throw exception;
            }
            //finally
            //{
            //security.WriteLUnlck();
            //}
        }
 internal static extern int ClusterRegGetKeySecurity(
     [In] SafeHKey hKey,
     [In] SecurityInfos securityInformation,
     [In, Out] byte[] securityDescriptor,
     [In, Out] ref uint lpcbSecurityDescriptor);
Exemplo n.º 31
0
        //
        // Attempts to persist the security descriptor onto the object
        //

        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 != Interop.mincore.Errors.ERROR_SUCCESS)
                {
                    System.Exception exception = null;

                    if (_exceptionFromErrorCode != null)
                    {
                        exception = _exceptionFromErrorCode(error, name, handle, exceptionContext);
                    }

                    if (exception == null)
                    {
                        if (error == Interop.mincore.Errors.ERROR_ACCESS_DENIED)
                        {
                            exception = new UnauthorizedAccessException();
                        }
                        else if (error == Interop.mincore.Errors.ERROR_INVALID_OWNER)
                        {
                            exception = new InvalidOperationException(SR.AccessControl_InvalidOwner);
                        }
                        else if (error == Interop.mincore.Errors.ERROR_INVALID_PRIMARY_GROUP)
                        {
                            exception = new InvalidOperationException(SR.AccessControl_InvalidGroup);
                        }
                        else if (error == Interop.mincore.Errors.ERROR_INVALID_NAME)
                        {
                            exception = new ArgumentException(
                                SR.Argument_InvalidName,
                                nameof(name));
                        }
                        else if (error == Interop.mincore.Errors.ERROR_INVALID_HANDLE)
                        {
                            exception = new NotSupportedException(SR.AccessControl_InvalidHandle);
                        }
                        else if (error == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND)
                        {
                            exception = new FileNotFoundException();
                        }
                        else if (error == Interop.mincore.Errors.ERROR_NO_SECURITY_ON_OBJECT)
                        {
                            exception = new NotSupportedException(SR.AccessControl_NoAssociatedSecurity);
                        }
                        else
                        {
                            Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Unexpected error code {0}", error));
                            exception = new InvalidOperationException(SR.Format(SR.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();
            }
        }
 internal static extern int ClusterRegSetKeySecurity(
     [In] SafeHKey hKey,
     [In] SecurityInfos securityInformation,
     [In] byte[] securityDescriptor);
Exemplo n.º 33
0
        internal static int ConvertSdToSddl(byte[] binaryForm, int requestedRevision, SecurityInfos si, out string resultSddl)
        {
            int    num;
            IntPtr ptr;
            uint   resultStringLength = 0;

            if (1 != Win32Native.ConvertSdToStringSd(binaryForm, (uint)requestedRevision, (uint)si, out ptr, ref resultStringLength))
            {
                num = Marshal.GetLastWin32Error();
            }
            else
            {
                resultSddl = Marshal.PtrToStringUni(ptr);
                Win32Native.LocalFree(ptr);
                return(0);
            }
            resultSddl = null;
            if (num == 8)
            {
                throw new OutOfMemoryException();
            }
            return(num);
        }
Exemplo n.º 34
0
 public static extern bool QueryServiceObjectSecurity(IntPtr serviceHandle, SecurityInfos secInfo, ref SECURITY_DESCRIPTOR lpSecDesrBuf, uint bufSize, out uint bufSizeNeeded);
Exemplo n.º 35
0
        // this method is called by SecurityInfoCCW.SetSecurity in order to handle 
        // security information saving process
        // it stores the data into the registry
        // [saves data from UI to registry]
        public void SetSecurity(
            SecurityInfos providedInformation,
            IntPtr pSecurityDescriptor
            )
        {
            string stringSecurityDescriptor = "";
            SecurityIdentifier sid;

            IntPtr pszSD;
            int size = 0;

#pragma warning suppress 56523
            bool ret = SafeNativeMethods.ConvertSecurityDescriptorToStringSecurityDescriptorW(
                pSecurityDescriptor,
                1 /* SDDL_REVISION_1 == 1 (according to specs, this should always be 1 */,
                providedInformation,
                out pszSD,
                out size
                );
            if (!ret)
            {
                current.KerberosGlobalAcl = new string[] { "" };
                return;
            }

            stringSecurityDescriptor = Marshal.PtrToStringUni(pszSD);
#pragma warning suppress 56523
            SafeNativeMethods.LocalFree(pszSD);

            ArrayList allowed = new ArrayList();
            RawAcl rawDacl = new RawSecurityDescriptor(stringSecurityDescriptor).DiscretionaryAcl;
            DiscretionaryAcl dacl = new DiscretionaryAcl(false, false, rawDacl);

            for (int i = 0; i < dacl.Count; i++)
            {
                if (((CommonAce)dacl[i]).AceType == AceType.AccessAllowed)
                {
                    sid = ((CommonAce)dacl[i]).SecurityIdentifier;
                    allowed.Add(sid.Translate(typeof(NTAccount)).Value);
                }
            }

            current.KerberosGlobalAcl = (string[])allowed.ToArray(typeof(string));
        }
Exemplo n.º 36
0
 public static extern bool SetServiceObjectSecurity(SafeHandle serviceHandle, SecurityInfos secInfos, byte[] lpSecDesrBuf);
Exemplo n.º 37
0
 public static extern bool QueryServiceObjectSecurity(SafeHandle serviceHandle, SecurityInfos secInfo, byte[] lpSecDesrBuf, uint bufSize, out uint bufSizeNeeded);
Exemplo n.º 38
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.Advapi32.SetSecurityInfoByName(name, (uint)type, unchecked ((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.Advapi32.SetSecurityInfoByHandle(handle, (uint)type, (uint)securityInformation, OwnerBinary, GroupBinary, DaclBinary, SaclBinary);
                    }
                }
                else
                {
                    // both are null, shouldn't happen
                    Debug.Fail("Internal error: both name and handle are null");
                    throw new ArgumentException();
                }

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

            return(errorCode);
        }
Exemplo n.º 39
0
 private static extern int SetKeySetSecurityInfo(SafeProvHandle hProv, SecurityInfos securityInfo, byte[] sd);
Exemplo n.º 40
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.Advapi32.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.Advapi32.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.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.Errors.ERROR_NOT_ALL_ASSIGNED ||
                         errorCode == Interop.Errors.ERROR_PRIVILEGE_NOT_HELD)
                {
                    throw new PrivilegeNotHeldException(Privilege.Security);
                }
                else if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED ||
                         errorCode == Interop.Errors.ERROR_CANT_OPEN_ANONYMOUS)
                {
                    throw new UnauthorizedAccessException();
                }

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

            byte[] BinaryForm = new byte[Length];

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

            Marshal.FreeHGlobal(ByteArray);

            resultSd = new RawSecurityDescriptor(BinaryForm, 0);

            return(Interop.Errors.ERROR_SUCCESS);

Error:

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

            return(errorCode);
        }
Exemplo n.º 41
0
        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)NativeMethods.SetSecurityInfoByName(name, (uint)type, (uint)securityInformation, OwnerBinary, GroupBinary, DaclBinary, SaclBinary);
                }
                else if (handle != null)
                {
                    if (handle.IsInvalid)
                    {
                        throw new ArgumentException("Invalid safe handle");
                    }
                    else
                    {
                        errorCode = (int)NativeMethods.SetSecurityInfoByHandle(handle, (uint)type, (uint)securityInformation, OwnerBinary, GroupBinary, DaclBinary, SaclBinary);
                    }
                }
                else
                {
                    // both are null, shouldn't happen
                    throw new InvalidProgramException();
                }

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

            return errorCode;
        }
Exemplo n.º 42
0
 public static extern bool SetServiceObjectSecurity(IntPtr serviceHandle,
                                                    SecurityInfos secInfos,
                                                    [In] byte[] lpSecDesrBuf);
Exemplo n.º 43
0
 public static extern bool QueryServiceObjectSecurity(IntPtr serviceHandle,
                                                      SecurityInfos secInfo,
                                                      [Out] byte[] lpSecDesrBuf, uint bufSize,
                                                      out uint bufSizeNeeded);
Exemplo n.º 44
0
        public static string CopyPermissions(string source_file, string dest_file)
        {
            string errmsg             = string.Empty;
            IntPtr sidOwner           = IntPtr.Zero;
            IntPtr sidOwnerDescriptor = IntPtr.Zero;
            IntPtr sidGroup           = IntPtr.Zero;
            IntPtr sidGroupDescriptor = IntPtr.Zero;
            IntPtr dacl           = IntPtr.Zero;
            IntPtr daclDescriptor = IntPtr.Zero;
            IntPtr sacl           = IntPtr.Zero;

            try
            {
                int result = GetNamedSecurityInfo(source_file, SE_OBJECT_TYPE.SE_FILE_OBJECT, SecurityInfos.DiscretionaryAcl, out sidOwner, out sidGroup, out dacl, out sacl, out daclDescriptor);
                if (result != 0)
                {
                    Win32Exception e = new Win32Exception(result);
                    errmsg = "ERROR: " + e.Message;
                    return(errmsg);
                }
                result = GetNamedSecurityInfo(source_file, SE_OBJECT_TYPE.SE_FILE_OBJECT, SecurityInfos.Owner, out sidOwner, out sidGroup, out dacl, out sacl, out sidGroupDescriptor);
                if (result != 0)
                {
                    Win32Exception e = new Win32Exception(result);
                    errmsg = "ERROR: " + e.Message;
                    return(errmsg);
                }
                result = GetNamedSecurityInfo(source_file, SE_OBJECT_TYPE.SE_FILE_OBJECT, SecurityInfos.Group, out sidOwner, out sidGroup, out dacl, out sacl, out sidGroupDescriptor);
                if (result != 0)
                {
                    Win32Exception e = new Win32Exception(result);
                    errmsg = "ERROR: " + e.Message;
                    return(errmsg);
                }
                SecurityInfos info = SecurityInfos.DiscretionaryAcl | SecurityInfos.Group | SecurityInfos.Owner;
                result = SetNamedSecurityInfo(dest_file, SE_OBJECT_TYPE.SE_FILE_OBJECT, info, sidOwner, sidGroup, dacl, sacl);
                if (result != 0)
                {
                    Win32Exception e = new Win32Exception(result);
                    errmsg = "ERROR: " + e.Message;
                    return(errmsg);
                }
            }
            finally
            {
                if (sidOwnerDescriptor != IntPtr.Zero && LocalFree(sidOwnerDescriptor) != IntPtr.Zero)
                {
                    int            err = Marshal.GetLastWin32Error();
                    Win32Exception e   = new Win32Exception(err);
                    errmsg += "ERROR: " + e.Message;
                }
                if (sidGroupDescriptor != IntPtr.Zero && LocalFree(sidGroupDescriptor) != IntPtr.Zero)
                {
                    int            err = Marshal.GetLastWin32Error();
                    Win32Exception e   = new Win32Exception(err);
                    errmsg += "ERROR: " + e.Message;
                }
                if (daclDescriptor != IntPtr.Zero && LocalFree(daclDescriptor) != IntPtr.Zero)
                {
                    int            err = Marshal.GetLastWin32Error();
                    Win32Exception e   = new Win32Exception(err);
                    errmsg += "ERROR: " + e.Message;
                }
            }
            return(errmsg);
        }
Exemplo n.º 45
0
		static extern int GetNamedSecurityInfo (string name, ResourceType resourceType, SecurityInfos securityInfos,
							out IntPtr owner, out IntPtr group, out IntPtr dacl, out IntPtr sacl,
							out IntPtr descriptor);
Exemplo n.º 46
0
        /// <summary>
        /// Gets a service's security descriptor as SDDL.
        /// </summary>
        public static string GetServiceSDDL(string ServiceName, SecurityInfos SecurityInfos)
        {
            ServiceController sc = new ServiceController(ServiceName);
            byte[] psd = new byte[0];
            uint bufSizeNeeded;
            bool ok = QueryServiceObjectSecurity(sc.ServiceHandle, SecurityInfos, psd, 0, out bufSizeNeeded);
            if (!ok)
            {
                int err = Marshal.GetLastWin32Error();
                if (err == 122) // ERROR_INSUFFICIENT_BUFFER
                {
                    // expected; now we know bufsize
                    psd = new byte[bufSizeNeeded];
                    ok = QueryServiceObjectSecurity(sc.ServiceHandle, SecurityInfos, psd, bufSizeNeeded, out bufSizeNeeded);
                }
                else
                {
                    throw new ApplicationException("error calling QueryServiceObjectSecurity() to get DACL for SeaweedService: error code=" + err);
                }
            }
            if (!ok)
                throw new ApplicationException("error calling QueryServiceObjectSecurity(2) to get DACL for SeaweedService: error code=" + Marshal.GetLastWin32Error());

            return ConvertSDtoStringSD(psd);
        }
Exemplo n.º 47
0
		static extern int SetNamedSecurityInfo (string name, ResourceType resourceType, SecurityInfos securityInfos,
							byte[] owner, byte[] group, byte[] dacl, byte[] sacl);
        private void Persist(string name, SafeHandle handle, AccessControlSections includeSections, object exceptionContext)
        {
            base.WriteLock();
            try
            {
                SecurityInfos      securityInformation = 0;
                SecurityIdentifier owner = null;
                SecurityIdentifier group = null;
                SystemAcl          sacl  = null;
                DiscretionaryAcl   dacl  = null;
                if (((includeSections & AccessControlSections.Owner) != AccessControlSections.None) && (base._securityDescriptor.Owner != null))
                {
                    securityInformation |= SecurityInfos.Owner;
                    owner = base._securityDescriptor.Owner;
                }
                if (((includeSections & AccessControlSections.Group) != AccessControlSections.None) && (base._securityDescriptor.Group != null))
                {
                    securityInformation |= SecurityInfos.Group;
                    group = base._securityDescriptor.Group;
                }
                if ((includeSections & AccessControlSections.Audit) != AccessControlSections.None)
                {
                    securityInformation |= SecurityInfos.SystemAcl;
                    if ((base._securityDescriptor.IsSystemAclPresent && (base._securityDescriptor.SystemAcl != null)) && (base._securityDescriptor.SystemAcl.Count > 0))
                    {
                        sacl = base._securityDescriptor.SystemAcl;
                    }
                    else
                    {
                        sacl = null;
                    }
                    if ((base._securityDescriptor.ControlFlags & ControlFlags.SystemAclProtected) != ControlFlags.None)
                    {
                        securityInformation |= (SecurityInfos)this.ProtectedSystemAcl;
                    }
                    else
                    {
                        securityInformation |= (SecurityInfos)this.UnprotectedSystemAcl;
                    }
                }
                if (((includeSections & AccessControlSections.Access) != AccessControlSections.None) && base._securityDescriptor.IsDiscretionaryAclPresent)
                {
                    securityInformation |= SecurityInfos.DiscretionaryAcl;
                    if (base._securityDescriptor.DiscretionaryAcl.EveryOneFullAccessForNullDacl)
                    {
                        dacl = null;
                    }
                    else
                    {
                        dacl = base._securityDescriptor.DiscretionaryAcl;
                    }
                    if ((base._securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected) != ControlFlags.None)
                    {
                        securityInformation |= (SecurityInfos)this.ProtectedDiscretionaryAcl;
                    }
                    else
                    {
                        securityInformation |= (SecurityInfos)this.UnprotectedDiscretionaryAcl;
                    }
                }
                if (securityInformation == 0)
                {
                    return;
                }
                int errorCode = System.Security.AccessControl.Win32.SetSecurityInfo(this._resourceType, name, handle, securityInformation, owner, group, sacl, dacl);
                if (errorCode == 0)
                {
                    goto Label_0249;
                }
                Exception exception = null;
                if (this._exceptionFromErrorCode != null)
                {
                    exception = this._exceptionFromErrorCode(errorCode, name, handle, exceptionContext);
                }
                if (exception == null)
                {
                    switch (errorCode)
                    {
                    case 5:
                        exception = new UnauthorizedAccessException();
                        goto Label_0246;

                    case 0x51b:
                        exception = new InvalidOperationException(Environment.GetResourceString("AccessControl_InvalidOwner"));
                        goto Label_0246;

                    case 0x51c:
                        exception = new InvalidOperationException(Environment.GetResourceString("AccessControl_InvalidGroup"));
                        goto Label_0246;

                    case 0x7b:
                        exception = new ArgumentException(Environment.GetResourceString("Argument_InvalidName"), "name");
                        goto Label_0246;

                    case 6:
                        exception = new NotSupportedException(Environment.GetResourceString("AccessControl_InvalidHandle"));
                        goto Label_0246;

                    case 2:
                        exception = new FileNotFoundException();
                        goto Label_0246;

                    case 0x546:
                        exception = new NotSupportedException(Environment.GetResourceString("AccessControl_NoAssociatedSecurity"));
                        goto Label_0246;
                    }
                    exception = new InvalidOperationException(Environment.GetResourceString("AccessControl_UnexpectedError", new object[] { errorCode }));
                }
Label_0246:
                throw exception;
Label_0249:
                base.OwnerModified       = false;
                base.GroupModified       = false;
                base.AccessRulesModified = false;
                base.AuditRulesModified  = false;
            }
            finally
            {
                base.WriteUnlock();
            }
        }