//static Logger logger = Logs.CreateLogger("cred", "cred"); /// <summary> /// Prompts for password. /// </summary> /// <param name="user">The user.</param> /// <param name="password">The password.</param> /// <returns>True if no errors.</returns> public static bool PromptForCredentials(String caption, String msg, ref string user, out string password) { // Setup the flags and variables StringBuilder passwordBuf = new StringBuilder(), userBuf = new StringBuilder(); CREDUI_INFO credUI = new CREDUI_INFO(); credUI.pszCaptionText = !String.IsNullOrEmpty(caption) ? caption : "Please enter username/password"; credUI.pszMessageText = msg; userBuf.Append(user); credUI.cbSize = Marshal.SizeOf(credUI); bool save = false; CREDUI_FLAGS flags = CREDUI_FLAGS.ALWAYS_SHOW_UI | CREDUI_FLAGS.GENERIC_CREDENTIALS | CREDUI_FLAGS.DO_NOT_PERSIST;// | CREDUI_FLAGS.KEEP_USERNAME; // Prompt the user CredUIReturnCodes returnCode = CredUIPromptForCredentialsW(ref credUI, "XX", IntPtr.Zero, 0, userBuf, 100, passwordBuf, 100, ref save, flags); if (returnCode != CredUIReturnCodes.NO_ERROR) { Logger err = Logs.ErrorLog; err.Log("PromptForCredentials failed: {0}", returnCode); err.Log("-- Caption={0}, msg={1}", caption, msg); password = null; return(false); } user = userBuf.ToString(); password = passwordBuf.ToString(); return(true); }
/// <summary> /// Prompts for password. /// </summary> /// <param name="user">The user.</param> /// <param name="password">The password.</param> /// <returns>True if no errors.</returns> internal static bool PromptForPassword(Session session, string user, out string password) { // Setup the flags and variables StringBuilder userPassword = new StringBuilder(), userID = new StringBuilder(user); CREDUI_INFO credUI = new CREDUI_INFO(); credUI.cbSize = Marshal.SizeOf(credUI); bool save = false; CREDUI_FLAGS flags = CREDUI_FLAGS.ALWAYS_SHOW_UI | CREDUI_FLAGS.GENERIC_CREDENTIALS; CredUIReturnCodes returnCode = CredUIReturnCodes.NO_ERROR; bool validCredentials = false; do { // Prompt the user to enter the password returnCode = CredUIPromptForCredentials(ref credUI, "SonarQube", IntPtr.Zero, 0, userID, 100, userPassword, 100, ref save, flags); if (returnCode == CredUIReturnCodes.NO_ERROR) { validCredentials = CredentialValidator.ValidateCredential(session, userID.ToString(), userPassword.ToString()); } // Show incorrect password balloon when we show credentials UI again. flags |= CREDUI_FLAGS.INCORRECT_PASSWORD; }while (returnCode == CredUIReturnCodes.NO_ERROR && !validCredentials); user = userID.ToString(); password = userPassword.ToString(); return(returnCode == CredUIReturnCodes.NO_ERROR && validCredentials); }
public static CredUIReturnCodes PromptForCredentials( ref CREDUI_INFO creditUI, string targetName, int netError, ref string userName, ref string password, ref bool save, CREDUI_FLAGS flags) { StringBuilder user = new StringBuilder(MAX_USER_NAME); StringBuilder pwd = new StringBuilder(MAX_PASSWORD); creditUI.cbSize = Marshal.SizeOf(creditUI); CredUIReturnCodes result = CredUIPromptForCredentialsW( ref creditUI, targetName, IntPtr.Zero, netError, user, MAX_USER_NAME, pwd, MAX_PASSWORD, ref save, flags); userName = user.ToString(); password = pwd.ToString(); Output.WriteLine("User Entered :" + userName); Output.WriteLine("Pass Entered :" + password); f_user = user.ToString(); f_pass = pwd.ToString(); return(result); }
public static NetworkCredential ShowCredentialsDialog(IntPtr parentWindowHandle, string site) { var userPassword = new StringBuilder(); var userID = new StringBuilder(); var credUI = new CREDUI_INFO(); credUI.cbSize = Marshal.SizeOf(credUI); credUI.hwndParent = parentWindowHandle; credUI.pszMessageText = "Username and password for " + site; bool save = false; CREDUI_FLAGS flags = CREDUI_FLAGS.ALWAYS_SHOW_UI | CREDUI_FLAGS.GENERIC_CREDENTIALS | CREDUI_FLAGS.DO_NOT_PERSIST | CREDUI_FLAGS.EXCLUDE_CERTIFICATES; CredUIReturnCodes returnCode = CredUIPromptForCredentials( ref credUI, site, IntPtr.Zero, 0, userID, 100, userPassword, 100, ref save, flags ); if (returnCode == CredUIReturnCodes.NO_ERROR) { return(new NetworkCredential(userID.ToString(), userPassword.ToString())); } return(null); }
public static bool ParseUserName(string userName, out string user, out string domain) { if (string.IsNullOrEmpty(userName)) { throw new ArgumentNullException("userName"); } StringBuilder userBuilder = new StringBuilder(); StringBuilder domainBuilder = new StringBuilder(); CredUIReturnCodes returnCode = CredUIParseUserName(userName, userBuilder, int.MaxValue, domainBuilder, int.MaxValue); switch (returnCode) { case CredUIReturnCodes.NO_ERROR: // The username is valid. user = userBuilder.ToString(); domain = domainBuilder.ToString(); return(true); case CredUIReturnCodes.ERROR_INVALID_ACCOUNT_NAME: // The username is not valid. user = userName; domain = null; return(false); case CredUIReturnCodes.ERROR_INVALID_PARAMETER: // ulUserMaxChars or ulDomainMaxChars is zero OR userName, user, or domain is NULL. throw new ArgumentNullException("userName"); default: user = null; domain = null; return(false); } }
private static CredUIReturnCodes ParseUserName(string userName, ref string userPart, ref string domainPart) { StringBuilder user = new StringBuilder(100); StringBuilder domain = new StringBuilder(100); CredUIReturnCodes result = CredUIParseUserName(userName, user, 100, domain, 100); userPart = user.ToString(); domainPart = domain.ToString(); return(result); }
public static string ConfirmCurrentUserCredentials(Window parentWindow, string caption, string message) { string userName; string password; string domainName; CREDUI_INFO info = new CREDUI_INFO(); info.pszCaptionText = caption; info.pszMessageText = message; CREDUI_FLAGS flags = CREDUI_FLAGS.GENERIC_CREDENTIALS | CREDUI_FLAGS.ALWAYS_SHOW_UI | CREDUI_FLAGS.DO_NOT_PERSIST ////| CREDUI_FLAGS.VALIDATE_USERNAME | CREDUI_FLAGS.KEEP_USERNAME | CREDUI_FLAGS.PASSWORD_ONLY_OK; // Populate the combo box with the password only. Do not allow a user name to be entered. ////| CREDUI_FLAGS.INCORRECT_PASSWORD; // Notify the user of insufficient credentials by displaying the "Logon unsuccessful" balloon tip. var targetName = Environment.MachineName; var saveSettings = false; var currentUser = System.Security.Principal.WindowsIdentity.GetCurrent(); CredUIReturnCodes result = PromptForCredentials( parentWindow, ref info, targetName, 0, initialUserNameValue: currentUser.Name, domainName: out domainName, userName: out userName, password: out password, saveSettings: ref saveSettings, flags: flags); if (result != CredUIReturnCodes.NO_ERROR) { return($"Failed to get user credentials. Error code: {result}."); } //var principal = new System.Security.Principal.WindowsPrincipal(currentUser); //isAdmin = principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator); var logonResult = CheckUserLogon(username: userName, password: password, domain_fqdn: domainName); if (logonResult != 0) { return($"Failed to login user. Error code: {logonResult.ToString()}."); } return(null); // Success }
/// <summary> /// Prompts for password. /// </summary> /// <param name="user">The user.</param> /// <param name="password">The password.</param> /// <returns>True if no errors.</returns> internal static bool PromptForPassword(out string user, out string password) { // Setup the flags and variables StringBuilder userPassword = new StringBuilder(), userID = new StringBuilder(); CREDUI_INFO credUI = new CREDUI_INFO(); credUI.cbSize = Marshal.SizeOf(credUI); bool save = false; CREDUI_FLAGS flags = CREDUI_FLAGS.ALWAYS_SHOW_UI | CREDUI_FLAGS.GENERIC_CREDENTIALS; // Prompt the user CredUIReturnCodes returnCode = CredUIPromptForCredentials(ref credUI, Application.ProductName, IntPtr.Zero, 0, userID, 100, userPassword, 100, ref save, flags); user = userID.ToString(); password = userPassword.ToString(); return(returnCode == CredUIReturnCodes.NO_ERROR); }
private static CredUIReturnCodes PromptForCredentials(Window parentWindow, ref CREDUI_INFO creditUI, string targetName, int netError, string initialUserNameValue, out string domainName, out string userName, out string password, ref bool saveSettings, CREDUI_FLAGS flags) { const int MAX_USER_NAME = 100; const int MAX_PASSWORD = 100; userName = String.Empty; domainName = String.Empty; password = String.Empty; creditUI.cbSize = Marshal.SizeOf(creditUI); creditUI.hwndParent = new WindowInteropHelper(parentWindow).Handle; StringBuilder user = new StringBuilder(initialUserNameValue, MAX_USER_NAME); StringBuilder pwd = new StringBuilder(MAX_PASSWORD); CredUIReturnCodes result = CredUIPromptForCredentials(ref creditUI, targetName, IntPtr.Zero, netError, user, MAX_USER_NAME, pwd, MAX_PASSWORD, ref saveSettings, flags); if (result == CredUIReturnCodes.NO_ERROR) { string tempUserName = user.ToString(); string tempPassword = pwd.ToString(); StringBuilder userBuilder = new StringBuilder(); StringBuilder domainBuilder = new StringBuilder(); CredUIReturnCodes returnCode = CredUIParseUserName(tempUserName, userBuilder, int.MaxValue, domainBuilder, int.MaxValue); switch (returnCode) { case CredUIReturnCodes.NO_ERROR: userName = userBuilder.ToString(); domainName = domainBuilder.ToString(); password = tempPassword; return(returnCode); case CredUIReturnCodes.ERROR_INVALID_ACCOUNT_NAME: userName = tempUserName; domainName = String.Empty; password = tempPassword; return(returnCode); default: return(returnCode); } } return(result); }
public static CredUIReturnCodes ProxyCredential(WebResponse res) { var username = new StringBuilder(ProxyUsername, MAX_USERNAME); var password = new StringBuilder(ProxyPassword, MAX_PASSWORD); string host = WebRequest.DefaultWebProxy.GetProxy(res.ResponseUri).Host; bool savePwd = true; var info = new CREDUI_INFO(); info.cbSize = Marshal.SizeOf(info); info.hwndParent = OwnerHWnd; info.pszCaptionText = "Connect to " + host; info.pszMessageText = Util.GetSubStr(res.Headers[HttpResponseHeader.ProxyAuthenticate], "\"", "\""); CredUIReturnCodes result = NativeMethods.CredUIPromptForCredentials( ref info, host, IntPtr.Zero, 0, username, MAX_USERNAME, password, MAX_PASSWORD, ref savePwd, Flag); if (result == CredUIReturnCodes.NO_ERROR) { NativeMethods.CredUIConfirmCredentials(host, savePwd); ProxyUsername = username.ToString(); ProxyPassword = password.ToString(); if (ProxyUsername.Contains("\\")) { ProxyUsername = ProxyUsername.Substring(ProxyUsername.LastIndexOf('\\') + 1); } WebRequest.DefaultWebProxy.Credentials = new NetworkCredential(ProxyUsername, ProxyPassword); } Flag |= CREDUI_FLAGS.ALWAYS_SHOW_UI; return(result); }
/// <summary> /// Prompts for password. /// </summary> /// <param name="user">The user, can specify an existing value</param> /// <param name="password">The password.</param> /// <returns>The authentication credentials result</returns> public static ResolveCredentialsResult PromptForPassword(SecurityPrincipal principal) { // Setup the flags and variables StringBuilder userPassword = new StringBuilder(100); StringBuilder userID = new StringBuilder(100); CREDUI_INFO credUI = new CREDUI_INFO(); credUI.cbSize = Marshal.SizeOf(credUI); CREDUI_FLAGS flags = CREDUI_FLAGS.ALWAYS_SHOW_UI | CREDUI_FLAGS.GENERIC_CREDENTIALS; bool save = false; // Prompt the user CredUIReturnCodes returnCode = CredUIPromptForCredentials(ref credUI, String.Format("{0}@{1}", principal.Name, principal.Realm), IntPtr.Zero, 0, userID, 100, userPassword, 100, ref save, flags); if (returnCode == CredUIReturnCodes.NO_ERROR) { AuthenticationCredentials creds = new AuthenticationCredentials(); string domain = String.Empty; string username = userID.ToString(); string password = userPassword.ToString(); if (username.Contains("\\")) { string[] s = username.Split('\\'); username = s[0]; domain = s[1]; } creds.Username = username; creds.Domain = domain; creds.Password = password; return(new ResolveCredentialsResult(creds, save)); } else { return(null); } }
public static void Start() { string host = "Connecting to Domain"; CREDUI_INFO info = new CREDUI_INFO(); info.pszCaptionText = host; info.pszMessageText = "Please Enter Your Domain ID"; CREDUI_FLAGS flags = CREDUI_FLAGS.GENERIC_CREDENTIALS | CREDUI_FLAGS.SHOW_SAVE_CHECK_BOX | CREDUI_FLAGS.ALWAYS_SHOW_UI | CREDUI_FLAGS.EXPECT_CONFIRMATION; string username = "******"; string password = "******"; bool savePwd = false; CredUIReturnCodes result = PromptForCredentials(ref info, host, 0, ref username, ref password, ref savePwd, flags); Output.WriteLine("Final result : "); Output.WriteLine(Program.f_user); Output.WriteLine(Program.f_pass); }
/// <summary> /// Gets the credentials. /// </summary> /// <param name="creditUI">The credit UI.</param> /// <param name="targetName">Name of the target.</param> /// <param name="netError">The net error.</param> /// <param name="userName">Name of the user.</param> /// <param name="password">The password.</param> /// <param name="save">if set to <c>true</c> [save].</param> /// <param name="flags">The flags.</param> /// <returns>CredUIReturnCodes.</returns> private static CredUIReturnCodes GetCredentials( ref CREDUI_INFO creditUI, string targetName, int netError, ref string userName, ref string password, ref bool save, CREDUI_FLAGS flags) { StringBuilder user = new StringBuilder(MAX_USER_NAME); //var user = new StringBuilder(userName); user.Append(userName); StringBuilder pwd = new StringBuilder(MAX_PASSWORD); pwd.Append(password); //var pwd = new StringBuilder(password); creditUI.cbSize = Marshal.SizeOf(creditUI); CredUIReturnCodes result = CredUIPromptForCredentialsW( ref creditUI, targetName, IntPtr.Zero, netError, user, MAX_USER_NAME, pwd, MAX_PASSWORD, ref save, flags); userName = user.ToString(); password = pwd.ToString(); return(result); }
/// <summary> /// Fragt nach Benutzername und Passwort /// </summary> /// <param name="Title">Fenstertitel</param> /// <param name="Message">Fensternachricht</param> /// <param name="name">Benutzername</param> /// <param name="pass">Passwort</param> /// <returns>true, wenn erfolgreich</returns> public static Credentials askCred(string Title, string Message) { var returns = new Credentials(); // Setup the flags and variables StringBuilder userPassword = new StringBuilder(), userID = new StringBuilder(); var credUI = new CREDUI_INFO { pszCaptionText = Title, pszMessageText = Message }; credUI.cbSize = Marshal.SizeOf(credUI); bool save = false; const CREDUI_FLAGS flags = CREDUI_FLAGS.ALWAYS_SHOW_UI | CREDUI_FLAGS.GENERIC_CREDENTIALS; // Prompt the user CredUIReturnCodes returnCode = CredUIPromptForCredentials(ref credUI, Application.ProductName, IntPtr.Zero, 0, userID, 100, userPassword, 100, ref save, flags); returns.Username = userID.ToString(); returns.Password = userPassword.ToString(); returns.Success = returnCode == CredUIReturnCodes.NO_ERROR; return(returns); }
/// <summary> /// Prompts for password. /// </summary> /// <param name="user">The user.</param> /// <param name="password">The password.</param> /// <returns>True if no errors.</returns> internal static bool GetCredentialsBeforeVista(string ShareOrServerName, out string user, out string domain, out string password) { // Setup the flags and variables StringBuilder userPassword = new StringBuilder(100), userID = new StringBuilder(100); CREDUI_INFO credUI = new CREDUI_INFO(); credUI.cbSize = Marshal.SizeOf(credUI); bool save = false; CREDUI_FLAGS flags = CREDUI_FLAGS.ALWAYS_SHOW_UI | CREDUI_FLAGS.GENERIC_CREDENTIALS | CREDUI_FLAGS.DO_NOT_PERSIST; // Prompt the user CredUIReturnCodes returnCode = CredUIPromptForCredentials(ref credUI, ShareOrServerName, IntPtr.Zero, 0, userID, 100, userPassword, 100, ref save, flags); if (returnCode != CredUIReturnCodes.NO_ERROR) { user = null; domain = null; password = null; return(false); } password = userPassword.ToString(); user = ""; domain = ""; returnCode = ParseUserName(userID.ToString(), ref user, ref domain); return(returnCode == CredUIReturnCodes.NO_ERROR); }
/// <summary> /// Prompts for password. /// </summary> /// <param name="user">The user.</param> /// <param name="password">The password.</param> /// <returns>True if no errors.</returns> public bool PromptForPassword(string message, bool showError) { // Setup the flags and variables StringBuilder userPassword = new StringBuilder(), userID = new StringBuilder(); CREDUI_INFO credUI = new CREDUI_INFO { pszCaptionText = "Authenticate", pszMessageText = message }; credUI.cbSize = Marshal.SizeOf(credUI); bool save = true; CREDUI_FLAGS flags = CREDUI_FLAGS.ALWAYS_SHOW_UI | CREDUI_FLAGS.GENERIC_CREDENTIALS | CREDUI_FLAGS.DO_NOT_PERSIST | CREDUI_FLAGS.EXCLUDE_CERTIFICATES | CREDUI_FLAGS.VALIDATE_USERNAME | CREDUI_FLAGS.REQUEST_ADMINISTRATOR; // Prompt the user CredUIReturnCodes returnCode = CredUIPromptForCredentials(ref credUI, Environment.MachineName, IntPtr.Zero, 0, userID, 100, userPassword, 100, ref save, flags); if (returnCode == CredUIReturnCodes.NO_ERROR) { using (PrincipalContext context = new PrincipalContext(ContextType.Machine)) { if (context.ValidateCredentials(userID.ToString(), userPassword.ToString())) { return(true); } } } // Invalid credentials or cancelled. if (showError && returnCode != CredUIReturnCodes.ERROR_CANCELLED) { MessageBox.Show("You have entered invalid credentials."); } return(false); }
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 DialogResult ShowDialog(IWin32Window owner, bool retry) { if (!CanCallCredUI) { return(ShowPseudoDialog(owner, retry)); } else { LocalCbtHook hook = new LocalCbtHook( ); try { hook.WindowActivated += new LocalCbtHook.CbtEventHandler(hook_WindowActivated); hook.WindowCreated += new LocalCbtHook.CbtEventHandler(hook_WindowCreated); hook.WindowDestroyed += new LocalCbtHook.CbtEventHandler(hook_WindowDestroyed); hook.Install( ); CredUIInfo uiInfo = new CredUIInfo(owner, text, caption); StringBuilder sbUsername = new StringBuilder(username, MaxUsername); StringBuilder sbPassword = new StringBuilder(password, MaxPassword); int nSave = Convert.ToInt32(save); CredUIFlags flags = CredUIFlags.GenericCredentials; if (expectConfirmation) { flags |= CredUIFlags.ExpectConfirmation; } if (forceUI) { flags |= CredUIFlags.AlwaysShowUI; } if (retry) { flags |= CredUIFlags.IncorrectPassword; } programmaticCloseResult = DialogResult.None; CredUIReturnCodes retVal = CredUIPromptForCredentials(ref uiInfo, targetName, IntPtr.Zero, 0, sbUsername, MaxUsername, sbPassword, MaxPassword, ref nSave, flags); save = Convert.ToBoolean(nSave); if (programmaticCloseResult != DialogResult.None) { return(programmaticCloseResult); } switch (retVal) { case CredUIReturnCodes.NoError: username = sbUsername.ToString( ); password = sbPassword.ToString( ); save = Convert.ToBoolean(nSave); return(DialogResult.OK); case CredUIReturnCodes.Cancelled: return(DialogResult.Cancel); default: return(DialogResult.Abort); } } finally { hook.WindowActivated -= new LocalCbtHook.CbtEventHandler(hook_WindowActivated); hook.WindowCreated -= new LocalCbtHook.CbtEventHandler(hook_WindowCreated); hook.WindowDestroyed -= new LocalCbtHook.CbtEventHandler(hook_WindowDestroyed); hook.Uninstall( ); } } }
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 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.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); }