Inheritance: GenericSecurityDescriptor
		private void CheckBinaryConstructor (string expectedSddl, byte[] binary)
		{
			RawSecurityDescriptor sd = new RawSecurityDescriptor (binary, 0);
			
			Assert.AreEqual (sd.BinaryLength, binary.Length);
			Assert.AreEqual (expectedSddl, sd.GetSddlForm (AccessControlSections.All));
		}
 internal CommonSecurityDescriptor(bool isContainer, bool isDS, RawSecurityDescriptor rawSecurityDescriptor, bool trusted)
 {
     if (rawSecurityDescriptor == null)
     {
         throw new ArgumentNullException("rawSecurityDescriptor");
     }
     this.CreateFromParts(isContainer, isDS, rawSecurityDescriptor.ControlFlags, rawSecurityDescriptor.Owner, rawSecurityDescriptor.Group, (rawSecurityDescriptor.SystemAcl == null) ? null : new System.Security.AccessControl.SystemAcl(isContainer, isDS, rawSecurityDescriptor.SystemAcl, trusted), (rawSecurityDescriptor.DiscretionaryAcl == null) ? null : new System.Security.AccessControl.DiscretionaryAcl(isContainer, isDS, rawSecurityDescriptor.DiscretionaryAcl, trusted));
 }
Beispiel #3
0
 public static void SetProcessSecurityDescriptor(IntPtr hWnd)
 {
     RawSecurityDescriptor sd = new RawSecurityDescriptor(ControlFlags.None, new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), null, null, new RawAcl(2, 0));
     sd.SetFlags(ControlFlags.DiscretionaryAclPresent | ControlFlags.DiscretionaryAclDefaulted);
     byte[] rawSd = new byte[sd.BinaryLength];
     sd.GetBinaryForm(rawSd, 0);
     if (!NativeMethods.Advapi32.SetKernelObjectSecurity(hWnd, (int)SecurityInfos.DiscretionaryAcl, rawSd))
         Console.WriteLine("Win32Exception(): {0}", new Win32Exception().Message);
 }
		private void CheckSddlConstructor (string sddl, byte[] expectedBinary)
		{
			RawSecurityDescriptor sd = new RawSecurityDescriptor (sddl);
			
			Assert.GreaterOrEqual (sd.BinaryLength, 0);
			byte[] buffer = new byte[sd.BinaryLength];
			
			sd.GetBinaryForm (buffer, 0);
			Assert.AreEqual (expectedBinary, buffer);
		}
		private void CheckRoundTrip (string sddl)
		{
			RawSecurityDescriptor sd = new RawSecurityDescriptor (sddl);
			
			byte[] buffer = new byte[sd.BinaryLength];
			sd.GetBinaryForm (buffer, 0);
			
			sd = new RawSecurityDescriptor (buffer, 0);
			Assert.AreEqual (sddl, sd.GetSddlForm (AccessControlSections.All));
		}
        public ACCESS_MASK ComputeAccess(RawSecurityDescriptor descriptor, IdentityReference identity)
        {
            var accessGranted = ACCESS_MASK.NONE;

            // Create the Resource Manager
            using (SafeAuthzRMHandle authzRM = InitializeResourceManager())
            using (SafeAuthzContextHandle userClientCtxt = InitializeContextFromSid(authzRM, identity))
            {
                accessGranted = AccessCheck(userClientCtxt, descriptor);
            }

            return accessGranted;
        }
        public void AllowUserAccessToCurrentProcess()
        {
            if (originalACL == null)
                return;

            IntPtr hProcess = GetCurrentProcess();
            // Read the DACL
            var dacl = new RawSecurityDescriptor(originalACL, 0);
            // Insert the new ACE

            SetProcessSecurityDescriptor(hProcess, dacl);

            originalACL = null;
        }
        private ACCESS_MASK AccessCheck(SafeAuthzContextHandle userClientCtxt, RawSecurityDescriptor descriptor)
        {
            ACCESS_MASK accessGranted;

            // Prepare the Access Check request
            var request = new NativeMethods.AUTHZ_ACCESS_REQUEST();
            request.DesiredAccess = ACCESS_MASK.MAXIMUM_ALLOWED;
            request.PrincipalSelfSid = null;
            request.ObjectTypeList = IntPtr.Zero;
            request.ObjectTypeListLength = 0;
            request.OptionalArguments = IntPtr.Zero;

            using (var grantedAccessBuffer = SafeAllocation.Create<ACCESS_MASK>())
            using (var errorBuffer = SafeAllocation.Create<uint>())
            {
                // Prepare the access check reply
                var reply = new NativeMethods.AUTHZ_ACCESS_REPLY();
                reply.ResultListLength = 1;
                reply.SaclEvaluationResults = IntPtr.Zero;
                reply.GrantedAccessMask = grantedAccessBuffer.DangerousGetHandle();
                reply.Error = errorBuffer.DangerousGetHandle();

                var rawSD = new byte[descriptor.BinaryLength];
                descriptor.GetBinaryForm(rawSD, 0);

                if (!NativeMethods.AuthzAccessCheck(
                    NativeMethods.AuthzACFlags.None,
                    userClientCtxt,
                    ref request,
                    IntPtr.Zero,
                    rawSD,
                    null,
                    0,
                    ref reply,
                    IntPtr.Zero))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                accessGranted = grantedAccessBuffer.ToStructure();
            }

            return accessGranted;
        }
