Example #1
0
 public override PSCredential PromptForCredential(
     string caption, string message, string userName, string targetName,
     PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
 {
     return null;
     //throw new NotImplementedException();
 }
        internal static PSCredential CredUIPromptForCredentials(
            string caption, string message, string userName, string targetName,
            PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options,
            IntPtr parentHwnd = default(IntPtr))
        {
            PSCredential credential = null;

            var info = new CreduiInfo
            {
                pszCaptionText = caption,
                pszMessageText = message
            };

            var pszUserName = new StringBuilder(userName, 0x201);
            var pszPassword = new StringBuilder(0x100);
            int pfSave      = Convert.ToInt32(false);

            info.cbSize     = Marshal.SizeOf(info);
            info.hwndParent = parentHwnd;

            var dwFlags = CreduiFlags.DO_NOT_PERSIST;

            if ((allowedCredentialTypes & PSCredentialTypes.Domain) != PSCredentialTypes.Domain)
            {
                dwFlags |= CreduiFlags.GENERIC_CREDENTIALS;
                if ((options & PSCredentialUIOptions.AlwaysPrompt) == PSCredentialUIOptions.AlwaysPrompt)
                {
                    dwFlags |= CreduiFlags.ALWAYS_SHOW_UI;
                }
            }

            var codes = CredUiReturnCodes.ERROR_INVALID_PARAMETER;

            if ((pszUserName.Length <= 0x201) &&
                (pszPassword.Length <= 0x100))
            {
                codes = CredUIPromptForCredentials(
                    ref info, targetName, IntPtr.Zero, 0, pszUserName,
                    0x201, pszPassword, 0x100, ref pfSave, dwFlags);
            }

            if (codes == CredUiReturnCodes.NO_ERROR)
            {
                string providedUserName = pszUserName.ToString();
                var    providedPassword = new SecureString();

                for (int i = 0; i < pszPassword.Length; i++)
                {
                    providedPassword.AppendChar(pszPassword[i]);
                    pszPassword[i] = '\0';
                }
                providedPassword.MakeReadOnly();

                if (!String.IsNullOrEmpty(providedUserName))
                {
                    credential = new PSCredential(providedUserName, providedPassword);
                }
            }
            return(credential);
        }
 public override PSCredential PromptForCredential(
     string caption, string message, string userName, string targetName,
     PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
 {
     return(null);
     //throw new NotImplementedException();
 }
Example #4
0
 public override PSCredential PromptForCredential(
     string caption,
     string message,
     string userName,
     string targetName,
     PSCredentialTypes allowedCredentialTypes,
     PSCredentialUIOptions options)
 {
     using (InternalHostUserInterface.tracer.TraceMethod(message, new object[0]))
     {
         if (this.externalUI == null)
         {
             this.ThrowNotInteractive();
         }
         PSCredential psCredential = (PSCredential)null;
         try
         {
             psCredential = this.externalUI.PromptForCredential(caption, message, userName, targetName, allowedCredentialTypes, options);
         }
         catch (PipelineStoppedException ex)
         {
             LocalPipeline currentlyRunningPipeline = (LocalPipeline)this.parent.Context.CurrentRunspace.GetCurrentlyRunningPipeline();
             if (currentlyRunningPipeline == null)
             {
                 throw;
             }
             else
             {
                 currentlyRunningPipeline.Stopper.Stop();
             }
         }
         InternalHostUserInterface.tracer.WriteLine((object)psCredential);
         return(psCredential);
     }
 }
Example #5
0
 public abstract PSCredential PromptForCredential(
     string caption,
     string message,
     string userName,
     string targetName,
     PSCredentialTypes allowedCredentialTypes,
     PSCredentialUIOptions options);
        PromptForCredential
        (
            string caption,
            string message,
            string userName,
            string targetName,
            PSCredentialTypes allowedCredentialTypes,
            PSCredentialUIOptions options
        )
        {
            if (_externalUI == null)
            {
                ThrowPromptNotInteractive(message);
            }

            PSCredential result = null;
            try
            {
                result = _externalUI.PromptForCredential(caption, message, userName, targetName, allowedCredentialTypes, options);
            }
            catch (PipelineStoppedException)
            {
                //PipelineStoppedException is thrown by host when it wants 
                //to stop the pipeline. 
                LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline();
                if (lpl == null)
                {
                    throw;
                }
                lpl.Stopper.Stop();
            }

            return result;
        }
        PromptForCredential
        (
            string caption,
            string message,
            string userName,
            string targetName,
            PSCredentialTypes allowedCredentialTypes,
            PSCredentialUIOptions options
        )
        {
            if (_externalUI == null)
            {
                ThrowPromptNotInteractive(message);
            }

            PSCredential result = null;

            try
            {
                result = _externalUI.PromptForCredential(caption, message, userName, targetName, allowedCredentialTypes, options);
            }
            catch (PipelineStoppedException)
            {
                //PipelineStoppedException is thrown by host when it wants
                //to stop the pipeline.
                LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline();
                if (lpl == null)
                {
                    throw;
                }
                lpl.Stopper.Stop();
            }

            return(result);
        }
Example #8
0
        public override PSCredential PromptForCredential(string caption, string message, string userName,
                                                         string targetName, PSCredentialTypes allowedCredentialTypes,
                                                         PSCredentialUIOptions options)
        {
            try
            {
                if (_settings.PromptForCredentialsInConsole)
                {
                    return(PromptForCredentialFromConsole(caption, message, userName, targetName, allowedCredentialTypes,
                                                          options));
                }
            }
            catch
            {
            }

            IntPtr handle = _control.GetSafeWindowHandle();

            return(NativeUtils.CredUIPromptForCredential(
                       caption,
                       message,
                       userName,
                       targetName,
                       allowedCredentialTypes,
                       options,
                       handle));
        }
Example #9
0
        internal static PSCredential CredUIPromptForCredential(string caption, string message, string userName,
                                                               string targetName,
                                                               PSCredentialTypes allowedCredentialTypes,
                                                               PSCredentialUIOptions options, IntPtr parentHWND)
        {
            PSCredential credential = null;

            CreduiInfo structure = new CreduiInfo();
            structure.pszCaptionText = caption;
            structure.pszMessageText = message;
            StringBuilder pszUserName = new StringBuilder(userName, 0x201);
            StringBuilder pszPassword = new StringBuilder(0x100);
            bool flag = false;
            int pfSave = Convert.ToInt32(flag);
            structure.cbSize = Marshal.SizeOf(structure);
            structure.hwndParent = parentHWND;
            CreduiFlags dwFlags = CreduiFlags.DO_NOT_PERSIST;
            if ((allowedCredentialTypes & PSCredentialTypes.Domain) != PSCredentialTypes.Domain)
            {
                dwFlags |= CreduiFlags.GENERIC_CREDENTIALS;
                if ((options & PSCredentialUIOptions.AlwaysPrompt) == PSCredentialUIOptions.AlwaysPrompt)
                {
                    dwFlags |= CreduiFlags.ALWAYS_SHOW_UI;
                }
            }
            CredUiReturnCodes codes = CredUiReturnCodes.ERROR_INVALID_PARAMETER;
            if ((pszUserName.Length <= 0x201) && (pszPassword.Length <= 0x100))
            {
                codes = CredUIPromptForCredentials(ref structure, targetName, IntPtr.Zero, 0, pszUserName, 0x201,
                                                   pszPassword, 0x100, ref pfSave, dwFlags);
            }
            if (codes == CredUiReturnCodes.NO_ERROR)
            {
                string str = null;
                if (pszUserName != null)
                {
                    str = pszUserName.ToString();
                }
                SecureString password = new SecureString();
                for (int i = 0; i < pszPassword.Length; i++)
                {
                    password.AppendChar(pszPassword[i]);
                    pszPassword[i] = '\0';
                }
                if (!string.IsNullOrEmpty(str))
                {
                    credential = new PSCredential(str, password);
                }
                else
                {
                    credential = null;
                }
            }
            else
            {
                credential = null;
            }
            return credential;
        }
Example #10
0
        internal static PSCredential CredUIPromptForCredentials(
            string caption, string message, string userName, string targetName,
            PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options,
            IntPtr parentHwnd = default(IntPtr))
        {

            PSCredential credential = null;

            var info = new CreduiInfo
            {
                pszCaptionText = caption,
                pszMessageText = message
            };

            var pszUserName = new StringBuilder(userName, 0x201);
            var pszPassword = new StringBuilder(0x100);
            int pfSave = Convert.ToInt32(false);
            info.cbSize = Marshal.SizeOf(info);
            info.hwndParent = parentHwnd;

            var dwFlags = CreduiFlags.DO_NOT_PERSIST;
            if ((allowedCredentialTypes & PSCredentialTypes.Domain) != PSCredentialTypes.Domain)
            {
                dwFlags |= CreduiFlags.GENERIC_CREDENTIALS;
                if ((options & PSCredentialUIOptions.AlwaysPrompt) == PSCredentialUIOptions.AlwaysPrompt)
                {
                    dwFlags |= CreduiFlags.ALWAYS_SHOW_UI;
                }
            }

            var codes = CredUiReturnCodes.ERROR_INVALID_PARAMETER;

            if ((pszUserName.Length <= 0x201) && (pszPassword.Length <= 0x100))
            {
                codes = CredUIPromptForCredentials(
                    ref info, targetName, IntPtr.Zero, 0, pszUserName,
                    0x201, pszPassword, 0x100, ref pfSave, dwFlags);
            }

            if (codes == CredUiReturnCodes.NO_ERROR)
            {

                string providedUserName = pszUserName.ToString();
                var providedPassword = new SecureString();

                for (int i = 0; i < pszPassword.Length; i++)
                {
                    providedPassword.AppendChar(pszPassword[i]);
                    pszPassword[i] = '\0';
                }
                providedPassword.MakeReadOnly();

                if (!String.IsNullOrEmpty(providedUserName))
                {
                    credential = new PSCredential(providedUserName, providedPassword);
                }
            }
            return credential;
        }
Example #11
0
 public override PSCredential PromptForCredential(
     string caption, string message, string userName,
     string targetName, PSCredentialTypes allowedCredentialTypes,
     PSCredentialUIOptions options)
 {
     throw new NotImplementedException(
               "The method PromptForCredential() is not implemented by MyHost.");
 }
Example #12
0
        public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
        {
            if (Settings.Default.UseCredentialUI)
            {
                if (string.IsNullOrEmpty(caption))
                    caption = "Windows PowerShell credential request";

                if (string.IsNullOrEmpty(message))
                    message = "Please enter your credentials";

                var pfwCredentialsOptions = new CredentialUI.PromptForWindowsCredentialsOptions(caption, message)
                {
                    HwndParent = _control.WindowHandle
                };

                if (allowedCredentialTypes == PSCredentialTypes.Domain)
                {
                    pfwCredentialsOptions.Flags ^= CredentialUI.PromptForWindowsCredentialsFlag.CREDUIWIN_GENERIC;
                }
                // If the targetName was set, we'd have a good way to tell one credential from another, and could save them ...
                // pfwCredentialsOptions.Flags |= CredentialUI.PromptForWindowsCredentialsFlag.CREDUIWIN_CHECKBOX;

                return CredentialUI.PromptForWindowsCredentials(pfwCredentialsOptions, userName, string.Empty);

                // THIS IS HOW PowerShell.exe does it ...
                // But MSDN says we're not supposed to do that anymore.

                //// Defaults to GenericCredentials
                //var credentialsOptions = new CredentialUI.PromptForCredentialsOptions(targetName, caption, message)
                //{
                //    HwndParent = _control.WindowHandle
                //};
                //if (allowedCredentialTypes.HasFlag(PSCredentialTypes.Domain))
                //{
                //    credentialsOptions.Flags ^= CredentialUI.PromptForCredentialsFlag.CREDUI_FLAGS_GENERIC_CREDENTIALS;
                //}
                //else if (options.HasFlag(PSCredentialUIOptions.AlwaysPrompt))
                //{
                //    credentialsOptions.Flags |= CredentialUI.PromptForCredentialsFlag.CREDUI_FLAGS_ALWAYS_SHOW_UI;
                //}

                //// Does this _ever_ happen?
                //if (options.HasFlag(PSCredentialUIOptions.ReadOnlyUserName))
                //     credentialsOptions.Flags |= CredentialUI.PromptForCredentialsFlag.CREDUI_FLAGS_KEEP_USERNAME;

                //// Does this ever _not_ happen?
                //if (options.HasFlag(PSCredentialUIOptions.ValidateUserNameSyntax))
                //    credentialsOptions.Flags |= CredentialUI.PromptForCredentialsFlag.CREDUI_FLAGS_VALIDATE_USERNAME;

                //return CredentialUI.PromptForCredentials(credentialsOptions, userName, String.Empty);

            }
            else
            {
                return _control.PromptForCredentialInline(caption, message, userName, targetName, allowedCredentialTypes, options);
            }
        }
 public override PSCredential PromptForCredential(
     string caption,
     string message,
     string userName,
     string targetName,
     PSCredentialTypes allowedCredentialTypes,
     PSCredentialUIOptions options)
 {
     throw new NotSupportedException(
               "'Get-Credential' is not yet supported.");
 }
 public override PSCredential PromptForCredential(
                                                  string caption,
                                                  string message,
                                                  string userName,
                                                  string targetName,
                                                  PSCredentialTypes allowedCredentialTypes,
                                                  PSCredentialUIOptions options)
 {
     Console.WriteLine("ReadLine");
     throw new NotImplementedException("PromptForCredential is not implemented.");
 }
 /// <summary>
 /// Prompts the user for credentials by using a specified prompt window
 /// caption, prompt message, user name and target name, credential types
 /// allowed to be returned, and UI behavior options.
 /// </summary>
 /// <param name="caption">The caption of the message window.</param>
 /// <param name="message">The text of the message.</param>
 /// <param name="userName">The user name whose credential is to be prompted for.</param>
 /// <param name="targetName">The name of the target for which the credential is collected.</param>
 /// <param name="allowedCredentialTypes">PSCredentialTypes cconstants that identify the type of
 /// credentials that can be returned.</param>
 /// <param name="options">A PSCredentialUIOptions constant that identifies the UI behavior
 /// when it gathers the credentials.</param>
 /// <returns>Throws a NotImplementException exception.</returns>
 public override PSCredential PromptForCredential(
     string caption,
     string message,
     string userName,
     string targetName,
     PSCredentialTypes allowedCredentialTypes,
     PSCredentialUIOptions options)
 {
     throw new NotImplementedException(
               "The method PromptForCredential() is not implemented by MyHost for usage in this application. Contact the system developers if this functionality is needed.");
 }
Example #16
0
 public override PSCredential PromptForCredential(
     string caption,
     string message,
     string userName,
     string targetName,
     PSCredentialTypes allowedCredentialTypes,
     PSCredentialUIOptions options)
 {
     Console.WriteLine("ReadLine");
     throw new NotImplementedException("PromptForCredential is not implemented.");
 }
 public override PSCredential PromptForCredential(
     string caption, string message, string userName, string targetName,
     PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
 {
     return(NativeMethods.CredUIPromptForCredentials(
                caption,
                message,
                userName,
                targetName,
                allowedCredentialTypes,
                options));
 }
Example #18
0
        /// <summary>
        /// Prompts the user for credentials by using a specified prompt window
        /// caption, prompt message, user name and target name, credential types
        /// allowed to be returned, and UI behavior options.
        /// </summary>
        /// <param name="caption">The caption of the message window.</param>
        /// <param name="message">The text of the message.</param>
        /// <param name="userName">The user name whose credential is to be prompted for.</param>
        /// <param name="targetName">The name of the target for which the credential is collected.</param>
        /// <param name="allowedCredentialTypes">PSCredentialTypes cconstants that identify the type of
        /// credentials that can be returned.</param>
        /// <param name="options">A PSCredentialUIOptions constant that identifies the UI behavior
        /// when it gathers the credentials.</param>
        /// <returns>Throws a NotImplementException exception.</returns>
        public override PSCredential PromptForCredential(
            string caption,
            string message,
            string userName,
            string targetName,
            PSCredentialTypes allowedCredentialTypes,
            PSCredentialUIOptions options)
        {
            PromptCredentialsResult result = CredentialUI.PromptForCredentials(targetName, caption, message, userName, null);

            return(result == null ? null : new PSCredential(result.UserName, result.Password.ToSecureString()));
        }
 /// <summary>
 /// Prompt for credentials.
 /// </summary>
 /// <param name="caption">Caption for the message.</param>
 /// <param name="message">Message to be displayed.</param>
 /// <param name="userName">Name of the user whose credentials are to be prompted for. If set to null or empty string, the function will prompt for user name first.</param>
 /// <param name="targetName">Name of the target for which credentials are being collected.</param>
 /// <param name="allowedCredentialTypes">What type of credentials can be supplied by the user.</param>
 /// <param name="options">Options that control the credential gathering UI behavior.</param>
 /// <returns>PSCredential object, or null if input was cancelled (or if reading from stdin and stdin at EOF).</returns>
 public override PSCredential PromptForCredential(
     string caption,
     string message,
     string userName,
     string targetName,
     PSCredentialTypes allowedCredentialTypes,
     PSCredentialUIOptions options)
 {
     return(PromptForCredential(
                caption,
                message,
                userName,
                confirmPassword: false,
                targetName,
                allowedCredentialTypes,
                options));
 }
Example #20
0
        private PSCredential PromptForCredentialFromConsole(string caption, string message, string userName,
                                                            string targetName, PSCredentialTypes allowedCredentialTypes,
                                                            PSCredentialUIOptions options)
        {
            _control.WriteWarningLine(caption);
            _control.WriteLine(message);

            var baseMoniker = String.IsNullOrEmpty(targetName) ? "{1}" : "{0}\\{1}";

            var moniker = String.Format(baseMoniker, targetName, userName);
            var prompt  = "Password for user " + moniker + ": ";

            _control.WritePrompt(prompt);

            var pwd = ReadLineAsSecureString();

            return(new PSCredential(moniker, pwd));
        }
Example #21
0
 public override PSCredential PromptForCredential(
     string caption,
     string message,
     string userName,
     string targetName,
     PSCredentialTypes allowedCredentialTypes,
     PSCredentialUIOptions options)
 {
     return(this._serverMethodExecutor.ExecuteMethod <PSCredential>(RemoteHostMethodId.PromptForCredential2, new object[6]
     {
         (object)caption,
         (object)message,
         (object)userName,
         (object)targetName,
         (object)allowedCredentialTypes,
         (object)options
     }));
 }
Example #22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="promptCaption"></param>
        /// <param name="promptMessage"></param>
        /// <param name="userName"></param>
        /// <param name="targetName"></param>
        /// <param name="allowedCredentialTypes"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public override PSCredential PromptForCredential(
            string promptCaption,
            string promptMessage,
            string userName,
            string targetName,
            PSCredentialTypes allowedCredentialTypes,
            PSCredentialUIOptions options)
        {
            CancellationTokenSource cancellationToken = new CancellationTokenSource();

            Task <Dictionary <string, object> > promptTask =
                this.CreateInputPromptHandler()
                .PromptForInput(
                    promptCaption,
                    promptMessage,
                    new FieldDetails[] { new CredentialFieldDetails("Credential", "Credential", userName) },
                    cancellationToken.Token);

            Task <PSCredential> unpackTask =
                promptTask.ContinueWith(
                    task =>
            {
                if (task.IsFaulted)
                {
                    throw task.Exception;
                }
                else if (task.IsCanceled)
                {
                    throw new TaskCanceledException(task);
                }

                // Return the value of the sole field
                return((PSCredential)task.Result?["Credential"]);
            });

            // Run the prompt task and wait for it to return
            this.WaitForPromptCompletion(
                unpackTask,
                "PromptForCredential",
                cancellationToken);

            return(unpackTask.Result);
        }
        public override PSCredential PromptForCredential(
            string caption,
            string message,
            string userName,
            string targetName,
            PSCredentialTypes allowedCredentialTypes,
            PSCredentialUIOptions options)
        {
            var password = _communicationAdapter.OnPromptForPassword(message, targetName, userName);

            SecureString secureString = new SecureString();

            foreach (char c in password)
            {
                secureString.AppendChar(c);
            }

            secureString.MakeReadOnly();

            return(new PSCredential(userName, secureString));
        }
        public override PSCredential PromptForCredential(string caption,
                                                         string message,
                                                         string userName,
                                                         string targetName,
                                                         PSCredentialTypes allowedCredentialTypes,
                                                         PSCredentialUIOptions options)
        {
            if (externalUI == null)
            {
                throw new InvalidOperationException("Unable to prompt user for credential in headless session");
            }

            PSCredential result = externalUI.PromptForCredential(caption,
                                                                 message,
                                                                 userName,
                                                                 targetName,
                                                                 allowedCredentialTypes,
                                                                 options);

            SendToSubscribers(s => s.CredentialPrompt(result));

            return(result);
        }
Example #25
0
 /// <summary>
 /// When overridden in a derived class, prompts the user for credentials by using a
 /// specified prompt window caption, prompt message, user name and target name, credential
 /// types allowed to be returned, and UI behavior options.
 /// </summary>
 /// <param name="caption">The caption for the message window.</param>
 /// <param name="message">The text of the message.</param>
 /// <param name="userName">
 /// The user name whose credential is to be prompted for. If this parameter set to
 /// <c>null</c> or an empty string, the function prompts for the user name first.
 /// </param>
 /// <param name="targetName">The name of the target for which the credential is collected.</param>
 /// <param name="allowedCredentialTypes">
 /// A bitwise combination of the <see cref="PSCredentialTypes" /> enumeration values that
 /// identify the types of credentials that can be returned.
 /// </param>
 /// <param name="options">
 /// A bitwise combination of the <see cref="PSCredentialUIOptions" /> enumeration values
 /// that identify the UI behavior when it gathers the credentials.
 /// </param>
 /// <returns>
 /// A <see cref="PSCredential" /> object that contains the credentials for the target.
 /// </returns>
 public override PSCredential PromptForCredential
 (
     string caption,
     string message,
     string userName,
     string targetName,
     PSCredentialTypes allowedCredentialTypes,
     PSCredentialUIOptions options
 )
 {
     if (PromptForCredentialsCallback == null)
     {
         throw new NotImplementedException();
     }
     return(PromptForCredentialsCallback
            (
                caption,
                message,
                userName,
                targetName,
                allowedCredentialTypes,
                options
            ));
 }
 public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
 {
     return this._serverMethodExecutor.ExecuteMethod<PSCredential>(RemoteHostMethodId.PromptForCredential2, new object[] { caption, message, userName, targetName, allowedCredentialTypes, options });
 }
Example #27
0
 public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
 {
     return NativeMethods.PromptForCredential(caption, message, userName, targetName, allowedCredentialTypes, options);
 }
Example #28
0
        public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
        {
            this.Log().Warn(caption.escape_curly_braces());
            if (string.IsNullOrWhiteSpace(userName))
            {
                this.Log().Warn("Please provide username:"******"Please provide password:"******"*");
                    password += info.KeyChar;
                    info = possibleNonInteractive ? Console.ReadKey(TIMEOUT_IN_SECONDS * 1000) : Console.ReadKey(true);
                }
                else if (info.Key == ConsoleKey.Backspace)
                {
                    if (!string.IsNullOrEmpty(password))
                    {
                        password = password.Substring(0, password.Length - 1);
                        // get the location of the cursor
                        int pos = System.Console.CursorLeft;
                        // move the cursor to the left by one character
                        System.Console.SetCursorPosition(pos - 1, System.Console.CursorTop);
                        // replace it with space
                        Console.Write(" ");
                        // move the cursor to the left by one character again
                        System.Console.SetCursorPosition(pos - 1, System.Console.CursorTop);
                    }
                    info = possibleNonInteractive ? Console.ReadKey(TIMEOUT_IN_SECONDS * 1000) : Console.ReadKey(true);
                }
            }
            for (int i = 0; i < password.Length; i++) Console.Write("*");
            System.Console.WriteLine("");

            if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
            {
                this.Log().Warn(ChocolateyLoggers.Important, "A userName or password was not entered. This may result in future failures.");
            }

            return new PSCredential(userName, password.to_secure_string());
        }
Example #29
0
 /// <summary>
 /// Prompt for credential.
 /// </summary>
 public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
 {
     return(_serverMethodExecutor.ExecuteMethod <PSCredential>(RemoteHostMethodId.PromptForCredential2,
                                                               new object[] { caption, message, userName, targetName, allowedCredentialTypes, options }));
 }
Example #30
0
 public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
 {
     throw new NotImplementedException("PromptForCredential is not implemented in PowerShell script engine");
 }
Example #31
0
        public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
        {
            var fds = new Collection <FieldDescription>();
            var fd  = new FieldDescription("Credential");

            fd.SetParameterType(typeof(PSCredential));

            if (!string.IsNullOrEmpty(userName))
            {
                fd.DefaultValue = PSObject.AsPSObject(new PSCredential(userName, new SecureString()));
            }

            fds.Add(fd);

            var result = this.Prompt(caption, message, fds);

            if (result != null && result.ContainsKey("Credential"))
            {
                return(result["Credential"].BaseObject as PSCredential);
            }
            else
            {
                return(null);
            }
        }
Example #32
0
        internal static PSCredential CredUIPromptForCredential(
            string caption,
            string message,
            string userName,
            string targetName,
            PSCredentialTypes allowedCredentialTypes,
            PSCredentialUIOptions options,
            IntPtr parentHWND)
        {
            PSCredential cred = null;

            // From WinCred.h
            const int CRED_MAX_USERNAME_LENGTH = (256 + 1 + 256);
            const int CRED_MAX_CREDENTIAL_BLOB_SIZE = 512;
            const int CRED_MAX_PASSWORD_LENGTH = CRED_MAX_CREDENTIAL_BLOB_SIZE / 2;
            const int CREDUI_MAX_MESSAGE_LENGTH = 1024;
            const int CREDUI_MAX_CAPTION_LENGTH = 128;

            // Populate the UI text with defaults, if required
            if (string.IsNullOrEmpty(caption))
            {
                caption = CredUI.PromptForCredential_DefaultCaption;
            }

            if (string.IsNullOrEmpty(message))
            {
                message = CredUI.PromptForCredential_DefaultMessage;
            }

            if (caption.Length > CREDUI_MAX_CAPTION_LENGTH)
            {
                throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, CredUI.PromptForCredential_InvalidCaption, CREDUI_MAX_CAPTION_LENGTH));
            }

            if (message.Length > CREDUI_MAX_MESSAGE_LENGTH)
            {
                throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, CredUI.PromptForCredential_InvalidMessage, CREDUI_MAX_MESSAGE_LENGTH));
            }

            if (userName != null && userName.Length > CRED_MAX_USERNAME_LENGTH)
            {
                throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, CredUI.PromptForCredential_InvalidUserName, CRED_MAX_USERNAME_LENGTH));
            }

            CREDUI_INFO credUiInfo = new CREDUI_INFO();
            credUiInfo.pszCaptionText = caption;
            credUiInfo.pszMessageText = message;

            StringBuilder usernameBuilder = new StringBuilder(userName, CRED_MAX_USERNAME_LENGTH);
            StringBuilder passwordBuilder = new StringBuilder(CRED_MAX_PASSWORD_LENGTH);

            bool save = false;
            int saveCredentials = Convert.ToInt32(save);
            credUiInfo.cbSize = Marshal.SizeOf(credUiInfo);
            credUiInfo.hwndParent = parentHWND;


            CREDUI_FLAGS flags = CREDUI_FLAGS.DO_NOT_PERSIST;

            // Set some of the flags if they have not requested a domain credential
            if ((allowedCredentialTypes & PSCredentialTypes.Domain) != PSCredentialTypes.Domain)
            {
                flags |= CREDUI_FLAGS.GENERIC_CREDENTIALS;

                // If they've asked to always prompt, do so.
                if ((options & PSCredentialUIOptions.AlwaysPrompt) == PSCredentialUIOptions.AlwaysPrompt)
                    flags |= CREDUI_FLAGS.ALWAYS_SHOW_UI;
            }

            // To prevent buffer overrun attack, only attempt call if buffer lengths are within bounds.
            CredUIReturnCodes result = CredUIReturnCodes.ERROR_INVALID_PARAMETER;
            if (usernameBuilder.Length <= CRED_MAX_USERNAME_LENGTH && passwordBuilder.Length <= CRED_MAX_PASSWORD_LENGTH)
            {
                result = CredUIPromptForCredentials(
                    ref credUiInfo,
                    targetName,
                    IntPtr.Zero,
                    0,
                    usernameBuilder,
                    CRED_MAX_USERNAME_LENGTH,
                    passwordBuilder,
                    CRED_MAX_PASSWORD_LENGTH,
                    ref saveCredentials,
                    flags);
            }

            if (result == CredUIReturnCodes.NO_ERROR)
            {
                // Extract the username
                string credentialUsername = null;
                if (usernameBuilder != null)
                    credentialUsername = usernameBuilder.ToString();

                // Trim the leading '\' from the username, which CredUI automatically adds
                // if you don't specify a domain.
                // This is a really common bug in V1 and V2, causing everybody to have to do
                // it themselves.
                // This could be a breaking change for hosts that do hard-coded hacking:
                // $cred.UserName.SubString(1, $cred.Username.Length - 1)
                // But that's OK, because they would have an even worse bug when you've
                // set the host (ConsolePrompting = true) configuration (which does not do this).
                credentialUsername = credentialUsername.TrimStart('\\');

                // Extract the password into a SecureString, zeroing out the memory
                // as soon as possible.
                SecureString password = new SecureString();
                for (int counter = 0; counter < passwordBuilder.Length; counter++)
                {
                    password.AppendChar(passwordBuilder[counter]);
                    passwordBuilder[counter] = (char)0;
                }

                if (!String.IsNullOrEmpty(credentialUsername))
                    cred = new PSCredential(credentialUsername, password);
                else
                    cred = null;
            }
            else // result is not CredUIReturnCodes.NO_ERROR
            {
                cred = null;
            }

            return cred;
        }
