public NativeSecurityAttributes(ObjectSecurity managedSecurityObject, bool inheritHandle)
 {
   length = Marshal.SizeOf(typeof(NativeSecurityAttributes));
   byte[] binarySecurityDescriptor = managedSecurityObject.GetSecurityDescriptorBinaryForm();
   securityDescriptor = Marshal.AllocHGlobal(binarySecurityDescriptor.Length);
   Marshal.Copy(binarySecurityDescriptor, 0, securityDescriptor, binarySecurityDescriptor.Length);
   this.inheritHandle = inheritHandle;
 }
      public KernelTransaction(ObjectSecurity securityDescriptor, uint timeout, string description)
      {
         if (!NativeMethods.IsAtLeastWindowsVista)
            throw new PlatformNotSupportedException(Resources.RequiresWindowsVistaOrHigher);

         using (var securityAttributes = new Security.NativeMethods.SecurityAttributes(securityDescriptor))
         {

            _hTrans = NativeMethods.CreateTransaction(securityAttributes, IntPtr.Zero, 0, 0, 0, timeout, description);
            int lastError = Marshal.GetLastWin32Error();            

            NativeMethods.IsValidHandle(_hTrans, lastError);
         }
      }
        } // GetSecurityDescriptor


        /// <summary>
        /// Internal wrapper for the SetSecurityDescriptor protected method. This method will
        /// only be called if the provider implements the ISecurityDescriptorCmdletProvider interface.
        /// </summary>
        /// 
        /// <param name="path">
        /// The path to the item to set the new security descriptor on.
        /// </param>
        /// 
        /// <param name="securityDescriptor">
        /// The new security descriptor for the item.
        /// </param>
        /// 
        /// <param name="context">
        /// The context under which this method is being called.
        /// </param>
        /// 
        /// <returns>
        /// Nothing. The security descriptor object that was set should be written
        /// to the context.
        /// </returns>
        /// 
        internal void SetSecurityDescriptor(
            string path,
            ObjectSecurity securityDescriptor,
            CmdletProviderContext context)
        {
            Context = context;

            ISecurityDescriptorCmdletProvider permissionProvider = this as ISecurityDescriptorCmdletProvider;

            //
            // if this is not supported, the fn will throw
            //
            CheckIfSecurityDescriptorInterfaceIsSupported(permissionProvider);

            // Call interface method

            permissionProvider.SetSecurityDescriptor(path, securityDescriptor);
        } // SetSecurityDescriptor
Exemple #4
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());
        }
 private static SafeGlobalMemoryBufferHandle ToUnmanagedSecurityAttributes(ObjectSecurity securityDescriptor)
 {
    if (securityDescriptor == null)
       return new SafeGlobalMemoryBufferHandle();
    
    
    byte[] src = securityDescriptor.GetSecurityDescriptorBinaryForm();
    var safeBuffer = new SafeGlobalMemoryBufferHandle(src.Length);
    try
    {
       safeBuffer.CopyFrom(src, 0, src.Length);
       return safeBuffer;
    }
    catch
    {
       safeBuffer.Close();
       throw;
    }
 }
 /// <summary>
 /// Sets the security descriptor for the item specified by the path.
 /// </summary>
 /// 
 /// <param name="path">
 /// The path to the item to set the new security descriptor on.
 /// </param>
 /// 
 /// <param name="securityDescriptor">
 /// The new security descriptor for the item.
 /// </param>
 /// 
 /// <remarks>
 /// An instance of an object that represents the security descriptor
 /// for the item specifed by the path should be written to the
 /// <see cref="System.Management.Automation.CmdletProvider.WriteSecurityDescriptorObject"/> 
 /// method.
 /// 
 /// This method should call
 /// <see cref="System.Management.Automation.CmdletProvider.ShouldProcess"/>
 /// and check its return value before making any changes to the store 
 /// this provider is working upon.
 /// </remarks>
 public void SetSecurityDescriptor( string path,
                 ObjectSecurity securityDescriptor )
 {
     // Write code for setting the new security
     // descriptor of the object here
     //
     // WriteSecurityDescriptorObject( path, securityDescriptor );
 }
