Пример #1
0
        /// <summary>
        /// constructor that is used to wrap an error record
        /// </summary>
        /// <param name="errorRecord"></param>
        /// <param name="originInfo"></param>
        /// <param name="replaceParentContainsErrorRecordException"></param>
        private RemotingErrorRecord(ErrorRecord errorRecord, OriginInfo originInfo, Exception replaceParentContainsErrorRecordException) :
            base(errorRecord, replaceParentContainsErrorRecordException)
        {
            if (null != errorRecord)
            {
                base.SetInvocationInfo(errorRecord.InvocationInfo);
            }

            _originInfo = originInfo;
        }
Пример #2
0
        public static ErrorRecord ToErrorRecord(this Error error)
        {
            var errorRecord = new ErrorRecord(
                error.Time.ToUniversalTime(),
                error.Message,
                error.ApplicationName,
                error.Cookies?.ToKeyValueCollection(),
                error.Detail,
                error.Exception?.Data.ToKeyValueCollection(),
                error.Form?.ToKeyValueCollection(),
                error.HostName, 
                error.QueryString?.ToKeyValueCollection(), 
                error.ServerVariables?.ToKeyValueCollection(), 
                error.Source, 
                error.StatusCode, 
                error.Type, 
                error.User, 
                error.WebHostHtmlMessage);

            return errorRecord;
        }
Пример #3
0
        }//End BeginProcessing()

        #endregion

        /// <summary>
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// </exception>
        private void EnableClientSideSettings()
        {
            String query   = helper.GetResourceMsgFromResourcetext("CredSSPContinueQuery");
            String caption = helper.GetResourceMsgFromResourcetext("CredSSPContinueCaption");

            if (!force && !ShouldContinue(query, caption))
            {
                return;
            }

            IWSManSession m_SessionObj = CreateWSManSession();

            if (m_SessionObj == null)
            {
                return;
            }

            try
            {
                //get the credssp node to check if wsman is configured on this machine
                string  result = m_SessionObj.Get(helper.CredSSP_RUri, 0);
                XmlNode node   = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.CredSSP_XMLNmsp);

                if (node == null)
                {
                    InvalidOperationException ex = new InvalidOperationException();
                    ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null);
                    WriteError(er);
                    return;
                }

                string newxmlcontent = @"<cfg:Auth xmlns:cfg=""http://schemas.microsoft.com/wbem/wsman/1/config/client/auth""><cfg:CredSSP>true</cfg:CredSSP></cfg:Auth>";
                try
                {
                    XmlDocument xmldoc = new XmlDocument();
                    //push the xml string with credssp enabled
                    xmldoc.LoadXml(m_SessionObj.Put(helper.CredSSP_RUri, newxmlcontent, 0));

                    // set the Registry using GroupPolicyObject
                    if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
                    {
                        this.UpdateCurrentUserRegistrySettings();
                    }
                    else
                    {
                        ThreadStart start  = new ThreadStart(this.UpdateCurrentUserRegistrySettings);
                        Thread      thread = new Thread(start);
                        thread.SetApartmentState(ApartmentState.STA);
                        thread.Start();
                        thread.Join();
                    }

                    if (helper.ValidateCreadSSPRegistryRetry(true, delegatecomputer, applicationname))
                    {
                        WriteObject(xmldoc.FirstChild);
                    }
                    else
                    {
                        helper.AssertError(helper.GetResourceMsgFromResourcetext("EnableCredSSPPolicyValidateError"), false, delegatecomputer);
                    }
                }
                catch (COMException)
                {
                    helper.AssertError(m_SessionObj.Error, true, delegatecomputer);
                }
            }
            finally
            {
                if (!String.IsNullOrEmpty(m_SessionObj.Error))
                {
                    helper.AssertError(m_SessionObj.Error, true, delegatecomputer);
                }

                if (m_SessionObj != null)
                {
                    Dispose(m_SessionObj);
                }
            }
        }
        /// <summary>
        /// Remove an object given either path,class name or pipeline input.
        /// </summary>
        protected override void ProcessRecord()
        {
            if (this.AsJob)
            {
                RunAsJob("Remove-WMIObject");
                return;
            }
            if (_inputObject != null)
            {
                try
                {
                    if (!ShouldProcess(_inputObject["__PATH"].ToString()))
                    {
                        return;
                    }
                    _inputObject.Delete();
                }
                catch (ManagementException e)
                {
                    ErrorRecord errorRecord = new ErrorRecord(e, "RemoveWMIManagementException", ErrorCategory.InvalidOperation, null);
                    WriteError(errorRecord);
                }
                catch (System.Runtime.InteropServices.COMException e)
                {
                    ErrorRecord errorRecord = new ErrorRecord(e, "RemoveWMICOMException", ErrorCategory.InvalidOperation, null);
                    WriteError(errorRecord);
                }
                return;
            }
            else
            {
                ConnectionOptions options = GetConnectionOption();
                ManagementPath mPath = null;
                ManagementObject mObject = null;
                if (_path != null)
                {
                    mPath = new ManagementPath(_path);
                    if (String.IsNullOrEmpty(mPath.NamespacePath))
                    {
                        mPath.NamespacePath = this.Namespace;
                    }
                    else if (namespaceSpecified)
                    {
                        //ThrowTerminatingError
                        ThrowTerminatingError(new ErrorRecord(
                            new InvalidOperationException(),
                            "NamespaceSpecifiedWithPath",
                            ErrorCategory.InvalidOperation,
                            this.Namespace));
                    }

                    if (mPath.Server != "." && serverNameSpecified)
                    {
                        //ThrowTerminatingError
                        ThrowTerminatingError(new ErrorRecord(
                            new InvalidOperationException(),
                            "ComputerNameSpecifiedWithPath",
                            ErrorCategory.InvalidOperation,
                            this.ComputerName));
                    }
                    if (!(mPath.Server == "." && serverNameSpecified))
                    {
                        string[] serverName = new string[] { mPath.Server };
                        ComputerName = serverName;
                    }
                }
                foreach (string name in ComputerName)
                {
                    try
                    {
                        if (_path != null)
                        {
                            mPath.Server = name;
                            if (mPath.IsClass)
                            {
                                ManagementClass mClass = new ManagementClass(mPath);
                                mObject = mClass;
                            }
                            else
                            {
                                ManagementObject mInstance = new ManagementObject(mPath);
                                mObject = mInstance;
                            }
                            ManagementScope mScope = new ManagementScope(mPath, options);
                            mObject.Scope = mScope;
                        }
                        else
                        {
                            ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, this.Namespace), options);
                            ManagementClass mClass = new ManagementClass(_className);
                            mObject = mClass;
                            mObject.Scope = scope;
                        }
                        if (!ShouldProcess(mObject["__PATH"].ToString()))
                        {
                            continue;
                        }
                        mObject.Delete();
                    }
                    catch (ManagementException e)
                    {
                        ErrorRecord errorRecord = new ErrorRecord(e, "RemoveWMIManagementException", ErrorCategory.InvalidOperation, null);
                        WriteError(errorRecord);
                    }
                    catch (System.Runtime.InteropServices.COMException e)
                    {
                        ErrorRecord errorRecord = new ErrorRecord(e, "RemoveWMICOMException", ErrorCategory.InvalidOperation, null);
                        WriteError(errorRecord);
                    }
                }
            }
        }
 /// <summary>
 /// Create the internal error record based on helpTopic.
 /// The ErrorRecord created will be stored in the _errorRecord member.
 /// </summary>
 private void CreateErrorRecord()
 {
     // if _error is empty, this exception is created using default
     // constructor. Don't create the error record since there is 
     // no useful information anyway.
     if (!String.IsNullOrEmpty(_error) && !String.IsNullOrEmpty(_assemblyName))
     {
         _errorRecord = new ErrorRecord(new ParentContainsErrorRecordException(this), _error, ErrorCategory.ResourceUnavailable, null);
         _errorRecord.ErrorDetails = new ErrorDetails(typeof(RunspaceConfigurationAttributeException).GetTypeInfo().Assembly, "MiniShellErrors", _error, _assemblyName);
     }
 }
Пример #6
0
 internal static void WriteNonTerminatingError(int errorcode, PSCmdlet cmdlet, string computername)
 {
     Win32Exception ex = new Win32Exception(errorcode);
     string additionalmessage = String.Empty;
     if (ex.NativeErrorCode.Equals(0x00000035))
     {
         additionalmessage = StringUtil.Format(ComputerResources.NetworkPathNotFound, computername);
     }
     string message = StringUtil.Format(ComputerResources.OperationFailed, ex.Message, computername, additionalmessage);
     ErrorRecord er = new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, computername);
     cmdlet.WriteError(er);
 }
Пример #7
0
        /// <summary>
        /// </summary>
        protected override void BeginProcessing()
        {
            // Validate that WinRM is OK and that the user can query system state
            RemotingCommandUtil.CheckRemotingCmdletPrerequisites();
            PSSessionConfigurationCommandUtilities.ThrowIfNotAdministrator();

            // Get the configuration for the given endpoint
            Collection<PSObject> configurations = null;
            using (PowerShellApi invoker = PowerShellApi.Create(RunspaceMode.CurrentRunspace))
            {
                invoker.AddCommand("Get-PSSessionConfiguration").AddParameter("Name", this.ConfigurationName).AddParameter("ErrorAction", "Stop");

                try
                {
                    // If the session name doesn't exist, this Invoke() throws
                    configurations = invoker.Invoke();
                }
                catch (ActionPreferenceStopException e)
                {
                    ThrowTerminatingError(new ErrorRecord(e.ErrorRecord.Exception, "CouldNotFindSessionConfiguration", ErrorCategory.ObjectNotFound, this.ConfigurationName));
                }
            }

            // The validator that will be applied to the role lookup
            Func<string, bool> validator = (role) => true;

            if (!String.IsNullOrEmpty(this.Username))
            {
                if (this.Username.IndexOf("\\", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    validator = null;

                    // Convert DOMAIN\user to the upn (user@DOMAIN)
                    string[] upnComponents = this.Username.Split(Utils.Separators.Backslash);
                    if (upnComponents.Length == 2)
                    {
                        this.Username = upnComponents[1] + "@" + upnComponents[0];
                    }
                }

                try
                {
                    System.Security.Principal.WindowsPrincipal windowsPrincipal = new System.Security.Principal.WindowsPrincipal(
                        new System.Security.Principal.WindowsIdentity(this.Username));
                    validator = (role) => windowsPrincipal.IsInRole(role);
                }
                catch (SecurityException e)
                {
                    // Identity could not be mapped
                    string message = StringUtil.Format(RemotingErrorIdStrings.CouldNotResolveUsername, this.Username);
                    ArgumentException ioe = new ArgumentException(message, e);
                    ErrorRecord er = new ErrorRecord(ioe, "CouldNotResolveUsername", ErrorCategory.InvalidArgument, this.Username);
                    ThrowTerminatingError(er);
                    return;
                }
            }

            foreach (PSObject foundConfiguration in configurations)
            {
                string configFilePath = null;
                PSPropertyInfo configFilePathProperty = foundConfiguration.Properties["ConfigFilePath"];
                if (configFilePathProperty != null)
                {
                    configFilePath = configFilePathProperty.Value as string;
                }

                // If we could not get the config file, throw an error that it's not a configuration created with
                // config file-based session configurations.
                if (configFilePath == null)
                {
                    string configurationName = (string)foundConfiguration.Properties["Name"].Value;
                    string message = StringUtil.Format(RemotingErrorIdStrings.SessionConfigurationMustBeFileBased, configurationName);
                    ArgumentException ioe = new ArgumentException(message);
                    ErrorRecord er = new ErrorRecord(ioe, "SessionConfigurationMustBeFileBased", ErrorCategory.InvalidArgument, foundConfiguration);
                    WriteError(er);
                    continue;
                }

                InitialSessionState iss = InitialSessionState.CreateFromSessionConfigurationFile(configFilePath, validator);
                if (this.Full)
                {
                    WriteObject(iss);
                }
                else
                {
                    using (PowerShellApi analyzer = PowerShellApi.Create(iss))
                    {
                        analyzer.AddCommand("Get-Command").AddParameter("CommandType", "All");
                        foreach (PSObject output in analyzer.Invoke())
                        {
                            WriteObject(output);
                        }
                    }
                }
            }
        }
Пример #8
0
        /// <summary>
        /// Handles a robust connection layer notification from the transport
        /// manager.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HandleRobustConnectionNotification(
            object sender,
            ConnectionStatusEventArgs e)
        {
            // Create event arguments and warnings/errors for this robust connection notification.
            PSConnectionRetryStatusEventArgs connectionRetryStatusArgs = null;
            WarningRecord warningRecord = null;
            ErrorRecord errorRecord = null;
            int maxRetryConnectionTimeMSecs = this.runspacePool.MaxRetryConnectionTime;
            int maxRetryConnectionTimeMinutes = maxRetryConnectionTimeMSecs / 60000;
            switch (e.Notification)
            {
                case ConnectionStatus.NetworkFailureDetected:
                    warningRecord = new WarningRecord(
                        PSConnectionRetryStatusEventArgs.FQIDNetworkFailureDetected,
                        StringUtil.Format(RemotingErrorIdStrings.RCNetworkFailureDetected,
                        this.computerName, maxRetryConnectionTimeMinutes));

                    connectionRetryStatusArgs =
                        new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.NetworkFailureDetected,
                            this.computerName, maxRetryConnectionTimeMSecs, warningRecord);
                    break;

                case ConnectionStatus.ConnectionRetryAttempt:
                    warningRecord = new WarningRecord(
                        PSConnectionRetryStatusEventArgs.FQIDConnectionRetryAttempt,
                        StringUtil.Format(RemotingErrorIdStrings.RCConnectionRetryAttempt, this.computerName));

                    connectionRetryStatusArgs =
                        new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.ConnectionRetryAttempt,
                            this.computerName, maxRetryConnectionTimeMSecs, warningRecord);
                    break;

                case ConnectionStatus.ConnectionRetrySucceeded:
                    warningRecord = new WarningRecord(
                        PSConnectionRetryStatusEventArgs.FQIDConnectionRetrySucceeded,
                        StringUtil.Format(RemotingErrorIdStrings.RCReconnectSucceeded, this.computerName));

                    connectionRetryStatusArgs =
                        new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.ConnectionRetrySucceeded,
                            this.computerName, maxRetryConnectionTimeMinutes, warningRecord);
                    break;

                case ConnectionStatus.AutoDisconnectStarting:
                    {
                        warningRecord = new WarningRecord(
                            PSConnectionRetryStatusEventArgs.FQIDAutoDisconnectStarting,
                            StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnectingWarning, this.computerName));

                        connectionRetryStatusArgs =
                            new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.AutoDisconnectStarting,
                                this.computerName, maxRetryConnectionTimeMinutes, warningRecord);
                    }
                    break;

                case ConnectionStatus.AutoDisconnectSucceeded:
                    warningRecord = new WarningRecord(
                        PSConnectionRetryStatusEventArgs.FQIDAutoDisconnectSucceeded,
                        StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnected, this.computerName));

                    connectionRetryStatusArgs =
                        new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.AutoDisconnectSucceeded,
                            this.computerName, maxRetryConnectionTimeMinutes, warningRecord);
                    break;

                case ConnectionStatus.InternalErrorAbort:
                    {
                        string msg = StringUtil.Format(RemotingErrorIdStrings.RCInternalError, this.computerName);
                        RuntimeException reason = new RuntimeException(msg);
                        errorRecord = new ErrorRecord(reason,
                            PSConnectionRetryStatusEventArgs.FQIDNetworkOrDisconnectFailed,
                            ErrorCategory.InvalidOperation, this);

                        connectionRetryStatusArgs =
                            new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.InternalErrorAbort,
                                this.computerName, maxRetryConnectionTimeMinutes, errorRecord);
                    }
                    break;
            }

            if (connectionRetryStatusArgs == null)
            {
                return;
            }

            // Update connection status.
            _connectionRetryStatus = connectionRetryStatusArgs.Notification;

            if (warningRecord != null)
            {
                RemotingWarningRecord remotingWarningRecord = new RemotingWarningRecord(
                    warningRecord,
                    new OriginInfo(this.computerName, this.InstanceId));

                // Add warning record to information channel.
                HandleInformationalMessageReceived(this,
                    new RemoteDataEventArgs<InformationalMessage>(
                        new InformationalMessage(remotingWarningRecord, RemotingDataType.PowerShellWarning)));

                // Write warning to host.
                RemoteHostCall writeWarning = new RemoteHostCall(
                    -100,
                    RemoteHostMethodId.WriteWarningLine,
                    new object[] { warningRecord.Message });

                try
                {
                    HandleHostCallReceived(this,
                        new RemoteDataEventArgs<RemoteHostCall>(writeWarning));
                }
                catch (PSNotImplementedException)
                { }
            }

            if (errorRecord != null)
            {
                RemotingErrorRecord remotingErrorRecord = new RemotingErrorRecord(
                    errorRecord,
                    new OriginInfo(this.computerName, this.InstanceId));

                // Add error record to error channel, will also be written to host.
                HandleErrorReceived(this,
                    new RemoteDataEventArgs<ErrorRecord>(remotingErrorRecord));
            }

            // Raise event.
            RCConnectionNotification.SafeInvoke(this, connectionRetryStatusArgs);
        }