Example #33
0
        private PSCredential PromptForCredentialFromConsole(string caption, string message, string userName,
                                                            string targetName, PSCredentialTypes allowedCredentialTypes,
                                                            PSCredentialUIOptions options)
        {
            _control.WriteWarningLine(caption);
            _control.WriteLine(message);

            var baseMoniker = String.IsNullOrEmpty(targetName) ? "{1}" : "{0}\\{1}";

            var moniker = String.Format(baseMoniker, targetName, userName);
            var prompt = "Password for user " + moniker + ": ";
            _control.WritePrompt(prompt);

            var pwd = ReadLineAsSecureString();

            return new PSCredential(moniker, pwd);
        }
 public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
 {
     throw new NotImplementedException("PromptForCredential1 is not implemented.  The script is asking for input, which is a problem since there's no console.  Make sure the script can execute without prompting the user for input.");
 }
 public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
 {
     return GetCreds(caption, message);
 }
 public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName,
                                                  PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
 {
     throw new Exception("Cannot use run commands that require user input");
 }
      PSCredential IPSConsole.PromptForCredential(string caption, string message, string userName, string targetName, 
         PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
      {

         Collection<FieldDescription> fields;
         Dictionary<string, PSObject> login, password;

         // NOTE: I'm not sure this is the right action for the PromptForCredential targetName
         if (!String.IsNullOrEmpty(targetName))
         {
            caption = string.Format("Credential for {0}\n\n{1}", targetName, caption);
         }

         if ((options & PSCredentialUIOptions.ReadOnlyUserName) == PSCredentialUIOptions.Default )
         {
            var user = new FieldDescription("User");
            user.SetParameterType(typeof(string));
            user.Label = "Username";
            user.DefaultValue = PSObject.AsPSObject(userName);
            user.IsMandatory = true;

            do
            {
               fields = new Collection<FieldDescription>(new[] {user});
               login = ((IPSConsole) this).Prompt(caption, message, fields);
               userName = login["User"].BaseObject as string;
            } while ( userName != null && userName.Length == 0);
         }

         // I think this is all I can do with the allowedCredentialTypes
         // domain required
         if (allowedCredentialTypes > PSCredentialTypes.Generic)
         {
            // and no domain
            if (userName != null && userName.IndexOfAny(new[] { '\\', '@' }) < 0)
            {
               userName = string.Format("{0}\\{1}", targetName, userName);
            }
         }

         var pass = new FieldDescription("Password");
         pass.SetParameterType(typeof(SecureString));
         pass.Label = "Password for " + userName;
         pass.IsMandatory = true;

         fields = new Collection<FieldDescription>(new[] { pass });
         password = ((IPSConsole)this).Prompt(String.Empty, String.Empty, fields);

         // TODO: I'm not sure what to do with the PSCredentialUIOptions options, because PowerShell.exe ignores them
         return new PSCredential(userName, (SecureString)password["Password"].BaseObject);
      }
 /// <summary>
 /// Prompts the user for credentials by using a specified prompt window 
 /// caption, prompt message, user name and target name, credential types 
 /// allowed to be returned, and UI behavior options.
 /// </summary>
 /// <param name="caption">The caption of the message window.</param>
 /// <param name="message">The text of the message.</param>
 /// <param name="userName">The user name whose credential is to be prompted for.</param>
 /// <param name="targetName">The name of the target for which the credential is collected.</param>
 /// <param name="allowedCredentialTypes">PSCredentialTypes cconstants that identify the type of 
 /// credentials that can be returned.</param>
 /// <param name="options">A PSCredentialUIOptions constant that identifies the UI behavior 
 /// when it gathers the credentials.</param>
 /// <returns>Throws a NotImplementException exception.</returns>
 public override PSCredential PromptForCredential(
                        string caption,
                        string message,
                        string userName,
                        string targetName,
                        PSCredentialTypes allowedCredentialTypes,
                        PSCredentialUIOptions options)
 {
     PromptCredentialsResult result = CredentialUI.PromptForCredentials(targetName, caption, message, userName, null);
     return result == null ? null : new PSCredential(result.UserName, result.Password.ToSecureString());
 }
Example #39
0
 public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName,
     PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
 {
     if (!InteractiveIO)
     {
         ThrowNotInteractiveException();
     }
     // TODO: add support for allowedCredentialTypes and options
     // TODO: what does targetName mean? is it a default password, like userName? If so, implement a default value
     //       in SecureStringReader and use it like that
     WriteLine();
     WriteLine(caption);
     WriteLine(message);
     Write("UserName: "******"Password: ");
     var pw = ReadLineAsSecureString();
     return new PSCredential(user, pw);
 }
 public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
 {
     throw new NotSupportedException();
 }
Example #41
0
        public PSCredential PromptForCredentialInline(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes = PSCredentialTypes.Generic, PSCredentialUIOptions options = PSCredentialUIOptions.None)
        {
            Collection <FieldDescription> fields;

            // NOTE: I'm not sure this is the right action for the PromptForCredential targetName
            if (!String.IsNullOrEmpty(targetName))
            {
                caption = $"Credential for {targetName}\n\n{caption}";
            }

            if ((options & PSCredentialUIOptions.ReadOnlyUserName) == PSCredentialUIOptions.Default)
            {
                var user = new FieldDescription("User");
                user.SetParameterType(typeof(string));
                user.Label        = "Username";
                user.DefaultValue = PSObject.AsPSObject(userName);
                user.IsMandatory  = true;

                do
                {
                    fields = new Collection <FieldDescription>(new[] { user });
                    var username = new PromptForObjectEventArgs(caption, message, fields);
                    var login    = OnPromptForObject(username);
                    userName = login["User"].BaseObject as string;
                } while (userName != null && userName.Length == 0);
            }

            // I think this is all I can do with the allowedCredentialTypes
            // domain required
            if (allowedCredentialTypes > PSCredentialTypes.Generic)
            {
                // and no domain
                if (userName != null && userName.IndexOfAny(new[] { '\\', '@' }) < 0)
                {
                    userName = $"{targetName}\\{userName}";
                }
            }

            var pass = new FieldDescription("Password");

            pass.SetParameterType(typeof(SecureString));
            pass.Label       = "Password for " + userName;
            pass.IsMandatory = true;

            fields = new Collection <FieldDescription>(new[] { pass });
            var pwd      = new PromptForObjectEventArgs(string.Empty, string.Empty, fields);
            var password = OnPromptForObject(pwd);

            // TODO: I'm not sure what to do with the PSCredentialUIOptions options, because PowerShell.exe ignores them
            return(new PSCredential(userName, (SecureString)password["Password"].BaseObject));
        }
Example #42
0
        /// <summary>
        /// Prompt for credentials.
        /// </summary>
        /// <param name="userName">Name of the user whose creds are to be prompted for. If set to null or empty string, the function will prompt for user name first.</param>
        /// <param name="targetName">Name of the target for which creds are being collected.</param>
        /// <param name="message">Message to be displayed.</param>
        /// <param name="caption">Caption for the message.</param>
        /// <param name="allowedCredentialTypes">What type of creds can be supplied by the user.</param>
        /// <param name="options">Options that control the cred gathering UI behavior.</param>
        /// <returns>PSCredential object, or null if input was cancelled (or if reading from stdin and stdin at EOF).</returns>
        public override PSCredential PromptForCredential(
            string caption,
            string message,
            string userName,
            string targetName,
            PSCredentialTypes allowedCredentialTypes,
            PSCredentialUIOptions options)
        {
            PSCredential cred           = null;
            SecureString password       = null;
            string       userPrompt     = null;
            string       passwordPrompt = null;

            if (!string.IsNullOrEmpty(caption))
            {
                // Should be a skin lookup

                WriteLineToConsole();
                WriteLineToConsole(PromptColor, RawUI.BackgroundColor, WrapToCurrentWindowWidth(caption));
            }

            if (!string.IsNullOrEmpty(message))
            {
                WriteLineToConsole(WrapToCurrentWindowWidth(message));
            }

            if (string.IsNullOrEmpty(userName))
            {
                userPrompt = ConsoleHostUserInterfaceSecurityResources.PromptForCredential_User;

                //
                // need to prompt for user name first
                //
                do
                {
                    WriteToConsole(userPrompt, true);
                    userName = ReadLine();
                    if (userName == null)
                    {
                        return(null);
                    }
                }while (userName.Length == 0);
            }

            passwordPrompt = StringUtil.Format(ConsoleHostUserInterfaceSecurityResources.PromptForCredential_Password, userName
                                               );

            //
            // now, prompt for the password
            //
            WriteToConsole(passwordPrompt, true);
            password = ReadLineAsSecureString();
            if (password == null)
            {
                return(null);
            }

            WriteLineToConsole();

            cred = new PSCredential(userName, password);

            return(cred);
        }
Example #43
0
        public override PSCredential PromptForCredential(string caption, string message, string userName,
                                                         string targetName, PSCredentialTypes allowedCredentialTypes,
                                                         PSCredentialUIOptions options)
        {
            try
            {
                if (_settings.PromptForCredentialsInConsole)
                {
                    return PromptForCredentialFromConsole(caption, message, userName, targetName, allowedCredentialTypes,
                                                          options);
                }
            }
            catch
            {
            }

            IntPtr handle = _control.GetSafeWindowHandle();
            return NativeUtils.CredUIPromptForCredential(
                caption,
                message,
                userName,
                targetName,
                allowedCredentialTypes,
                options,
                handle);
        }
 public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
 {
     if (this.externalUI == null)
     {
         this.ThrowPromptNotInteractive(message);
     }
     PSCredential credential = null;
     try
     {
         credential = this.externalUI.PromptForCredential(caption, message, userName, targetName, allowedCredentialTypes, options);
     }
     catch (PipelineStoppedException)
     {
         LocalPipeline currentlyRunningPipeline = (LocalPipeline) ((RunspaceBase) this.parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline();
         if (currentlyRunningPipeline == null)
         {
             throw;
         }
         currentlyRunningPipeline.Stopper.Stop();
     }
     return credential;
 }
Example #45
0
        internal static PSCredential CredUIPromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options, IntPtr parentHWND)
        {
            PSCredential credential = null;

            CreduiInfo structure = new CreduiInfo();

            structure.pszCaptionText = caption;
            structure.pszMessageText = message;
            StringBuilder pszUserName = new StringBuilder(userName, 0x201);
            StringBuilder pszPassword = new StringBuilder(0x100);
            bool          flag        = false;
            int           pfSave      = Convert.ToInt32(flag);

            structure.cbSize     = Marshal.SizeOf(structure);
            structure.hwndParent = parentHWND;
            CreduiFlags dwFlags = CreduiFlags.DO_NOT_PERSIST;

            if ((allowedCredentialTypes & PSCredentialTypes.Domain) != PSCredentialTypes.Domain)
            {
                dwFlags |= CreduiFlags.GENERIC_CREDENTIALS;
                if ((options & PSCredentialUIOptions.AlwaysPrompt) == PSCredentialUIOptions.AlwaysPrompt)
                {
                    dwFlags |= CreduiFlags.ALWAYS_SHOW_UI;
                }
            }
            CredUiReturnCodes codes = CredUiReturnCodes.ERROR_INVALID_PARAMETER;

            if ((pszUserName.Length <= 0x201) && (pszPassword.Length <= 0x100))
            {
                codes = CredUIPromptForCredentials(ref structure, targetName, IntPtr.Zero, 0, pszUserName, 0x201, pszPassword, 0x100, ref pfSave, dwFlags);
            }
            if (codes == CredUiReturnCodes.NO_ERROR)
            {
                string str = null;
                if (pszUserName != null)
                {
                    str = pszUserName.ToString();
                }
                SecureString password = new SecureString();
                for (int i = 0; i < pszPassword.Length; i++)
                {
                    password.AppendChar(pszPassword[i]);
                    pszPassword[i] = '\0';
                }
                if (!string.IsNullOrEmpty(str))
                {
                    credential = new PSCredential(str, password);
                }
                else
                {
                    credential = null;
                }
            }
            else
            {
                credential = null;
            }
            return(credential);
        }
Example #46
0
 internal static PSCredential CredUIPromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options, IntPtr parentHWND)
 {
     if (string.IsNullOrEmpty(caption))
     {
         caption = CredUI.PromptForCredential_DefaultCaption;
     }
     if (string.IsNullOrEmpty(message))
     {
         message = CredUI.PromptForCredential_DefaultMessage;
     }
     if (caption.Length > 0x80)
     {
         throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, CredUI.PromptForCredential_InvalidCaption, new object[] { 0x80 }));
     }
     if (message.Length > 0x400)
     {
         throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, CredUI.PromptForCredential_InvalidMessage, new object[] { 0x400 }));
     }
     if ((userName != null) && (userName.Length > 0x201))
     {
         throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, CredUI.PromptForCredential_InvalidUserName, new object[] { 0x201 }));
     }
     CREDUI_INFO structure = new CREDUI_INFO {
         pszCaptionText = caption,
         pszMessageText = message
     };
     StringBuilder pszUserName = new StringBuilder(userName, 0x201);
     StringBuilder pszPassword = new StringBuilder(0x100);
     bool flag = false;
     int pfSave = Convert.ToInt32(flag);
     structure.cbSize = Marshal.SizeOf(structure);
     structure.hwndParent = parentHWND;
     CREDUI_FLAGS dwFlags = CREDUI_FLAGS.DO_NOT_PERSIST;
     if ((allowedCredentialTypes & PSCredentialTypes.Domain) != PSCredentialTypes.Domain)
     {
         dwFlags |= CREDUI_FLAGS.GENERIC_CREDENTIALS;
         if ((options & PSCredentialUIOptions.AlwaysPrompt) == PSCredentialUIOptions.AlwaysPrompt)
         {
             dwFlags |= CREDUI_FLAGS.ALWAYS_SHOW_UI;
         }
     }
     CredUIReturnCodes codes = CredUIReturnCodes.ERROR_INVALID_PARAMETER;
     if ((pszUserName.Length <= 0x201) && (pszPassword.Length <= 0x100))
     {
         codes = CredUIPromptForCredentials(ref structure, targetName, IntPtr.Zero, 0, pszUserName, 0x201, pszPassword, 0x100, ref pfSave, dwFlags);
     }
     if (codes == CredUIReturnCodes.NO_ERROR)
     {
         string str = null;
         if (pszUserName != null)
         {
             str = pszUserName.ToString();
         }
         str = str.TrimStart(new char[] { '\\' });
         SecureString password = new SecureString();
         for (int i = 0; i < pszPassword.Length; i++)
         {
             password.AppendChar(pszPassword[i]);
             pszPassword[i] = '\0';
         }
         if (!string.IsNullOrEmpty(str))
         {
             return new PSCredential(str, password);
         }
         return null;
     }
     return null;
 }
 public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
 {
     throw new NotImplementedException("PromptForCredential1 is not implemented.  The script is asking for input, which is a problem since there's no console.  Make sure the script can execute without prompting the user for input.");
 }