Exemple #7
0
 public void WriteSecurityDescriptorObject(ObjectSecurity securityDescriptor, string path)
 {
     provider.WriteSecurityDescriptorObject(securityDescriptor, path);
 }
Exemple #8
0
 public void SetAccessControl(ObjectSecurity securityDescriptor)
 {
     throw new NotImplementedException("SetAccessControl(ObjectSecurity securityDescriptor) is not implemented. TransactedRegistry related APIs should not be used.");
 }
        void ISecurityDescriptorCmdletProvider.SetSecurityDescriptor(string path, ObjectSecurity securityDescriptor)
        {
            GenericObjectSecurity obj_security = securityDescriptor as GenericObjectSecurity;
            if (obj_security != null)
            {
                string relative_path = GetRelativePath(PSPathToNT(path));
                using (NtDirectory dir = GetPathDirectory(relative_path))
                {
                    ObjectDirectoryInformation dir_info = GetEntry(dir, relative_path);
                    if (dir_info == null)
                    {
                        throw new NtException(NtStatus.STATUS_OBJECT_NAME_NOT_FOUND);
                    }

                    using (NtObject obj = dir_info.Open(GenericAccessRights.WriteDac))
                    {
                        obj_security.PersistHandle(obj.Handle);
                    }
                }
            }
        }
      internal static DirectoryInfo CreateDirectoryInternal(KernelTransaction transaction, string path, string templatePath, ObjectSecurity directorySecurity, bool compress, PathFormat pathFormat)
      {
         if (pathFormat == PathFormat.RelativePath)
         {
            if (path != null && path[0] == Path.VolumeSeparatorChar)
               throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.PathFormatUnsupported, path));

            if (templatePath != null && templatePath[0] == Path.VolumeSeparatorChar)
               throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.PathFormatUnsupported, templatePath));

            Path.CheckValidPath(path, true, true);
            Path.CheckValidPath(templatePath, true, true);
         }
         else
            // MSDN:. NET 3.5+: NotSupportedException: Path contains a colon character (:) that is not part of a drive label ("C:\").
            Path.CheckValidPath(path, false, false);

         string pathLp = Path.GetExtendedLengthPathInternal(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator);

         // Return DirectoryInfo instance if the directory specified by path already exists.
         if (File.ExistsInternal(true, transaction, pathLp, PathFormat.LongFullPath))
            return new DirectoryInfo(transaction, pathLp, PathFormat.LongFullPath);

         // MSDN: .NET 3.5+: IOException: The directory specified by path is a file or the network name was not found.
         if (File.ExistsInternal(false, transaction, pathLp, PathFormat.LongFullPath))
            NativeError.ThrowException(Win32Errors.ERROR_ALREADY_EXISTS, pathLp);


         string templatePathLp = Utils.IsNullOrWhiteSpace(templatePath)
            ? null
            : Path.GetExtendedLengthPathInternal(transaction, templatePath, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator);

         #region Construct Full Path

         string longPathPrefix = Path.IsUncPath(path, false) ? Path.LongPathUncPrefix : Path.LongPathPrefix;
         path = Path.GetRegularPathInternal(pathLp, GetFullPathOptions.None);

         int length = path.Length;
         if (length >= 2 && Path.IsDVsc(path[length - 1], false))
            --length;

         int rootLength = Path.GetRootLength(path, false);
         if (length == 2 && Path.IsDVsc(path[1], false))
            throw new ArgumentException(Resources.CannotCreateDirectory, path);


         // Check if directories are missing.
         Stack<string> list = new Stack<string>(100);

         if (length > rootLength)
         {
            for (int index = length - 1; index >= rootLength; --index)
            {
               string path1 = path.Substring(0, index + 1);
               string path2 = longPathPrefix + path1.TrimStart('\\');

               if (!File.ExistsInternal(true, transaction, path2, PathFormat.LongFullPath))
                  list.Push(path2);

               while (index > rootLength && !Path.IsDVsc(path[index], false))
                  --index;
            }
         }

         #endregion // Construct Full Path

         // Directory security.
         using (Security.NativeMethods.SecurityAttributes securityAttributes = new Security.NativeMethods.SecurityAttributes(directorySecurity))
         {
            // Create the directory paths.
            while (list.Count > 0)
            {
               string folderLp = list.Pop();

               // In the ANSI version of this function, the name is limited to 248 characters.
               // To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.
               // 2013-01-13: MSDN confirms LongPath usage.

               bool createOk = (transaction == null || !NativeMethods.IsAtLeastWindowsVista
                  ? (templatePathLp == null
                     ? NativeMethods.CreateDirectory(folderLp, securityAttributes)
                     : NativeMethods.CreateDirectoryEx(templatePathLp, folderLp, securityAttributes))
                  : NativeMethods.CreateDirectoryTransacted(templatePathLp, folderLp, securityAttributes, transaction.SafeHandle));

               if (!createOk)
               {
                  int lastError = Marshal.GetLastWin32Error();

                  switch ((uint)lastError)
                  {
                     // MSDN: .NET 3.5+: If the directory already exists, this method does nothing.
                     // MSDN: .NET 3.5+: IOException: The directory specified by path is a file.
                     case Win32Errors.ERROR_ALREADY_EXISTS:
                        if (File.ExistsInternal(false, transaction, pathLp, PathFormat.LongFullPath))
                           NativeError.ThrowException(lastError, pathLp);

                        if (File.ExistsInternal(false, transaction, folderLp, PathFormat.LongFullPath))
                           NativeError.ThrowException(Win32Errors.ERROR_PATH_NOT_FOUND, folderLp);
                        break;

                     case Win32Errors.ERROR_BAD_NET_NAME:
                        NativeError.ThrowException(lastError, pathLp);
                        break;

                     case Win32Errors.ERROR_DIRECTORY:
                        // MSDN: .NET 3.5+: NotSupportedException: path contains a colon character (:) that is not part of a drive label ("C:\").
                        throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, Resources.PathFormatUnsupported, path));

                     default:
                        NativeError.ThrowException(lastError, folderLp);
                        break;
                  }
               }
               else if (compress)
                  Device.ToggleCompressionInternal(true, transaction, folderLp, true, PathFormat.LongFullPath);
            }
         }

         return new DirectoryInfo(transaction, pathLp, PathFormat.FullPath);
      }