Beispiel #9
0
        /// <summary>Sort ACEs according to canonical form for this <see cref="ObjectSecurity"/>.</summary>
        /// <param name="objectSecurity">The object security whose DiscretionaryAcl will be made canonical.</param>
        public static void CanonicalizeAccessRules(this ObjectSecurity objectSecurity)
        {
            if (objectSecurity == null)
            {
                throw new ArgumentNullException(nameof(objectSecurity));
            }
            if (objectSecurity.AreAccessRulesCanonical)
            {
                return;
            }

            // Get raw SD from objectSecurity and canonicalize DACL
            var sd = new RawSecurityDescriptor(objectSecurity.GetSecurityDescriptorBinaryForm(), 0);

            sd.DiscretionaryAcl.Canonicalize();

            // Convert SD back into objectSecurity
            objectSecurity.SetSecurityDescriptorBinaryForm(sd.GetBinaryForm());
        }
		void Init (bool isContainer, bool isDS, RawSecurityDescriptor rawSecurityDescriptor)
		{
			if (null == rawSecurityDescriptor)
				throw new ArgumentNullException ("rawSecurityDescriptor");
				
			SystemAcl sacl = null;
			if (null != rawSecurityDescriptor.SystemAcl)
				sacl = new SystemAcl (isContainer, isDS, rawSecurityDescriptor.SystemAcl);
				
			DiscretionaryAcl dacl = null;
			if (null != rawSecurityDescriptor.DiscretionaryAcl)
				dacl = new DiscretionaryAcl (isContainer, isDS, rawSecurityDescriptor.DiscretionaryAcl);
				
			Init (isContainer, isDS,
			      rawSecurityDescriptor.ControlFlags,
			      rawSecurityDescriptor.Owner,
			      rawSecurityDescriptor.Group,
			      sacl, dacl);
		}
        public void AclInheritance()
        {
            NtfsFileSystem ntfs = new FileSystemSource().NtfsFileSystem();

            RawSecurityDescriptor sd = new RawSecurityDescriptor("O:BAG:BAD:(A;OICINP;GA;;;BA)");
            ntfs.CreateDirectory("dir");
            ntfs.SetSecurity("dir", sd);

            ntfs.CreateDirectory(@"dir\subdir");
            RawSecurityDescriptor inheritedSd = ntfs.GetSecurity(@"dir\subdir");

            Assert.NotNull(inheritedSd);
            Assert.AreEqual("O:BAG:BAD:(A;ID;GA;;;BA)", inheritedSd.GetSddlForm(AccessControlSections.All));

            using (ntfs.OpenFile(@"dir\subdir\file", FileMode.Create, FileAccess.ReadWrite)) { }
            inheritedSd = ntfs.GetSecurity(@"dir\subdir\file");
            Assert.NotNull(inheritedSd);
            Assert.AreEqual("O:BAG:BAD:", inheritedSd.GetSddlForm(AccessControlSections.All));
        }
        public RawSecurityDescriptor GetSecurityDescriptor()
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentException("Path cannot be null or whitespace.", "path");
            }

            FileSystemSecurity security;
            if (!TryGetFileSecurity(path, AccessSectionsNeeded, out security))
            {
                if (!TryGetDirectorySecurity(path, AccessSectionsNeeded, out security))
                {
                    throw new ArgumentException("The path must be an existing file or directory.", path);
                }
            }

            var descriptorBinaryForm = security.GetSecurityDescriptorBinaryForm();
            var descriptor = new RawSecurityDescriptor(descriptorBinaryForm, 0);

            return descriptor;
        }
 // Token: 0x06001F8E RID: 8078 RVA: 0x0006E320 File Offset: 0x0006C520
 private void UpdateWithNewSecurityDescriptor(RawSecurityDescriptor newOne, AccessControlSections includeSections)
 {
     if ((includeSections & AccessControlSections.Owner) != AccessControlSections.None)
     {
         this._ownerModified            = true;
         this._securityDescriptor.Owner = newOne.Owner;
     }
     if ((includeSections & AccessControlSections.Group) != AccessControlSections.None)
     {
         this._groupModified            = true;
         this._securityDescriptor.Group = newOne.Group;
     }
     if ((includeSections & AccessControlSections.Audit) != AccessControlSections.None)
     {
         this._saclModified = true;
         if (newOne.SystemAcl != null)
         {
             this._securityDescriptor.SystemAcl = new SystemAcl(this.IsContainer, this.IsDS, newOne.SystemAcl, true);
         }
         else
         {
             this._securityDescriptor.SystemAcl = null;
         }
         this._securityDescriptor.UpdateControlFlags(ObjectSecurity.SACL_CONTROL_FLAGS, newOne.ControlFlags & ObjectSecurity.SACL_CONTROL_FLAGS);
     }
     if ((includeSections & AccessControlSections.Access) != AccessControlSections.None)
     {
         this._daclModified = true;
         if (newOne.DiscretionaryAcl != null)
         {
             this._securityDescriptor.DiscretionaryAcl = new DiscretionaryAcl(this.IsContainer, this.IsDS, newOne.DiscretionaryAcl, true);
         }
         else
         {
             this._securityDescriptor.DiscretionaryAcl = null;
         }
         ControlFlags controlFlags = this._securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclPresent;
         this._securityDescriptor.UpdateControlFlags(ObjectSecurity.DACL_CONTROL_FLAGS, (newOne.ControlFlags | controlFlags) & ObjectSecurity.DACL_CONTROL_FLAGS);
     }
 }
 public static string DecodeSsdl(string ssdlStr, StringBuilder decodeBuffer,
     StringBuilder domainBuffer, StringBuilder usernameBuffer, ref int formatted)
 {
     try
     {
         var ssdl = new RawSecurityDescriptor(ssdlStr);
         ++formatted;
         decodeBuffer.Remove(0, decodeBuffer.Length);
         decodeBuffer.Append("ControlFlags=")
           .Append(ssdl.ControlFlags)
           .Append("; ResourceManagerControlBits=")
           .Append(ssdl.ResourceManagerControl);
         if (ssdl.Group != null)
             decodeBuffer.Append("; Group=").Append(ssdl.Group);
         if (ssdl.Owner != null)
             decodeBuffer.Append("; Owner=").Append(ssdl.Owner);
         if (ssdl.DiscretionaryAcl != null)
         {
             foreach (var acl in ssdl.DiscretionaryAcl)
             {
                 decodeBuffer.Append("; DiscretionaryAcl");
                 DecodeAcl(acl, decodeBuffer, domainBuffer, usernameBuffer);
             }
         }
         if (ssdl.SystemAcl != null)
         {
             foreach (var acl in ssdl.SystemAcl)
             {
                 decodeBuffer.Append("; SystemAcl");
                 DecodeAcl(acl, decodeBuffer, domainBuffer, usernameBuffer);
             }
         }
         return decodeBuffer.ToString();
     }
     catch
     {
         return ssdlStr;
     }
 }
        public static VirtualHardDisk Create(string filename, ulong maximumSize,
            VirtualStorageDeviceTypes deviceType = VirtualStorageDeviceTypes.Vhd,
            VirtualDiskAccessMasks mask = VirtualDiskAccessMasks.All, RawSecurityDescriptor securityDescriptor = null,
            CreateVirtualDiskFlags flags = CreateVirtualDiskFlags.None, uint providerSpecificFlags = 0,
            Guid uniqueId = default(Guid), uint blockSizeInBytes = 0, uint sectorSizeInBytes = 0,
            string parentPath = null, string sourcePath = null, Overlapped overlapped = null)
        {
            if ()

            var storageType = new VirtualStorageType {DeviceId = deviceType};

            var parameters = new CreateVirtualDiskParameters
            {
                Version = CreateVirtualDiskVersions.Version1,
                Version1 = new CreateVirtualDiskParametersVersion1
                {
                    UniqueId = uniqueId,
                    MaximumSize = maximumSize,
                    BlockSizeInBytes = blockSizeInBytes,
                    SectorSizeInBytes = sectorSizeInBytes,
                    ParentPath = parentPath,
                    SourcePath = sourcePath
                }
            };

            var handle = VirtualDiskCore.CreateVirtualDisk(storageType, filename, mask, securityDescriptor, flags,
                providerSpecificFlags, parameters, overlapped);

            var vhd = new VirtualHardDisk(filename, handle);

            // ReSharper disable once InvertIf
            if (vhd.VirtualStorageType.DeviceId == VirtualStorageDeviceTypes.Iso)
            {
                vhd.Dispose();
                throw new NotSupportedException("This class does not support ISO files.");
            }

            return vhd;
        }
        public EffectiveAccess(string path,
                               string targetMachine,
                               RawSecurityDescriptor shareSD,
                               SecurityIdentifier userSid,
                               SecurityIdentifier deviceSid,
                               ClaimValueDictionary userClaims,
                               ClaimValueDictionary deviceClaims,
                               GroupsCollection userGroups,
                               GroupsCollection deviceGroups)
        {
            if (string.IsNullOrEmpty(targetMachine) && shareSD != null)
            {
                throw new ArgumentException("targetMachine must be value when shareSD is not-empty", "targetMachine");
            }

            handle = NativeMethods.CreateFile(path,
                                                NativeMethods.FileAccess.GenericRead,
                                                NativeMethods.FileShare.Read
                                              | NativeMethods.FileShare.Write
                                              | NativeMethods.FileShare.Delete,
                                              IntPtr.Zero,
                                              NativeMethods.FileMode.OpenExisting,
                                              NativeMethods.FileFlagAttrib.BackupSemantics,
                                              IntPtr.Zero);
            if (handle.IsInvalid)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            this.targetMachine = targetMachine;
            this.shareSD = shareSD;
            this.userSid = userSid;
            this.deviceSid = deviceSid;
            this.userClaims = userClaims;
            this.deviceClaims = deviceClaims;
            this.userGroups = userGroups;
            this.deviceGroups = deviceGroups;
        }