Example #48
0
		public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
		{
			PSCredential reply;
			string str;
			PowwaEvents.PowwaEVENT_DEBUG_LOG0("PromptForCredential(): Enter");
			try
			{
				if (string.IsNullOrEmpty(targetName))
				{
					bool flag = (allowedCredentialTypes & PSCredentialTypes.Domain) == PSCredentialTypes.Domain;
					string str1 = "PromptForCredential()";
					string str2 = "domainCredentials";
					if (flag)
					{
						str = "true";
					}
					else
					{
						str = "false";
					}
					PowwaEvents.PowwaEVENT_DEBUG_LOG1(str1, str2, str);
					MessageCreatedEventArgs messageCreatedEventArg = new MessageCreatedEventArgs(new PromptForCredentialMessage(caption, message, userName, flag), true);
					this.OnMessageCreated(messageCreatedEventArg);
					reply = (PSCredential)messageCreatedEventArg.Reply;
				}
				else
				{
					PowwaEvents.PowwaEVENT_DEBUG_LOG1("PromptForCredential(): Invalid Argument", "targetName", "null");
					throw new NotSupportedException(Resources.PromptForCredentialTargetNameNotSupported);
				}
			}
			finally
			{
				PowwaEvents.PowwaEVENT_DEBUG_LOG0("PromptForCredential(): Exit");
			}
			return reply;
		}
 /// <summary>
 /// Prompts the user for credentials by using a specified prompt window 
 /// caption, prompt message, user name and target name, credential types 
 /// allowed to be returned, and UI behavior options.
 /// </summary>
 /// <param name="caption">The caption of the message window.</param>
 /// <param name="message">The text of the message.</param>
 /// <param name="userName">The user name whose credential is to be prompted for.</param>
 /// <param name="targetName">The name of the target for which the credential is collected.</param>
 /// <param name="allowedCredentialTypes">PSCredentialTypes cconstants that identify the type of 
 /// credentials that can be returned.</param>
 /// <param name="options">A PSCredentialUIOptions constant that identifies the UI behavior 
 /// when it gathers the credentials.</param>
 /// <returns>Throws a NotImplementException exception.</returns>
 public override PSCredential PromptForCredential(
     string caption,
     string message,
     string userName,
     string targetName,
     PSCredentialTypes allowedCredentialTypes,
     PSCredentialUIOptions options)
 {
     if (string.IsNullOrEmpty(userName))
     {
         Log.DebugFormat("Prompting for username");
         var userPrompt = !string.IsNullOrEmpty(targetName)
                           ? string.Format("Enter username to use to log to {0}", targetName)
                           : "Enter username";
         _buffers.QueueOutCommand(OutCommand.CreatePrint(userPrompt));
         userName = ReadLine();
     }
     Log.DebugFormat("Prompting for password for {0} at {1}", userName, targetName);
     var passwordPrompt = !string.IsNullOrEmpty(targetName)
                              ? string.Format("Enter password for user {0} at {1}", userName, targetName)
                              : string.Format("Enter password for user {0}", userName);
     _buffers.QueueOutCommand(OutCommand.CreatePrint(passwordPrompt));
     var password = ReadLineAsSecureString();
     return new PSCredential(userName, password);
 }
