Пример #1
0
		protected override void ProcessRecord()
		{
			string sddlForm;
			ObjectSecurity objectSecurity = this.securityDescriptor as ObjectSecurity;
			if (this.inputObject == null)
			{
				if (this.Path != null)
				{
					if (objectSecurity != null)
					{
						if ((this.CentralAccessPolicy != null || this.ClearCentralAccessPolicy) && !DownLevelHelper.IsWin8AndAbove())
						{
							Exception parameterBindingException = new ParameterBindingException();
							base.WriteError(new ErrorRecord(parameterBindingException, "SetAcl_OperationNotSupported", ErrorCategory.InvalidArgument, null));
							return;
						}
						else
						{
							if (this.CentralAccessPolicy == null || !this.ClearCentralAccessPolicy)
							{
								IntPtr zero = IntPtr.Zero;
								NativeMethods.TOKEN_PRIVILEGE tOKENPRIVILEGE = new NativeMethods.TOKEN_PRIVILEGE();
								try
								{
									if (this.CentralAccessPolicy == null)
									{
										if (this.ClearCentralAccessPolicy)
										{
											zero = this.GetEmptySacl();
											if (zero == IntPtr.Zero)
											{
												SystemException systemException = new SystemException(UtilsStrings.GetEmptySaclFail);
												base.WriteError(new ErrorRecord(systemException, "SetAcl_ClearCentralAccessPolicy", ErrorCategory.InvalidResult, null));
												return;
											}
										}
									}
									else
									{
										zero = this.GetSaclWithCapId(this.CentralAccessPolicy);
										if (zero == IntPtr.Zero)
										{
											SystemException systemException1 = new SystemException(UtilsStrings.GetSaclWithCapIdFail);
											base.WriteError(new ErrorRecord(systemException1, "SetAcl_CentralAccessPolicy", ErrorCategory.InvalidResult, null));
											return;
										}
									}
									string[] path = this.Path;
									for (int i = 0; i < (int)path.Length; i++)
									{
										string str = path[i];
										Collection<PathInfo> pathInfos = new Collection<PathInfo>();
										CmdletProviderContext cmdletProviderContext = base.CmdletProviderContext;
										cmdletProviderContext.PassThru = this.Passthru;
										if (!this.isLiteralPath)
										{
											pathInfos = base.SessionState.Path.GetResolvedPSPathFromPSPath(str, base.CmdletProviderContext);
										}
										else
										{
											ProviderInfo providerInfo = null;
											PSDriveInfo pSDriveInfo = null;
											string unresolvedProviderPathFromPSPath = base.SessionState.Path.GetUnresolvedProviderPathFromPSPath(str, out providerInfo, out pSDriveInfo);
											pathInfos.Add(new PathInfo(pSDriveInfo, providerInfo, unresolvedProviderPathFromPSPath, base.SessionState));
											cmdletProviderContext.SuppressWildcardExpansion = true;
										}
										foreach (PathInfo pathInfo in pathInfos)
										{
											if (!base.ShouldProcess(pathInfo.Path))
											{
												continue;
											}
											try
											{
												base.InvokeProvider.SecurityDescriptor.Set(pathInfo.Path, objectSecurity, cmdletProviderContext);
												if (this.CentralAccessPolicy != null || this.ClearCentralAccessPolicy)
												{
													if (pathInfo.Provider.NameEquals(base.Context.ProviderNames.FileSystem))
													{
														IntPtr tokenWithEnabledPrivilege = this.GetTokenWithEnabledPrivilege("SeSecurityPrivilege", tOKENPRIVILEGE);
														if (tokenWithEnabledPrivilege != IntPtr.Zero)
														{
															int num = NativeMethods.SetNamedSecurityInfo(pathInfo.ProviderPath, NativeMethods.SeObjectType.SE_FILE_OBJECT, NativeMethods.SecurityInformation.SCOPE_SECURITY_INFORMATION, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, zero);
															if (tokenWithEnabledPrivilege != IntPtr.Zero)
															{
																NativeMethods.TOKEN_PRIVILEGE tOKENPRIVILEGE1 = new NativeMethods.TOKEN_PRIVILEGE();
																uint num1 = 0;
																NativeMethods.AdjustTokenPrivileges(tokenWithEnabledPrivilege, false, ref tOKENPRIVILEGE, Marshal.SizeOf(tOKENPRIVILEGE1), ref tOKENPRIVILEGE1, ref num1);
																NativeMethods.CloseHandle(tokenWithEnabledPrivilege);
															}
															if (num != 0)
															{
																SystemException win32Exception = new Win32Exception(num, UtilsStrings.SetCentralAccessPolicyFail);
																base.WriteError(new ErrorRecord(win32Exception, "SetAcl_SetNamedSecurityInfo", ErrorCategory.InvalidResult, null));
															}
														}
														else
														{
															SystemException systemException2 = new SystemException(UtilsStrings.GetTokenWithEnabledPrivilegeFail);
															base.WriteError(new ErrorRecord(systemException2, "SetAcl_AdjustTokenPrivileges", ErrorCategory.InvalidResult, null));
															return;
														}
													}
													else
													{
														Exception argumentException = new ArgumentException("Path");
														base.WriteError(new ErrorRecord(argumentException, "SetAcl_Path", ErrorCategory.InvalidArgument, this.AclObject));
														continue;
													}
												}
											}
											catch (NotSupportedException notSupportedException)
											{
												object[] objArray = new object[1];
												objArray[0] = pathInfo.Path;
												ErrorRecord errorRecord = SecurityUtils.CreateNotSupportedErrorRecord(UtilsStrings.OperationNotSupportedOnPath, "SetAcl_OperationNotSupported", objArray);
												base.WriteError(errorRecord);
											}
										}
									}
									return;
								}
								finally
								{
									Marshal.FreeHGlobal(zero);
								}
							}
							else
							{
								Exception exception = new ArgumentException(UtilsStrings.InvalidCentralAccessPolicyParameters);
								ErrorRecord errorRecord1 = SecurityUtils.CreateInvalidArgumentErrorRecord(exception, "SetAcl_OperationNotSupported");
								base.WriteError(errorRecord1);
								return;
							}
						}
					}
					else
					{
						Exception argumentException1 = new ArgumentException("AclObject");
						base.WriteError(new ErrorRecord(argumentException1, "SetAcl_AclObject", ErrorCategory.InvalidArgument, this.AclObject));
						return;
					}
				}
				else
				{
					Exception exception1 = new ArgumentException("Path");
					base.WriteError(new ErrorRecord(exception1, "SetAcl_Path", ErrorCategory.InvalidArgument, this.AclObject));
				}
			}
			else
			{
				PSMethodInfo item = this.inputObject.Methods["SetSecurityDescriptor"];
				if (item == null)
				{
					ErrorRecord errorRecord2 = SecurityUtils.CreateNotSupportedErrorRecord(UtilsStrings.SetMethodNotFound, "SetAcl_OperationNotSupported", new object[0]);
					base.WriteError(errorRecord2);
					return;
				}
				else
				{
					CommonSecurityDescriptor commonSecurityDescriptor = this.securityDescriptor as CommonSecurityDescriptor;
					if (objectSecurity == null)
					{
						if (commonSecurityDescriptor == null)
						{
							Exception argumentException2 = new ArgumentException("AclObject");
							base.WriteError(new ErrorRecord(argumentException2, "SetAcl_AclObject", ErrorCategory.InvalidArgument, this.AclObject));
							return;
						}
						else
						{
							sddlForm = commonSecurityDescriptor.GetSddlForm(AccessControlSections.All);
						}
					}
					else
					{
						sddlForm = objectSecurity.GetSecurityDescriptorSddlForm(AccessControlSections.All);
					}
					try
					{
						object[] objArray1 = new object[1];
						objArray1[0] = sddlForm;
						item.Invoke(objArray1);
						return;
					}
					catch (Exception exception3)
					{
						Exception exception2 = exception3;
						CommandProcessorBase.CheckForSevereException(exception2);
						ErrorRecord errorRecord3 = SecurityUtils.CreateNotSupportedErrorRecord(UtilsStrings.MethodInvokeFail, "SetAcl_OperationNotSupported", new object[0]);
						base.WriteError(errorRecord3);
					}
				}
			}
		}