Пример #9
0
 /// <summary>
 /// Throw out terminating error for LSA function invocations
 /// </summary>
 /// <param name="ret"></param>
 /// <param name="cmdlet"></param>
 private static void ThrowOutLsaError(uint ret, PSCmdlet cmdlet)
 {
     var ex = new Win32Exception(SAMAPI.LsaNtStatusToWinError((int)ret));
     string errMsg = StringUtil.Format(ComputerResources.FailToResetPasswordOnLocalMachine, ex.Message);
     ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToResetPasswordOnLocalMachine",
                                         ErrorCategory.OperationStopped, Dns.GetHostName());
     cmdlet.ThrowTerminatingError(error);
 }
Пример #10
0
        /// <summary>
        /// Create the internal error record.
        /// The ErrorRecord created will be stored in the _errorRecord member.
        /// </summary>
        private void CreateErrorRecord()
        {
            StringBuilder sb = new StringBuilder();

            if (PSSnapInExceptions != null)
            {
                foreach (PSSnapInException e in PSSnapInExceptions)
                {
                    sb.Append("\n");
                    sb.Append(e.Message);
                }
            }

            _errorRecord = new ErrorRecord(new ParentContainsErrorRecordException(this), "ConsoleLoadFailure", ErrorCategory.ResourceUnavailable, null);
            _errorRecord.ErrorDetails = new ErrorDetails(String.Format(ConsoleInfoErrorStrings.ConsoleLoadFailure, _consoleFileName, sb.ToString()));
        }
Пример #11
0
        } // WritePropertyValueObject
#endif

        /// <Content contentref="System.Management.Automation.Cmdlet.WriteError" />
        public void WriteError(ErrorRecord errorRecord)
        {
            using (PSTransactionManager.GetEngineProtectionScope())
            {
                Diagnostics.Assert(
                    Context != null,
                    "The context should always be set");

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

                if (null != errorRecord.ErrorDetails
                    && null != errorRecord.ErrorDetails.TextLookupError)
                {
                    MshLog.LogProviderHealthEvent(
                        this.Context.ExecutionContext,
                        ProviderInfo.Name,
                        errorRecord.ErrorDetails.TextLookupError,
                        Severity.Warning);
                }

                Context.WriteError(errorRecord);
            }
        } // WriteError
Пример #12
0
        private void DisableClientSideSettings()
        {
            WSManHelper   helper       = new WSManHelper(this);
            IWSManSession m_SessionObj = CreateWSManSession();

            if (m_SessionObj == null)
            {
                return;
            }

            try
            {
                string      result      = m_SessionObj.Get(helper.CredSSP_RUri, 0);
                XmlDocument resultopxml = new XmlDocument();
                string      inputXml    = null;
                resultopxml.LoadXml(result);
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(resultopxml.NameTable);
                nsmgr.AddNamespace("cfg", helper.CredSSP_XMLNmsp);
                XmlNode xNode = resultopxml.SelectSingleNode(helper.CredSSP_SNode, nsmgr);
                if (!(xNode == null))
                {
                    inputXml = @"<cfg:Auth xmlns:cfg=""http://schemas.microsoft.com/wbem/wsman/1/config/client/auth""><cfg:CredSSP>false</cfg:CredSSP></cfg:Auth>";
                }
                else
                {
                    InvalidOperationException ex = new InvalidOperationException();
                    ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null);
                    WriteError(er);
                    return;
                }

                m_SessionObj.Put(helper.CredSSP_RUri, inputXml, 0);

                if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
                {
                    this.DeleteUserDelegateSettings();
                }
                else
                {
                    ThreadStart start  = new ThreadStart(this.DeleteUserDelegateSettings);
                    Thread      thread = new Thread(start);
                    thread.SetApartmentState(ApartmentState.STA);
                    thread.Start();
                    thread.Join();
                }

                if (!helper.ValidateCreadSSPRegistryRetry(false, null, applicationname))
                {
                    helper.AssertError(helper.GetResourceMsgFromResourcetext("DisableCredSSPPolicyValidateError"), false, null);
                }
            }
            catch (System.Xml.XPath.XPathException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "XpathException", ErrorCategory.InvalidOperation, null);
                WriteError(er);
            }
            finally
            {
                if (!String.IsNullOrEmpty(m_SessionObj.Error))
                {
                    helper.AssertError(m_SessionObj.Error, true, null);
                }

                if (m_SessionObj != null)
                {
                    Dispose(m_SessionObj);
                }
            }
        }
Пример #13
0
        private void DeleteDelegateSettings(string applicationname, RegistryKey rootKey, string Registry_Path, IGroupPolicyObject GPO)
        {
            WSManHelper helper = new WSManHelper(this);
            RegistryKey rKey;
            int         i         = 0;
            bool        otherkeys = false;

            try
            {
                string      Registry_Path_Credentials_Delegation = Registry_Path + @"\CredentialsDelegation";
                RegistryKey Allow_Fresh_Credential_Key           = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation + @"\" + helper.Key_Allow_Fresh_Credentials, true);
                if (Allow_Fresh_Credential_Key != null)
                {
                    string[] valuenames = Allow_Fresh_Credential_Key.GetValueNames();
                    if (valuenames.Length > 0)
                    {
                        Collection <string> KeyCollection = new Collection <string>();
                        foreach (string value in valuenames)
                        {
                            object keyvalue = Allow_Fresh_Credential_Key.GetValue(value);
                            if (keyvalue != null)
                            {
                                if (!keyvalue.ToString().StartsWith(applicationname, StringComparison.OrdinalIgnoreCase))
                                {
                                    KeyCollection.Add(keyvalue.ToString());
                                    otherkeys = true;
                                }
                            }

                            Allow_Fresh_Credential_Key.DeleteValue(value);
                        }

                        foreach (string keyvalue in KeyCollection)
                        {
                            Allow_Fresh_Credential_Key.SetValue(Convert.ToString(i + 1, CultureInfo.InvariantCulture), keyvalue, RegistryValueKind.String);
                            i++;
                        }
                    }
                }

                if (!otherkeys)
                {
                    rKey = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation, true);
                    if (rKey != null)
                    {
                        object regval1 = rKey.GetValue(helper.Key_Allow_Fresh_Credentials);
                        if (regval1 != null)
                        {
                            rKey.DeleteValue(helper.Key_Allow_Fresh_Credentials, false);
                        }

                        object regval2 = rKey.GetValue(helper.Key_Concatenate_Defaults_AllowFresh);
                        if (regval2 != null)
                        {
                            rKey.DeleteValue(helper.Key_Concatenate_Defaults_AllowFresh, false);
                        }

                        if (rKey.OpenSubKey(helper.Key_Allow_Fresh_Credentials) != null)
                        {
                            rKey.DeleteSubKeyTree(helper.Key_Allow_Fresh_Credentials);
                        }
                    }
                }

                GPO.Save(true, true, new Guid("35378EAC-683F-11D2-A89A-00C04FBBCFA2"), new Guid("6AD20875-336C-4e22-968F-C709ACB15814"));
            }
            catch (InvalidOperationException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "InvalidOperation", ErrorCategory.InvalidOperation, null);
                WriteError(er);
            }
            catch (ArgumentException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "InvalidArgument", ErrorCategory.InvalidArgument, null);
                WriteError(er);
            }
            catch (SecurityException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "SecurityException", ErrorCategory.SecurityError, null);
                WriteError(er);
            }
            catch (UnauthorizedAccessException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "UnauthorizedAccess", ErrorCategory.SecurityError, null);
                WriteError(er);
            }
        }
 protected new void ThrowTerminatingError(ErrorRecord errorRecord)
 {
     FlushDebugMessages(IsDataCollectionAllowed());
     base.ThrowTerminatingError(errorRecord);
 }
Пример #15
0
        /// <summary>
        /// Handles a robust connection layer notification from the transport
        /// manager.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HandleRobustConnectionNotification(
            object sender,
            ConnectionStatusEventArgs e)
        {
            // Create event arguments and warnings/errors for this robust connection notification.
            PSConnectionRetryStatusEventArgs connectionRetryStatusArgs = null;
            WarningRecord warningRecord = null;
            ErrorRecord   errorRecord   = null;
            int           maxRetryConnectionTimeMSecs   = this.runspacePool.MaxRetryConnectionTime;
            int           maxRetryConnectionTimeMinutes = maxRetryConnectionTimeMSecs / 60000;

            switch (e.Notification)
            {
            case ConnectionStatus.NetworkFailureDetected:
                warningRecord = new WarningRecord(
                    PSConnectionRetryStatusEventArgs.FQIDNetworkFailureDetected,
                    StringUtil.Format(RemotingErrorIdStrings.RCNetworkFailureDetected,
                                      this.computerName, maxRetryConnectionTimeMinutes));

                connectionRetryStatusArgs =
                    new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.NetworkFailureDetected,
                                                         this.computerName, maxRetryConnectionTimeMSecs, warningRecord);
                break;

            case ConnectionStatus.ConnectionRetryAttempt:
                warningRecord = new WarningRecord(
                    PSConnectionRetryStatusEventArgs.FQIDConnectionRetryAttempt,
                    StringUtil.Format(RemotingErrorIdStrings.RCConnectionRetryAttempt, this.computerName));

                connectionRetryStatusArgs =
                    new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.ConnectionRetryAttempt,
                                                         this.computerName, maxRetryConnectionTimeMSecs, warningRecord);
                break;

            case ConnectionStatus.ConnectionRetrySucceeded:
                warningRecord = new WarningRecord(
                    PSConnectionRetryStatusEventArgs.FQIDConnectionRetrySucceeded,
                    StringUtil.Format(RemotingErrorIdStrings.RCReconnectSucceeded, this.computerName));

                connectionRetryStatusArgs =
                    new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.ConnectionRetrySucceeded,
                                                         this.computerName, maxRetryConnectionTimeMinutes, warningRecord);
                break;

            case ConnectionStatus.AutoDisconnectStarting:
            {
                warningRecord = new WarningRecord(
                    PSConnectionRetryStatusEventArgs.FQIDAutoDisconnectStarting,
                    StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnectingWarning, this.computerName));

                connectionRetryStatusArgs =
                    new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.AutoDisconnectStarting,
                                                         this.computerName, maxRetryConnectionTimeMinutes, warningRecord);
            }
            break;

            case ConnectionStatus.AutoDisconnectSucceeded:
                warningRecord = new WarningRecord(
                    PSConnectionRetryStatusEventArgs.FQIDAutoDisconnectSucceeded,
                    StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnected, this.computerName));

                connectionRetryStatusArgs =
                    new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.AutoDisconnectSucceeded,
                                                         this.computerName, maxRetryConnectionTimeMinutes, warningRecord);
                break;

            case ConnectionStatus.InternalErrorAbort:
            {
                string           msg    = StringUtil.Format(RemotingErrorIdStrings.RCInternalError, this.computerName);
                RuntimeException reason = new RuntimeException(msg);
                errorRecord = new ErrorRecord(reason,
                                              PSConnectionRetryStatusEventArgs.FQIDNetworkOrDisconnectFailed,
                                              ErrorCategory.InvalidOperation, this);

                connectionRetryStatusArgs =
                    new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.InternalErrorAbort,
                                                         this.computerName, maxRetryConnectionTimeMinutes, errorRecord);
            }
            break;
            }

            if (connectionRetryStatusArgs == null)
            {
                return;
            }

            // Update connection status.
            _connectionRetryStatus = connectionRetryStatusArgs.Notification;

            if (warningRecord != null)
            {
                RemotingWarningRecord remotingWarningRecord = new RemotingWarningRecord(
                    warningRecord,
                    new OriginInfo(this.computerName, this.InstanceId));

                // Add warning record to information channel.
                HandleInformationalMessageReceived(this,
                                                   new RemoteDataEventArgs <InformationalMessage>(
                                                       new InformationalMessage(remotingWarningRecord, RemotingDataType.PowerShellWarning)));

                // Write warning to host.
                RemoteHostCall writeWarning = new RemoteHostCall(
                    -100,
                    RemoteHostMethodId.WriteWarningLine,
                    new object[] { warningRecord.Message });

                try
                {
                    HandleHostCallReceived(this,
                                           new RemoteDataEventArgs <RemoteHostCall>(writeWarning));
                }
                catch (PSNotImplementedException)
                { }
            }

            if (errorRecord != null)
            {
                RemotingErrorRecord remotingErrorRecord = new RemotingErrorRecord(
                    errorRecord,
                    new OriginInfo(this.computerName, this.InstanceId));

                // Add error record to error channel, will also be written to host.
                HandleErrorReceived(this,
                                    new RemoteDataEventArgs <ErrorRecord>(remotingErrorRecord));
            }

            // Raise event.
            RCConnectionNotification.SafeInvoke(this, connectionRetryStatusArgs);
        }