Example #50
0
        public static PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
        {
            if (string.IsNullOrEmpty(caption))
            {
                caption = Res.Me + " Credential Request";
            }
            if (string.IsNullOrEmpty(message))
            {
                message = "Enter your credentials.";
            }
            CREDUI_INFO cREDUI_INFO = default(CREDUI_INFO);
            cREDUI_INFO.pszCaptionText = caption;
            cREDUI_INFO.pszMessageText = message;
            StringBuilder stringBuilder = new StringBuilder(userName, 513);
            StringBuilder stringBuilder2 = new StringBuilder(256);
            bool value = false;
            int num = Convert.ToInt32(value);
            cREDUI_INFO.cbSize = Marshal.SizeOf(cREDUI_INFO);
            cREDUI_INFO.hwndParent = Far.Api.UI.MainWindowHandle; //! works for conemu, too, but the effect is as if we use IntPtr.Zero
            CREDUI_FLAGS cREDUI_FLAGS = CREDUI_FLAGS.DO_NOT_PERSIST;
            if ((allowedCredentialTypes & PSCredentialTypes.Domain) != PSCredentialTypes.Domain)
            {
                cREDUI_FLAGS |= CREDUI_FLAGS.GENERIC_CREDENTIALS;
                if ((options & PSCredentialUIOptions.AlwaysPrompt) == PSCredentialUIOptions.AlwaysPrompt)
                {
                    cREDUI_FLAGS |= CREDUI_FLAGS.ALWAYS_SHOW_UI;
                }
            }
            CredUIReturnCodes credUIReturnCodes = CredUIReturnCodes.ERROR_INVALID_PARAMETER;
            if (stringBuilder.Length <= 513 && stringBuilder2.Length <= 256)
            {
                credUIReturnCodes = CredUIPromptForCredentials(ref cREDUI_INFO, targetName, IntPtr.Zero, 0, stringBuilder, 513, stringBuilder2, 256, ref num, cREDUI_FLAGS);
            }
            PSCredential pSCredential;
            if (credUIReturnCodes == CredUIReturnCodes.NO_ERROR)
            {
                string text = null;
                if (stringBuilder != null)
                {
                    text = stringBuilder.ToString();
                }
                SecureString secureString = new SecureString();
                for (int i = 0; i < stringBuilder2.Length; i++)
                {
                    secureString.AppendChar(stringBuilder2[i]);
                    stringBuilder2[i] = '\0';
                }
                if (!string.IsNullOrEmpty(text))
                {
                    pSCredential = new PSCredential(text, secureString);
                }
                else
                {
                    pSCredential = null;
                }
            }
            else
            {
                //if (credUIReturnCodes != CredUIReturnCodes.ERROR_CANCELLED)
                //    throw new InvalidOperationException("Getting credentials error: " + credUIReturnCodes);

                pSCredential = null;
            }
            return pSCredential;
        }