Exemple #11
0
 private void SetSecurityDescriptor(string path, ObjectSecurity sd, AccessControlSections sections)
 {
     byte[] securityDescriptorBinaryForm = sd.GetSecurityDescriptorBinaryForm();
     if (Directory.Exists(path))
     {
         DirectorySecurity directorySecurity = new DirectorySecurity();
         directorySecurity.SetSecurityDescriptorBinaryForm(securityDescriptorBinaryForm, sections);
         Directory.SetAccessControl(path, directorySecurity);
         base.WriteSecurityDescriptorObject(directorySecurity, path);
     }
     else
     {
         FileSecurity fileSecurity = new FileSecurity();
         fileSecurity.SetSecurityDescriptorBinaryForm(securityDescriptorBinaryForm, sections);
         File.SetAccessControl(path, fileSecurity);
         base.WriteSecurityDescriptorObject(fileSecurity, path);
     }
 }
Exemple #12
0
		public void SetSecurityDescriptor(string path, ObjectSecurity securityDescriptor)
		{
			ADPropertyValueCollection aDPropertyValueCollection;
			this.Trace(DebugLogLevel.Verbose, "Entering SetSecurityDescriptor");
			Collection<string> strs = new Collection<string>();
			if (!this.IsValidRootDSEPath(path))
			{
				path = this.ValidateAndNormalizePath(path);
				if (securityDescriptor != null)
				{
					ActiveDirectorySecurity activeDirectorySecurity = securityDescriptor as ActiveDirectorySecurity;
					if (activeDirectorySecurity != null)
					{
						if (base.ShouldProcess(path, "Set"))
						{
							ADSessionInfo sessionInfo = this.GetSessionInfo(null, base.Credential, this.ExtendedDriveInfo);
							ADObject aDObject = new ADObject();
							aDObject.DistinguishedName = path;
							ADActiveObject aDActiveObject = new ADActiveObject(sessionInfo, aDObject);
							strs.Add("ntSecurityDescriptor");
							aDActiveObject.SecurityDescriptorFlags = SecurityMasks.None;
							using (aDActiveObject)
							{
								try
								{
									if (!aDObject.Contains("ntSecurityDescriptor"))
									{
										aDPropertyValueCollection = new ADPropertyValueCollection();
										aDObject.Add("ntSecurityDescriptor", aDPropertyValueCollection);
									}
									else
									{
										aDPropertyValueCollection = aDObject["ntSecurityDescriptor"];
									}
									aDObject["ntSecurityDescriptor"].Value = activeDirectorySecurity;
									aDActiveObject.Update();
									aDObject = this.GetValidatedADObject(path, strs, null, base.Credential, this.ExtendedDriveInfo);
								}
								catch (ADException aDException1)
								{
									ADException aDException = aDException1;
									base.WriteError(ADUtilities.GetErrorRecord(aDException, "ADProvider:SetSecurityDescriptor:ADError", path));
									this.Trace(DebugLogLevel.Error, "Leaving SetSecurityDescriptor: ADException: AD error");
									return;
								}
								catch (UnauthorizedAccessException unauthorizedAccessException1)
								{
									UnauthorizedAccessException unauthorizedAccessException = unauthorizedAccessException1;
									base.WriteError(ADUtilities.GetErrorRecord(unauthorizedAccessException, "ADProvider:SetSecurityDescriptor:AccessDenied", path));
									this.Trace(DebugLogLevel.Error, "Leaving SetSecurityDescriptor: ADException: access denied");
									return;
								}
								catch (AuthenticationException authenticationException1)
								{
									AuthenticationException authenticationException = authenticationException1;
									base.WriteError(ADUtilities.GetErrorRecord(authenticationException, "ADProvider:SetSecurityDescriptor:InvalidCredentials", path));
									this.Trace(DebugLogLevel.Error, "Leaving SetSecurityDescriptor: ADException: invalid credentials");
									return;
								}
								catch (InvalidOperationException invalidOperationException1)
								{
									InvalidOperationException invalidOperationException = invalidOperationException1;
									base.WriteError(ADUtilities.GetErrorRecord(invalidOperationException, "ADProvider:SetSecurityDescriptor:InvalidOperation", path));
									this.Trace(DebugLogLevel.Error, "Leaving SetSecurityDescriptor: ADException: invalid operation");
									return;
								}
								this.WriteADObjectSecurityDescriptor(aDObject, activeDirectorySecurity, null, this.ExtendedDriveInfo);
								this.Trace(DebugLogLevel.Verbose, "Leaving SetSecurityDescriptor");
								return;
							}
							return;
						}
						else
						{
							this.Trace(DebugLogLevel.Info, "Leaving SetSecurityDescriptor: ShouldProcess returned false.");
							return;
						}
					}
					else
					{
						base.WriteError(ADUtilities.GetErrorRecord(new ArgumentException("securityDescriptor"), "ADProvider:SetSecurityDescriptor:InvalidSecurityDescriptor", path));
						this.Trace(DebugLogLevel.Error, "Leaving SetSecurityDescriptor: ArgumentException: securityDescriptor is of incorrect type");
						return;
					}
				}
				else
				{
					base.WriteError(ADUtilities.GetErrorRecord(new ArgumentException("securityDescriptor"), "ADProvider:SetSecurityDescriptor:InvalidSecurityDescriptor", path));
					this.Trace(DebugLogLevel.Error, "Leaving SetSecurityDescriptor: ArgumentException: securityDescriptor is null");
					return;
				}
			}
			else
			{
				base.WriteError(ADUtilities.GetErrorRecord(new NotSupportedException(StringResources.ADProviderOperationNotSupportedForRootDSE), "NotSupported", path));
				this.Trace(DebugLogLevel.Error, "Leaving SetSecurityDescriptor: NotSupportedException: path is rootdse");
				return;
			}
		}
        public void SetSecurityDescriptor(string path, ObjectSecurity securityDescriptor)
        {
            GenericObjectSecurity obj_security = securityDescriptor as GenericObjectSecurity;
            if (obj_security != null)
            {
                using (NtDirectory dir = GetPathDirectory(path))
                {
                    ObjectDirectoryInformation dir_info = GetEntry(dir, path);
                    if (dir_info == null)
                    {
                        throw new NtException(NtStatus.STATUS_OBJECT_NAME_NOT_FOUND);
                    }

                    using (NtObject obj = dir_info.Open(GenericAccessRights.WriteDac))
                    {
                        obj_security.PersistHandle(obj.Handle);
                    }
                }
            }
        }