Пример #16
0
        /// <summary>
        /// Processes the process phase of the cmdlet
        /// </summary>
        protected override void ProcessRecord()
        {
            #region Perform Transforms
            if ((!_fromStopFunction) && (Target != null))
            {
                Target = ResolveTarget(Target);
            }

            if (!_fromStopFunction)
            {
                if (Exception != null)
                {
                    Exception = ResolveException(Exception);
                }
                else if (ErrorRecord != null)
                {
                    Exception tempException = null;
                    for (int n = 0; n < ErrorRecord.Length; n++)
                    {
                        // If both Exception and ErrorRecord are specified, override the first error record's exception.
                        if ((n == 0) && (Exception != null))
                        {
                            tempException = Exception;
                        }
                        else
                        {
                            tempException = ResolveException(ErrorRecord[n].Exception);
                        }
                        if (tempException != ErrorRecord[n].Exception)
                        {
                            ErrorRecord[n] = new ErrorRecord(tempException, ErrorRecord[n].FullyQualifiedErrorId, ErrorRecord[n].CategoryInfo.Category, ErrorRecord[n].TargetObject);
                        }
                    }
                }
            }

            if (Level != MessageLevel.Warning)
            {
                Level = ResolveLevel(Level);
            }
            #endregion Perform Transforms

            #region Exception Integration

            /*
             *  While conclusive error handling must happen after message handling,
             *  in order to integrate the exception message into the actual message,
             *  it becomes necessary to first integrate the exception and error record parameters into a uniform view
             *
             *  Note: Stop-PSFFunction never specifies this parameter, thus it is not necessary to check,
             *  whether this function was called from Stop-PSFFunction.
             */
            if ((ErrorRecord == null) && (Exception != null))
            {
                ErrorRecord    = new ErrorRecord[1];
                ErrorRecord[0] = new ErrorRecord(Exception, String.Format("{0}_{1}", ModuleName, FunctionName), ErrorCategory.NotSpecified, Target);
            }
            #endregion Exception Integration

            #region Error handling
            if (ErrorRecord != null)
            {
                if (!_fromStopFunction)
                {
                    if (EnableException)
                    {
                        foreach (ErrorRecord record in ErrorRecord)
                        {
                            WriteError(record);
                        }
                    }
                }

                LogHost.WriteErrorEntry(ErrorRecord, FunctionName, ModuleName, _Tags, _timestamp, _MessageSystem, System.Management.Automation.Runspaces.Runspace.DefaultRunspace.InstanceId, Environment.MachineName);
            }
            #endregion Error handling

            LogEntryType channels = LogEntryType.None;

            #region Warning handling
            if (Level == MessageLevel.Warning)
            {
                if (!_silent)
                {
                    if (!String.IsNullOrEmpty(Once))
                    {
                        string onceName = String.Format("MessageOnce.{0}.{1}", FunctionName, Once).ToLower();
                        if (!(Configuration.ConfigurationHost.Configurations.ContainsKey(onceName) && (bool)Configuration.ConfigurationHost.Configurations[onceName].Value))
                        {
                            WriteWarning(_MessageStreams);
                            channels = channels | LogEntryType.Warning;

                            Configuration.Config cfg = new Configuration.Config();
                            cfg.Module      = "messageonce";
                            cfg.Name        = String.Format("{0}.{1}", FunctionName, Once).ToLower();
                            cfg.Hidden      = true;
                            cfg.Description = "Locking setting that disables further display of the specified message";
                            cfg.Value       = true;

                            Configuration.ConfigurationHost.Configurations[onceName] = cfg;
                        }
                    }
                    else
                    {
                        WriteWarning(_MessageStreams);
                        channels = channels | LogEntryType.Warning;
                    }
                }
                WriteDebug(_MessageStreams);
                channels = channels | LogEntryType.Debug;
            }
            #endregion Warning handling

            #region Message handling
            if (!_silent)
            {
                if ((MessageHost.MaximumInformation >= (int)Level) && (MessageHost.MinimumInformation <= (int)Level))
                {
                    if (!String.IsNullOrEmpty(Once))
                    {
                        string onceName = String.Format("MessageOnce.{0}.{1}", FunctionName, Once).ToLower();
                        if (!(Configuration.ConfigurationHost.Configurations.ContainsKey(onceName) && (bool)Configuration.ConfigurationHost.Configurations[onceName].Value))
                        {
                            InvokeCommand.InvokeScript(false, ScriptBlock.Create(_writeHostScript), null, _MessageHost);
                            channels = channels | LogEntryType.Information;

                            Configuration.Config cfg = new Configuration.Config();
                            cfg.Module      = "messageonce";
                            cfg.Name        = String.Format("{0}.{1}", FunctionName, Once).ToLower();
                            cfg.Hidden      = true;
                            cfg.Description = "Locking setting that disables further display of the specified message";
                            cfg.Value       = true;

                            Configuration.ConfigurationHost.Configurations[onceName] = cfg;
                        }
                    }
                    else
                    {
                        //InvokeCommand.InvokeScript(_writeHostScript, _MessageHost);
                        InvokeCommand.InvokeScript(false, ScriptBlock.Create(_writeHostScript), null, _MessageHost);
                        channels = channels | LogEntryType.Information;
                    }
                }
            }

            if ((MessageHost.MaximumVerbose >= (int)Level) && (MessageHost.MinimumVerbose <= (int)Level))
            {
                if ((_callStack.Count() > 1) && _callStack.ElementAt(_callStack.Count() - 2).InvocationInfo.BoundParameters.ContainsKey("Verbose"))
                {
                    InvokeCommand.InvokeScript(@"$VerbosePreference = 'Continue'");
                }
                //SessionState.PSVariable.Set("VerbosePreference", ActionPreference.Continue);

                WriteVerbose(_MessageStreams);
                channels = channels | LogEntryType.Verbose;
            }

            if ((MessageHost.MaximumDebug >= (int)Level) && (MessageHost.MinimumDebug <= (int)Level))
            {
                bool restoreInquire = false;
                if (_isDebug)
                {
                    if (Breakpoint.ToBool())
                    {
                        InvokeCommand.InvokeScript(false, ScriptBlock.Create(@"$DebugPreference = 'Inquire'"), null, null);
                    }
                    else
                    {
                        InvokeCommand.InvokeScript(false, ScriptBlock.Create(@"$DebugPreference = 'Continue'"), null, null);
                        restoreInquire = true;
                    }
                    WriteDebug(String.Format("{0} | {1}", Line, _MessageStreams));
                    channels = channels | LogEntryType.Debug;
                }
                else
                {
                    WriteDebug(_MessageStreams);
                    channels = channels | LogEntryType.Debug;
                }

                if (restoreInquire)
                {
                    InvokeCommand.InvokeScript(false, ScriptBlock.Create(@"$DebugPreference = 'Inquire'"), null, null);
                }
            }
            #endregion Message handling

            #region Logging
            LogEntry entry = LogHost.WriteLogEntry(_MessageSystem, channels, _timestamp, FunctionName, ModuleName, _Tags, Level, System.Management.Automation.Runspaces.Runspace.DefaultRunspace.InstanceId, Environment.MachineName, File, Line, _callStack, String.Format("{0}\\{1}", Environment.UserDomainName, Environment.UserName), Target);
            #endregion Logging

            foreach (MessageEventSubscription subscription in MessageHost.Events.Values)
            {
                if (subscription.Applies(entry))
                {
                    try { InvokeCommand.InvokeScript(subscription.ScriptBlock.ToString(), entry); }
                    catch (Exception e) { WriteError(new ErrorRecord(e, "", ErrorCategory.NotSpecified, entry)); }
                }
            }
        }
        private Collection <AliasInfo> GetAliasesFromFile(bool isLiteralPath)
        {
            Collection <AliasInfo> result = new Collection <AliasInfo>();

            string filePath = null;

            using (StreamReader reader = OpenFile(out filePath, isLiteralPath))
            {
                CSVHelper csvHelper = new CSVHelper(',');

                Int64  lineNumber = 0;
                string line       = null;
                while ((line = reader.ReadLine()) != null)
                {
                    ++lineNumber;

                    // Ignore blank lines
                    if (line.Length == 0)
                    {
                        continue;
                    }

                    // Ignore lines that only contain whitespace
                    if (OnlyContainsWhitespace(line))
                    {
                        continue;
                    }

                    // Ignore comment lines
                    if (line[0] == '#')
                    {
                        continue;
                    }

                    Collection <string> values = csvHelper.ParseCsv(line);

                    if (values.Count != 4)
                    {
                        string message = StringUtil.Format(AliasCommandStrings.ImportAliasFileInvalidFormat, filePath, lineNumber);

                        FormatException formatException =
                            new FormatException(message);

                        ErrorRecord errorRecord =
                            new ErrorRecord(
                                formatException,
                                "ImportAliasFileFormatError",
                                ErrorCategory.ReadError,
                                filePath);

                        errorRecord.ErrorDetails = new ErrorDetails(message);

                        ThrowTerminatingError(errorRecord);
                    }

                    ScopedItemOptions options = ScopedItemOptions.None;

                    try
                    {
                        options = (ScopedItemOptions)Enum.Parse(typeof(ScopedItemOptions), values[3], true);
                    }
                    catch (ArgumentException argException)
                    {
                        string message = StringUtil.Format(AliasCommandStrings.ImportAliasOptionsError, filePath, lineNumber);

                        ErrorRecord errorRecord =
                            new ErrorRecord(
                                argException,
                                "ImportAliasOptionsError",
                                ErrorCategory.ReadError,
                                filePath);

                        errorRecord.ErrorDetails = new ErrorDetails(message);
                        WriteError(errorRecord);
                        continue;
                    }

                    AliasInfo newAlias =
                        new AliasInfo(
                            values[0],
                            values[1],
                            Context,
                            options);

                    if (!String.IsNullOrEmpty(values[2]))
                    {
                        newAlias.Description = values[2];
                    }

                    result.Add(newAlias);
                }
                reader.Dispose();
            }
            return(result);
        }
Пример #18
0
        /// <summary>
        /// 1. Set the throttling limit and reset operations complete
        /// 2. Create helper objects
        /// 3. For async case, write the async result object down the
        ///    pipeline.
        /// </summary>
        protected override void BeginProcessing()
        {
            if (!File.Exists(PowerShellProcessInstance.PwshExePath))
            {
                // The pwsh executable file is not found under $PSHOME.
                // This means that PowerShell is currently being hosted in another application,
                // and 'Start-Job' is not supported by design in that scenario.
                string message = StringUtil.Format(
                    RemotingErrorIdStrings.IPCPwshExecutableNotFound,
                    PowerShellProcessInstance.PwshExePath);

                var errorRecord = new ErrorRecord(
                    new PSNotSupportedException(message),
                    "IPCPwshExecutableNotFound",
                    ErrorCategory.NotInstalled,
                    PowerShellProcessInstance.PwshExePath);

                ThrowTerminatingError(errorRecord);
            }

            if (RunAs32.IsPresent && Environment.Is64BitProcess)
            {
                // We cannot start a 32-bit 'pwsh' process from a 64-bit 'pwsh' installation.
                string message     = RemotingErrorIdStrings.RunAs32NotSupported;
                var    errorRecord = new ErrorRecord(
                    new PSNotSupportedException(message),
                    "RunAs32NotSupported",
                    ErrorCategory.InvalidOperation,
                    targetObject: null);

                ThrowTerminatingError(errorRecord);
            }

            if (WorkingDirectory != null && !Directory.Exists(WorkingDirectory))
            {
                string message     = StringUtil.Format(RemotingErrorIdStrings.StartJobWorkingDirectoryNotFound, WorkingDirectory);
                var    errorRecord = new ErrorRecord(
                    new DirectoryNotFoundException(message),
                    "DirectoryNotFoundException",
                    ErrorCategory.InvalidOperation,
                    targetObject: null);

                ThrowTerminatingError(errorRecord);
            }

            if (WorkingDirectory == null)
            {
                try
                {
                    WorkingDirectory = SessionState.Internal.CurrentLocation.Path;
                }
                catch (PSInvalidOperationException)
                {
                }
            }

            CommandDiscovery.AutoloadModulesWithJobSourceAdapters(this.Context, this.CommandOrigin);

            if (ParameterSetName == DefinitionNameParameterSet)
            {
                return;
            }

            // since jobs no more depend on WinRM
            // we will have to skip the check for the same
            SkipWinRMCheck = true;

            base.BeginProcessing();
        }
 /// <summary>
 /// Create the internal error record based on assembly name and type.
 /// The ErrorRecord created will be stored in the _errorRecord member.
 /// </summary>
 private void CreateErrorRecord()
 {
     if (!String.IsNullOrEmpty(_assemblyName) && !String.IsNullOrEmpty(_typeName))
     {
         _errorRecord = new ErrorRecord(new ParentContainsErrorRecordException(this), "UndefinedRunspaceConfigurationType", ErrorCategory.ResourceUnavailable, null);
         _errorRecord.ErrorDetails = new ErrorDetails(typeof(RunspaceConfigurationTypeException).GetTypeInfo().Assembly, "MiniShellErrors", "UndefinedRunspaceConfigurationType", _assemblyName, _typeName);
     }
 }
Пример #20
0
        private void EnableServerSideSettings()
        {
            String query   = helper.GetResourceMsgFromResourcetext("CredSSPServerContinueQuery");
            String caption = helper.GetResourceMsgFromResourcetext("CredSSPContinueCaption");

            if (!force && !ShouldContinue(query, caption))
            {
                return;
            }

            IWSManSession m_SessionObj = CreateWSManSession();

            if (m_SessionObj == null)
            {
                return;
            }

            try
            {
                //get the credssp node to check if wsman is configured on this machine
                string  result = m_SessionObj.Get(helper.Service_CredSSP_Uri, 0);
                XmlNode node   = helper.GetXmlNode(result,
                                                   helper.CredSSP_SNode,
                                                   helper.Service_CredSSP_XMLNmsp);

                if (node == null)
                {
                    InvalidOperationException ex = new InvalidOperationException();
                    ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null);
                    WriteError(er);
                    return;
                }

                try
                {
                    XmlDocument xmldoc        = new XmlDocument();
                    string      newxmlcontent = string.Format(CultureInfo.InvariantCulture,
                                                              @"<cfg:Auth xmlns:cfg=""{0}""><cfg:CredSSP>true</cfg:CredSSP></cfg:Auth>",
                                                              helper.Service_CredSSP_XMLNmsp);
                    //push the xml string with credssp enabled
                    xmldoc.LoadXml(m_SessionObj.Put(helper.Service_CredSSP_Uri, newxmlcontent, 0));
                    WriteObject(xmldoc.FirstChild);
                }
                catch (COMException)
                {
                    helper.AssertError(m_SessionObj.Error, true, delegatecomputer);
                }
            }
            finally
            {
                if (!String.IsNullOrEmpty(m_SessionObj.Error))
                {
                    helper.AssertError(m_SessionObj.Error, true, delegatecomputer);
                }

                if (m_SessionObj != null)
                {
                    Dispose(m_SessionObj);
                }
            }
        }
Пример #21
0
        WriteDebugLine(string message, ref ActionPreference preference)
        {
            string errorMsg = null;
            ErrorRecord errorRecord = null;
            switch (preference)
            {
                case ActionPreference.Continue:
                    WriteDebugLineHelper(message);
                    break;
                case ActionPreference.SilentlyContinue:
                case ActionPreference.Ignore:
                    break;
                case ActionPreference.Inquire:
                    if (!DebugShouldContinue(message, ref preference))
                    {
                        // user asked to exit with an error

                        errorMsg = InternalHostUserInterfaceStrings.WriteDebugLineStoppedError;
                        errorRecord = new ErrorRecord(new ParentContainsErrorRecordException(errorMsg),
                            "UserStopRequest", ErrorCategory.OperationStopped, null);
                        ActionPreferenceStopException e = new ActionPreferenceStopException(errorRecord);
                        // We cannot call ThrowTerminatingError since this is not a cmdlet or provider
                        throw e;
                    }
                    else
                    {
                        WriteDebugLineHelper(message);
                    }
                    break;
                case ActionPreference.Stop:
                    WriteDebugLineHelper(message);

                    errorMsg = InternalHostUserInterfaceStrings.WriteDebugLineStoppedError;
                    errorRecord = new ErrorRecord(new ParentContainsErrorRecordException(errorMsg),
                        "ActionPreferenceStop", ErrorCategory.OperationStopped, null);
                    ActionPreferenceStopException ense = new ActionPreferenceStopException(errorRecord);
                    // We cannot call ThrowTerminatingError since this is not a cmdlet or provider
                    throw ense;
                default:
                    Dbg.Assert(false, "all preferences should be checked");
                    throw PSTraceSource.NewArgumentException("preference",
                        InternalHostUserInterfaceStrings.UnsupportedPreferenceError, preference);
                    // break;
            }
        }
Пример #22
0
        /// <summary>
        /// Method to begin processing.
        /// </summary>
        protected override void BeginProcessing()
        {
            //If not running elevated, then throw an "elevation required" error message.
            WSManHelper.ThrowIfNotAdministrator();
            helper = new WSManHelper(this);
            IWSManSession m_SessionObj = null;

            try
            {
                IWSManEx wsmanObject = (IWSManEx) new WSManClass();
                m_SessionObj = (IWSManSession)wsmanObject.CreateSession(null, 0, null);
                string  result = m_SessionObj.Get(helper.CredSSP_RUri, 0);
                XmlNode node   = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.CredSSP_XMLNmsp);
                if (node == null)
                {
                    InvalidOperationException ex = new InvalidOperationException();
                    ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null);
                    WriteError(er);
                    return;
                }
                // The application name MUST be "wsman" as wsman got approval from security
                // folks who suggested to register the SPN with name "wsman".
                string applicationname = "wsman";
                string credsspResult   = GetDelegateSettings(applicationname);
                if (string.IsNullOrEmpty(credsspResult))
                {
                    WriteObject(helper.GetResourceMsgFromResourcetext("NoDelegateFreshCred"));
                }
                else
                {
                    WriteObject(helper.GetResourceMsgFromResourcetext("DelegateFreshCred") + credsspResult);
                }

                // Get the server side settings
                result = m_SessionObj.Get(helper.Service_CredSSP_Uri, 0);
                node   = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.Service_CredSSP_XMLNmsp);
                if (node == null)
                {
                    InvalidOperationException ex = new InvalidOperationException();
                    ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null);
                    WriteError(er);
                    return;
                }

                if (node.InnerText.Equals("true", StringComparison.OrdinalIgnoreCase))
                {
                    WriteObject(helper.GetResourceMsgFromResourcetext("CredSSPServiceConfigured"));
                }
                else
                {
                    WriteObject(helper.GetResourceMsgFromResourcetext("CredSSPServiceNotConfigured"));
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "UnauthorizedAccess", ErrorCategory.PermissionDenied, null);
                WriteError(er);
            }
            catch (SecurityException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "SecurityException", ErrorCategory.InvalidOperation, null);
                WriteError(er);
            }
            catch (ArgumentException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "InvalidArgument", ErrorCategory.InvalidOperation, null);
                WriteError(er);
            }
            catch (System.Xml.XPath.XPathException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "XPathException", ErrorCategory.InvalidOperation, null);
                WriteError(er);
            }
            finally
            {
                if (!String.IsNullOrEmpty(m_SessionObj.Error))
                {
                    helper.AssertError(m_SessionObj.Error, true, null);
                }

                if (m_SessionObj != null)
                {
                    Dispose(m_SessionObj);
                }
            }
        }
Пример #23
0
        private bool VerifySecureChannel(string domain, string localMachineName)
        {
            IntPtr queryInfo = IntPtr.Zero;
            IntPtr domainPtr = Marshal.StringToCoTaskMemAuto(domain);
            bool scInGoodState = false;

            try
            {
                int errorCode = SAMAPI.I_NetLogonControl2(null, NETLOGON_CONTROL_TC_QUERY, NETLOGON_INFO_2, ref domainPtr, out queryInfo);

                if (errorCode != 0)
                {
                    var ex = new Win32Exception(errorCode);
                    string errMsg = StringUtil.Format(ComputerResources.FailToTestSecureChannel, ex.Message);
                    ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToTestSecureChannel",
                                                    ErrorCategory.OperationStopped, localMachineName);
                    ThrowTerminatingError(error);
                }

                var infoData = (SAMAPI.NetLogonInfo2)Marshal.PtrToStructure(queryInfo, typeof(SAMAPI.NetLogonInfo2));
                scInGoodState = infoData.PdcConnectionStatus == 0;
            }
            finally
            {
                if (domainPtr != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(domainPtr);
                }
                if (queryInfo != IntPtr.Zero)
                {
                    int freeResult = SAMAPI.NetApiBufferFree(queryInfo);
                    Dbg.Diagnostics.Assert(freeResult == 0, "NetApiBufferFree returned non-zero value");
                }
            }

            return scInGoodState;
        }