Beispiel #17
0
 private void CreateFromParts(bool isContainer, bool isDS, System.Security.AccessControl.ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, System.Security.AccessControl.SystemAcl systemAcl, System.Security.AccessControl.DiscretionaryAcl discretionaryAcl)
 {
     if ((systemAcl != null) && (systemAcl.IsContainer != isContainer))
     {
         throw new ArgumentException(Environment.GetResourceString(isContainer ? "AccessControl_MustSpecifyContainerAcl" : "AccessControl_MustSpecifyLeafObjectAcl"), "systemAcl");
     }
     if ((discretionaryAcl != null) && (discretionaryAcl.IsContainer != isContainer))
     {
         throw new ArgumentException(Environment.GetResourceString(isContainer ? "AccessControl_MustSpecifyContainerAcl" : "AccessControl_MustSpecifyLeafObjectAcl"), "discretionaryAcl");
     }
     this._isContainer = isContainer;
     if ((systemAcl != null) && (systemAcl.IsDS != isDS))
     {
         throw new ArgumentException(Environment.GetResourceString(isDS ? "AccessControl_MustSpecifyDirectoryObjectAcl" : "AccessControl_MustSpecifyNonDirectoryObjectAcl"), "systemAcl");
     }
     if ((discretionaryAcl != null) && (discretionaryAcl.IsDS != isDS))
     {
         throw new ArgumentException(Environment.GetResourceString(isDS ? "AccessControl_MustSpecifyDirectoryObjectAcl" : "AccessControl_MustSpecifyNonDirectoryObjectAcl"), "discretionaryAcl");
     }
     this._isDS = isDS;
     this._sacl = systemAcl;
     if (discretionaryAcl == null)
     {
         discretionaryAcl = System.Security.AccessControl.DiscretionaryAcl.CreateAllowEveryoneFullAccess(this._isDS, this._isContainer);
     }
     this._dacl = discretionaryAcl;
     System.Security.AccessControl.ControlFlags flags2 = flags | System.Security.AccessControl.ControlFlags.DiscretionaryAclPresent;
     if (systemAcl == null)
     {
         flags2 &= ~System.Security.AccessControl.ControlFlags.SystemAclPresent;
     }
     else
     {
         flags2 |= System.Security.AccessControl.ControlFlags.SystemAclPresent;
     }
     this._rawSd = new RawSecurityDescriptor(flags2, owner, group, (systemAcl == null) ? null : systemAcl.RawAcl, discretionaryAcl.RawAcl);
 }
 private void CreateFromParts(bool isContainer, bool isDS, System.Security.AccessControl.ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, System.Security.AccessControl.SystemAcl systemAcl, System.Security.AccessControl.DiscretionaryAcl discretionaryAcl)
 {
     if ((systemAcl != null) && (systemAcl.IsContainer != isContainer))
     {
         throw new ArgumentException(Environment.GetResourceString(isContainer ? "AccessControl_MustSpecifyContainerAcl" : "AccessControl_MustSpecifyLeafObjectAcl"), "systemAcl");
     }
     if ((discretionaryAcl != null) && (discretionaryAcl.IsContainer != isContainer))
     {
         throw new ArgumentException(Environment.GetResourceString(isContainer ? "AccessControl_MustSpecifyContainerAcl" : "AccessControl_MustSpecifyLeafObjectAcl"), "discretionaryAcl");
     }
     this._isContainer = isContainer;
     if ((systemAcl != null) && (systemAcl.IsDS != isDS))
     {
         throw new ArgumentException(Environment.GetResourceString(isDS ? "AccessControl_MustSpecifyDirectoryObjectAcl" : "AccessControl_MustSpecifyNonDirectoryObjectAcl"), "systemAcl");
     }
     if ((discretionaryAcl != null) && (discretionaryAcl.IsDS != isDS))
     {
         throw new ArgumentException(Environment.GetResourceString(isDS ? "AccessControl_MustSpecifyDirectoryObjectAcl" : "AccessControl_MustSpecifyNonDirectoryObjectAcl"), "discretionaryAcl");
     }
     this._isDS = isDS;
     this._sacl = systemAcl;
     if (discretionaryAcl == null)
     {
         discretionaryAcl = System.Security.AccessControl.DiscretionaryAcl.CreateAllowEveryoneFullAccess(this._isDS, this._isContainer);
     }
     this._dacl = discretionaryAcl;
     System.Security.AccessControl.ControlFlags flags2 = flags | System.Security.AccessControl.ControlFlags.DiscretionaryAclPresent;
     if (systemAcl == null)
     {
         flags2 &= ~System.Security.AccessControl.ControlFlags.SystemAclPresent;
     }
     else
     {
         flags2 |= System.Security.AccessControl.ControlFlags.SystemAclPresent;
     }
     this._rawSd = new RawSecurityDescriptor(flags2, owner, group, (systemAcl == null) ? null : systemAcl.RawAcl, discretionaryAcl.RawAcl);
 }
Beispiel #19
0
            public byte[] GetSecurity(SecurityInformation requestedInformation, bool wantDefault)
            {
                //FileSecurity fsec= new FileSecurity(@"c:\Test1\test.txt",~AccessControlSections.Audit);
                //return fsec.GetSecurityDescriptorBinaryForm();
                WindowsIdentity user = WindowsIdentity.GetCurrent();
                if (user != null)
                {
                    int length = 0;
                    IntPtr token = user.Token;
                    GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenDefaultDacl, IntPtr.Zero, 0, out length);
                    IntPtr TokenInformation = Marshal.AllocHGlobal((int) length);
                    bool Result = GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenDefaultDacl, TokenInformation, (uint) length,
                                                      out length);
                    TOKEN_DEFAULT_DACL dacl =
                        (TOKEN_DEFAULT_DACL) Marshal.PtrToStructure(TokenInformation, typeof (TOKEN_DEFAULT_DACL));
                    ACL acl = (ACL) Marshal.PtrToStructure(dacl.DefaultDacl, typeof (ACL));

                    byte[] aceArr = new byte[acl.AclSize];
                    Marshal.Copy(dacl.DefaultDacl, aceArr, 0, acl.AclSize);

                    RawAcl rawAcl = new RawAcl(aceArr, 0);

                    Marshal.FreeHGlobal(TokenInformation);
                    GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenOwner, IntPtr.Zero, 0, out length);
                    TokenInformation = Marshal.AllocHGlobal((int) length);
                    GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenOwner, TokenInformation, (uint)length,
                                                      out length);
                    TOKEN_OWNER tokOwner = (TOKEN_OWNER) Marshal.PtrToStructure(TokenInformation, typeof (TOKEN_OWNER));
                    SecurityIdentifier ownerSID= new SecurityIdentifier(tokOwner.Owner);

                    Marshal.FreeHGlobal(TokenInformation);
                    GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenPrimaryGroup, IntPtr.Zero, 0, out length);
                    TokenInformation = Marshal.AllocHGlobal((int)length);
                    GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenPrimaryGroup, TokenInformation, (uint)length,
                                                      out length);
                    TOKEN_PRIMARY_GROUP tokGroup= (TOKEN_PRIMARY_GROUP)Marshal.PtrToStructure(TokenInformation, typeof(TOKEN_PRIMARY_GROUP));
                    SecurityIdentifier groupSID = new SecurityIdentifier(tokGroup.PrimaryGroup);

                    RawSecurityDescriptor rawDesc = new RawSecurityDescriptor(ControlFlags.DiscretionaryAclPresent, ownerSID, groupSID, null, rawAcl);
                    byte[] ret = new byte[rawDesc.BinaryLength];
                    rawDesc.GetBinaryForm(ret, 0);
                    return ret;

                }
                return null;
            }