Example #51
0
        /// <summary>
        /// Prompts the user for credentials by using a specified prompt window caption, prompt message, user name and target name, credential types allowed to 
        /// be returned, and UI behavior options.
        /// </summary>
        /// <param name="caption">The caption for the message window.</param>
        /// <param name="message">The text of the message.</param>
        /// <param name="userName">The user name whose credential is to be prompted for.</param>
        /// <param name="targetName">The name of the target for which the credential is collected.</param>
        /// <param name="allowedCredentialTypes">A constant that identifies the type of credentials that can be returned.</param>
        /// <param name="options">A constant that identifies the UI behavior when it gathers the credentials.</param>
        /// <returns>The populated credentials that the user entered.</returns>
        public override PSCredential PromptForCredential(
			string caption, string message, string userName, string targetName,
			PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
        {
            throw new NotImplementedException("The method or operation is not implemented.");
        }
        public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
        {
            if (!string.IsNullOrWhiteSpace(caption)) this.Log().Warn(caption.escape_curly_braces());
            if (!string.IsNullOrWhiteSpace(message)) this.Log().Warn(ChocolateyLoggers.Important, message.escape_curly_braces());

            if (string.IsNullOrWhiteSpace(userName))
            {
                this.Log().Warn("Please provide username:"******"Please provide password:"******"A userName or password was not entered. This may result in future failures.");
            }

            return new PSCredential(userName, password.to_secure_string());
        }
Example #53
0
        internal static PSCredential CredUIPromptForCredential(
            string caption,
            string message,
            string userName,
            string targetName,
            PSCredentialTypes allowedCredentialTypes,
            PSCredentialUIOptions options,
            IntPtr parentHWND)
        {
            PSCredential cred = null;

            // From WinCred.h
            const int CRED_MAX_USERNAME_LENGTH      = (256 + 1 + 256);
            const int CRED_MAX_CREDENTIAL_BLOB_SIZE = 512;
            const int CRED_MAX_PASSWORD_LENGTH      = CRED_MAX_CREDENTIAL_BLOB_SIZE / 2;
            const int CREDUI_MAX_MESSAGE_LENGTH     = 1024;
            const int CREDUI_MAX_CAPTION_LENGTH     = 128;

            // Populate the UI text with defaults, if required
            if (string.IsNullOrEmpty(caption))
            {
                caption = CredUI.PromptForCredential_DefaultCaption;
            }

            if (string.IsNullOrEmpty(message))
            {
                message = CredUI.PromptForCredential_DefaultMessage;
            }

            if (caption.Length > CREDUI_MAX_CAPTION_LENGTH)
            {
                throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, CredUI.PromptForCredential_InvalidCaption, CREDUI_MAX_CAPTION_LENGTH));
            }

            if (message.Length > CREDUI_MAX_MESSAGE_LENGTH)
            {
                throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, CredUI.PromptForCredential_InvalidMessage, CREDUI_MAX_MESSAGE_LENGTH));
            }

            if (userName != null && userName.Length > CRED_MAX_USERNAME_LENGTH)
            {
                throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, CredUI.PromptForCredential_InvalidUserName, CRED_MAX_USERNAME_LENGTH));
            }

            CREDUI_INFO credUiInfo = new CREDUI_INFO();

            credUiInfo.pszCaptionText = caption;
            credUiInfo.pszMessageText = message;

            StringBuilder usernameBuilder = new StringBuilder(userName, CRED_MAX_USERNAME_LENGTH);
            StringBuilder passwordBuilder = new StringBuilder(CRED_MAX_PASSWORD_LENGTH);

            bool save            = false;
            int  saveCredentials = Convert.ToInt32(save);

            credUiInfo.cbSize     = Marshal.SizeOf(credUiInfo);
            credUiInfo.hwndParent = parentHWND;

            CREDUI_FLAGS flags = CREDUI_FLAGS.DO_NOT_PERSIST;

            // Set some of the flags if they have not requested a domain credential
            if ((allowedCredentialTypes & PSCredentialTypes.Domain) != PSCredentialTypes.Domain)
            {
                flags |= CREDUI_FLAGS.GENERIC_CREDENTIALS;

                // If they've asked to always prompt, do so.
                if ((options & PSCredentialUIOptions.AlwaysPrompt) == PSCredentialUIOptions.AlwaysPrompt)
                {
                    flags |= CREDUI_FLAGS.ALWAYS_SHOW_UI;
                }
            }

            // To prevent buffer overrun attack, only attempt call if buffer lengths are within bounds.
            CredUIReturnCodes result = CredUIReturnCodes.ERROR_INVALID_PARAMETER;

            if (usernameBuilder.Length <= CRED_MAX_USERNAME_LENGTH && passwordBuilder.Length <= CRED_MAX_PASSWORD_LENGTH)
            {
                result = CredUIPromptForCredentials(
                    ref credUiInfo,
                    targetName,
                    IntPtr.Zero,
                    0,
                    usernameBuilder,
                    CRED_MAX_USERNAME_LENGTH,
                    passwordBuilder,
                    CRED_MAX_PASSWORD_LENGTH,
                    ref saveCredentials,
                    flags);
            }

            if (result == CredUIReturnCodes.NO_ERROR)
            {
                // Extract the username
                string credentialUsername = null;
                if (usernameBuilder != null)
                {
                    credentialUsername = usernameBuilder.ToString();
                }

                // Trim the leading '\' from the username, which CredUI automatically adds
                // if you don't specify a domain.
                // This is a really common bug in V1 and V2, causing everybody to have to do
                // it themselves.
                // This could be a breaking change for hosts that do hard-coded hacking:
                // $cred.UserName.SubString(1, $cred.Username.Length - 1)
                // But that's OK, because they would have an even worse bug when you've
                // set the host (ConsolePrompting = true) configuration (which does not do this).
                credentialUsername = credentialUsername.TrimStart('\\');

                // Extract the password into a SecureString, zeroing out the memory
                // as soon as possible.
                SecureString password = new SecureString();
                for (int counter = 0; counter < passwordBuilder.Length; counter++)
                {
                    password.AppendChar(passwordBuilder[counter]);
                    passwordBuilder[counter] = (char)0;
                }

                if (!String.IsNullOrEmpty(credentialUsername))
                {
                    cred = new PSCredential(credentialUsername, password);
                }
                else
                {
                    cred = null;
                }
            }
            else // result is not CredUIReturnCodes.NO_ERROR
            {
                cred = null;
            }

            return(cred);
        }
 public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName,
     PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
 {
     return new PSCredential("*****@*****.**", new SecureString());
 }