Пример #24
0
        /// <summary>
        /// Executes the cmdlet.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            var subscriptions =
                (this.Subscription ?? this.DefaultContext.Account.GetSubscriptions()).ToList();
            var first = MyInvocation.BoundParameters.ContainsKey("First") ? this.First : 100;
            var skip  = MyInvocation.BoundParameters.ContainsKey("Skip") ? this.Skip : 0;

            var           results  = new List <PSObject>();
            QueryResponse response = null;

            try
            {
                do
                {
                    var requestTop       = Math.Min(first - results.Count, RowsPerPage);
                    var requestSkip      = skip + results.Count;
                    var requestSkipToken = response?.SkipToken;
                    WriteVerbose($"Sent top={requestTop} skip={requestSkip} skipToken={requestSkipToken}");

                    var requestOptions = new QueryRequestOptions(
                        top: requestTop,
                        skip: requestSkip,
                        skipToken: requestSkipToken);

                    var request = new QueryRequest(subscriptions, this.Query, requestOptions);

                    response = this.ResourceGraphClient.ResourcesWithHttpMessagesAsync(request)
                               .Result
                               .Body;

                    var requestResults = response.Data.ToPsObjects().ToList();
                    results.AddRange(requestResults);
                    WriteVerbose($"Received results: {requestResults.Count}");
                } while (results.Count < first && response.SkipToken != null);
            }
            catch (Exception ex)
            {
                var aggregateEx = ex as AggregateException;
                if (aggregateEx?.InnerException != null && aggregateEx.InnerExceptions.Count == 1)
                {
                    var errorResponseEx = aggregateEx.InnerException as ErrorResponseException;
                    if (errorResponseEx != null)
                    {
                        var errorRecord = new ErrorRecord(
                            errorResponseEx, errorResponseEx.Body.Error.Code,
                            ErrorCategory.CloseError, null)
                        {
                            ErrorDetails = new System.Management.Automation.ErrorDetails(
                                errorResponseEx.ToDisplayableJson())
                        };

                        this.WriteError(errorRecord);
                        return;
                    }
                }

                this.WriteExceptionError(ex);
                return;
            }

            this.WriteObject(results, true);
        }
Пример #25
0
        /// <summary>
        /// BeginProcessing method.
        /// </summary>
        protected override void BeginProcessing()
        {
            if (Server != null)
            {
                if (Server.Length == 1 && Server[0] == '.')
                {
                    Server = "localhost";
                }

                try
                {
                    string resolveFullName = Dns.GetHostEntry(Server).HostName;
                }
                catch (Exception exception)
                {
                    CommandProcessorBase.CheckForSevereException(exception);

                    string errMsg = StringUtil.Format(ComputerResources.CannotResolveComputerName, Server, exception.Message);
                    ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "AddressResolutionException", ErrorCategory.InvalidArgument, Server);
                    ThrowTerminatingError(error);
                }
            }
        }//End BeginProcessing()
Пример #26
0
        /// <summary>
        /// <para>
        /// Throw terminating error
        /// </para>
        /// </summary>
        internal void ThrowTerminatingError(Exception exception, string operation)
        {
            ErrorRecord errorRecord = new ErrorRecord(exception, operation, ErrorCategory.InvalidOperation, this);

            this.CmdletOperation.ThrowTerminatingError(errorRecord);
        }
Пример #27
0
        /// <summary>
        /// Invokes the Win32Shutdown command on provided target computer using WSMan
        /// over a CIMSession.  The flags parameter determines the type of shutdown operation
        /// such as shutdown, reboot, force etc.
        /// </summary>
        /// <param name="cmdlet">Cmdlet host for reporting errors</param>
        /// <param name="isLocalhost">True if local host computer</param>
        /// <param name="computerName">Target computer</param>
        /// <param name="flags">Win32Shutdown flags</param>
        /// <param name="credential">Optional credential</param>
        /// <param name="authentication">Optional authentication</param>
        /// <param name="formatErrorMessage">Error message format string that takes two parameters</param>
        /// <param name="ErrorFQEID">Fully qualified error Id</param>
        /// <param name="cancelToken">Cancel token</param>
        /// <returns>True on success</returns>
        internal static bool InvokeWin32ShutdownUsingWsman(
            PSCmdlet cmdlet,
            bool isLocalhost,
            string computerName,
            object[] flags,
            PSCredential credential,
            string authentication,
            string formatErrorMessage,
            string ErrorFQEID,
            CancellationToken cancelToken)
        {
            Dbg.Diagnostics.Assert(flags.Length == 2, "Caller need to verify the flags passed in");

            bool isSuccess = false;
            string targetMachine = isLocalhost ? "localhost" : computerName;
            string authInUse = isLocalhost ? null : authentication;
            PSCredential credInUse = isLocalhost ? null : credential;
            var currentPrivilegeState = new PlatformInvokes.TOKEN_PRIVILEGE();
            var operationOptions = new CimOperationOptions
            {
                Timeout = TimeSpan.FromMilliseconds(10000),
                CancellationToken = cancelToken,
                //This prefix works against all versions of the WinRM server stack, both win8 and win7
                ResourceUriPrefix = new Uri(ComputerWMIHelper.CimUriPrefix)
            };

            try
            {
                if (!(isLocalhost && PlatformInvokes.EnableTokenPrivilege(ComputerWMIHelper.SE_SHUTDOWN_NAME, ref currentPrivilegeState)) &&
                    !(!isLocalhost && PlatformInvokes.EnableTokenPrivilege(ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME, ref currentPrivilegeState)))
                {
                    string message =
                        StringUtil.Format(ComputerResources.PrivilegeNotEnabled, computerName,
                            isLocalhost ? ComputerWMIHelper.SE_SHUTDOWN_NAME : ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME);
                    ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(message), "PrivilegeNotEnabled", ErrorCategory.InvalidOperation, null);
                    cmdlet.WriteError(errorRecord);
                    return false;
                }

                using (CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(targetMachine, credInUse, authInUse, cancelToken, cmdlet))
                {
                    var methodParameters = new CimMethodParametersCollection();
                    methodParameters.Add(CimMethodParameter.Create(
                        "Flags",
                        flags[0],
                        Microsoft.Management.Infrastructure.CimType.SInt32,
                        CimFlags.None));

                    methodParameters.Add(CimMethodParameter.Create(
                        "Reserved",
                        flags[1],
                        Microsoft.Management.Infrastructure.CimType.SInt32,
                        CimFlags.None));

                    CimMethodResult result = cimSession.InvokeMethod(
                        ComputerWMIHelper.CimOperatingSystemNamespace,
                        ComputerWMIHelper.WMI_Class_OperatingSystem,
                        ComputerWMIHelper.CimOperatingSystemShutdownMethod,
                        methodParameters,
                        operationOptions);

                    int retVal = Convert.ToInt32(result.ReturnValue.Value, CultureInfo.CurrentCulture);
                    if (retVal != 0)
                    {
                        var ex = new Win32Exception(retVal);
                        string errMsg = StringUtil.Format(formatErrorMessage, computerName, ex.Message);
                        ErrorRecord error = new ErrorRecord(
                            new InvalidOperationException(errMsg), ErrorFQEID, ErrorCategory.OperationStopped, computerName);
                        cmdlet.WriteError(error);
                    }
                    else
                    {
                        isSuccess = true;
                    }
                }
            }
            catch (CimException ex)
            {
                string errMsg = StringUtil.Format(formatErrorMessage, computerName, ex.Message);
                ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), ErrorFQEID,
                                                    ErrorCategory.OperationStopped, computerName);
                cmdlet.WriteError(error);
            }
            catch (Exception ex)
            {
                CommandProcessorBase.CheckForSevereException(ex);
                string errMsg = StringUtil.Format(formatErrorMessage, computerName, ex.Message);
                ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), ErrorFQEID,
                                                    ErrorCategory.OperationStopped, computerName);
                cmdlet.WriteError(error);
            }
            finally
            {
                // Restore the previous privilege state if something unexpected happened
                PlatformInvokes.RestoreTokenPrivilege(
                    isLocalhost ? ComputerWMIHelper.SE_SHUTDOWN_NAME : ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME, ref currentPrivilegeState);
            }

            return isSuccess;
        }
Пример #28
0
        BeginProcessing()
        {
            try
            {
                // Set the sender address of the mail message
                _mMailMessage.From = new MailAddress(_from);
            }
            catch (FormatException e)
            {
                ErrorRecord er = new ErrorRecord(e, "FormatException", ErrorCategory.InvalidType, _from);
                ThrowTerminatingError(er);
                // return;
            }

            // Set the recipient address of the mail message
            AddAddressesToMailMessage(_to, "to");

            // Set the BCC address of the mail message
            if (_bcc != null)
            {
                AddAddressesToMailMessage(_bcc, "bcc");
            }

            // Set the CC address of the mail message
            if (_cc != null)
            {
                AddAddressesToMailMessage(_cc, "cc");
            }

            //set the delivery notification
            _mMailMessage.DeliveryNotificationOptions = _deliverynotification;

            // Set the subject of the mail message
            _mMailMessage.Subject = _subject;

            // Set the body of the mail message
            _mMailMessage.Body = _body;

            //set the subject and body encoding
            _mMailMessage.SubjectEncoding = Encoding;
            _mMailMessage.BodyEncoding    = Encoding;

            // Set the format of the mail message body as HTML
            _mMailMessage.IsBodyHtml = _bodyashtml;

            // Set the priority of the mail message to normal
            _mMailMessage.Priority = _priority;

            //get the PowerShell environment variable
            //globalEmailServer might be null if it is deleted by: PS> del variable:PSEmailServer
            PSVariable globalEmailServer = SessionState.Internal.GetVariable(SpecialVariables.PSEmailServer);

            if (_smtpserver == null && globalEmailServer != null)
            {
                _smtpserver = Convert.ToString(globalEmailServer.Value, CultureInfo.InvariantCulture);
            }
            if (string.IsNullOrEmpty(_smtpserver))
            {
                ErrorRecord er = new ErrorRecord(new InvalidOperationException(SendMailMessageStrings.HostNameValue), null, ErrorCategory.InvalidArgument, null);
                this.ThrowTerminatingError(er);
            }

            if (_port == 0)
            {
                _mSmtpClient = new SmtpClient(_smtpserver);
            }
            else
            {
                _mSmtpClient = new SmtpClient(_smtpserver, _port);
            }

            if (_usessl)
            {
                _mSmtpClient.EnableSsl = true;
            }

            if (_credential != null)
            {
                _mSmtpClient.UseDefaultCredentials = false;
                _mSmtpClient.Credentials           = _credential.GetNetworkCredential();
            }
            else if (!_usessl)
            {
                _mSmtpClient.UseDefaultCredentials = true;
            }
        }
Пример #29
0
 public void ThrowTerminatingError(ErrorRecord errorRecord)
 {
     throw new NotImplementedException();
 }
 protected void Append(StringBuilder sb, ErrorRecord error)
 {
     sb.Append(error).Append(Environment.NewLine);
     sb.Append(error.InvocationInfo.PositionMessage);
     sb.Append(Environment.NewLine);
 }
Пример #31
0
        /// <summary>
        /// Create the internal error record.
        /// The ErrorRecord created will be stored in the _errorRecord member.
        /// </summary>
        private void CreateErrorRecord()
        {
            // if _PSSnapin or _reason is empty, this exception is created using default
            // constructor. Don't create the error record since there is 
            // no useful information anyway.
            if (!String.IsNullOrEmpty(_PSSnapin) && !String.IsNullOrEmpty(_reason))
            {
                Assembly currentAssembly = typeof(PSSnapInException).GetTypeInfo().Assembly;

                if (_warning)
                {
                    _errorRecord = new ErrorRecord(new ParentContainsErrorRecordException(this), "PSSnapInLoadWarning", ErrorCategory.ResourceUnavailable, null);
                    _errorRecord.ErrorDetails = new ErrorDetails(String.Format(ConsoleInfoErrorStrings.PSSnapInLoadWarning, _PSSnapin, _reason));
                }
                else
                {
                    _errorRecord = new ErrorRecord(new ParentContainsErrorRecordException(this), "PSSnapInLoadFailure", ErrorCategory.ResourceUnavailable, null);
                    _errorRecord.ErrorDetails = new ErrorDetails(String.Format(ConsoleInfoErrorStrings.PSSnapInLoadFailure, _PSSnapin, _reason));
                }
            }
        }
        /// <summary>
        /// Process input.
        /// </summary>
        protected override void ProcessRecord()
        {
            string targetString = StringUtil.Format(ScheduledJobErrorStrings.DefinitionWhatIf, Name);

            if (!ShouldProcess(targetString, VerbsLifecycle.Register))
            {
                return;
            }

            ScheduledJobDefinition definition = null;

            switch (ParameterSetName)
            {
            case ScriptBlockParameterSet:
                definition = CreateScriptBlockDefinition();
                break;

            case FilePathParameterSet:
                definition = CreateFilePathDefinition();
                break;
            }

            if (definition != null)
            {
                // Set the MaxCount value if available.
                if (MyInvocation.BoundParameters.ContainsKey(nameof(MaxResultCount)))
                {
                    if (MaxResultCount < 1)
                    {
                        string      msg         = StringUtil.Format(ScheduledJobErrorStrings.InvalidMaxResultCount);
                        Exception   reason      = new RuntimeException(msg);
                        ErrorRecord errorRecord = new ErrorRecord(reason, "InvalidMaxResultCountParameterForRegisterScheduledJobDefinition", ErrorCategory.InvalidArgument, null);
                        WriteError(errorRecord);

                        return;
                    }

                    definition.SetExecutionHistoryLength(MaxResultCount, false);
                }

                try
                {
                    // If RunEvery parameter is specified then create a job trigger for the definition that
                    // runs the job at the requested interval.
                    if (MyInvocation.BoundParameters.ContainsKey(nameof(RunEvery)))
                    {
                        AddRepetitionJobTriggerToDefinition(
                            definition,
                            RunEvery,
                            false);
                    }

                    definition.Register();
                    WriteObject(definition);

                    if (_runNow)
                    {
                        definition.RunAsTask();
                    }
                }
                catch (ScheduledJobException e)
                {
                    // Check for access denied error.
                    if (e.InnerException != null && e.InnerException is System.UnauthorizedAccessException)
                    {
                        string      msg         = StringUtil.Format(ScheduledJobErrorStrings.UnauthorizedAccessError, definition.Name);
                        Exception   reason      = new RuntimeException(msg, e);
                        ErrorRecord errorRecord = new ErrorRecord(reason, "UnauthorizedAccessToRegisterScheduledJobDefinition", ErrorCategory.PermissionDenied, definition);
                        WriteError(errorRecord);
                    }
                    else if (e.InnerException != null && e.InnerException is System.IO.DirectoryNotFoundException)
                    {
                        string      msg         = StringUtil.Format(ScheduledJobErrorStrings.DirectoryNotFoundError, definition.Name);
                        Exception   reason      = new RuntimeException(msg, e);
                        ErrorRecord errorRecord = new ErrorRecord(reason, "DirectoryNotFoundWhenRegisteringScheduledJobDefinition", ErrorCategory.ObjectNotFound, definition);
                        WriteError(errorRecord);
                    }
                    else if (e.InnerException != null && e.InnerException is System.Runtime.Serialization.InvalidDataContractException)
                    {
                        string      innerMsg    = (!string.IsNullOrEmpty(e.InnerException.Message)) ? e.InnerException.Message : string.Empty;
                        string      msg         = StringUtil.Format(ScheduledJobErrorStrings.CannotSerializeData, definition.Name, innerMsg);
                        Exception   reason      = new RuntimeException(msg, e);
                        ErrorRecord errorRecord = new ErrorRecord(reason, "CannotSerializeDataWhenRegisteringScheduledJobDefinition", ErrorCategory.InvalidData, definition);
                        WriteError(errorRecord);
                    }
                    else
                    {
                        // Create record around known exception type.
                        ErrorRecord errorRecord = new ErrorRecord(e, "CantRegisterScheduledJobDefinition", ErrorCategory.InvalidOperation, definition);
                        WriteError(errorRecord);
                    }
                }
            }
        }
Пример #33
0
 /// <summary>
 /// constructor
 /// </summary>
 /// <param name="errorRecord">the error record that is wrapped</param>
 /// <param name="originInfo">origin information</param>
 public RemotingErrorRecord(ErrorRecord errorRecord, OriginInfo originInfo) : this(errorRecord, originInfo, null) { }