Пример #2
0
        /// Processes records from the input pipeline.
        /// For each input file, the command sets its
        /// security descriptor to the specified 
        /// Access Control List (ACL).
        protected override void ProcessRecord()
        {
            ObjectSecurity aclObjectSecurity = _securityDescriptor as ObjectSecurity;

            if (_inputObject != null)
            {
                PSMethodInfo methodInfo = _inputObject.Methods["SetSecurityDescriptor"];

                if (methodInfo != null)
                {
                    CommonSecurityDescriptor aclCommonSD = _securityDescriptor as CommonSecurityDescriptor;
                    string sddl;

                    if (aclObjectSecurity != null)
                    {
                        sddl = aclObjectSecurity.GetSecurityDescriptorSddlForm(AccessControlSections.All);
                    }
                    else if (aclCommonSD != null)
                    {
                        sddl = aclCommonSD.GetSddlForm(AccessControlSections.All);
                    }
                    else
                    {
                        Exception e = new ArgumentException("AclObject");
                        WriteError(new ErrorRecord(
                            e,
                            "SetAcl_AclObject",
                            ErrorCategory.InvalidArgument,
                            AclObject));
                        return;
                    }

                    try
                    {
                        methodInfo.Invoke(sddl);
                    }
                    catch (Exception e)
                    {
                        // Calling user code, Catch-all OK
                        CommandProcessorBase.CheckForSevereException(e);

                        ErrorRecord er =
                        SecurityUtils.CreateNotSupportedErrorRecord(
                            UtilsStrings.MethodInvokeFail,
                            "SetAcl_OperationNotSupported"
                            );

                        WriteError(er);
                        return;
                    }
                }
                else
                {
                    ErrorRecord er =
                        SecurityUtils.CreateNotSupportedErrorRecord(
                            UtilsStrings.SetMethodNotFound,
                            "SetAcl_OperationNotSupported"
                            );

                    WriteError(er);
                }
            }
            else
            {
                if (Path == null)
                {
                    Exception e = new ArgumentException("Path");
                    WriteError(new ErrorRecord(
                        e,
                        "SetAcl_Path",
                        ErrorCategory.InvalidArgument,
                        AclObject));
                    return;
                }

                if (aclObjectSecurity == null)
                {
                    Exception e = new ArgumentException("AclObject");
                    WriteError(new ErrorRecord(
                        e,
                        "SetAcl_AclObject",
                        ErrorCategory.InvalidArgument,
                        AclObject));
                    return;
                }

                if (CentralAccessPolicy != null || ClearCentralAccessPolicy)
                {
                    if (!DownLevelHelper.IsWin8AndAbove())
                    {
                        Exception e = new ParameterBindingException();
                        WriteError(new ErrorRecord(
                            e,
                            "SetAcl_OperationNotSupported",
                            ErrorCategory.InvalidArgument,
                            null));
                        return;
                    }
                }

                if (CentralAccessPolicy != null && ClearCentralAccessPolicy)
                {
                    Exception e = new ArgumentException(UtilsStrings.InvalidCentralAccessPolicyParameters);
                    ErrorRecord er =
                    SecurityUtils.CreateInvalidArgumentErrorRecord(
                        e,
                        "SetAcl_OperationNotSupported"
                        );

                    WriteError(er);
                    return;
                }

                IntPtr pSacl = IntPtr.Zero;
                NativeMethods.TOKEN_PRIVILEGE previousState = new NativeMethods.TOKEN_PRIVILEGE();
                try
                {
                    if (CentralAccessPolicy != null)
                    {
                        pSacl = GetSaclWithCapId(CentralAccessPolicy);
                        if (pSacl == IntPtr.Zero)
                        {
                            SystemException e = new SystemException(
                                UtilsStrings.GetSaclWithCapIdFail);
                            WriteError(new ErrorRecord(e,
                                                        "SetAcl_CentralAccessPolicy",
                                                        ErrorCategory.InvalidResult,
                                                        null));
                            return;
                        }
                    }
                    else if (ClearCentralAccessPolicy)
                    {
                        pSacl = GetEmptySacl();
                        if (pSacl == IntPtr.Zero)
                        {
                            SystemException e = new SystemException(
                                UtilsStrings.GetEmptySaclFail);
                            WriteError(new ErrorRecord(e,
                                                        "SetAcl_ClearCentralAccessPolicy",
                                                        ErrorCategory.InvalidResult,
                                                        null));
                            return;
                        }
                    }

                    foreach (string p in Path)
                    {
                        Collection<PathInfo> pathsToProcess = new Collection<PathInfo>();

                        CmdletProviderContext context = this.CmdletProviderContext;
                        context.PassThru = Passthru;
                        if (_isLiteralPath)
                        {
                            ProviderInfo Provider = null;
                            PSDriveInfo Drive = null;
                            string pathStr = SessionState.Path.GetUnresolvedProviderPathFromPSPath(p, out Provider, out Drive);
                            pathsToProcess.Add(new PathInfo(Drive, Provider, pathStr, SessionState));
                            context.SuppressWildcardExpansion = true;
                        }
                        else
                        {
                            pathsToProcess = SessionState.Path.GetResolvedPSPathFromPSPath(p, CmdletProviderContext);
                        }

                        foreach (PathInfo pathInfo in pathsToProcess)
                        {
                            if (ShouldProcess(pathInfo.Path))
                            {
                                try
                                {
                                    InvokeProvider.SecurityDescriptor.Set(pathInfo.Path,
                                                                          aclObjectSecurity,
                                                                          context);

                                    if (CentralAccessPolicy != null || ClearCentralAccessPolicy)
                                    {
                                        if (!pathInfo.Provider.NameEquals(Context.ProviderNames.FileSystem))
                                        {
                                            Exception e = new ArgumentException("Path");
                                            WriteError(new ErrorRecord(
                                                e,
                                                "SetAcl_Path",
                                                ErrorCategory.InvalidArgument,
                                                AclObject));
                                            continue;
                                        }

                                        // Enable the security privilege required to set SCOPE_SECURITY_INFORMATION.
                                        IntPtr pToken = GetTokenWithEnabledPrivilege("SeSecurityPrivilege", previousState);
                                        if (pToken == IntPtr.Zero)
                                        {
                                            SystemException e = new SystemException(
                                                UtilsStrings.GetTokenWithEnabledPrivilegeFail);
                                            WriteError(new ErrorRecord(e,
                                                                        "SetAcl_AdjustTokenPrivileges",
                                                                        ErrorCategory.InvalidResult,
                                                                        null));
                                            return;
                                        }

                                        // Set the file's CAPID.
                                        uint rs = NativeMethods.SetNamedSecurityInfo(
                                            pathInfo.ProviderPath,
                                            NativeMethods.SeObjectType.SE_FILE_OBJECT,
                                            NativeMethods.SecurityInformation.SCOPE_SECURITY_INFORMATION,
                                            IntPtr.Zero,
                                            IntPtr.Zero,
                                            IntPtr.Zero,
                                            pSacl);

                                        // Restore privileges to the previous state.
                                        if (pToken != IntPtr.Zero)
                                        {
                                            NativeMethods.TOKEN_PRIVILEGE newState = new NativeMethods.TOKEN_PRIVILEGE();
                                            uint newSize = 0;
                                            NativeMethods.AdjustTokenPrivileges(
                                                pToken,
                                                false,
                                                ref previousState,
                                                (uint)Marshal.SizeOf(newState),
                                                ref newState,
                                                ref newSize);

                                            NativeMethods.CloseHandle(pToken);
                                            pToken = IntPtr.Zero;
                                        }

                                        if (rs != NativeMethods.ERROR_SUCCESS)
                                        {
                                            Exception e = new Win32Exception(
                                                (int)rs,
                                                UtilsStrings.SetCentralAccessPolicyFail);
                                            WriteError(new ErrorRecord(e,
                                                                       "SetAcl_SetNamedSecurityInfo",
                                                                       ErrorCategory.InvalidResult,
                                                                       null));
                                        }
                                    }
                                }
                                catch (NotSupportedException)
                                {
                                    ErrorRecord er =
                                        SecurityUtils.CreateNotSupportedErrorRecord(
                                            UtilsStrings.OperationNotSupportedOnPath,
                                            "SetAcl_OperationNotSupported",
                                            pathInfo.Path
                                        );

                                    WriteError(er);
                                }
                            }
                        }
                    }
                }
                finally
                {
                    Marshal.FreeHGlobal(pSacl);
                }
            }
        }