Example #55
0
 public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
 {
     return(null);
 }
        /// <summary>
        /// Prompt for credentials.
        /// </summary>
        /// <param name="userName"> name of the user whose creds are to be prompted for. If set to null or empty string, the function will prompt for user name first. </param>
        /// 
        /// <param name="targetName"> name of the target for which creds are being collected </param>
        /// 
        /// <param name="message"> message to be displayed. </param>
        /// 
        /// <param name="caption"> caption for the message. </param>
        /// 
        /// <param name="allowedCredentialTypes"> what type of creds can be supplied by the user </param>
        /// 
        /// <param name="options"> options that control the cred gathering UI behavior </param>
        /// 
        /// <returns> PSCredential object, or null if input was cancelled (or if reading from stdin and stdin at EOF)</returns>
        ///

        public override PSCredential PromptForCredential(
            string caption,
            string message,
            string userName,
            string targetName,
            PSCredentialTypes allowedCredentialTypes,
            PSCredentialUIOptions options)
        {
            if (!PromptUsingConsole())
            {
                IntPtr mainWindowHandle = GetMainWindowHandle();
                return HostUtilities.CredUIPromptForCredential(caption, message, userName, targetName, allowedCredentialTypes, options, mainWindowHandle);
            }
            else
            {
                PSCredential cred = null;
                SecureString password = null;
                string userPrompt = null;
                string passwordPrompt = null;

                if (!string.IsNullOrEmpty(caption))
                {
                    // Should be a skin lookup

                    WriteLineToConsole();
                    WriteToConsole(PromptColor, RawUI.BackgroundColor, WrapToCurrentWindowWidth(caption));
                    WriteLineToConsole();
                }

                if (!string.IsNullOrEmpty(message))
                {
                    WriteLineToConsole(WrapToCurrentWindowWidth(message));
                }

                if (string.IsNullOrEmpty(userName))
                {
                    userPrompt = ConsoleHostUserInterfaceSecurityResources.PromptForCredential_User;

                    //
                    // need to prompt for user name first
                    //
                    do
                    {
                        WriteToConsole(userPrompt, true);
                        userName = ReadLine();
                        if (userName == null)
                        {
                            return null;
                        }
                    }
                    while (userName.Length == 0);
                }

                passwordPrompt = StringUtil.Format(ConsoleHostUserInterfaceSecurityResources.PromptForCredential_Password, userName
                );

                //
                // now, prompt for the password
                //
                WriteToConsole(passwordPrompt, true);
                password = ReadLineAsSecureString();
                if (password == null)
                {
                    return null;
                }
                WriteLineToConsole();

                cred = new PSCredential(userName, password);

                return cred;
            }
        }