Пример #34
0
        }//End BeginProcessing()

        #region private

        private void QuickConfigRemoting(bool serviceonly)
        {
            IWSManSession m_SessionObj = null;

            try
            {
                string   transport;
                IWSManEx wsmanObject = (IWSManEx) new WSManClass();
                m_SessionObj = (IWSManSession)wsmanObject.CreateSession(null, 0, null);
                string xpathEnabled     = string.Empty;
                string xpathText        = string.Empty;
                string xpathUpdate      = string.Empty;
                string analysisInputXml = string.Empty;
                string action           = string.Empty;
                string xpathStatus      = string.Empty;
                string xpathResult      = string.Empty;

                if (!usessl)
                {
                    transport = "http";
                }
                else
                {
                    transport = "https";
                }

                if (serviceonly)
                {
                    analysisInputXml = @"<AnalyzeService_INPUT xmlns=""http://schemas.microsoft.com/wbem/wsman/1/config/service""></AnalyzeService_INPUT>";
                    action           = "AnalyzeService";
                }
                else
                {
                    string openAllProfiles = skipNetworkProfileCheck ? "<Force/>" : string.Empty;
                    analysisInputXml = @"<Analyze_INPUT xmlns=""http://schemas.microsoft.com/wbem/wsman/1/config/service""><Transport>" + transport + "</Transport>" + openAllProfiles + "</Analyze_INPUT>";
                    action           = "Analyze";
                }

                string      analysisOutputXml = m_SessionObj.Invoke(action, "winrm/config/service", analysisInputXml, 0);
                XmlDocument resultopxml       = new XmlDocument();
                resultopxml.LoadXml(analysisOutputXml);

                if (serviceonly)
                {
                    xpathEnabled = "/cfg:AnalyzeService_OUTPUT/cfg:RemotingEnabled";
                    xpathText    = "/cfg:AnalyzeService_OUTPUT/cfg:Results";
                    xpathUpdate  = "/cfg:AnalyzeService_OUTPUT/cfg:EnableService_INPUT";
                }
                else
                {
                    xpathEnabled = "/cfg:Analyze_OUTPUT/cfg:RemotingEnabled";
                    xpathText    = "/cfg:Analyze_OUTPUT/cfg:Results";
                    xpathUpdate  = "/cfg:Analyze_OUTPUT/cfg:EnableRemoting_INPUT";
                }

                XmlNamespaceManager nsmgr = new XmlNamespaceManager(resultopxml.NameTable);
                nsmgr.AddNamespace("cfg", "http://schemas.microsoft.com/wbem/wsman/1/config/service");
                string  enabled         = resultopxml.SelectSingleNode(xpathEnabled, nsmgr).InnerText;
                XmlNode sourceAttribute = resultopxml.SelectSingleNode(xpathEnabled, nsmgr).Attributes.GetNamedItem("Source");
                string  source          = null;
                if (sourceAttribute != null)
                {
                    source = sourceAttribute.Value;
                }

                string rxml = string.Empty;
                if (enabled.Equals("true"))
                {
                    string Err_Msg = string.Empty;
                    if (serviceonly)
                    {
                        Err_Msg = WSManResourceLoader.GetResourceString("L_QuickConfigNoServiceChangesNeeded_Message");
                    }
                    else
                    {
                        Err_Msg = WSManResourceLoader.GetResourceString("L_QuickConfigNoChangesNeeded_Message");
                    }
                    //  ArgumentException e = new ArgumentException(Err_Msg);
                    // ErrorRecord er = new ErrorRecord(e, "InvalidOperation", ErrorCategory.InvalidOperation, null);
                    //  WriteError(er);
                    WriteObject(Err_Msg);
                    return;
                }

                if (!enabled.Equals("false"))
                {
                    ArgumentException e  = new ArgumentException(WSManResourceLoader.GetResourceString("L_QuickConfig_InvalidBool_0_ErrorMessage"));
                    ErrorRecord       er = new ErrorRecord(e, "InvalidOperation", ErrorCategory.InvalidOperation, null);
                    WriteError(er);
                    return;
                }

                string resultAction = resultopxml.SelectSingleNode(xpathText, nsmgr).InnerText;
                if (source != null && source.Equals("GPO"))
                {
                    String Info_Msg = WSManResourceLoader.GetResourceString("L_QuickConfig_RemotingDisabledbyGP_00_ErrorMessage");
                    Info_Msg += " " + resultAction;
                    ArgumentException e = new ArgumentException(Info_Msg);
                    WriteError(new ErrorRecord(e, "NotSpecified", ErrorCategory.NotSpecified, null));
                    return;
                }

                string inputXml = resultopxml.SelectSingleNode(xpathUpdate, nsmgr).OuterXml;
                if (resultAction.Equals(string.Empty) || inputXml.Equals(string.Empty))
                {
                    ArgumentException e  = new ArgumentException(WSManResourceLoader.GetResourceString("L_ERR_Message") + WSManResourceLoader.GetResourceString("L_QuickConfig_MissingUpdateXml_0_ErrorMessage"));
                    ErrorRecord       er = new ErrorRecord(e, "InvalidOperation", ErrorCategory.InvalidOperation, null);
                    WriteError(er);
                    return;
                }

                if (serviceonly)
                {
                    action = "EnableService";
                }
                else
                {
                    action = "EnableRemoting";
                }

                rxml = m_SessionObj.Invoke(action, "winrm/config/service", inputXml, 0);
                XmlDocument finalxml = new XmlDocument();
                finalxml.LoadXml(rxml);

                if (serviceonly)
                {
                    xpathStatus = "/cfg:EnableService_OUTPUT/cfg:Status";
                    xpathResult = "/cfg:EnableService_OUTPUT/cfg:Results";
                }
                else
                {
                    xpathStatus = "/cfg:EnableRemoting_OUTPUT/cfg:Status";
                    xpathResult = "/cfg:EnableRemoting_OUTPUT/cfg:Results";
                }

                if (finalxml.SelectSingleNode(xpathStatus, nsmgr).InnerText.ToString().Equals("succeeded"))
                {
                    if (serviceonly)
                    {
                        WriteObject(WSManResourceLoader.GetResourceString("L_QuickConfigUpdatedService_Message"));
                    }
                    else
                    {
                        WriteObject(WSManResourceLoader.GetResourceString("L_QuickConfigUpdated_Message"));
                    }

                    WriteObject(finalxml.SelectSingleNode(xpathResult, nsmgr).InnerText);
                }
                else
                {
                    helper.AssertError(WSManResourceLoader.GetResourceString("L_ERR_Message") + WSManResourceLoader.GetResourceString("L_QuickConfigUpdateFailed_ErrorMessage"), false, null);
                }
            }
            finally
            {
                if (!string.IsNullOrEmpty(m_SessionObj.Error))
                {
                    helper.AssertError(m_SessionObj.Error, true, null);
                }

                if (m_SessionObj != null)
                {
                    Dispose(m_SessionObj);
                }
            }
        }
Пример #35
0
        /// <summary>
        /// TraceErrorRecord
        /// </summary>
        public bool TraceErrorRecord(ErrorRecord errorRecord)
        {
            if (errorRecord != null)
            {
                Exception exception = errorRecord.Exception;
                string innerException = "None";
                if (exception.InnerException != null)
                {
                    innerException = exception.InnerException.Message;
                }

                ErrorCategoryInfo cinfo = errorRecord.CategoryInfo;
                string message = "None";

                if (errorRecord.ErrorDetails != null)
                {
                    message = errorRecord.ErrorDetails.Message;
                }
                return DebugChannel.TraceError(PowerShellTraceEvent.ErrorRecord,
                                               PowerShellTraceOperationCode.Exception, PowerShellTraceTask.None,
                                               message,
                                               cinfo.Category.ToString(), cinfo.Reason, cinfo.TargetName,
                                               errorRecord.FullyQualifiedErrorId,
                                               exception.Message, exception.StackTrace, innerException);
            }
            else
            {
                return DebugChannel.TraceError(PowerShellTraceEvent.ErrorRecord,
                                               PowerShellTraceOperationCode.Exception, PowerShellTraceTask.None,
                                               "NULL errorRecord");
            }
        }
Пример #36
0
        /// <summary>
        /// Perform runspace disconnect processing on all input.
        /// </summary>
        protected override void ProcessRecord()
        {
            Dictionary <Guid, PSSession> psSessions;
            List <IThrottleOperation>    disconnectOperations = new List <IThrottleOperation>();

            try
            {
                // Get all remote runspaces to disconnect.
                if (ParameterSetName == DisconnectPSSessionCommand.SessionParameterSet)
                {
                    if (Session == null || Session.Length == 0)
                    {
                        return;
                    }

                    psSessions = new Dictionary <Guid, PSSession>();
                    foreach (PSSession psSession in Session)
                    {
                        psSessions.Add(psSession.InstanceId, psSession);
                    }
                }
                else
                {
                    psSessions = GetMatchingRunspaces(false, true);
                }

                // Look for local sessions that have the EnableNetworkAccess property set and
                // return a string containing all of the session names.  Emit a warning for
                // these sessions.
                string cnNames = GetLocalhostWithNetworkAccessEnabled(psSessions);
                if (!string.IsNullOrEmpty(cnNames))
                {
                    WriteWarning(
                        StringUtil.Format(RemotingErrorIdStrings.EnableNetworkAccessWarning, cnNames));
                }

                // Create a disconnect operation for each runspace to disconnect.
                foreach (PSSession psSession in psSessions.Values)
                {
                    if (ShouldProcess(psSession.Name, VerbsCommunications.Disconnect))
                    {
                        // PS session disconnection is not supported for VM/Container sessions.
                        if (psSession.ComputerType != TargetMachineType.RemoteMachine)
                        {
                            // Write error record.
                            string msg = StringUtil.Format(RemotingErrorIdStrings.RunspaceCannotBeDisconnectedForVMContainerSession,
                                                           psSession.Name, psSession.ComputerName, psSession.ComputerType);
                            Exception   reason      = new PSNotSupportedException(msg);
                            ErrorRecord errorRecord = new ErrorRecord(reason, "CannotDisconnectVMContainerSession", ErrorCategory.InvalidOperation, psSession);
                            WriteError(errorRecord);
                            continue;
                        }

                        // Can only disconnect an Opened runspace.
                        if (psSession.Runspace.RunspaceStateInfo.State == RunspaceState.Opened)
                        {
                            // Update the connectionInfo object with passed in session options.
                            if (_sessionOption != null)
                            {
                                psSession.Runspace.ConnectionInfo.SetSessionOptions(_sessionOption);
                            }

                            // Validate the ConnectionInfo IdleTimeout value against the MaxIdleTimeout
                            // value returned by the server and the hard coded minimum allowed value.
                            if (!ValidateIdleTimeout(psSession))
                            {
                                continue;
                            }

                            DisconnectRunspaceOperation disconnectOperation = new DisconnectRunspaceOperation(psSession, _stream);
                            disconnectOperations.Add(disconnectOperation);
                        }
                        else if (psSession.Runspace.RunspaceStateInfo.State != RunspaceState.Disconnected)
                        {
                            // Write error record.
                            string      msg         = StringUtil.Format(RemotingErrorIdStrings.RunspaceCannotBeDisconnected, psSession.Name);
                            Exception   reason      = new RuntimeException(msg);
                            ErrorRecord errorRecord = new ErrorRecord(reason, "CannotDisconnectSessionWhenNotOpened", ErrorCategory.InvalidOperation, psSession);
                            WriteError(errorRecord);
                        }
                        else
                        {
                            // Session is already disconnected.  Write to output.
                            WriteObject(psSession);
                        }
                    }
                }
            }
            catch (PSRemotingDataStructureException)
            {
                // Allow cmdlet to end and then re-throw exception.
                _operationsComplete.Set();
                throw;
            }
            catch (PSRemotingTransportException)
            {
                // Allow cmdlet to end and then re-throw exception.
                _operationsComplete.Set();
                throw;
            }
            catch (RemoteException)
            {
                // Allow cmdlet to end and then re-throw exception.
                _operationsComplete.Set();
                throw;
            }
            catch (InvalidRunspaceStateException)
            {
                // Allow cmdlet to end and then re-throw exception.
                _operationsComplete.Set();
                throw;
            }

            if (disconnectOperations.Count > 0)
            {
                // Make sure operations are not set as complete while processing input.
                _operationsComplete.Reset();

                // Submit list of disconnect operations.
                _throttleManager.SubmitOperations(disconnectOperations);

                // Write any output now.
                Collection <object> streamObjects = _stream.ObjectReader.NonBlockingRead();
                foreach (object streamObject in streamObjects)
                {
                    WriteStreamObject((Action <Cmdlet>)streamObject);
                }
            }
        }
 void ISchedulerService.AddErrorRecord(ErrorRecord record)
 {
     _faults += 1;
 }
Пример #38
0
        /// <summary>
        /// Sets up the PowerShell shell stream event handlers.
        /// </summary>
        /// <param name="shell">The PowerShell shell.</param>
        private static void SetupStreamEventHandlers(PowerShell shell)
        {
            Logger.Instance.WriteMethodEntry(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlers);

            try
            {
                shell.Streams.ClearStreams();
                shell.Streams.Error.DataAdded += delegate(object sender, DataAddedEventArgs e)
                {
                    PSDataCollection <ErrorRecord> errorStream = (PSDataCollection <ErrorRecord>)sender;
                    ErrorRecord record = errorStream[e.Index];
                    if (record == null)
                    {
                        return;
                    }

                    StringBuilder builder = new StringBuilder();
                    builder.AppendLine(record.ToString());

                    if (record.InvocationInfo != null)
                    {
                        builder.AppendLine();
                        builder.AppendLine(record.InvocationInfo.PositionMessage);
                    }

                    Logger.Instance.WriteError(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersErrorEvents, builder.ToString());
                };
                shell.Streams.Warning.DataAdded += delegate(object sender, DataAddedEventArgs e)
                {
                    PSDataCollection <WarningRecord> warningStream = (PSDataCollection <WarningRecord>)sender;
                    WarningRecord record = warningStream[e.Index];
                    if (record != null)
                    {
                        Logger.Instance.WriteWarning(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersWarningEvents, record.ToString());
                    }
                };
                shell.Streams.Debug.DataAdded += delegate(object sender, DataAddedEventArgs e)
                {
                    PSDataCollection <DebugRecord> debugStream = (PSDataCollection <DebugRecord>)sender;
                    DebugRecord record = debugStream[e.Index];
                    if (record != null)
                    {
                        Logger.Instance.WriteInfo(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersDebugEvents, record.ToString());
                    }
                };
                shell.Streams.Verbose.DataAdded += delegate(object sender, DataAddedEventArgs e)
                {
                    PSDataCollection <VerboseRecord> versboseStream = (PSDataCollection <VerboseRecord>)sender;
                    VerboseRecord record = versboseStream[e.Index];
                    if (record != null)
                    {
                        Logger.Instance.WriteVerbose(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersEvents, record.ToString());
                    }
                };
                shell.Streams.Progress.DataAdded += delegate(object sender, DataAddedEventArgs e)
                {
                    PSDataCollection <ProgressRecord> progressStream = (PSDataCollection <ProgressRecord>)sender;
                    ProgressRecord record = progressStream[e.Index];
                    if (record != null)
                    {
                        Logger.Instance.WriteInfo(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersProgressEvents, record.ToString());
                    }
                };
            }
            finally
            {
                Logger.Instance.WriteMethodExit(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlers);
            }
        }
Пример #39
0
        } // GetResourceString
        #endregion IResourceSupplier

        #region ThrowTerminatingError
        /// <Content contentref="System.Management.Automation.Cmdlet.ThrowTerminatingError" />
        public void ThrowTerminatingError(ErrorRecord errorRecord)
        {
            using (PSTransactionManager.GetEngineProtectionScope())
            {
                if (null == errorRecord)
                {
                    throw PSTraceSource.NewArgumentNullException("errorRecord");
                }

                if (null != errorRecord.ErrorDetails
                    && null != errorRecord.ErrorDetails.TextLookupError)
                {
                    Exception textLookupError = errorRecord.ErrorDetails.TextLookupError;
                    errorRecord.ErrorDetails.TextLookupError = null;
                    MshLog.LogProviderHealthEvent(
                        this.Context.ExecutionContext,
                        ProviderInfo.Name,
                        textLookupError,
                        Severity.Warning);
                }

                // We can't play the same game as Cmdlet.ThrowTerminatingError
                //  and save the exception in the "pipeline".  We need to pass
                //  the actual exception as a thrown exception.  So, we wrap
                //  it in ProviderInvocationException.

                ProviderInvocationException providerInvocationException =
                    new ProviderInvocationException(ProviderInfo, errorRecord);

                // Log a provider health event

                MshLog.LogProviderHealthEvent(
                    this.Context.ExecutionContext,
                    ProviderInfo.Name,
                    providerInvocationException,
                    Severity.Warning);

                throw providerInvocationException;
            }
        }