Beispiel #20
0
            private void SetCurrentProcessTokenDacl(RawAcl dacl)
            {
                IntPtr hProcess = IntPtr.Zero;
                IntPtr hProcessToken = IntPtr.Zero;
                IntPtr securityDescriptorPtr = IntPtr.Zero;
                try
                {
                    hProcess = NativeMethods.GetCurrentProcess();

                    if (!NativeMethods.OpenProcessToken(hProcess, NativeMethods.TOKEN_ALL_ACCESS, out hProcessToken))
                        Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());

                    // Get security descriptor associated with the kernel object and modify it.
                    uint returnLength;

                    NativeMethods.GetKernelObjectSecurity(hProcessToken, NativeMethods.SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, IntPtr.Zero, 0, out returnLength);
                    int lasterror = Marshal.GetLastWin32Error(); //#pragma warning disable 56523 doesnt recognize 56523

                    securityDescriptorPtr = Marshal.AllocCoTaskMem((int)returnLength);

                    if (!NativeMethods.GetKernelObjectSecurity(hProcessToken, NativeMethods.SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, securityDescriptorPtr, returnLength, out returnLength))
                        Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());

                    byte[] sdBytes = new byte[returnLength];
                    Marshal.Copy(securityDescriptorPtr, sdBytes, 0, (int)returnLength);

                    RawSecurityDescriptor rawSecurityDescriptor = new RawSecurityDescriptor(sdBytes, 0);
                    rawSecurityDescriptor.DiscretionaryAcl = dacl;

                    sdBytes = new byte[rawSecurityDescriptor.BinaryLength];
                    rawSecurityDescriptor.GetBinaryForm(sdBytes, 0);
                    Marshal.FreeCoTaskMem(securityDescriptorPtr);
                    securityDescriptorPtr = Marshal.AllocCoTaskMem(rawSecurityDescriptor.BinaryLength);
                    Marshal.Copy(sdBytes, 0, securityDescriptorPtr, rawSecurityDescriptor.BinaryLength);

                    if (!NativeMethods.SetKernelObjectSecurity(hProcessToken, NativeMethods.SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, securityDescriptorPtr))
                        Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }
                finally
                {
                    if (hProcess != IntPtr.Zero && hProcess != (IntPtr)(-1))
                        if (!NativeMethods.CloseHandle(hProcess))
                            Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());

                    if (hProcessToken != IntPtr.Zero)
                        if (!NativeMethods.CloseHandle(hProcessToken))
                            Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());

                    if (securityDescriptorPtr != IntPtr.Zero)
                        Marshal.FreeCoTaskMem(securityDescriptorPtr);

                }
            }
 /// <summary>Initializes a new instance of the <see cref="T:System.Security.AccessControl.CommonSecurityDescriptor" /> class from the specified <see cref="T:System.Security.AccessControl.RawSecurityDescriptor" /> object.</summary><param name="isContainer">true if the new security descriptor is associated with a container object.</param><param name="isDS">true if the new security descriptor is associated with a directory object.</param><param name="rawSecurityDescriptor">The <see cref="T:System.Security.AccessControl.RawSecurityDescriptor" /> object from which to create the new <see cref="T:System.Security.AccessControl.CommonSecurityDescriptor" /> object.</param>
 public CommonSecurityDescriptor(bool isContainer, bool isDS, RawSecurityDescriptor rawSecurityDescriptor)
 {
     throw new NotImplementedException();
 }
		public void GetSddlForm ()
		{
			RawSecurityDescriptor sd = new RawSecurityDescriptor ("");
			Assert.AreEqual ("", sd.GetSddlForm (AccessControlSections.All));
			
			// Ask for part of SD that isn't represented
			sd.Owner = new SecurityIdentifier (WellKnownSidType.BuiltinUsersSid, null);
			sd.Group = new SecurityIdentifier (WellKnownSidType.BuiltinAdministratorsSid, null);
			Assert.AreEqual ("", sd.GetSddlForm (AccessControlSections.Access));
			
			// Empty ACL form
			sd.DiscretionaryAcl = new RawAcl (2, 0);
			sd.SystemAcl = new RawAcl (1, 0);
			sd.SetFlags (sd.ControlFlags | ControlFlags.DiscretionaryAclPresent | ControlFlags.SystemAclPresent);
			Assert.AreEqual ("O:BUG:BAD:S:", sd.GetSddlForm (AccessControlSections.All));
			
			// Add an ACE to the DACL
			SecurityIdentifier builtInAdmins = new SecurityIdentifier (WellKnownSidType.BuiltinAdministratorsSid, null);
			CommonAce ace = new CommonAce (AceFlags.None, AceQualifier.AccessAllowed, 0x7FFFFFFF, builtInAdmins, false, null);
			sd.DiscretionaryAcl.InsertAce (0, ace);
			Assert.AreEqual ("O:BUG:BAD:(A;;0x7fffffff;;;BA)S:", sd.GetSddlForm (AccessControlSections.All));
			
			// Add second ACE to the DACL
			SecurityIdentifier randomUser = new SecurityIdentifier ("S-1-5-21-324-23423-234-334");
			ace = new CommonAce (AceFlags.Inherited | AceFlags.ContainerInherit, AceQualifier.AccessDenied, 0x12345678, randomUser, true, null);
			sd.DiscretionaryAcl.InsertAce (0, ace);
			Assert.AreEqual ("O:BUD:(XD;CIID;0x12345678;;;S-1-5-21-324-23423-234-334)(A;;0x7fffffff;;;BA)", sd.GetSddlForm (AccessControlSections.Owner | AccessControlSections.Access));
			
			// DACL & SACL flags
			sd.SetFlags (sd.ControlFlags | ControlFlags.DiscretionaryAclProtected | ControlFlags.DiscretionaryAclAutoInherited | ControlFlags.DiscretionaryAclAutoInheritRequired | ControlFlags.SystemAclAutoInherited);
			sd.DiscretionaryAcl = new RawAcl (1, 0);
			ace = new CommonAce (AceFlags.None, AceQualifier.AccessAllowed, 0x7FFFFFFF, builtInAdmins, false, null);
			sd.DiscretionaryAcl.InsertAce (0, ace);
			Assert.AreEqual ("O:BUG:BAD:PARAI(A;;0x7fffffff;;;BA)S:AI", sd.GetSddlForm (AccessControlSections.All));
			
			sd.SetFlags (sd.ControlFlags | ControlFlags.ServerSecurity | ControlFlags.DiscretionaryAclDefaulted);
			Assert.AreEqual ("O:BUG:BAD:PARAI(A;;0x7fffffff;;;BA)S:AI", sd.GetSddlForm (AccessControlSections.All));
		}
Beispiel #23
0
        private void DoSetSecurity(File file, RawSecurityDescriptor securityDescriptor)
        {
            NtfsStream legacyStream = file.GetStream(AttributeType.SecurityDescriptor, null);
            if (legacyStream != null)
            {
                SecurityDescriptor sd = new SecurityDescriptor();
                sd.Descriptor = securityDescriptor;
                legacyStream.SetContent(sd);
            }
            else
            {
                uint id = _context.SecurityDescriptors.AddDescriptor(securityDescriptor);

                // Update the standard information attribute - so it reflects the actual file state
                NtfsStream stream = file.GetStream(AttributeType.StandardInformation, null);
                StandardInformation si = stream.GetContent<StandardInformation>();
                si.SecurityId = id;
                stream.SetContent(si);

                // Write attribute changes back to the Master File Table
                file.UpdateRecordInMft();
            }
        }
Beispiel #24
0
 /// <summary>The SetServiceObjectSecurity function sets the security descriptor of a service object.</summary>
 /// <param name="hService">
 ///     A handle to the service. This handle is returned by the <see cref="OpenService" /> or
 ///     <see cref="CreateService(SafeServiceHandle,string,string,ACCESS_MASK,ServiceType,ServiceStartType,ServiceErrorControl,string,string,int, string,string,string)" /> function. The access required for this handle depends on the security information
 ///     specified in the <paramref name="dwSecurityInformation" /> parameter.
 /// </param>
 /// <param name="dwSecurityInformation">
 ///     Specifies the components of the security descriptor to set. This parameter can be a
 ///     combination of the following values : <see cref="SECURITY_INFORMATION.DACL_SECURITY_INFORMATION" />,
 ///     <see cref="SECURITY_INFORMATION.GROUP_SECURITY_INFORMATION" />,
 ///     <see cref="SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION" />,
 ///     <see cref="SECURITY_INFORMATION.SACL_SECURITY_INFORMATION" />. Note that flags not handled by
 ///     SetServiceObjectSecurity will be silently ignored.
 /// </param>
 /// <param name="lpSecurityDescriptor">The new security information.</param>
 public static void SetServiceObjectSecurity(
     SafeServiceHandle hService,
     SECURITY_INFORMATION dwSecurityInformation,
     RawSecurityDescriptor lpSecurityDescriptor)
 {
     var binaryForm = new byte[lpSecurityDescriptor.BinaryLength];
     lpSecurityDescriptor.GetBinaryForm(binaryForm, 0);
     if (!SetServiceObjectSecurity(hService, dwSecurityInformation, binaryForm))
     {
         throw new Win32Exception();
     }
 }
 public CommonSecurityDescriptor(bool isContainer, bool isDS, RawSecurityDescriptor rawSecurityDescriptor)
     : this(isContainer, isDS, rawSecurityDescriptor, false)
 {
 }
Beispiel #26
0
 public RawSecurityDescriptor(string sddlForm)
     : this(RawSecurityDescriptor.BinaryFormFromSddlForm(sddlForm), 0)
 {
 }