Example #57
0
 public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
 {
     if (!InteractiveIO)
     {
         ThrowNotInteractiveException();
     }
     throw new NotImplementedException();
 }
        public override PSCredential PromptForCredential(string caption,
                                                         string message,
                                                         string userName,
                                                         string targetName,
                                                         PSCredentialTypes allowedCredentialTypes,
                                                         PSCredentialUIOptions options)
        {
            if (this.externalUi == null)
            {
                throw new InvalidOperationException();
            }

            PSCredential result = this.externalUi.PromptForCredential(caption,
                                                                       message,
                                                                       userName,
                                                                       targetName,
                                                                       allowedCredentialTypes,
                                                                       options);

            this.SendToSubscribers("CredentialPrompt", result);

            return result;
        }
        public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
        {
            PSCredential result = null;
            CREDUI_INFO  credui = new CREDUI_INFO();

            credui.pszCaptionText = caption;
            credui.pszMessageText = message;
            credui.cbSize         = Marshal.SizeOf(credui);
            uint   authPackage   = 0;
            IntPtr outCredBuffer = new IntPtr();
            uint   outCredSize;
            bool   save      = false;
            int    w32Result = CredUIPromptForWindowsCredentials(ref credui, 0, ref authPackage, IntPtr.Zero, 0, out outCredBuffer, out outCredSize, ref save, 1);

            int           maxLength   = 100;
            StringBuilder usernameBuf = new StringBuilder(maxLength);
            StringBuilder passwordBuf = new StringBuilder(maxLength);
            StringBuilder domainBuf   = new StringBuilder(maxLength);

            if (w32Result == 0)
            {
                if (CredUnPackAuthenticationBuffer(0, outCredBuffer, outCredSize, usernameBuf, ref maxLength, domainBuf, ref maxLength, passwordBuf, ref maxLength))
                {
                    CoTaskMemFree(outCredBuffer);

                    SecureString password = new SecureString();
                    foreach (char c in passwordBuf.ToString())
                    {
                        password.AppendChar(c);
                    }

                    string domainName = domainBuf.ToString();

                    if (domainName != null && domainName != string.Empty)
                    {
                        result = new PSCredential(string.Format("{0}\\{1}", domainName, usernameBuf.ToString()), password);
                    }
                    else
                    {
                        result = new PSCredential(usernameBuf.ToString(), password);
                    }
                }
            }

            return(result);
        }