Пример #40
0
        /// <summary>
        /// </summary>
        protected override void BeginProcessing()
        {
            // ValidateNotNullOrEmpty attribute is not working for System.Uri datatype, so handling it here
            if ((_cssuriSpecified) && (string.IsNullOrEmpty(_cssuri.OriginalString.Trim())))
            {
                ArgumentException ex = new ArgumentException(StringUtil.Format(UtilityCommonStrings.EmptyCSSUri, "CSSUri"));
                ErrorRecord       er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidArgument, "CSSUri");
                ThrowTerminatingError(er);
            }

            _propertyMshParameterList = ProcessParameter(_property);

            if (!string.IsNullOrEmpty(_title))
            {
                WebUtility.HtmlEncode(_title);
            }

            // This first line ensures w3c validation will succeed. However we are not specifying
            // an encoding in the HTML because we don't know where the text will be written and
            // if a particular encoding will be used.

            if (!_fragment)
            {
                if (!_transitional)
                {
                    WriteObject("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"  \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
                }
                else
                {
                    WriteObject("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"  \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
                }

                WriteObject("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
                WriteObject("<head>");
                if (_charsetSpecified)
                {
                    WriteObject("<meta charset=\"" + _charset + "\">");
                }

                if (_metaSpecified)
                {
                    List <string> useditems = new List <string>();
                    foreach (string s in _meta.Keys)
                    {
                        if (!useditems.Contains(s))
                        {
                            switch (s.ToLower())
                            {
                            case "content-type":
                            case "default-style":
                            case "x-ua-compatible":
                                WriteObject("<meta http-equiv=\"" + s + "\" content=\"" + _meta[s] + "\">");
                                break;

                            case "application-name":
                            case "author":
                            case "description":
                            case "generator":
                            case "keywords":
                            case "viewport":
                                WriteObject("<meta name=\"" + s + "\" content=\"" + _meta[s] + "\">");
                                break;

                            default:
                                MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime;
                                string            Message           = StringUtil.Format(ConvertHTMLStrings.MetaPropertyNotFound, s, _meta[s]);
                                WarningRecord     record            = new WarningRecord(Message);
                                InvocationInfo    invocationInfo    = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo;

                                if (invocationInfo != null)
                                {
                                    record.SetInvocationInfo(invocationInfo);
                                }

                                mshCommandRuntime.WriteWarning(record);
                                WriteObject("<meta name=\"" + s + "\" content=\"" + _meta[s] + "\">");
                                break;
                            }

                            useditems.Add(s);
                        }
                    }
                }

                WriteObject(_head ?? new string[] { "<title>" + _title + "</title>" }, true);
                if (_cssuriSpecified)
                {
                    WriteObject("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + _cssuri + "\" />");
                }

                WriteObject("</head><body>");
                if (_body != null)
                {
                    WriteObject(_body, true);
                }
            }

            if (_preContent != null)
            {
                WriteObject(_preContent, true);
            }

            WriteObject("<table>");
            _isTHWritten = false;
        }
Пример #41
0
 public void WriteError(ErrorRecord errorRecord)
 {
     ProviderRuntime.WriteError(errorRecord);
 }
Пример #42
0
 /// <summary>
 /// constructor
 /// </summary>
 /// <param name="errorRecord">the error record that is wrapped</param>
 /// <param name="originInfo">origin information</param>
 public RemotingErrorRecord(ErrorRecord errorRecord, OriginInfo originInfo) : this(errorRecord, originInfo, null)
 {
 }
Пример #43
0
 /// <summary>
 /// BeginProcessing method.
 /// </summary>
 protected override void BeginProcessing()
 {
     try
     {
         string computer = string.Empty;
         foreach (string compName in ComputerName)
         {
             if ((compName.Equals("localhost", StringComparison.CurrentCultureIgnoreCase)) || (compName.Equals(".", StringComparison.OrdinalIgnoreCase)))
             {
                 computer = "localhost";
             }
             else
             {
                 computer = compName;
             }
             if (ParameterSetName.Equals("Default"))
             {
                 foreach (string log in LogName)
                 {
                     try
                     {
                         if (EventLog.Exists(log, compName))
                         {
                             if (!ShouldProcess(StringUtil.Format(EventlogResources.RemoveEventLogWarning, log, computer)))
                             {
                                 continue;
                             }
                             EventLog.Delete(log, compName);
                         }
                         else
                         {
                             ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.LogDoesNotExist, log, computer)), null, ErrorCategory.InvalidOperation, null);
                             WriteError(er);
                             continue;
                         }
                     }
                     catch (System.IO.IOException)
                     {
                         ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.PathDoesNotExist, null, computer)), null, ErrorCategory.InvalidOperation, null);
                         WriteError(er);
                         continue;
                     }
                 }
             }
             else
             {
                 foreach (string src in Source)
                 {
                     try
                     {
                         if (EventLog.SourceExists(src, compName))
                         {
                             if (!ShouldProcess(StringUtil.Format(EventlogResources.RemoveSourceWarning, src, computer)))
                             {
                                 continue;
                             }
                             EventLog.DeleteEventSource(src, compName);
                         }
                         else
                         {
                             ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.SourceDoesNotExist, "", computer, src)), null, ErrorCategory.InvalidOperation, null);
                             WriteError(er);
                             continue;
                         }
                     }
                     catch (System.IO.IOException)
                     {
                         ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.PathDoesNotExist, null, computer)), null, ErrorCategory.InvalidOperation, null);
                         WriteError(er);
                         continue;
                     }
                 }
             }
         }
     }
     catch (System.Security.SecurityException ex)
     {
         ErrorRecord er = new ErrorRecord(ex, "NewEventlogException", ErrorCategory.SecurityError, null);
         WriteError(er);
     }
 }//End BeginProcessing()
Пример #44
0
        /// <summary>
        /// Executes the cmdlet.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            var subscriptions = this.GetSubscriptions().ToList();

            if (subscriptions == null || subscriptions.Count == 0)
            {
                var exception = new ArgumentException("No subscriptions were found to run query. " +
                                                      "Please try to add them implicitly as param to your request (e.g. Search-AzGraph -Query '' -Subscription '11111111-1111-1111-1111-111111111111')");

                var errorRecord = new ErrorRecord(
                    exception, "400",
                    ErrorCategory.InvalidArgument, null);
                this.WriteError(errorRecord);
                return;
            }

            var first = this.MyInvocation.BoundParameters.ContainsKey("First") ? this.First : 100;
            var skip  = this.MyInvocation.BoundParameters.ContainsKey("Skip") ? this.Skip : 0;

            var           results  = new List <PSObject>();
            QueryResponse response = null;

            try
            {
                do
                {
                    var requestTop       = Math.Min(first - results.Count, RowsPerPage);
                    var requestSkip      = skip + results.Count;
                    var requestSkipToken = response?.SkipToken;
                    this.WriteVerbose($"Sent top={requestTop} skip={requestSkip} skipToken={requestSkipToken}");

                    var requestOptions = new QueryRequestOptions(
                        top: requestTop,
                        skip: requestSkip,
                        skipToken: requestSkipToken,
                        resultFormat: ResultFormat.ObjectArray);

                    var request = new QueryRequest(subscriptions, this.Query, options: requestOptions);
                    response = this.ResourceGraphClient.ResourcesWithHttpMessagesAsync(request)
                               .Result
                               .Body;
                    var requestResults = response.Data.ToPsObjects();
                    results.AddRange(requestResults);
                    this.WriteVerbose($"Received results: {requestResults.Count}");
                }while (results.Count < first && response.SkipToken != null);
            }
            catch (Exception ex)
            {
                var aggregateEx = ex as AggregateException;
                if (aggregateEx?.InnerException != null && aggregateEx.InnerExceptions.Count == 1)
                {
                    var errorResponseEx = aggregateEx.InnerException as ErrorResponseException;
                    if (errorResponseEx != null)
                    {
                        var errorRecord = new ErrorRecord(
                            errorResponseEx, errorResponseEx.Body.Error.Code,
                            ErrorCategory.CloseError, null)
                        {
                            ErrorDetails = new System.Management.Automation.ErrorDetails(
                                errorResponseEx.ToDisplayableJson())
                        };

                        this.WriteError(errorRecord);
                        return;
                    }
                }

                this.WriteExceptionError(ex);
                return;
            }

            this.WriteObject(results, true);
        }
Пример #45
0
        /// <summary>
        /// Processes records from the input pipeline.
        /// For each input file, the command retrieves its
        /// corresponding certificate.
        /// </summary>
        protected override void ProcessRecord()
        {
            //
            // this cannot happen as we have specified the Path
            // property to be a mandatory parameter
            //
            Dbg.Assert((FilePath != null) && (FilePath.Length > 0),
                       "GetCertificateCommand: Param binder did not bind path");

            X509Certificate2 cert = null;

            foreach (string p in FilePath)
            {
                List <string> paths = new List <string>();

                // Expand wildcard characters
                if (_isLiteralPath)
                {
                    paths.Add(SessionState.Path.GetUnresolvedProviderPathFromPSPath(p));
                }
                else
                {
                    try
                    {
                        foreach (PathInfo tempPath in SessionState.Path.GetResolvedPSPathFromPSPath(p))
                        {
                            paths.Add(tempPath.ProviderPath);
                        }
                    }
                    catch (ItemNotFoundException)
                    {
                        _filesNotFound.Add(p);
                    }
                }

                foreach (string resolvedPath in paths)
                {
                    string resolvedProviderPath =
                        SecurityUtils.GetFilePathOfExistingFile(this, resolvedPath);

                    if (resolvedProviderPath == null)
                    {
                        _filesNotFound.Add(p);
                    }
                    else
                    {
                        if (Password == null && !NoPromptForPassword.IsPresent)
                        {
                            try
                            {
                                cert = GetCertFromPfxFile(resolvedProviderPath, null);
                                WriteObject(cert);
                                continue;
                            }
                            catch (CryptographicException)
                            {
                                Password = SecurityUtils.PromptForSecureString(
                                    Host.UI,
                                    CertificateCommands.GetPfxCertPasswordPrompt);
                            }
                        }

                        try
                        {
                            cert = GetCertFromPfxFile(resolvedProviderPath, Password);
                        }
                        catch (CryptographicException e)
                        {
                            ErrorRecord er =
                                new ErrorRecord(e,
                                                "GetPfxCertificateUnknownCryptoError",
                                                ErrorCategory.NotSpecified,
                                                null);
                            WriteError(er);
                            continue;
                        }

                        WriteObject(cert);
                    }
                }
            }

            if (_filesNotFound.Count > 0)
            {
                if (_filesNotFound.Count == FilePath.Length)
                {
                    ErrorRecord er =
                        SecurityUtils.CreateFileNotFoundErrorRecord(
                            CertificateCommands.NoneOfTheFilesFound,
                            "GetPfxCertCommandNoneOfTheFilesFound");

                    ThrowTerminatingError(er);
                }
                else
                {
                    //
                    // we found some files but not others.
                    // Write error for each missing file
                    //
                    foreach (string f in _filesNotFound)
                    {
                        ErrorRecord er =
                            SecurityUtils.CreateFileNotFoundErrorRecord(
                                CertificateCommands.FileNotFound,
                                "GetPfxCertCommandFileNotFound",
                                f
                                );

                        WriteError(er);
                    }
                }
            }
        }
Пример #46
0
        // PrivateData format in manifest file when PrivateData value is a HashTable or not specified.
        // <#
        // # Private data to pass to the module specified in RootModule/ModuleToProcess
        // PrivateData = @{
        //
        // PSData = @{
        // # Tags of this module
        // Tags = @()
        // # LicenseUri of this module
        // LicenseUri = ''
        // # ProjectUri of this module
        // ProjectUri = ''
        // # IconUri of this module
        // IconUri = ''
        // # ReleaseNotes of this module
        // ReleaseNotes = ''
        // }# end of PSData hashtable
        //
        // # User's private data keys
        //
        // }# end of PrivateData hashtable
        // #>
        private void BuildPrivateDataInModuleManifest(StringBuilder result, StreamWriter streamWriter)
        {
            var  privateDataHashTable      = PrivateData as Hashtable;
            bool specifiedPSDataProperties = !(Tags == null && ReleaseNotes == null && ProjectUri == null && IconUri == null && LicenseUri == null);

            if (_privateData != null && privateDataHashTable == null)
            {
                if (specifiedPSDataProperties)
                {
                    var ioe = new InvalidOperationException(Modules.PrivateDataValueTypeShouldBeHashTableError);
                    var er  = new ErrorRecord(ioe, "PrivateDataValueTypeShouldBeHashTable", ErrorCategory.InvalidArgument, _privateData);
                    ThrowTerminatingError(er);
                }
                else
                {
                    WriteWarning(Modules.PrivateDataValueTypeShouldBeHashTableWarning);

                    BuildModuleManifest(result, nameof(PrivateData), Modules.PrivateData, _privateData != null,
                                        () => QuoteName((string)LanguagePrimitives.ConvertTo(_privateData, typeof(string), CultureInfo.InvariantCulture)),
                                        streamWriter);
                }
            }
            else
            {
                result.Append(ManifestComment(Modules.PrivateData, streamWriter));
                result.Append("PrivateData = @{");
                result.Append(streamWriter.NewLine);

                result.Append(streamWriter.NewLine);
                result.Append("    PSData = @{");
                result.Append(streamWriter.NewLine);
                result.Append(streamWriter.NewLine);

                _indent = "        ";

                BuildModuleManifest(result, nameof(Tags), Modules.Tags, Tags != null && Tags.Length > 0, () => QuoteNames(Tags, streamWriter), streamWriter);
                BuildModuleManifest(result, nameof(LicenseUri), Modules.LicenseUri, LicenseUri != null, () => QuoteName(LicenseUri), streamWriter);
                BuildModuleManifest(result, nameof(ProjectUri), Modules.ProjectUri, ProjectUri != null, () => QuoteName(ProjectUri), streamWriter);
                BuildModuleManifest(result, nameof(IconUri), Modules.IconUri, IconUri != null, () => QuoteName(IconUri), streamWriter);
                BuildModuleManifest(result, nameof(ReleaseNotes), Modules.ReleaseNotes, !string.IsNullOrEmpty(ReleaseNotes), () => QuoteName(ReleaseNotes), streamWriter);
                BuildModuleManifest(result, nameof(Prerelease), Modules.Prerelease, !string.IsNullOrEmpty(Prerelease), () => QuoteName(Prerelease), streamWriter);
                BuildModuleManifest(result, nameof(RequireLicenseAcceptance), Modules.RequireLicenseAcceptance, RequireLicenseAcceptance.IsPresent, () => { return(RequireLicenseAcceptance.IsPresent ? "$true" : "$false"); }, streamWriter);
                BuildModuleManifest(result, nameof(ExternalModuleDependencies), Modules.ExternalModuleDependencies, ExternalModuleDependencies != null && ExternalModuleDependencies.Length > 0, () => QuoteNames(ExternalModuleDependencies, streamWriter), streamWriter);

                result.Append("    } ");
                result.Append(ManifestComment(StringUtil.Format(Modules.EndOfManifestHashTable, "PSData"), streamWriter));
                result.Append(streamWriter.NewLine);

                _indent = "    ";
                if (privateDataHashTable != null)
                {
                    result.Append(streamWriter.NewLine);

                    foreach (DictionaryEntry entry in privateDataHashTable)
                    {
                        result.Append(ManifestFragment(entry.Key.ToString(), entry.Key.ToString(), QuoteName((string)LanguagePrimitives.ConvertTo(entry.Value, typeof(string), CultureInfo.InvariantCulture)), streamWriter));
                    }
                }

                result.Append("} ");
                result.Append(ManifestComment(StringUtil.Format(Modules.EndOfManifestHashTable, "PrivateData"), streamWriter));

                _indent = string.Empty;

                result.Append(streamWriter.NewLine);
            }
        }
Пример #47
0
        protected override void ProcessRecord()
        {
            string localMachineName = Dns.GetHostName();
            string domain = null;
            Exception exception = null;

            if (!ShouldProcess(localMachineName))
            {
                return;
            }

            try
            {
                ManagementObject computerSystemInstance = new ManagementObject("Win32_ComputerSystem.Name=\"" + localMachineName + "\"");
                if (!(bool)computerSystemInstance["PartOfDomain"])
                {
                    string errMsg = ComputerResources.TestComputerNotInDomain;
                    ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "ComputerNotInDomain",
                                                        ErrorCategory.InvalidOperation, localMachineName);
                    ThrowTerminatingError(error);
                }
                domain = (string)LanguagePrimitives.ConvertTo(computerSystemInstance["Domain"], typeof(string), CultureInfo.InvariantCulture);
            }
            catch (ManagementException ex)
            {
                exception = ex;
            }
            catch (COMException ex)
            {
                exception = ex;
            }
            catch (UnauthorizedAccessException ex)
            {
                exception = ex;
            }
            if (exception != null)
            {
                string errMsg = StringUtil.Format(ComputerResources.FailToGetDomainInformation, exception.Message);
                ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToGetDomainInformation",
                                                    ErrorCategory.OperationStopped, localMachineName);
                ThrowTerminatingError(error);
            }

            Dbg.Diagnostics.Assert(domain != null, "domain should not be null at this point");
            bool scInGoodState = false;
            string verboseMsg = null;
            if (Repair)
            {
                ResetComputerMachinePasswordCommand.
                    ResetMachineAccountPassword(domain, localMachineName, Server, Credential, this);

                scInGoodState = ResetSecureChannel(domain);
                verboseMsg = scInGoodState
                    ? StringUtil.Format(ComputerResources.RepairSecureChannelSucceed, domain)
                    : StringUtil.Format(ComputerResources.RepairSecureChannelFail, domain);
            }
            else
            {
                scInGoodState = VerifySecureChannel(domain, localMachineName);
                verboseMsg = scInGoodState
                    ? StringUtil.Format(ComputerResources.SecureChannelAlive, domain)
                    : StringUtil.Format(ComputerResources.SecureChannelBroken, domain);
            }

            WriteObject(scInGoodState);
            WriteVerbose(verboseMsg);
        }