Exemple #14
0
 public void SetSecurityDescriptor(string path, ObjectSecurity securityDescriptor)
 {
     IRegistryWrapper regkeyForPathWriteIfError = null;
     ObjectSecurity security;
     if (string.IsNullOrEmpty(path))
     {
         throw PSTraceSource.NewArgumentException("path");
     }
     if (securityDescriptor == null)
     {
         throw PSTraceSource.NewArgumentNullException("securityDescriptor");
     }
     path = this.NormalizePath(path);
     if (base.TransactionAvailable())
     {
         security = securityDescriptor as TransactedRegistrySecurity;
         if (security == null)
         {
             throw PSTraceSource.NewArgumentException("securityDescriptor");
         }
     }
     else
     {
         security = securityDescriptor as RegistrySecurity;
         if (security == null)
         {
             throw PSTraceSource.NewArgumentException("securityDescriptor");
         }
     }
     regkeyForPathWriteIfError = this.GetRegkeyForPathWriteIfError(path, true);
     if (regkeyForPathWriteIfError != null)
     {
         try
         {
             regkeyForPathWriteIfError.SetAccessControl(security);
         }
         catch (SecurityException exception)
         {
             base.WriteError(new ErrorRecord(exception, exception.GetType().FullName, ErrorCategory.PermissionDenied, path));
             return;
         }
         catch (UnauthorizedAccessException exception2)
         {
             base.WriteError(new ErrorRecord(exception2, exception2.GetType().FullName, ErrorCategory.PermissionDenied, path));
             return;
         }
         base.WriteSecurityDescriptorObject(security, path);
     }
 }
 public Collection<PSObject> Set(string path, ObjectSecurity sd)
 {
     throw new NotImplementedException();
 }
