Beispiel #1
0
        /// <summary>
        /// Retrieves credentials from the OS store.
        /// </summary>
        /// <param name="target">The credential target.</param>
        /// <param name="username">The retrieved username.</param>
        /// <param name="password">The retrieved password.</param>
        /// <returns>Returns true if it successfully reads the OS credentials.</returns>
        private static bool ReadOSCredentials(string target, out string username, out string password)
        {
            username = string.Empty;
            password = string.Empty;

            if (string.IsNullOrEmpty(target))
            {
                return(false);
            }

            IntPtr credPtr       = IntPtr.Zero;
            IntPtr customCredPtr = IntPtr.Zero;

            try
            {
                bool queriedDomainPassword = false;
                bool readCredentials       = true;

                // Query the OS credential store.
                if (!ProxyNativeMethods.CredRead(
                        target,
                        ProxyNativeMethods.CRED_TYPE_GENERIC,
                        0,
                        out credPtr))
                {
                    readCredentials = false;

                    // Query for the DOMAIN_PASSWORD credential type to retrieve the
                    // credentials. CredUPromptForCredentials will store credentials
                    // as DOMAIN_PASSWORD credential type if it is not able to resolve
                    // the target using CredGetTargetInfo() function.
                    if (Marshal.GetLastWin32Error() == ProxyNativeMethods.ERROR_NOT_FOUND)
                    {
                        queriedDomainPassword = true;
                        // try queryiing for CRED_TYPE_DOMAIN_PASSWORD
                        if (ProxyNativeMethods.CredRead(
                                target,
                                ProxyNativeMethods.CRED_TYPE_DOMAIN_PASSWORD,
                                0,
                                out credPtr))
                        {
                            readCredentials = true;
                        }
                    }
                }

                if (readCredentials)
                {
                    // Get the native credentials if CredRead succeeds.
                    ProxyNativeMethods.NativeCredential nativeCredential = (ProxyNativeMethods.NativeCredential)Marshal.PtrToStructure(credPtr, typeof(ProxyNativeMethods.NativeCredential));
                    password = (nativeCredential.credentialBlob != IntPtr.Zero) ?
                               Marshal.PtrToStringUni(nativeCredential.credentialBlob, (int)(nativeCredential.credentialBlobSize / Marshal.SystemDefaultCharSize))
                                            : string.Empty;

                    username = nativeCredential.userName;

                    // If we retrieved the username using the credentials type as DOMAIN_PASSWORD, and
                    // we are not able to retrieve password, we query the GENERIC credentials to
                    // retrieve the password. Read comments in the ShowOSCredentialDialog() funtion
                    // for more details.
                    if (string.IsNullOrEmpty(password) && queriedDomainPassword)
                    {
                        // Read custom credentials.
                        if (ProxyNativeMethods.CredRead(
                                CreateCustomTarget(target),
                                ProxyNativeMethods.CRED_TYPE_GENERIC,
                                0,
                                out customCredPtr))
                        {
                            ProxyNativeMethods.NativeCredential customNativeCredential = (ProxyNativeMethods.NativeCredential)Marshal.PtrToStructure(customCredPtr, typeof(ProxyNativeMethods.NativeCredential));
                            if (string.Equals(username, customNativeCredential.userName, StringComparison.OrdinalIgnoreCase))
                            {
                                password = (customNativeCredential.credentialBlob != IntPtr.Zero) ?
                                           Marshal.PtrToStringUni(customNativeCredential.credentialBlob, (int)(customNativeCredential.credentialBlobSize / Marshal.SystemDefaultCharSize))
                                                        : string.Empty;
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                username = string.Empty;
                password = string.Empty;
            }
            finally
            {
                if (credPtr != IntPtr.Zero)
                {
                    ProxyNativeMethods.CredFree(credPtr);
                }

                if (customCredPtr != IntPtr.Zero)
                {
                    ProxyNativeMethods.CredFree(customCredPtr);
                }
            }

            bool successfullyReadCredentials = true;

            if (string.IsNullOrEmpty(username) ||
                string.IsNullOrEmpty(password))
            {
                username = string.Empty;
                password = string.Empty;
                successfullyReadCredentials = false;
            }

            return(successfullyReadCredentials);
        }
Beispiel #2
0
        //---------------------------------------------------------------------
        // private methods
        //---------------------------------------------------------------------


        /// <summary>
        /// This function calls the OS dialog to prompt user for credential.
        /// </summary>
        /// <param name="target">
        /// The credential target. It is displayed in the prompt dialog and is
        /// used for credential storage.
        /// </param>
        /// <param name="hwdOwner">The parent for the dialog.</param>
        /// <param name="userName">The username supplied by the user.</param>
        /// <param name="password">The password supplied by the user.</param>
        /// <returns>
        /// DialogResult.OK = if Successfully prompted user for credentials.
        /// DialogResult.Cancel = if user cancelled the prompt dialog.
        /// </returns>
        private static DialogResult ShowOSCredentialDialog(string target, IntPtr hwdOwner, out string userName, out string password)
        {
            DialogResult retValue;

            userName = string.Empty;
            password = string.Empty;

            string titleFormat       = SR.CredentialDialog_TitleFormat;
            string descriptionFormat = SR.CredentialDialog_DescriptionTextFormat;

            // Create the CREDUI_INFO structure.
            ProxyNativeMethods.CREDUI_INFO info = new ProxyNativeMethods.CREDUI_INFO();
            info.pszCaptionText      = string.Format(CultureInfo.CurrentUICulture, titleFormat, target);
            info.pszMessageText      = string.Format(CultureInfo.CurrentUICulture, descriptionFormat, target);
            info.hwndParentCERParent = hwdOwner;
            info.hbmBannerCERHandle  = IntPtr.Zero;
            info.cbSize = Marshal.SizeOf(info);

            // We do not use CREDUI_FLAGS_VALIDATE_USERNAME flag as it doesn't allow plain user
            // (one with no domain component). Instead we use CREDUI_FLAGS_COMPLETE_USERNAME.
            // It does some basic username validation (like doesnt allow two "\" in the user name.
            // It does adds the target to the username. For example, if user entered "foo" for
            // taget "bar.com", it will return username as "bar.com\foo". We trim out bar.com
            // while parsing the username. User can input "*****@*****.**" as workaround to provide
            // "bar.com\foo" as the username.
            // We specify CRED_TYPE_SERVER_CREDENTIAL flag as the stored credentials appear in the
            // "Control Panel->Stored Usernames and Password". It is how IE stores and retrieve
            // credentials. By using the CRED_TYPE_SERVER_CREDENTIAL flag allows IE and VS to
            // share credentials.
            // We dont specify the CREDUI_FLAGS_EXPECT_CONFIRMATION as the VS proxy service consumers
            // dont call back into the service to confirm that the call succeeded.
            ProxyNativeMethods.CREDUI_FLAGS flags = ProxyNativeMethods.CREDUI_FLAGS.SERVER_CREDENTIAL |
                                                    ProxyNativeMethods.CREDUI_FLAGS.SHOW_SAVE_CHECK_BOX |
                                                    ProxyNativeMethods.CREDUI_FLAGS.COMPLETE_USERNAME |
                                                    ProxyNativeMethods.CREDUI_FLAGS.EXCLUDE_CERTIFICATES;

            StringBuilder user            = new StringBuilder(Convert.ToInt32(ProxyNativeMethods.CREDUI_MAX_USERNAME_LENGTH));
            StringBuilder pwd             = new StringBuilder(Convert.ToInt32(ProxyNativeMethods.CREDUI_MAX_PASSWORD_LENGTH));
            int           saveCredentials = 0;
            // Ensures that CredUPPromptForCredentials results in a prompt.
            int netError = ProxyNativeMethods.ERROR_LOGON_FAILURE;

            // Call the OS API to prompt for credentials.
            ProxyNativeMethods.CredUIReturnCodes result = ProxyNativeMethods.CredUIPromptForCredentials(
                info,
                target,
                IntPtr.Zero,
                netError,
                user,
                ProxyNativeMethods.CREDUI_MAX_USERNAME_LENGTH,
                pwd,
                ProxyNativeMethods.CREDUI_MAX_PASSWORD_LENGTH,
                ref saveCredentials,
                flags);


            if (result == ProxyNativeMethods.CredUIReturnCodes.NO_ERROR)
            {
                userName = user.ToString();
                password = pwd.ToString();

                try
                {
                    if (Convert.ToBoolean(saveCredentials))
                    {
                        // Try reading the credentials back to ensure that we can read the stored credentials. If
                        // the CredUIPromptForCredentials() function is not able successfully call CredGetTargetInfo(),
                        // it will store credentials with credential type as DOMAIN_PASSWORD. For DOMAIN_PASSWORD
                        // credential type we can only retrive the user name. As a workaround, we store the credentials
                        // as credential type as GENERIC.
                        bool successfullyReadCredentials = ReadOSCredentials(target, out string storedUserName, out string storedPassword);
                        if (!successfullyReadCredentials ||
                            !string.Equals(userName, storedUserName, StringComparison.Ordinal) ||
                            !string.Equals(password, storedPassword, StringComparison.Ordinal))
                        {
                            // We are not able to retrieve the credentials. Try storing them as GENERIC credetails.

                            // Create the NativeCredential object.
                            ProxyNativeMethods.NativeCredential customCredential = new ProxyNativeMethods.NativeCredential();
                            customCredential.userName   = userName;
                            customCredential.type       = ProxyNativeMethods.CRED_TYPE_GENERIC;
                            customCredential.targetName = CreateCustomTarget(target);
                            // Store credentials across sessions.
                            customCredential.persist = (uint)ProxyNativeMethods.CRED_PERSIST.LOCAL_MACHINE;
                            if (!string.IsNullOrEmpty(password))
                            {
                                customCredential.credentialBlobSize = (uint)Marshal.SystemDefaultCharSize * ((uint)password.Length);
                                customCredential.credentialBlob     = Marshal.StringToCoTaskMemAuto(password);
                            }

                            try
                            {
                                ProxyNativeMethods.CredWrite(ref customCredential, 0);
                            }
                            finally
                            {
                                if (customCredential.credentialBlob != IntPtr.Zero)
                                {
                                    Marshal.FreeCoTaskMem(customCredential.credentialBlob);
                                }
                            }
                        }
                    }
                }
                catch
                {
                    // Ignore that failure to read back the credentials. We still have
                    // username and password to use in the current session.
                }

                retValue = DialogResult.OK;
            }
            else if (result == ProxyNativeMethods.CredUIReturnCodes.ERROR_CANCELLED)
            {
                retValue = DialogResult.Cancel;
            }
            else
            {
                Debug.Fail("CredUIPromptForCredentials failed with result = " + result.ToString());
                retValue = DialogResult.Cancel;
            }

            info.Dispose();
            return(retValue);
        }