Пример #48
0
        /// <summary>
        /// Generate the module manifest...
        /// </summary>
        protected override void EndProcessing()
        {
            // Win8: 264471 - Error message for New-ModuleManifest -ProcessorArchitecture is obsolete.
            // If an undefined value is passed for the ProcessorArchitecture parameter, the error message from parameter binder includes all the values from the enum.
            // The value 'IA64' for ProcessorArchitecture is not supported. But since we do not own the enum System.Reflection.ProcessorArchitecture, we cannot control the values in it.
            // So, we add a separate check in our code to give an error if user specifies IA64
            if (ProcessorArchitecture == ProcessorArchitecture.IA64)
            {
                string message = StringUtil.Format(Modules.InvalidProcessorArchitectureInManifest, ProcessorArchitecture);
                InvalidOperationException ioe = new InvalidOperationException(message);
                ErrorRecord er = new ErrorRecord(ioe, "Modules_InvalidProcessorArchitectureInManifest",
                                                 ErrorCategory.InvalidArgument, ProcessorArchitecture);
                ThrowTerminatingError(er);
            }

            ProviderInfo provider = null;
            PSDriveInfo  drive;
            string       filePath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(_path, out provider, out drive);

            if (!provider.NameEquals(Context.ProviderNames.FileSystem) || !filePath.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
            {
                string message = StringUtil.Format(Modules.InvalidModuleManifestPath, _path);
                InvalidOperationException ioe = new InvalidOperationException(message);
                ErrorRecord er = new ErrorRecord(ioe, "Modules_InvalidModuleManifestPath",
                                                 ErrorCategory.InvalidArgument, _path);
                ThrowTerminatingError(er);
            }

            // By default, we want to generate a module manifest the encourages the best practice of explicitly specifying
            // the commands exported (even if it's an empty array.) Unfortunately, changing the default breaks automation
            // (however unlikely, this cmdlet isn't really meant for automation). Instead of trying to detect interactive
            // use (which is quite hard), we infer interactive use if none of RootModule/NestedModules/RequiredModules is
            // specified - because the manifest needs to be edited to actually be of use in those cases.
            //
            // If one of these parameters has been specified, default back to the old behavior by specifying
            // wildcards for exported commands that weren't specified on the command line.
            if (_rootModule != null || _nestedModules != null || _requiredModules != null)
            {
                if (_exportedFunctions == null)
                {
                    _exportedFunctions = new string[] { "*" }
                }
                ;
                if (_exportedAliases == null)
                {
                    _exportedAliases = new string[] { "*" }
                }
                ;
                if (_exportedCmdlets == null)
                {
                    _exportedCmdlets = new string[] { "*" }
                }
                ;
            }

            ValidateUriParameterValue(ProjectUri, "ProjectUri");
            ValidateUriParameterValue(LicenseUri, "LicenseUri");
            ValidateUriParameterValue(IconUri, "IconUri");
            if (_helpInfoUri != null)
            {
                ValidateUriParameterValue(new Uri(_helpInfoUri), "HelpInfoUri");
            }

            if (CompatiblePSEditions != null && (CompatiblePSEditions.Distinct(StringComparer.OrdinalIgnoreCase).Count() != CompatiblePSEditions.Count()))
            {
                string message = StringUtil.Format(Modules.DuplicateEntriesInCompatiblePSEditions, string.Join(",", CompatiblePSEditions));
                var    ioe     = new InvalidOperationException(message);
                var    er      = new ErrorRecord(ioe, "Modules_DuplicateEntriesInCompatiblePSEditions", ErrorCategory.InvalidArgument, CompatiblePSEditions);
                ThrowTerminatingError(er);
            }

            string action = StringUtil.Format(Modules.CreatingModuleManifestFile, filePath);

            if (ShouldProcess(filePath, action))
            {
                if (string.IsNullOrEmpty(_author))
                {
                    _author = Environment.UserName;
                }

                if (string.IsNullOrEmpty(_companyName))
                {
                    _companyName = Modules.DefaultCompanyName;
                }

                if (string.IsNullOrEmpty(_copyright))
                {
                    _copyright = StringUtil.Format(Modules.DefaultCopyrightMessage, _author);
                }

                FileStream   fileStream;
                StreamWriter streamWriter;
                FileInfo     readOnlyFileInfo;

                // Now open the output file...
                PathUtils.MasterStreamOpen(
                    cmdlet: this,
                    filePath: filePath,
                    resolvedEncoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: false),
                    defaultEncoding: false,
                    Append: false,
                    Force: false,
                    NoClobber: false,
                    fileStream: out fileStream,
                    streamWriter: out streamWriter,
                    readOnlyFileInfo: out readOnlyFileInfo,
                    isLiteralPath: false
                    );

                try
                {
                    StringBuilder result = new StringBuilder();

                    // Insert the formatted manifest header...
                    result.Append(ManifestComment(string.Empty, streamWriter));
                    result.Append(ManifestComment(StringUtil.Format(Modules.ManifestHeaderLine1, System.IO.Path.GetFileNameWithoutExtension(filePath)),
                                                  streamWriter));
                    result.Append(ManifestComment(string.Empty, streamWriter));
                    result.Append(ManifestComment(StringUtil.Format(Modules.ManifestHeaderLine2, _author),
                                                  streamWriter));
                    result.Append(ManifestComment(string.Empty, streamWriter));
                    result.Append(ManifestComment(StringUtil.Format(Modules.ManifestHeaderLine3, DateTime.Now.ToString("d", CultureInfo.CurrentCulture)),
                                                  streamWriter));
                    result.Append(ManifestComment(string.Empty, streamWriter));
                    result.Append(streamWriter.NewLine);
                    result.Append("@{");
                    result.Append(streamWriter.NewLine);
                    result.Append(streamWriter.NewLine);

                    if (_rootModule == null)
                    {
                        _rootModule = string.Empty;
                    }

                    BuildModuleManifest(result, nameof(RootModule), Modules.RootModule, !string.IsNullOrEmpty(_rootModule), () => QuoteName(_rootModule), streamWriter);

                    BuildModuleManifest(result, nameof(ModuleVersion), Modules.ModuleVersion, _moduleVersion != null && !string.IsNullOrEmpty(_moduleVersion.ToString()), () => QuoteName(_moduleVersion), streamWriter);

                    BuildModuleManifest(result, nameof(CompatiblePSEditions), Modules.CompatiblePSEditions, _compatiblePSEditions != null && _compatiblePSEditions.Length > 0, () => QuoteNames(_compatiblePSEditions, streamWriter), streamWriter);

                    BuildModuleManifest(result, nameof(Modules.GUID), Modules.GUID, !string.IsNullOrEmpty(_guid.ToString()), () => QuoteName(_guid.ToString()), streamWriter);

                    BuildModuleManifest(result, nameof(Author), Modules.Author, !string.IsNullOrEmpty(_author), () => QuoteName(Author), streamWriter);

                    BuildModuleManifest(result, nameof(CompanyName), Modules.CompanyName, !string.IsNullOrEmpty(_companyName), () => QuoteName(_companyName), streamWriter);

                    BuildModuleManifest(result, nameof(Copyright), Modules.Copyright, !string.IsNullOrEmpty(_copyright), () => QuoteName(_copyright), streamWriter);

                    BuildModuleManifest(result, nameof(Description), Modules.Description, !string.IsNullOrEmpty(_description), () => QuoteName(_description), streamWriter);

                    BuildModuleManifest(result, nameof(PowerShellVersion), Modules.PowerShellVersion, _powerShellVersion != null && !string.IsNullOrEmpty(_powerShellVersion.ToString()), () => QuoteName(_powerShellVersion), streamWriter);

                    BuildModuleManifest(result, nameof(PowerShellHostName), Modules.PowerShellHostName, !string.IsNullOrEmpty(_PowerShellHostName), () => QuoteName(_PowerShellHostName), streamWriter);

                    BuildModuleManifest(result, nameof(PowerShellHostVersion), Modules.PowerShellHostVersion, _PowerShellHostVersion != null && !string.IsNullOrEmpty(_PowerShellHostVersion.ToString()), () => QuoteName(_PowerShellHostVersion), streamWriter);

                    BuildModuleManifest(result, nameof(DotNetFrameworkVersion), StringUtil.Format(Modules.DotNetFrameworkVersion, Modules.PrerequisiteForDesktopEditionOnly), _DotNetFrameworkVersion != null && !string.IsNullOrEmpty(_DotNetFrameworkVersion.ToString()), () => QuoteName(_DotNetFrameworkVersion), streamWriter);

                    BuildModuleManifest(result, nameof(CLRVersion), StringUtil.Format(Modules.CLRVersion, Modules.PrerequisiteForDesktopEditionOnly), _ClrVersion != null && !string.IsNullOrEmpty(_ClrVersion.ToString()), () => QuoteName(_ClrVersion), streamWriter);

                    BuildModuleManifest(result, nameof(ProcessorArchitecture), Modules.ProcessorArchitecture, _processorArchitecture.HasValue, () => QuoteName(_processorArchitecture.ToString()), streamWriter);

                    BuildModuleManifest(result, nameof(RequiredModules), Modules.RequiredModules, _requiredModules != null && _requiredModules.Length > 0, () => QuoteModules(_requiredModules, streamWriter), streamWriter);

                    BuildModuleManifest(result, nameof(RequiredAssemblies), Modules.RequiredAssemblies, _requiredAssemblies != null, () => QuoteFiles(_requiredAssemblies, streamWriter), streamWriter);

                    BuildModuleManifest(result, nameof(ScriptsToProcess), Modules.ScriptsToProcess, _scripts != null, () => QuoteFiles(_scripts, streamWriter), streamWriter);

                    BuildModuleManifest(result, nameof(TypesToProcess), Modules.TypesToProcess, _types != null, () => QuoteFiles(_types, streamWriter), streamWriter);

                    BuildModuleManifest(result, nameof(FormatsToProcess), Modules.FormatsToProcess, _formats != null, () => QuoteFiles(_formats, streamWriter), streamWriter);

                    BuildModuleManifest(result, nameof(NestedModules), Modules.NestedModules, _nestedModules != null, () => QuoteModules(PreProcessModuleSpec(_nestedModules), streamWriter), streamWriter);

                    BuildModuleManifest(result, nameof(FunctionsToExport), Modules.FunctionsToExport, true, () => QuoteNames(_exportedFunctions, streamWriter), streamWriter);

                    BuildModuleManifest(result, nameof(CmdletsToExport), Modules.CmdletsToExport, true, () => QuoteNames(_exportedCmdlets, streamWriter), streamWriter);

                    BuildModuleManifest(result, nameof(VariablesToExport), Modules.VariablesToExport, _exportedVariables != null && _exportedVariables.Length > 0, () => QuoteNames(_exportedVariables, streamWriter), streamWriter);

                    BuildModuleManifest(result, nameof(AliasesToExport), Modules.AliasesToExport, true, () => QuoteNames(_exportedAliases, streamWriter), streamWriter);

                    BuildModuleManifest(result, nameof(DscResourcesToExport), Modules.DscResourcesToExport, _dscResourcesToExport != null && _dscResourcesToExport.Length > 0, () => QuoteNames(_dscResourcesToExport, streamWriter), streamWriter);

                    BuildModuleManifest(result, nameof(ModuleList), Modules.ModuleList, _moduleList != null, () => QuoteModules(_moduleList, streamWriter), streamWriter);

                    BuildModuleManifest(result, nameof(FileList), Modules.FileList, _miscFiles != null, () => QuoteFiles(_miscFiles, streamWriter), streamWriter);

                    BuildPrivateDataInModuleManifest(result, streamWriter);

                    BuildModuleManifest(result, nameof(Modules.HelpInfoURI), Modules.HelpInfoURI, !string.IsNullOrEmpty(_helpInfoUri), () => QuoteName((_helpInfoUri != null) ? new Uri(_helpInfoUri) : null), streamWriter);

                    BuildModuleManifest(result, nameof(DefaultCommandPrefix), Modules.DefaultCommandPrefix, !string.IsNullOrEmpty(_defaultCommandPrefix), () => QuoteName(_defaultCommandPrefix), streamWriter);

                    result.Append("}");
                    result.Append(streamWriter.NewLine);
                    result.Append(streamWriter.NewLine);
                    string strResult = result.ToString();

                    if (_passThru)
                    {
                        WriteObject(strResult);
                    }

                    streamWriter.Write(strResult);
                }
                finally
                {
                    streamWriter.Dispose();
                }
            }
        }
Пример #49
0
        internal static void ResetMachineAccountPassword(string domain, string localMachineName, string server, PSCredential credential, PSCmdlet cmdlet)
        {
            // Get domain directory entry and reset the password on the machine account of the local machine
            string newPassword = null;
            string domainOrServerName = server ?? domain;

            try
            {
                string dUserName = credential != null ? credential.UserName : null;
                string dPassword = credential != null ? Utils.GetStringFromSecureString(credential.Password) : null;

                using (var domainEntry = new DirectoryEntry(
                       "LDAP://" + domainOrServerName,
                       dUserName,
                       dPassword,
                       AuthenticationTypes.Secure))
                {
                    using (var searcher = new DirectorySearcher(domainEntry))
                    {
                        searcher.Filter = "(&(objectClass=computer)(|(cn=" + localMachineName + ")(dn=" + localMachineName + ")))";
                        SearchResult result = searcher.FindOne();

                        if (result == null)
                        {
                            string format = server != null
                                                ? ComputerResources.CannotFindMachineAccountFromServer
                                                : ComputerResources.CannotFindMachineAccountFromDomain;
                            string errMsg = StringUtil.Format(format, domainOrServerName);
                            ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "CannotFindMachineAccount",
                                                                ErrorCategory.OperationStopped, localMachineName);
                            cmdlet.ThrowTerminatingError(error);
                        }
                        else
                        {
                            // Generate a random password of length 120, and reset the password on the machine account
                            using (var targetEntry = result.GetDirectoryEntry())
                            {
                                newPassword = ComputerWMIHelper.GetRandomPassword(PasswordLength);
                                targetEntry.Invoke("SetPassword", new object[] { newPassword });
                                targetEntry.Properties["LockOutTime"].Value = 0;
                            }
                        }
                    }
                }
            }
            catch (DirectoryServicesCOMException ex)
            {
                string errMsg = StringUtil.Format(ComputerResources.FailToResetPasswordOnDomain, ex.Message);
                ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToResetPasswordOnDomain",
                                                    ErrorCategory.OperationStopped, localMachineName);
                cmdlet.ThrowTerminatingError(error);
            }
            catch (TargetInvocationException ex)
            {
                string errMsg = StringUtil.Format(ComputerResources.FailToResetPasswordOnDomain, ex.InnerException.Message);
                ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToResetPasswordOnDomain",
                                                    ErrorCategory.OperationStopped, localMachineName);
                cmdlet.ThrowTerminatingError(error);
            }
            catch (COMException ex)
            {
                string errMsg = StringUtil.Format(ComputerResources.FailToResetPasswordOnDomain, ex.Message);
                ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToResetPasswordOnDomain",
                                                    ErrorCategory.OperationStopped, localMachineName);
                cmdlet.ThrowTerminatingError(error);
            }

            // Set the same password to the local machine
            Dbg.Diagnostics.Assert(newPassword != null, "the newPassword should not be null at this point");

            // A direct translation of function NetpManageMachineSecret2 in //depot/winmain/ds/netapi/netjoin/joinutl.c
            // Initialize the LSA_OBJECT_ATTRIBUTES
            var lsaAttr = new SAMAPI.LSA_OBJECT_ATTRIBUTES();
            lsaAttr.RootDirectory = IntPtr.Zero;
            lsaAttr.ObjectName = IntPtr.Zero;
            lsaAttr.Attributes = 0;
            lsaAttr.SecurityDescriptor = IntPtr.Zero;
            lsaAttr.SecurityQualityOfService = IntPtr.Zero;
            lsaAttr.Length = Marshal.SizeOf(typeof(SAMAPI.LSA_OBJECT_ATTRIBUTES));

            // Initialize the policy handle and secret handle
            IntPtr policyHandle = IntPtr.Zero;
            IntPtr secretHandle = IntPtr.Zero;

            // Initialize variables for LsaQuerySecret call
            IntPtr currentPassword = IntPtr.Zero;

            // Declare the key, newData and currentData
            var key = new SAMAPI.LSA_UNICODE_STRING { Buffer = IntPtr.Zero };
            var newData = new SAMAPI.LSA_UNICODE_STRING { Buffer = IntPtr.Zero };

            // Initialize the systemName for the localhost
            var localhost = new SAMAPI.LSA_UNICODE_STRING();
            localhost.Buffer = IntPtr.Zero;
            localhost.Length = 0;
            localhost.MaximumLength = 0;

            try
            {
                // Open the LSA policy
                uint ret = SAMAPI.LsaOpenPolicy(ref localhost, ref lsaAttr, (int)SAMAPI.LSA_ACCESS.AllAccess, out policyHandle);
                if (ret == STATUS_ACCESS_DENIED)
                {
                    string errMsg = ComputerResources.NeedAdminPrivilegeToResetPassword;
                    ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "UnauthorizedAccessException",
                                                        ErrorCategory.InvalidOperation, localMachineName);
                    cmdlet.ThrowTerminatingError(error);
                }
                if (ret != 0)
                {
                    ThrowOutLsaError(ret, cmdlet);
                }

                // Initialize secret key, new secret
                SAMAPI.InitLsaString(SecretKey, ref key);
                SAMAPI.InitLsaString(newPassword, ref newData);
                bool secretCreated = false;

                // Open the secret. If the secret is not found, create the secret
                ret = SAMAPI.LsaOpenSecret(policyHandle, ref key, SECRET_SET_VALUE | SECRET_QUERY_VALUE, out secretHandle);
                if (ret == STATUS_OBJECT_NAME_NOT_FOUND)
                {
                    ret = SAMAPI.LsaCreateSecret(policyHandle, ref key, SECRET_SET_VALUE, out secretHandle);
                    secretCreated = true;
                }
                if (ret != 0)
                {
                    ThrowOutLsaError(ret, cmdlet);
                }

                SAMAPI.LSA_UNICODE_STRING currentData;
                // Get the current password
                if (secretCreated)
                {
                    // Use the new password as the current one
                    currentData = newData;
                }
                else
                {
                    // Query for the current password
                    ret = SAMAPI.LsaQuerySecret(secretHandle, out currentPassword, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
                    if (ret != 0)
                    {
                        ThrowOutLsaError(ret, cmdlet);
                    }

                    currentData = (SAMAPI.LSA_UNICODE_STRING)Marshal.PtrToStructure(currentPassword, typeof(SAMAPI.LSA_UNICODE_STRING));
                }

                ret = SAMAPI.LsaSetSecret(secretHandle, ref newData, ref currentData);
                if (ret != 0)
                {
                    ThrowOutLsaError(ret, cmdlet);
                }
            }
            finally
            {
                // Release pointers
                if (currentPassword != IntPtr.Zero)
                {
                    int releaseResult = SAMAPI.LsaFreeMemory(currentPassword);
                    Dbg.Diagnostics.Assert(releaseResult == 0, "LsaFreeMemory returned non-zero value");
                }

                // Release handles
                if (policyHandle != IntPtr.Zero)
                {
                    int releaseResult = SAMAPI.LsaClose(policyHandle);
                    Dbg.Diagnostics.Assert(releaseResult == 0, "LsaClose returned non-zero value");
                }

                if (secretHandle != IntPtr.Zero)
                {
                    int releaseResult = SAMAPI.LsaClose(secretHandle);
                    Dbg.Diagnostics.Assert(releaseResult == 0, "LsaClose returned non-zero value");
                }

                // Release LSA_UNICODE_STRING
                SAMAPI.FreeLsaString(ref key);
                SAMAPI.FreeLsaString(ref newData);
            }
        }