Пример #3
0
		private IntPtr GetTokenWithEnabledPrivilege(string privilege, NativeMethods.TOKEN_PRIVILEGE previousState)
		{
			IntPtr zero = IntPtr.Zero;
			bool flag = true;
			try
			{
				flag = NativeMethods.OpenThreadToken(NativeMethods.GetCurrentThread(), 40, true, out zero);
				if (!flag)
				{
					if ((long)Marshal.GetLastWin32Error() == (long)0x3f0)
					{
						flag = NativeMethods.OpenProcessToken(NativeMethods.GetCurrentProcess(), 40, out zero);
					}
					if (!flag)
					{
						throw new Win32Exception(Marshal.GetLastWin32Error());
					}
				}
				NativeMethods.LUID lUID = new NativeMethods.LUID();
				flag = NativeMethods.LookupPrivilegeValue(null, privilege, ref lUID);
				if (flag)
				{
					NativeMethods.TOKEN_PRIVILEGE tOKENPRIVILEGE = new NativeMethods.TOKEN_PRIVILEGE();
					tOKENPRIVILEGE.PrivilegeCount = 1;
					tOKENPRIVILEGE.Privilege.Attributes = 2;
					tOKENPRIVILEGE.Privilege.Luid = lUID;
					uint num = 0;
					flag = NativeMethods.AdjustTokenPrivileges(zero, false, ref tOKENPRIVILEGE, Marshal.SizeOf(previousState), ref previousState, ref num);
					if (!flag)
					{
						throw new Win32Exception(Marshal.GetLastWin32Error());
					}
				}
				else
				{
					throw new Win32Exception(Marshal.GetLastWin32Error());
				}
			}
			finally
			{
				if (!flag)
				{
					NativeMethods.CloseHandle(zero);
					zero = IntPtr.Zero;
				}
			}
			return zero;
		}