Example #60
0
        public PSCredential PromptForCredentialInline(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes = PSCredentialTypes.Generic, PSCredentialUIOptions options = PSCredentialUIOptions.None)
        {
            Collection<FieldDescription> fields;

            // NOTE: I'm not sure this is the right action for the PromptForCredential targetName
            if (!String.IsNullOrEmpty(targetName))
            {
                caption = $"Credential for {targetName}\n\n{caption}";
            }

            if ((options & PSCredentialUIOptions.ReadOnlyUserName) == PSCredentialUIOptions.Default)
            {
                var user = new FieldDescription("User");
                user.SetParameterType(typeof(string));
                user.Label = "Username";
                user.DefaultValue = PSObject.AsPSObject(userName);
                user.IsMandatory = true;

                do
                {
                    fields = new Collection<FieldDescription>(new[] { user });
                    var username = new PromptForObjectEventArgs(caption, message, fields);
                    var login = OnPromptForObject(username);
                    userName = login["User"].BaseObject as string;
                } while (userName != null && userName.Length == 0);
            }

            // I think this is all I can do with the allowedCredentialTypes
            // domain required
            if (allowedCredentialTypes > PSCredentialTypes.Generic)
            {
                // and no domain
                if (userName != null && userName.IndexOfAny(new[] { '\\', '@' }) < 0)
                {
                    userName = $"{targetName}\\{userName}";
                }
            }

            var pass = new FieldDescription("Password");
            pass.SetParameterType(typeof(SecureString));
            pass.Label = "Password for " + userName;
            pass.IsMandatory = true;

            fields = new Collection<FieldDescription>(new[] { pass });
            var pwd = new PromptForObjectEventArgs(string.Empty, string.Empty, fields);
            var password = OnPromptForObject(pwd);

            // TODO: I'm not sure what to do with the PSCredentialUIOptions options, because PowerShell.exe ignores them
            return new PSCredential(userName, (SecureString)password["Password"].BaseObject);
        }