Пример #50
0
 public static object ConvertFromJson(string input, out ErrorRecord error)
 {
     return(ConvertFromJson(input, returnHashtable: false, out error));
 }
Пример #51
0
        protected override void ProcessRecord()
        {
            // Not to use Environment.MachineName to avoid the injection attack
            string localMachineName = Dns.GetHostName();
            string domainName = null;
            Exception exception = null;

            if (!ShouldProcess(localMachineName))
            {
                return;
            }

            try
            {
                ManagementObject computerSystemInstance = new ManagementObject("Win32_ComputerSystem.Name=\"" + localMachineName + "\"");
                if (!(bool)computerSystemInstance["PartOfDomain"])
                {
                    string errMsg = ComputerResources.ResetComputerNotInDomain;
                    ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "ComputerNotInDomain",
                                                        ErrorCategory.InvalidOperation, localMachineName);
                    ThrowTerminatingError(error);
                }
                domainName = (string)LanguagePrimitives.ConvertTo(computerSystemInstance["Domain"], typeof(string), CultureInfo.InvariantCulture);
            }
            catch (ManagementException ex)
            {
                exception = ex;
            }
            catch (COMException ex)
            {
                exception = ex;
            }
            catch (UnauthorizedAccessException ex)
            {
                exception = ex;
            }
            if (exception != null)
            {
                string errMsg = StringUtil.Format(ComputerResources.FailToGetDomainInformation, exception.Message);
                ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToGetDomainInformation",
                                                    ErrorCategory.OperationStopped, localMachineName);
                ThrowTerminatingError(error);
            }

            // Get domain directory entry and reset the password on the machine account of the local machine
            Dbg.Diagnostics.Assert(domainName != null, "domainOrServerName should not be null at this point");
            ResetMachineAccountPassword(domainName, localMachineName, Server, Credential, this);
        }
Пример #52
0
 public static object ConvertFromJson(string input, bool returnHashtable, out ErrorRecord error)
 {
     return(ConvertFromJson(input, returnHashtable, maxDepth: 1024, out error));
 }
Пример #53
0
 /// <summary>
 /// System Restore APIs are not supported on the ARM platform. Skip the system restore operation is necessary.
 /// </summary>
 /// <param name="cmdlet"></param>
 /// <returns></returns>
 internal static bool SkipSystemRestoreOperationForARMPlatform(PSCmdlet cmdlet)
 {
     bool retValue = false;
     if (PsUtils.IsRunningOnProcessorArchitectureARM())
     {
         var ex = new InvalidOperationException(ComputerResources.SystemRestoreNotSupported);
         var er = new ErrorRecord(ex, "SystemRestoreNotSupported", ErrorCategory.InvalidOperation, null);
         cmdlet.WriteError(er);
         retValue = true;
     }
     return retValue;
 }
Пример #54
0
        public static object ConvertFromJson(string input, bool returnHashtable, int?maxDepth, out ErrorRecord error)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }

            error = null;
            try
            {
                // JsonConvert.DeserializeObject does not throw an exception when an invalid Json array is passed.
                // This issue is being tracked by https://github.com/JamesNK/Newtonsoft.Json/issues/1930.
                // To work around this, we need to identify when input is a Json array, and then try to parse it via JArray.Parse().

                // If input starts with '[' (ignoring white spaces).
                if (Regex.Match(input, @"^\s*\[").Success)
                {
                    // JArray.Parse() will throw a JsonException if the array is invalid.
                    // This will be caught by the catch block below, and then throw an
                    // ArgumentException - this is done to have same behavior as the JavaScriptSerializer.
                    JArray.Parse(input);

                    // Please note that if the Json array is valid, we don't do anything,
                    // we just continue the deserialization.
                }

                var obj = JsonConvert.DeserializeObject(
                    input,
                    new JsonSerializerSettings
                {
                    // This TypeNameHandling setting is required to be secure.
                    TypeNameHandling         = TypeNameHandling.None,
                    MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
                    MaxDepth = maxDepth
                });

                switch (obj)
                {
                case JObject dictionary:
                    // JObject is a IDictionary
                    return(returnHashtable
                                   ? PopulateHashTableFromJDictionary(dictionary, out error)
                                   : PopulateFromJDictionary(dictionary, new DuplicateMemberHashSet(dictionary.Count), out error));

                case JArray list:
                    return(returnHashtable
                                   ? PopulateHashTableFromJArray(list, out error)
                                   : PopulateFromJArray(list, out error));

                default:
                    return(obj);
                }
            }
            catch (JsonException je)
            {
                var msg = string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.JsonDeserializationFailed, je.Message);

                // the same as JavaScriptSerializer does
                throw new ArgumentException(msg, je);
            }
        }
Пример #55
0
        /// <summary>
        /// Returns valid computer name or null on failure.
        /// </summary>
        /// <param name="nameToCheck">Computer name to validate</param>
        /// <param name="shortLocalMachineName"></param>
        /// <param name="fullLocalMachineName"></param>
        /// <param name="error"></param>
        /// <returns>Valid computer name</returns>
        internal static string ValidateComputerName(
            string nameToCheck,
            string shortLocalMachineName,
            string fullLocalMachineName,
            ref ErrorRecord error)
        {
            string validatedComputerName = null;

            if (nameToCheck.Equals(".", StringComparison.OrdinalIgnoreCase) ||
                nameToCheck.Equals(localhostStr, StringComparison.OrdinalIgnoreCase) ||
                nameToCheck.Equals(shortLocalMachineName, StringComparison.OrdinalIgnoreCase) ||
                nameToCheck.Equals(fullLocalMachineName, StringComparison.OrdinalIgnoreCase))
            {
                validatedComputerName = localhostStr;
            }
            else
            {
                bool isIPAddress = false;
                try
                {
                    IPAddress unused;
                    isIPAddress = IPAddress.TryParse(nameToCheck, out unused);
                }
                catch (Exception e)
                {
                    CommandProcessorBase.CheckForSevereException(e);
                }

                try
                {
                    string fqcn = Dns.GetHostEntryAsync(nameToCheck).Result.HostName;
                    if (fqcn.Equals(shortLocalMachineName, StringComparison.OrdinalIgnoreCase) ||
                        fqcn.Equals(fullLocalMachineName, StringComparison.OrdinalIgnoreCase))
                    {
                        // The IPv4 or IPv6 of the local machine is specified
                        validatedComputerName = localhostStr;
                    }
                    else
                    {
                        validatedComputerName = nameToCheck;
                    }
                }
                catch (Exception e)
                {
                    CommandProcessorBase.CheckForSevereException(e);

                    // If GetHostEntry() throw exception, then the target should not be the local machine
                    if (!isIPAddress)
                    {
                        // Return error if the computer name is not an IP address. Dns.GetHostEntry() may not work on IP addresses.
                        string errMsg = StringUtil.Format(ComputerResources.CannotResolveComputerName, nameToCheck, e.Message);
                        error = new ErrorRecord(
                            new InvalidOperationException(errMsg), "AddressResolutionException",
                            ErrorCategory.InvalidArgument, nameToCheck);

                        return null;
                    }
                    validatedComputerName = nameToCheck;
                }
            }

            return validatedComputerName;
        }
Пример #56
0
        // This function is a clone of PopulateFromDictionary using JObject as an input.
        private static PSObject PopulateFromJDictionary(JObject entries, DuplicateMemberHashSet memberHashTracker, out ErrorRecord error)
        {
            error = null;
            var result = new PSObject(entries.Count);

            foreach (var entry in entries)
            {
                if (string.IsNullOrEmpty(entry.Key))
                {
                    var errorMsg = string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.EmptyKeyInJsonString);
                    error = new ErrorRecord(
                        new InvalidOperationException(errorMsg),
                        "EmptyKeyInJsonString",
                        ErrorCategory.InvalidOperation,
                        null);
                    return(null);
                }

                // Case sensitive duplicates should normally not occur since JsonConvert.DeserializeObject
                // does not throw when encountering duplicates and just uses the last entry.
                if (memberHashTracker.TryGetValue(entry.Key, out var maybePropertyName) &&
                    string.Equals(entry.Key, maybePropertyName, StringComparison.Ordinal))
                {
                    var errorMsg = string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.DuplicateKeysInJsonString, entry.Key);
                    error = new ErrorRecord(
                        new InvalidOperationException(errorMsg),
                        "DuplicateKeysInJsonString",
                        ErrorCategory.InvalidOperation,
                        null);
                    return(null);
                }

                // Compare case insensitive to tell the user to use the -AsHashTable option instead.
                // This is because PSObject cannot have keys with different casing.
                if (memberHashTracker.TryGetValue(entry.Key, out var propertyName))
                {
                    var errorMsg = string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.KeysWithDifferentCasingInJsonString, propertyName, entry.Key);
                    error = new ErrorRecord(
                        new InvalidOperationException(errorMsg),
                        "KeysWithDifferentCasingInJsonString",
                        ErrorCategory.InvalidOperation,
                        null);
                    return(null);
                }

                // Array
                switch (entry.Value)
                {
                case JArray list:
                {
                    var listResult = PopulateFromJArray(list, out error);
                    if (error != null)
                    {
                        return(null);
                    }

                    result.Properties.Add(new PSNoteProperty(entry.Key, listResult));
                    break;
                }

                case JObject dic:
                {
                    // Dictionary
                    var dicResult = PopulateFromJDictionary(dic, new DuplicateMemberHashSet(dic.Count), out error);
                    if (error != null)
                    {
                        return(null);
                    }

                    result.Properties.Add(new PSNoteProperty(entry.Key, dicResult));
                    break;
                }

                case JValue value:
                {
                    result.Properties.Add(new PSNoteProperty(entry.Key, value.Value));
                    break;
                }
                }

                memberHashTracker.Add(entry.Key);
            }

            return(result);
        }
Пример #57
0
 private Management.ErrorRecord Parse(ErrorRecord record)
 {
     return new Management.ErrorRecord()
     {
         ID = record.ID,
         CreateTime = record.CreateTime,
         Reason = record.Reason,
         Process = this.Parse(record.Process)
     };
 }
Пример #58
0
        /// <summary>
        /// Execute void.
        /// </summary>
        internal void ExecuteVoid(Action<ErrorRecord> writeErrorAction)
        {
            try
            {
                _remoteHostCall.ExecuteVoidMethod(_clientHost);
            }
            catch (Exception exception)
            {
                // Catch-all OK, 3rd party callout.
                CommandProcessorBase.CheckForSevereException(exception);

                // Extract inner exception.
                if (exception.InnerException != null)
                {
                    exception = exception.InnerException;
                }

                // Create an error record and write it to the stream.
                ErrorRecord errorRecord = new ErrorRecord(
                    exception,
                    PSRemotingErrorId.RemoteHostCallFailed.ToString(),
                    ErrorCategory.InvalidArgument,
                    _remoteHostCall.MethodName);
                writeErrorAction(errorRecord);
            }
        }
Пример #59
0
 public void WriteError(ErrorRecord errorRecord)
 {
     throw new NotImplementedException();
 }
Пример #60
0
        /// <summary>
        /// Executes the cmdlet.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            var managementGroups = this.ManagementGroup?.ToList();

            if (managementGroups != null && managementGroups.Count > ManagementGroupLimit)
            {
                managementGroups = managementGroups.Take(ManagementGroupLimit).ToList();
                this.WriteWarning("The query included more management groups than allowed. " +
                                  $"Only the first {ManagementGroupLimit} management groups were included for the results. " +
                                  $"To use more than {ManagementGroupLimit} management groups, see the docs for examples: https://aka.ms/arg-error-toomanysubs");
            }

            IList <string> subscriptions = null;

            if (managementGroups == null)
            {
                subscriptions = this.GetSubscriptions()?.ToList();
                if (subscriptions != null && subscriptions.Count > SubscriptionLimit)
                {
                    subscriptions = subscriptions.Take(SubscriptionLimit).ToList();
                    this.WriteWarning("The query included more subscriptions than allowed. " +
                                      $"Only the first {SubscriptionLimit} subscriptions were included for the results. " +
                                      $"To use more than {SubscriptionLimit} subscriptions, see the docs for examples: https://aka.ms/arg-error-toomanysubs");
                }
            }

            var           psResourceGraphResponse = new PSResourceGraphResponse <PSObject>();
            QueryResponse response = null;

            var resultTruncated = false;

            try
            {
                var skipToken         = this.SkipToken;
                var isSkipTokenPassed = this.MyInvocation.BoundParameters.ContainsKey("SkipToken");

                int?first = null;
                if (this.MyInvocation.BoundParameters.ContainsKey("First"))
                {
                    first = Math.Min(First, MaxRowsPerPage);
                }
                else if (!isSkipTokenPassed)
                {
                    first = 100;
                }

                int?skip = null;
                if (this.MyInvocation.BoundParameters.ContainsKey("Skip"))
                {
                    skip = this.Skip;
                }
                else if (!isSkipTokenPassed)
                {
                    skip = 0;
                }

                var allowPartialScopes = AllowPartialScope.IsPresent;
                this.WriteVerbose($"Sent top={first} skip={skip} skipToken={skipToken}");

                var requestOptions = new QueryRequestOptions(
                    top: first,
                    skip: skip,
                    skipToken: skipToken,
                    resultFormat: ResultFormat.ObjectArray,
                    allowPartialScopes: allowPartialScopes);

                var request = new QueryRequest(this.Query, subscriptions, managementGroups, options: requestOptions);
                response = this.ResourceGraphClient.ResourcesWithHttpMessagesAsync(request)
                           .Result
                           .Body;

                if (response.ResultTruncated == ResultTruncated.True)
                {
                    resultTruncated = true;
                }

                var requestResults = response.Data.ToPsObjects();
                psResourceGraphResponse.Data      = requestResults;
                psResourceGraphResponse.SkipToken = response.SkipToken;
                this.WriteVerbose($"Received results: {requestResults.Count}");

                if (resultTruncated && psResourceGraphResponse.Data.Count < first)
                {
                    this.WriteWarning("Unable to paginate the results of the query. " +
                                      "Some resources may be missing from the results. " +
                                      "To rewrite the query and enable paging, " +
                                      "see the docs for an example: https://aka.ms/arg-results-truncated");
                }
            }
            catch (Exception ex)
            {
                var aggregateEx = ex as AggregateException;
                if (aggregateEx?.InnerException != null && aggregateEx.InnerExceptions.Count == 1)
                {
                    var errorResponseEx = aggregateEx.InnerException as ErrorResponseException;
                    if (errorResponseEx != null)
                    {
                        var errorRecord = new ErrorRecord(
                            errorResponseEx, errorResponseEx.Body.Error.Code,
                            ErrorCategory.CloseError, null)
                        {
                            ErrorDetails = new System.Management.Automation.ErrorDetails(
                                errorResponseEx.ToDisplayableJson())
                        };

                        this.WriteError(errorRecord);
                        return;
                    }
                }

                this.WriteExceptionError(ex);
                return;
            }

            this.WriteObject(psResourceGraphResponse);
        }