Пример #4
0
        /// <summary>
        /// Returns the current thread or process token with the specified privilege enabled 
        /// and the previous state of this privilege. Free the returned token 
        /// by calling NativeMethods.CloseHandle.
        /// </summary>
        private IntPtr GetTokenWithEnabledPrivilege(
            string privilege,
            NativeMethods.TOKEN_PRIVILEGE previousState)
        {
            IntPtr pToken = IntPtr.Zero;
            bool ret = true;

            try
            {
                // First try to open the thread token for privilege adjustment.
                ret = NativeMethods.OpenThreadToken(
                    NativeMethods.GetCurrentThread(),
                    NativeMethods.TOKEN_QUERY | NativeMethods.TOKEN_ADJUST_PRIVILEGES,
                    true,
                    out pToken);

                if (!ret)
                {
                    if (Marshal.GetLastWin32Error() == NativeMethods.ERROR_NO_TOKEN)
                    {
                        // Client is not impersonating. Open the process token.
                        ret = NativeMethods.OpenProcessToken(
                            NativeMethods.GetCurrentProcess(),
                            NativeMethods.TOKEN_QUERY | NativeMethods.TOKEN_ADJUST_PRIVILEGES,
                            out pToken);
                    }

                    if (!ret)
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }

                // Get the LUID of the specified privilege.
                NativeMethods.LUID luid = new NativeMethods.LUID();
                ret = NativeMethods.LookupPrivilegeValue(
                    null,
                    privilege,
                    ref luid);
                if (!ret)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                // Enable the privilege.
                NativeMethods.TOKEN_PRIVILEGE newState = new NativeMethods.TOKEN_PRIVILEGE();
                newState.PrivilegeCount = 1;
                newState.Privilege.Attributes = NativeMethods.SE_PRIVILEGE_ENABLED;
                newState.Privilege.Luid = luid;
                uint previousSize = 0;
                ret = NativeMethods.AdjustTokenPrivileges(
                    pToken,
                    false,
                    ref newState,
                    (uint)Marshal.SizeOf(previousState),
                    ref previousState,
                    ref previousSize);
                if (!ret)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            finally
            {
                if (!ret)
                {
                    NativeMethods.CloseHandle(pToken);
                    pToken = IntPtr.Zero;
                }
            }

            return pToken;
        }