Beispiel #27
0
        public static IEnumerable <ACL> Get_DomainObjectAcl(Args_Get_DomainObjectAcl args = null)
        {
            if (args == null)
            {
                args = new Args_Get_DomainObjectAcl();
            }

            var SearcherArguments = new Args_Get_DomainSearcher
            {
                Properties      = new[] { "samaccountname", "ntsecuritydescriptor", "distinguishedname", "objectsid" },
                SecurityMasks   = args.Sacl ? SecurityMasks.Sacl : SecurityMasks.Dacl,
                Domain          = args.Domain,
                SearchBase      = args.SearchBase,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };
            var Searcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);

            var DomainGUIDMapArguments = new Args_Get_DomainGUIDMap
            {
                Domain          = args.Domain,
                Server          = args.Server,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                Credential      = args.Credential
            };

            // get a GUID -> name mapping
            IDictionary <string, string> GUIDs = null;

            if (args.ResolveGUIDs)
            {
                GUIDs = GetDomainGUIDMap.Get_DomainGUIDMap(DomainGUIDMapArguments);
            }

            var ACLs = new List <ACL>();

            if (Searcher != null)
            {
                var IdentityFilter = "";
                var Filter         = "";
                if (args.Identity != null)
                {
                    foreach (var item in args.Identity)
                    {
                        var IdentityInstance = item.Replace(@"(", @"\28").Replace(@")", @"\29");
                        if (IdentityInstance.IsRegexMatch(@"^S-1-.*"))
                        {
                            IdentityFilter += $@"(objectsid={IdentityInstance})";
                        }
                        else if (IdentityInstance.IsRegexMatch(@"^(CN|OU|DC)=.*"))
                        {
                            IdentityFilter += $@"(distinguishedname={IdentityInstance})";
                            if (args.Domain.IsNullOrEmpty() && args.SearchBase.IsNullOrEmpty())
                            {
                                // if a -Domain isn't explicitly set, extract the object domain out of the distinguishedname
                                // and rebuild the domain searcher
                                var IdentityDomain = IdentityInstance.Substring(IdentityInstance.IndexOf("DC=")).Replace("DC=", "").Replace(",", ".");
                                Logger.Write_Verbose($@"[Get-DomainObjectAcl] Extracted domain '{IdentityDomain}' from '{IdentityInstance}'");
                                SearcherArguments.Domain = IdentityDomain;
                                Searcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);
                                if (Searcher == null)
                                {
                                    Logger.Write_Warning($@"[Get-DomainObjectAcl] Unable to retrieve domain searcher for '{IdentityDomain}'");
                                }
                            }
                        }
                        else if (IdentityInstance.IsRegexMatch(@"^[0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}$"))
                        {
                            var GuidByteString = string.Join(string.Empty, Guid.Parse(IdentityInstance).ToByteArray().Select(x => x.ToString(@"\X2")));
                            IdentityFilter += $@"(objectguid={GuidByteString})";
                        }
                        else if (IdentityInstance.Contains('.'))
                        {
                            IdentityFilter += $@"(|(samAccountName={IdentityInstance})(name={IdentityInstance})(dnshostname={IdentityInstance}))";
                        }
                        else
                        {
                            IdentityFilter += $@"(|(samAccountName={IdentityInstance})(name={IdentityInstance})(displayname={IdentityInstance}))";
                        }
                    }
                }
                if (IdentityFilter != null && IdentityFilter.Trim() != "")
                {
                    Filter += $@"(|{IdentityFilter})";
                }

                if (args.LDAPFilter.IsNotNullOrEmpty())
                {
                    Logger.Write_Verbose($@"[Get-DomainObjectAcl] Using additional LDAP filter: {args.LDAPFilter}");
                    Filter += $@"{args.LDAPFilter}";
                }

                if (Filter.IsNotNullOrEmpty())
                {
                    Searcher.Filter = $@"(&{Filter})";
                }
                Logger.Write_Verbose($@"[Get-DomainObjectAcl] Get-DomainObjectAcl filter string: {Searcher.Filter}");

                var Results = Searcher.FindAll();
                foreach (SearchResult result in Results)
                {
                    var Object = result.Properties;

                    string ObjectSid = null;
                    if (Object["objectsid"] != null && Object["objectsid"].Count > 0 && Object["objectsid"][0] != null)
                    {
                        ObjectSid = new System.Security.Principal.SecurityIdentifier(Object["objectsid"][0] as byte[], 0).Value;
                    }
                    else
                    {
                        ObjectSid = null;
                    }

                    try
                    {
                        var rsd    = new System.Security.AccessControl.RawSecurityDescriptor(Object["ntsecuritydescriptor"][0] as byte[], 0);
                        var rawAcl = args.Sacl ? rsd.SystemAcl : rsd.DiscretionaryAcl;
                        foreach (var ace in rawAcl)
                        {
                            var acl = new ACL {
                                Ace = ace
                            };
                            bool Continue = false;
                            if (args.RightsFilter != null)
                            {
                                string GuidFilter = null;
                                switch (args.RightsFilter.Value)
                                {
                                case Rights.ResetPassword:
                                    GuidFilter = "00299570-246d-11d0-a768-00aa006e0529";
                                    break;

                                case Rights.WriteMembers:
                                    GuidFilter = "bf9679c0-0de6-11d0-a285-00aa003049e2";
                                    break;

                                default:
                                    GuidFilter = "00000000-0000-0000-0000-000000000000";
                                    break;
                                }
                                if (ace is System.Security.AccessControl.ObjectAccessRule)
                                {
                                    if (string.Compare(((object)ace as System.Security.AccessControl.ObjectAccessRule).ObjectType.ToString(), GuidFilter, StringComparison.OrdinalIgnoreCase) == 0)
                                    {
                                        acl.ObjectDN  = Object["distinguishedname"][0] as string;
                                        acl.ObjectSID = ObjectSid;
                                        Continue      = true;
                                    }
                                }
                            }
                            else
                            {
                                acl.ObjectDN  = Object["distinguishedname"][0] as string;
                                acl.ObjectSID = ObjectSid;
                                Continue      = true;
                            }
                            if (Continue)
                            {
                                if (ace is System.Security.AccessControl.KnownAce)
                                {
                                    acl.ActiveDirectoryRights = (System.DirectoryServices.ActiveDirectoryRights)(ace as System.Security.AccessControl.KnownAce).AccessMask;
                                }
                                if (GUIDs != null)
                                {
                                    // if we're resolving GUIDs, map them them to the resolved hash table
                                    if (ace is ObjectAce)
                                    {
                                        try { (acl.Ace as ObjectAce).ObjectAceType = new Guid(GUIDs[(ace as ObjectAce).ObjectAceType.ToString()]); }
                                        catch { }
                                        try { (acl.Ace as ObjectAce).InheritedObjectAceType = new Guid(GUIDs[(ace as ObjectAce).InheritedObjectAceType.ToString()]); }
                                        catch { }
                                    }
                                    else if (ace is ObjectAccessRule)
                                    {
                                        /*try { (acl.Ace as ObjectAccessRule).ObjectType = new Guid(GUIDs[(ace as ObjectAccessRule).ObjectType.ToString()]); }
                                         * catch { }
                                         * try { (acl.Ace as ObjectAccessRule).InheritedObjectType = new Guid(GUIDs[(ace as ObjectAccessRule).InheritedObjectType.ToString()]); }
                                         * catch { }*/
                                    }
                                }

                                ACLs.Add(acl);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Write_Verbose($@"[Get-DomainObjectAcl] Error: {e}");
                    }
                }
            }
            return(ACLs);
        }
        public static LDAPProperty Convert_LDAPProperty(System.DirectoryServices.ResultPropertyCollection Properties)
        {
            var ObjectProperties = new LDAPProperty();

            foreach (string propName in Properties.PropertyNames)
            {
                if (string.Compare(propName, @"adspath", StringComparison.OrdinalIgnoreCase) != 0)
                {
                    if (string.Compare(propName, @"objectsid", StringComparison.OrdinalIgnoreCase) == 0 ||
                        string.Compare(propName, @"sidhistory", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        // convert all listed sids (i.e. if multiple are listed in sidHistory)
                        var values = new List <string>();
                        foreach (var property in Properties[propName])
                        {
                            var sid = new System.Security.Principal.SecurityIdentifier(property as byte[], 0);
                            values.Add(sid.Value);
                        }
                        if (string.Compare(propName, @"objectsid", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            ObjectProperties.objectsid = values.ToArray();
                        }
                        else
                        {
                            ObjectProperties.sidhistory = values.ToArray();
                        }
                    }
                    else if (string.Compare(propName, @"grouptype", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.grouptype = (GroupType)Properties[propName][0];
                    }
                    else if (string.Compare(propName, @"samaccounttype", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.samaccounttype = (SamAccountType)Properties[propName][0];
                    }
                    else if (string.Compare(propName, @"objectguid", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        // convert the GUID to a string
                        ObjectProperties.objectguid = new Guid(Properties[propName][0] as byte[]).ToString();
                    }
                    else if (string.Compare(propName, @"useraccountcontrol", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.useraccountcontrol = (UACEnumValue)Properties[propName][0];
                    }
                    else if (string.Compare(propName, @"ntsecuritydescriptor", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        // $ObjectProperties[$_] = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList $Properties[$_][0], 0
                        var Descriptor = new System.Security.AccessControl.RawSecurityDescriptor(Properties[propName][0] as byte[], 0);
                        if (Descriptor.Owner != null)
                        {
                            ObjectProperties.Owner = Descriptor.Owner;
                        }
                        if (Descriptor.Group != null)
                        {
                            ObjectProperties.Group = Descriptor.Group;
                        }
                        if (Descriptor.DiscretionaryAcl != null)
                        {
                            ObjectProperties.DiscretionaryAcl = Descriptor.DiscretionaryAcl;
                        }
                        if (Descriptor.SystemAcl != null)
                        {
                            ObjectProperties.SystemAcl = Descriptor.SystemAcl;
                        }
                    }
                    else if (string.Compare(propName, @"accountexpires", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        if ((long)Properties[propName][0] >= DateTime.MaxValue.Ticks)
                        {
                            ObjectProperties.accountexpires = "NEVER";
                        }
                        else
                        {
                            ObjectProperties.accountexpires = DateTime.FromFileTime((long)Properties[propName][0]);
                        }
                    }
                    else if (string.Compare(propName, @"lastlogon", StringComparison.OrdinalIgnoreCase) == 0 ||
                             string.Compare(propName, @"lastlogontimestamp", StringComparison.OrdinalIgnoreCase) == 0 ||
                             string.Compare(propName, @"pwdlastset", StringComparison.OrdinalIgnoreCase) == 0 ||
                             string.Compare(propName, @"lastlogoff", StringComparison.OrdinalIgnoreCase) == 0 ||
                             string.Compare(propName, @"badPasswordTime", StringComparison.OrdinalIgnoreCase) == 0 ||
                             string.Compare(propName, @"whencreated", StringComparison.OrdinalIgnoreCase) == 0 ||
                             string.Compare(propName, @"whenchanged", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        DateTime dt;
                        // convert timestamps
                        if (Properties[propName][0] is System.MarshalByRefObject)
                        {
                            // if we have a System.__ComObject
                            var Temp = Properties[propName][0];
                            var High = (Int32)Temp.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, Temp, null);
                            var Low  = (Int32)Temp.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, Temp, null);
                            dt = DateTime.FromFileTime(Int64.Parse(string.Format("0x{0:x8}{1:x8}", High, Low)));
                        }
                        if (Properties[propName][0] is System.DateTime)
                        {
                            dt = (DateTime)Properties[propName][0];
                        }
                        else
                        {
                            // otherwise just a string
                            dt = DateTime.FromFileTime((long)Properties[propName][0]);
                        }
                        if (string.Compare(propName, @"lastlogon", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            ObjectProperties.lastlogon = dt;
                        }
                        else if (string.Compare(propName, @"lastlogontimestamp", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            ObjectProperties.lastlogontimestamp = dt;
                        }
                        else if (string.Compare(propName, @"pwdlastset", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            ObjectProperties.pwdlastset = dt;
                        }
                        else if (string.Compare(propName, @"lastlogoff", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            ObjectProperties.lastlogoff = dt;
                        }
                        else if (string.Compare(propName, @"badPasswordTime", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            ObjectProperties.badPasswordTime = dt;
                        }
                        else if (string.Compare(propName, @"whencreated", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            ObjectProperties.whencreated = dt;
                        }
                        else if (string.Compare(propName, @"whenchanged", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            ObjectProperties.whenchanged = dt;
                        }
                    }
                    else if (string.Compare(propName, @"name", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.name = Properties[propName][0] as string;
                    }
                    else if (string.Compare(propName, @"distinguishedname", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.distinguishedname = Properties[propName][0] as string;
                    }
                    else if (string.Compare(propName, @"dnsrecord", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.dnsrecord = Properties[propName][0];
                    }
                    else if (string.Compare(propName, @"samaccountname", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.samaccountname = Properties[propName][0] as string;
                    }
                    else if (string.Compare(propName, @"member", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.member = Properties[propName].GetValues <string>().ToArray();
                    }
                    else if (string.Compare(propName, @"memberof", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.memberof = Properties[propName].GetValues <string>().ToArray();
                    }
                    else if (string.Compare(propName, @"cn", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.cn = Properties[propName].GetValues <string>().ToArray();
                    }
                    else if (string.Compare(propName, @"objectclass", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.objectclass = Properties[propName].GetValues <string>().ToArray();
                    }
                    else if (string.Compare(propName, @"managedby", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.managedby = Properties[propName][0] as string;
                    }
                    else if (string.Compare(propName, @"siteobject", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.siteobject = Properties[propName][0] as string;
                    }
                    else if (string.Compare(propName, @"ServicePrincipalName", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.ServicePrincipalName = Properties[propName][0] as string;
                    }
                    else if (string.Compare(propName, @"dnshostname", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.dnshostname = Properties[propName][0] as string;
                    }
                    else if (string.Compare(propName, @"gplink", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.gplink = Properties[propName][0] as string;
                    }
                    else if (string.Compare(propName, @"gpoptions", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.gpoptions = (int)Properties[propName][0];
                    }
                    else if (string.Compare(propName, @"displayname", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.displayname = Properties[propName][0] as string;
                    }
                    else if (string.Compare(propName, @"path", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.path = Properties[propName][0] as string;
                    }
                    else if (string.Compare(propName, @"siteobjectbl", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ObjectProperties.siteobjectbl = Properties[propName][0] as string;
                    }
                    else if (Properties[propName][0] is System.MarshalByRefObject)
                    {
                        // try to convert misc com objects
                        var Prop = Properties[propName];
                        try
                        {
                            var Temp = Properties[propName][0];
                            var High = (Int32)Temp.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, Temp, null);
                            var Low  = (Int32)Temp.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, Temp, null);
                            ObjectProperties.others.Add(propName, Int64.Parse(string.Format("0x{0:x8}{1:x8}", High, Low)));
                        }
                        catch (Exception e)
                        {
                            Logger.Write_Verbose($@"[Convert-LDAPProperty] error: {e}");
                            ObjectProperties.others.Add(propName, Prop[0]);
                        }
                    }
                    else if (Properties[propName].Count == 1)
                    {
                        ObjectProperties.others.Add(propName, Properties[propName][0]);
                    }
                    else
                    {
                        ObjectProperties.others.Add(propName, Properties[propName]);
                    }
                }
            }
            return(ObjectProperties);
        }
        [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);
        }
Beispiel #30
0
        private void UpdateWithNewSecurityDescriptor( RawSecurityDescriptor newOne, AccessControlSections includeSections )
        {
            Contract.Assert( newOne != null, "Must not supply a null parameter here" );

            if (( includeSections & AccessControlSections.Owner ) != 0 )
            {
                _ownerModified = true;
                _securityDescriptor.Owner = newOne.Owner;
            }
 
            if (( includeSections & AccessControlSections.Group ) != 0 )
            {
                _groupModified = true;
                _securityDescriptor.Group = newOne.Group;
            }

            if (( includeSections & AccessControlSections.Audit ) != 0 )
            {
                _saclModified = true;
                if ( newOne.SystemAcl != null )
                {
                    _securityDescriptor.SystemAcl = new SystemAcl( IsContainer, IsDS, newOne.SystemAcl, true );
                }
                else
                {
                    _securityDescriptor.SystemAcl = null;
                }
                // carry forward the SACL related control flags
                _securityDescriptor.UpdateControlFlags(SACL_CONTROL_FLAGS, (ControlFlags)(newOne.ControlFlags & SACL_CONTROL_FLAGS));
            }

            if (( includeSections & AccessControlSections.Access ) != 0 )
            {
                _daclModified = true;
                if ( newOne.DiscretionaryAcl != null )
                {
                    _securityDescriptor.DiscretionaryAcl = new DiscretionaryAcl( IsContainer, IsDS, newOne.DiscretionaryAcl, true );
                }
                else
                {
                    _securityDescriptor.DiscretionaryAcl = null;
                }
                // by the following property set, the _securityDescriptor's control flags
                // may contains DACL present flag. That needs to be carried forward! Therefore, we OR
                // the current _securityDescriptor.s DACL present flag.
                ControlFlags daclFlag = (_securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclPresent);
                
                _securityDescriptor.UpdateControlFlags(DACL_CONTROL_FLAGS, 
                    (ControlFlags)((newOne.ControlFlags | daclFlag) & DACL_CONTROL_FLAGS));
            }
         }
Beispiel #31
0
        internal CommonSecurityDescriptor(bool isContainer, bool isDS, RawSecurityDescriptor rawSecurityDescriptor, bool trusted)
        {
            if (rawSecurityDescriptor == null)
            {
                throw new ArgumentNullException(nameof(rawSecurityDescriptor));
            }
            Contract.EndContractBlock();

            CreateFromParts(
                isContainer,
                isDS,
                rawSecurityDescriptor.ControlFlags,
                rawSecurityDescriptor.Owner,
                rawSecurityDescriptor.Group,
                rawSecurityDescriptor.SystemAcl == null ? null : new SystemAcl(isContainer, isDS, rawSecurityDescriptor.SystemAcl, trusted),
                rawSecurityDescriptor.DiscretionaryAcl == null ? null : new DiscretionaryAcl(isContainer, isDS, rawSecurityDescriptor.DiscretionaryAcl, trusted));
        }
Beispiel #32
0
        /// <summary>
        /// Sets the security descriptor associated with the file or directory.
        /// </summary>
        /// <param name="path">The file or directory to change.</param>
        /// <param name="securityDescriptor">The new security descriptor.</param>
        public void SetSecurity(string path, RawSecurityDescriptor securityDescriptor)
        {
            using (new NtfsTransaction())
            {
                DirectoryEntry dirEntry = GetDirectoryEntry(path);
                if (dirEntry == null)
                {
                    throw new FileNotFoundException("File not found", path);
                }
                else
                {
                    File file = GetFile(dirEntry.Reference);
                    DoSetSecurity(file, securityDescriptor);

                    // Update the directory entry used to open the file
                    dirEntry.UpdateFrom(file);
                }
            }
        }
Beispiel #33
0
        private static void CanonicalizeDacl(NativeObjectSecurity objectSecurity)
        {
            if (objectSecurity == null) { throw new ArgumentNullException("objectSecurity"); }
            if (objectSecurity.AreAccessRulesCanonical) { return; }

            // A canonical ACL must have ACES sorted according to the following order:
            // 1. Access-denied on the object
            // 2. Access-denied on a child or property
            // 3. Access-allowed on the object
            // 4. Access-allowed on a child or property
            // 5. All inherited ACEs
            RawSecurityDescriptor descriptor = new RawSecurityDescriptor(objectSecurity.GetSecurityDescriptorSddlForm(AccessControlSections.Access));

            List<CommonAce> implicitDenyDacl = new List<CommonAce>();
            List<CommonAce> implicitDenyObjectDacl = new List<CommonAce>();
            List<CommonAce> inheritedDacl = new List<CommonAce>();
            List<CommonAce> implicitAllowDacl = new List<CommonAce>();
            List<CommonAce> implicitAllowObjectDacl = new List<CommonAce>();

            foreach (CommonAce ace in descriptor.DiscretionaryAcl)
            {
                if ((ace.AceFlags & AceFlags.Inherited) == AceFlags.Inherited) { inheritedDacl.Add(ace); }
                else
                {
                    switch (ace.AceType)
                    {
                        case AceType.AccessAllowed:
                            implicitAllowDacl.Add(ace);
                            break;

                        case AceType.AccessDenied:
                            implicitDenyDacl.Add(ace);
                            break;

                        case AceType.AccessAllowedObject:
                            implicitAllowObjectDacl.Add(ace);
                            break;

                        case AceType.AccessDeniedObject:
                            implicitDenyObjectDacl.Add(ace);
                            break;
                    }
                }
            }

            Int32 aceIndex = 0;
            RawAcl newDacl = new RawAcl(descriptor.DiscretionaryAcl.Revision, descriptor.DiscretionaryAcl.Count);
            implicitDenyDacl.ForEach(x => newDacl.InsertAce(aceIndex++, x));
            implicitDenyObjectDacl.ForEach(x => newDacl.InsertAce(aceIndex++, x));
            implicitAllowDacl.ForEach(x => newDacl.InsertAce(aceIndex++, x));
            implicitAllowObjectDacl.ForEach(x => newDacl.InsertAce(aceIndex++, x));
            inheritedDacl.ForEach(x => newDacl.InsertAce(aceIndex++, x));

            if (aceIndex != descriptor.DiscretionaryAcl.Count)
            {
                System.Diagnostics.Debug.Fail("The DACL cannot be canonicalized since it would potentially result in a loss of information");
                return;
            }

            descriptor.DiscretionaryAcl = newDacl;
            objectSecurity.SetSecurityDescriptorSddlForm(descriptor.GetSddlForm(AccessControlSections.Access), AccessControlSections.Access);
        }
		public void FlagMismatch ()
		{
			// Check setting DACL-present flag on empty SD
			RawSecurityDescriptor sd = new RawSecurityDescriptor ("");
			Assert.AreEqual (20, sd.BinaryLength);
			sd.SetFlags (ControlFlags.DiscretionaryAclPresent);
			Assert.AreEqual (20, sd.BinaryLength);
			byte[] buffer = new byte[sd.BinaryLength];
			sd.GetBinaryForm (buffer, 0);
			byte[] sdBinary = new byte[] {
				0x01, 0x00, 0x04, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
				0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
			Assert.AreEqual (sdBinary, buffer);
			
			// Check unsetting DACL-present flag on SD with DACL
			sd = new RawSecurityDescriptor ("O:BUG:BAD:(A;;RPWPCCDCLCSWRCWDWOGA;;;S-1-0-0)");
			Assert.AreEqual (80, sd.BinaryLength);
			sd.SetFlags (sd.ControlFlags & ~ControlFlags.DiscretionaryAclPresent);
			Assert.AreEqual (ControlFlags.SelfRelative, sd.ControlFlags);
			Assert.AreEqual (52, sd.BinaryLength);
			buffer = new byte[sd.BinaryLength];
			sd.GetBinaryForm (buffer, 0);
			sdBinary = new byte[] {
				0x01, 0x00, 0x00, 0x80, 0x14, 0x00, 0x00, 0x00, 0x24, 0x00,
				0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
				0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00,
				0x00, 0x00, 0x21, 0x02, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00,
				0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02,
				0x00, 0x00 };
			Assert.AreEqual (sdBinary, buffer);
		}
        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);
        }
		public void GetBinaryForm ()
		{
			RawSecurityDescriptor sd = new RawSecurityDescriptor ("");
			sd.Owner = new SecurityIdentifier (WellKnownSidType.BuiltinUsersSid, null);
			sd.Group = new SecurityIdentifier (WellKnownSidType.BuiltinAdministratorsSid, null);
			sd.DiscretionaryAcl = new RawAcl (1, 0);
			sd.SystemAcl = new RawAcl (1, 0);
			sd.SetFlags (sd.ControlFlags | ControlFlags.DiscretionaryAclPresent | ControlFlags.SystemAclPresent);
			
			// Empty ACL form
			byte[] buffer = new byte[sd.BinaryLength];
			sd.GetBinaryForm (buffer, 0);
			byte[] sdBinary = new byte[] {
				0x01, 0x00, 0x14, 0x80, 0x14, 0x00, 0x00, 0x00, 0x24, 0x00,
				0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x3C, 0x00, 0x00, 0x00,
				0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00,
				0x00, 0x00, 0x21, 0x02, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00,
				0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02,
				0x00, 0x00, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,
				0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00 };
			Assert.AreEqual (sdBinary, buffer);
			
			// Add an ACE to the DACL
			SecurityIdentifier builtInAdmins = new SecurityIdentifier (WellKnownSidType.BuiltinAdministratorsSid, null);
			CommonAce ace = new CommonAce (AceFlags.None, AceQualifier.AccessAllowed, 0x7FFFFFFF, builtInAdmins, false, null);
			sd.DiscretionaryAcl.InsertAce (0, ace);
			buffer = new byte[sd.BinaryLength];
			sd.GetBinaryForm (buffer, 0);
			sdBinary = new byte[] {
				0x01, 0x00, 0x14, 0x80, 0x14, 0x00, 0x00, 0x00, 0x24, 0x00,
				0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x3C, 0x00, 0x00, 0x00,
				0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00,
				0x00, 0x00, 0x21, 0x02, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00,
				0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02,
				0x00, 0x00, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,
				0x01, 0x00, 0x20, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
				0x18, 0x00, 0xFF, 0xFF, 0xFF, 0x7F, 0x01, 0x02, 0x00, 0x00,
				0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02,
				0x00, 0x00 };
			Assert.AreEqual (sdBinary, buffer);
			
			// This time with an Object ACE
			ObjectAce objectAce = new ObjectAce (AceFlags.Inherited, AceQualifier.AccessAllowed, 0x12345678, builtInAdmins, ObjectAceFlags.ObjectAceTypePresent | ObjectAceFlags.InheritedObjectAceTypePresent, new Guid ("189c0dc7-b849-4dea-93a5-6d4cb8857a5c"), new Guid ("53b4a3d4-fe39-468b-bc60-b4fcba772fa5"), false, null);
			sd.DiscretionaryAcl = new RawAcl (2, 0);
			sd.DiscretionaryAcl.InsertAce (0, objectAce);
			buffer = new byte[sd.BinaryLength];
			sd.GetBinaryForm (buffer, 0);
			sdBinary = new byte[] {
				0x01, 0x00, 0x14, 0x80, 0x14, 0x00, 0x00, 0x00, 0x24, 0x00,
				0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x3C, 0x00, 0x00, 0x00,
				0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00,
				0x00, 0x00, 0x21, 0x02, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00,
				0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02,
				0x00, 0x00, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,
				0x02, 0x00, 0x44, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05, 0x10,
				0x3C, 0x00, 0x78, 0x56, 0x34, 0x12, 0x03, 0x00, 0x00, 0x00,
				0xC7, 0x0D, 0x9C, 0x18, 0x49, 0xB8, 0xEA, 0x4D, 0x93, 0xA5,
				0x6D, 0x4C, 0xB8, 0x85, 0x7A, 0x5C, 0xD4, 0xA3, 0xB4, 0x53,
				0x39, 0xFE, 0x8B, 0x46, 0xBC, 0x60, 0xB4, 0xFC, 0xBA, 0x77,
				0x2F, 0xA5, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05,
				0x20, 0x00, 0x00, 0x00, 0x20, 0x02, 0x00, 0x00 };
			Assert.AreEqual (sdBinary, buffer);
		}
 public CommonSecurityDescriptor(bool isContainer, bool isDS, RawSecurityDescriptor rawSecurityDescriptor)
 {
 }
Beispiel #38
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;
        }
Beispiel #39
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);
        }
        private void CreateFromParts(bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, SystemAcl systemAcl, DiscretionaryAcl discretionaryAcl)
        {
            if (systemAcl != null &&
                systemAcl.IsContainer != isContainer)
            {
                throw new ArgumentException(
                          isContainer ?
                          SR.AccessControl_MustSpecifyContainerAcl :
                          SR.AccessControl_MustSpecifyLeafObjectAcl,
                          nameof(systemAcl));
            }

            if (discretionaryAcl != null &&
                discretionaryAcl.IsContainer != isContainer)
            {
                throw new ArgumentException(
                          isContainer ?
                          SR.AccessControl_MustSpecifyContainerAcl :
                          SR.AccessControl_MustSpecifyLeafObjectAcl,
                          nameof(discretionaryAcl));
            }

            _isContainer = isContainer;

            if (systemAcl != null &&
                systemAcl.IsDS != isDS)
            {
                throw new ArgumentException(
                          isDS ?
                          SR.AccessControl_MustSpecifyDirectoryObjectAcl :
                          SR.AccessControl_MustSpecifyNonDirectoryObjectAcl,
                          nameof(systemAcl));
            }

            if (discretionaryAcl != null &&
                discretionaryAcl.IsDS != isDS)
            {
                throw new ArgumentException(
                          isDS ?
                          SR.AccessControl_MustSpecifyDirectoryObjectAcl :
                          SR.AccessControl_MustSpecifyNonDirectoryObjectAcl,
                          nameof(discretionaryAcl));
            }

            _isDS = isDS;

            _sacl = systemAcl;

            //
            // Replace null DACL with an allow-all for everyone DACL
            //

            if (discretionaryAcl == null)
            {
                //
                // to conform to native behavior, we will add allow everyone ace for DACL
                //

                discretionaryAcl = DiscretionaryAcl.CreateAllowEveryoneFullAccess(_isDS, _isContainer);
            }

            _dacl = discretionaryAcl;

            //
            // DACL is never null. So always set the flag bit on
            //

            ControlFlags actualFlags = flags | ControlFlags.DiscretionaryAclPresent;

            //
            // Keep SACL and the flag bit in sync.
            //

            if (systemAcl == null)
            {
                unchecked { actualFlags &= ~(ControlFlags.SystemAclPresent); }
            }
            else
            {
                actualFlags |= (ControlFlags.SystemAclPresent);
            }

            _rawSd = new RawSecurityDescriptor(actualFlags, owner, group, systemAcl == null ? null : systemAcl.RawAcl, discretionaryAcl.RawAcl);
        }
Beispiel #41
0
        private void CreateFromParts(bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, SystemAcl systemAcl, DiscretionaryAcl discretionaryAcl)
        {
            if (systemAcl != null &&
                systemAcl.IsContainer != isContainer)
            {
                throw new ArgumentException(
                     isContainer ?
                        SR.AccessControl_MustSpecifyContainerAcl :
                        SR.AccessControl_MustSpecifyLeafObjectAcl,
nameof(systemAcl));
            }

            if (discretionaryAcl != null &&
                discretionaryAcl.IsContainer != isContainer)
            {
                throw new ArgumentException(
                     isContainer ?
                        SR.AccessControl_MustSpecifyContainerAcl :
                        SR.AccessControl_MustSpecifyLeafObjectAcl,
nameof(discretionaryAcl));
            }

            _isContainer = isContainer;

            if (systemAcl != null &&
                systemAcl.IsDS != isDS)
            {
                throw new ArgumentException(
                     isDS ?
                        SR.AccessControl_MustSpecifyDirectoryObjectAcl :
                        SR.AccessControl_MustSpecifyNonDirectoryObjectAcl,
nameof(systemAcl));
            }

            if (discretionaryAcl != null &&
                discretionaryAcl.IsDS != isDS)
            {
                throw new ArgumentException(
                    isDS ?
                        SR.AccessControl_MustSpecifyDirectoryObjectAcl :
                        SR.AccessControl_MustSpecifyNonDirectoryObjectAcl,
nameof(discretionaryAcl));
            }

            _isDS = isDS;

            _sacl = systemAcl;

            //
            // Replace null DACL with an allow-all for everyone DACL
            //

            if (discretionaryAcl == null)
            {
                //
                // to conform to native behavior, we will add allow everyone ace for DACL
                //

                discretionaryAcl = DiscretionaryAcl.CreateAllowEveryoneFullAccess(_isDS, _isContainer);
            }

            _dacl = discretionaryAcl;

            //
            // DACL is never null. So always set the flag bit on
            //

            ControlFlags actualFlags = flags | ControlFlags.DiscretionaryAclPresent;

            //
            // Keep SACL and the flag bit in sync.
            //

            if (systemAcl == null)
            {
                unchecked { actualFlags &= ~(ControlFlags.SystemAclPresent); }
            }
            else
            {
                actualFlags |= (ControlFlags.SystemAclPresent);
            }

            _rawSd = new RawSecurityDescriptor(actualFlags, owner, group, systemAcl == null ? null : systemAcl.RawAcl, discretionaryAcl.RawAcl);
        }
 // Summary:
 //     Initializes a new instance of the System.Security.AccessControl.CommonSecurityDescriptor
 //     class from the specified System.Security.AccessControl.RawSecurityDescriptor
 //     object.
 //
 // Parameters:
 //   isContainer:
 //     true if the new security descriptor is associated with a container object.
 //
 //   isDS:
 //     true if the new security descriptor is associated with a directory object.
 //
 //   rawSecurityDescriptor:
 //     The System.Security.AccessControl.RawSecurityDescriptor object from which
 //     to create the new System.Security.AccessControl.CommonSecurityDescriptor
 //     object.
 extern public CommonSecurityDescriptor(bool isContainer, bool isDS, RawSecurityDescriptor rawSecurityDescriptor);
Beispiel #43
0
 public CommonSecurityDescriptor(bool isContainer, bool isDS, RawSecurityDescriptor rawSecurityDescriptor)
     : this(isContainer, isDS, rawSecurityDescriptor, false)
 {
 }