Exemple #16
0
 public void SetSecurityDescriptor(string path, ObjectSecurity securityDescriptor)
 {
     if (string.IsNullOrEmpty(path))
     {
         throw PSTraceSource.NewArgumentException("path");
     }
     path = NormalizePath(path);
     if (securityDescriptor == null)
     {
         throw PSTraceSource.NewArgumentNullException("securityDescriptor");
     }
     if (!File.Exists(path) && !Directory.Exists(path))
     {
         base.ThrowTerminatingError(CreateErrorRecord(path, "SetSecurityDescriptor_FileNotFound"));
     }
     FileSystemSecurity sd = securityDescriptor as FileSystemSecurity;
     if (sd == null)
     {
         throw PSTraceSource.NewArgumentException("securityDescriptor");
     }
     try
     {
         this.SetSecurityDescriptor(path, sd, AccessControlSections.All);
     }
     catch (PrivilegeNotHeldException)
     {
         ObjectSecurity accessControl = File.GetAccessControl(path);
         Type targetType = typeof(NTAccount);
         AccessControlSections all = AccessControlSections.All;
         if ((sd.GetAuditRules(true, true, targetType).Count == 0) && (sd.AreAuditRulesProtected == accessControl.AreAccessRulesProtected))
         {
             all &= ~AccessControlSections.Audit;
         }
         if (sd.GetOwner(targetType) == accessControl.GetOwner(targetType))
         {
             all &= ~AccessControlSections.Owner;
         }
         if (sd.GetGroup(targetType) == accessControl.GetGroup(targetType))
         {
             all &= ~AccessControlSections.Group;
         }
         this.SetSecurityDescriptor(path, sd, all);
     }
 }
Exemple #17
0
		private void WriteSecurityDescriptorObjectWithAbsolutePath(ObjectSecurity securityDescriptor, string path)
		{
			base.WriteSecurityDescriptorObject(securityDescriptor, ADProvider.AddAbsolutePathPrefix(path));
		}
Exemple #18
0
        } // WritePropertyObject

        /// <summary>
        /// Writes a Security Descriptor object to the output as a PSObject with extra data attached
        /// as notes.
        /// </summary>
        /// 
        /// <param name="securityDescriptor">
        /// The Security Descriptor to be written.
        /// </param>
        ///
        /// <param name="path">
        /// The path of the item from which the Security Descriptor was retrieved.
        /// </param> 
        ///
        /// <!--
        /// If streaming is on and the writeObjectHandler was specified then the object
        /// gets written to the writeObjectHandler. If streaming is on and the writeObjectHandler
        /// was not specified and the command object was specified, the object gets written to
        /// the WriteObject method of the command object. 
        /// If streaming is off the object gets written to an accumulator collection. The collection
        /// of written object can be retrieved using the AccumulatedObjects method.
        /// -->
        public void WriteSecurityDescriptorObject(
            ObjectSecurity securityDescriptor,
            string path)
        {
            using (PSTransactionManager.GetEngineProtectionScope())
            {
                WriteObject(securityDescriptor, path);
            }
        } // WriteSecurityDescriptorObject
Exemple #19
0
 public void SetAccessControl(ObjectSecurity securityDescriptor)
 {
     using (_provider.CurrentPSTransaction)
     {
         _txRegKey.SetAccessControl((TransactedRegistrySecurity)securityDescriptor);
     }
 }
Exemple #20
0
 public void SetAccessControl(ObjectSecurity fileSecurity)
 {
    File.SetAccessControlInternal(null, SafeFileHandle, fileSecurity, AccessControlSections.All, PathFormat.RelativePath);
 }
      internal static void SetAccessControlInternal(string path, SafeHandle handle, ObjectSecurity objectSecurity, AccessControlSections includeSections, PathFormat pathFormat)
      {
         if (pathFormat == PathFormat.RelativePath)
            Path.CheckValidPath(path, true, true);

         if (objectSecurity == null)
            throw new ArgumentNullException("objectSecurity");

         byte[] managedDescriptor = objectSecurity.GetSecurityDescriptorBinaryForm();
         using (var safeBuffer = new SafeGlobalMemoryBufferHandle(managedDescriptor.Length))
         {
            string pathLp = Path.GetExtendedLengthPathInternal(null, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars);

            safeBuffer.CopyFrom(managedDescriptor, 0, managedDescriptor.Length);

            SecurityDescriptorControl control;
            uint revision;
            if (!Security.NativeMethods.GetSecurityDescriptorControl(safeBuffer, out control, out revision))
               NativeError.ThrowException(Marshal.GetLastWin32Error(), pathLp);

            PrivilegeEnabler privilegeEnabler = null;
            try
            {
               var securityInfo = SecurityInformation.None;

               IntPtr pDacl = IntPtr.Zero;
               if ((includeSections & AccessControlSections.Access) != 0)
               {
                  bool daclDefaulted, daclPresent;
                  if (!Security.NativeMethods.GetSecurityDescriptorDacl(safeBuffer, out daclPresent, out pDacl, out daclDefaulted))
                     NativeError.ThrowException(Marshal.GetLastWin32Error(), pathLp);

                  if (daclPresent)
                  {
                     securityInfo |= SecurityInformation.Dacl;
                     securityInfo |= (control & SecurityDescriptorControl.DaclProtected) != 0
                        ? SecurityInformation.ProtectedDacl
                        : SecurityInformation.UnprotectedDacl;
                  }
               }

               IntPtr pSacl = IntPtr.Zero;
               if ((includeSections & AccessControlSections.Audit) != 0)
               {
                  bool saclDefaulted, saclPresent;
                  if (!Security.NativeMethods.GetSecurityDescriptorSacl(safeBuffer, out saclPresent, out pSacl, out saclDefaulted))
                     NativeError.ThrowException(Marshal.GetLastWin32Error(), pathLp);

                  if (saclPresent)
                  {
                     securityInfo |= SecurityInformation.Sacl;
                     securityInfo |= (control & SecurityDescriptorControl.SaclProtected) != 0
                        ? SecurityInformation.ProtectedSacl
                        : SecurityInformation.UnprotectedSacl;

                     privilegeEnabler = new PrivilegeEnabler(Privilege.Security);
                  }
               }

               IntPtr pOwner = IntPtr.Zero;
               if ((includeSections & AccessControlSections.Owner) != 0)
               {
                  bool ownerDefaulted;
                  if (!Security.NativeMethods.GetSecurityDescriptorOwner(safeBuffer, out pOwner, out ownerDefaulted))
                     NativeError.ThrowException(Marshal.GetLastWin32Error(), pathLp);

                  if (pOwner != IntPtr.Zero)
                     securityInfo |= SecurityInformation.Owner;
               }

               IntPtr pGroup = IntPtr.Zero;
               if ((includeSections & AccessControlSections.Group) != 0)
               {
                  bool groupDefaulted;
                  if (!Security.NativeMethods.GetSecurityDescriptorGroup(safeBuffer, out pGroup, out groupDefaulted))
                     NativeError.ThrowException(Marshal.GetLastWin32Error(), pathLp);

                  if (pGroup != IntPtr.Zero)
                     securityInfo |= SecurityInformation.Group;
               }


               uint lastError;
               if (!Utils.IsNullOrWhiteSpace(pathLp))
               {
                  // SetNamedSecurityInfo()
                  // In the ANSI version of this function, the name is limited to MAX_PATH characters.
                  // To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.
                  // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists.

                  lastError = Security.NativeMethods.SetNamedSecurityInfo(pathLp, ObjectType.FileObject, securityInfo, pOwner, pGroup, pDacl, pSacl);
                  if (lastError != Win32Errors.ERROR_SUCCESS)
                     NativeError.ThrowException(lastError, pathLp);
               }
               else if (NativeMethods.IsValidHandle(handle))
               {
                  lastError = Security.NativeMethods.SetSecurityInfo(handle, ObjectType.FileObject, securityInfo, pOwner, pGroup, pDacl, pSacl);
                  if (lastError != Win32Errors.ERROR_SUCCESS)
                     NativeError.ThrowException((int)lastError);
               }
            }
            finally
            {
               if (privilegeEnabler != null)
                  privilegeEnabler.Dispose();
            }
         }
      }
Exemple #22
0
        /// <summary>
        /// Sets the security descriptor for the item specified by <paramref name="path"/>
        /// </summary>
        /// 
        /// <param name="path">
        /// The path to the item to set the security descriptor on.
        /// </param>
        /// 
        /// <param name="securityDescriptor">
        /// The new security descriptor for the item.
        /// </param>
        public void SetSecurityDescriptor(
            string path,
            ObjectSecurity securityDescriptor)
        {
            IRegistryWrapper key = null;

            if (String.IsNullOrEmpty(path))
            {
                throw PSTraceSource.NewArgumentException("path");
            }

            if (securityDescriptor == null)
            {
                throw PSTraceSource.NewArgumentNullException("securityDescriptor");
            }

            path = NormalizePath(path);

            ObjectSecurity sd;
            if (TransactionAvailable())
            {
                sd = securityDescriptor as TransactedRegistrySecurity;

                if (sd == null)
                {
                    throw PSTraceSource.NewArgumentException("securityDescriptor");
                }
            }
            else
            {
                sd = securityDescriptor as RegistrySecurity;

                if (sd == null)
                {
                    throw PSTraceSource.NewArgumentException("securityDescriptor");
                }
            }

            key = GetRegkeyForPathWriteIfError(path, true);

            if (key != null)
            {
                //
                // the caller already checks for the following exceptions:
                // -- UnauthorizedAccessException
                // -- PrivilegeNotHeldException
                // -- NotSupportedException
                // -- SystemException
                //
                try
                {
                    key.SetAccessControl(sd);
                }
                catch (System.Security.SecurityException e)
                {
                    WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.PermissionDenied, path));
                    return;
                }
                catch (System.UnauthorizedAccessException e)
                {
                    WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.PermissionDenied, path));
                    return;
                }

                WriteSecurityDescriptorObject(sd, path);
            }
        } // SetSecurityDescriptor
Exemple #23
0
 internal Collection<PSObject> SetSecurityDescriptor(string path, ObjectSecurity securityDescriptor)
 {
     if (path == null)
     {
         throw PSTraceSource.NewArgumentNullException("path");
     }
     if (securityDescriptor == null)
     {
         throw PSTraceSource.NewArgumentNullException("securityDescriptor");
     }
     CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
     this.SetSecurityDescriptor(path, securityDescriptor, context);
     context.ThrowFirstErrorOrDoNothing();
     Collection<PSObject> accumulatedObjects = context.GetAccumulatedObjects();
     if (accumulatedObjects == null)
     {
         accumulatedObjects = new Collection<PSObject>();
     }
     return accumulatedObjects;
 }
Exemple #24
0
 public void SetAccessControl(ObjectSecurity securityDescriptor)
 {
     this.regKey.SetAccessControl((RegistrySecurity) securityDescriptor);
 }
Exemple #25
0
 internal void SetSecurityDescriptor(string path, ObjectSecurity securityDescriptor, CmdletProviderContext context)
 {
     if (path == null)
     {
         throw PSTraceSource.NewArgumentNullException("path");
     }
     if (securityDescriptor == null)
     {
         throw PSTraceSource.NewArgumentNullException("securityDescriptor");
     }
     ProviderInfo info = null;
     CmdletProvider providerInstance = null;
     foreach (string str in this.Globber.GetGlobbedProviderPathsFromMonadPath(path, false, context, out info, out providerInstance))
     {
         this.SetSecurityDescriptor(providerInstance, str, securityDescriptor, context);
     }
 }
Exemple #26
0
        private static void SetSecurity(ObjectSecurity security)
        {
            if (null == security)
            {
                throw new ArgumentNullException("security");
            }

            // Set the DACL.
            security.SetSecurityDescriptorSddlForm("D:(A;;GA;;;WD)", AccessControlSections.Access);

            // Can only set integrity levels in the SACL for Vista and newer.
            Version vista = new Version(6, 0);
            if (vista <= Environment.OSVersion.Version)
            {
                security.SetSecurityDescriptorSddlForm("S:(ML;;NW;;;ME)", AccessControlSections.Audit);
            }
        }
Exemple #27
0
 private void SetSecurityDescriptor(CmdletProvider providerInstance, string path, ObjectSecurity securityDescriptor, CmdletProviderContext context)
 {
     GetPermissionProviderInstance(providerInstance);
     try
     {
         providerInstance.SetSecurityDescriptor(path, securityDescriptor, context);
     }
     catch (LoopFlowException)
     {
         throw;
     }
     catch (PipelineStoppedException)
     {
         throw;
     }
     catch (ActionPreferenceStopException)
     {
         throw;
     }
     catch (PrivilegeNotHeldException exception)
     {
         context.WriteError(new ErrorRecord(exception, exception.GetType().FullName, ErrorCategory.PermissionDenied, path));
     }
     catch (UnauthorizedAccessException exception2)
     {
         context.WriteError(new ErrorRecord(exception2, exception2.GetType().FullName, ErrorCategory.PermissionDenied, path));
     }
     catch (NotSupportedException exception3)
     {
         context.WriteError(new ErrorRecord(exception3, exception3.GetType().FullName, ErrorCategory.InvalidOperation, path));
     }
     catch (SystemException exception4)
     {
         CommandProcessorBase.CheckForSevereException(exception4);
         context.WriteError(new ErrorRecord(exception4, exception4.GetType().FullName, ErrorCategory.InvalidOperation, path));
     }
     catch (Exception exception5)
     {
         CommandProcessorBase.CheckForSevereException(exception5);
         throw this.NewProviderInvocationException("SetSecurityDescriptorProviderException", SessionStateStrings.SetSecurityDescriptorProviderException, providerInstance.ProviderInfo, path, exception5);
     }
 }
Exemple #28
0
 public void SetSecurityDescriptor(Path path, ObjectSecurity securityDescriptor)
 {
     throw new NotImplementedException();
 }
 public Collection<PSObject> Set(string path, ObjectSecurity sd)
 {
     return this.sessionState.SetSecurityDescriptor(path, sd);
 }
Exemple #30
0
 public void WriteSecurityDescriptorObject(ObjectSecurity securityDescriptor, string path)
 {
     throw new NotImplementedException();
 }
 internal void Set(string path, ObjectSecurity sd, CmdletProviderContext context)
 {
     this.sessionState.SetSecurityDescriptor(path, sd, context);
 }