Ejemplo n.º 1
0
        private void LoadUserDomainValues(StringBuilder principalName)
        {
            StringBuilder user   = new StringBuilder(Win32Native.CREDUI_MAX_USERNAME_LENGTH);
            StringBuilder domain = new StringBuilder(Win32Native.CREDUI_MAX_DOMAIN_TARGET_LENGTH);

            Win32Native.CredUIReturnCodes result = Win32Native.CredUIParseUserNameW(principalName.ToString(),
                                                                                    user, Win32Native.CREDUI_MAX_USERNAME_LENGTH, domain, Win32Native.CREDUI_MAX_DOMAIN_TARGET_LENGTH);

            if (result == Win32Native.CredUIReturnCodes.NO_ERROR)
            {
                User = user.ToString();
                if (User != "MiAdmin")
                {
                    Domain = domain.ToString();
                }
            }
            else
            {
                throw new InvalidOperationException(TranslateReturnCode(result));
                //User = principalName.ToString();
                //if (User != "MiAdmin")
                //    Domain = Environment.UserDomainName;
                //else
                //    Domain = string.Empty;
            }
        }
        protected override bool RunDialog(IntPtr hwndOwner)
        {
            if (Environment.OSVersion.Version.Major < 5)
            {
                throw new PlatformNotSupportedException("The Credential Management API requires Windows XP / Windows Server 2003 or later.");
            }

            Win32Native.CredUIInfo credInfo = new Win32Native.CredUIInfo(hwndOwner,
                                                                         this.caption, this.message, this.banner);
            StringBuilder usr = new StringBuilder(Win32Native.CREDUI_MAX_USERNAME_LENGTH);
            StringBuilder pwd = new StringBuilder(Win32Native.CREDUI_MAX_PASSWORD_LENGTH);

            if (!string.IsNullOrEmpty(this.User))
            {
                if (!string.IsNullOrEmpty(this.Domain))
                {
                    usr.Append(this.Domain + "\\");
                }
                usr.Append(this.User);
            }
            if (this.Password != null)
            {
                pwd.Append(this.PasswordToString());
            }

            try
            {
                Win32Native.CredUIReturnCodes result = Win32Native.CredUIPromptForCredentials(
                    ref credInfo, this.target,
                    IntPtr.Zero, 0,
                    usr, Win32Native.CREDUI_MAX_USERNAME_LENGTH,
                    pwd, Win32Native.CREDUI_MAX_PASSWORD_LENGTH,
                    ref this.saveChecked, this.flags);
                switch (result)
                {
                case Win32Native.CredUIReturnCodes.NO_ERROR:
                    LoadUserDomainValues(usr);
                    LoadPasswordValue(pwd);
                    return(true);

                case Win32Native.CredUIReturnCodes.ERROR_CANCELLED:
                    this.User     = null;
                    this.Password = null;
                    return(false);

                default:
                    throw new InvalidOperationException(TranslateReturnCode(result));
                }
            }
            finally
            {
                usr.Remove(0, usr.Length);
                pwd.Remove(0, pwd.Length);
                if (this.banner != null)
                {
                    Win32Native.DeleteObject(credInfo.hbmBanner);
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Do Not Use.
        /// </summary>
        /// <param name="hwndOwner">handle</param>
        /// <returns>bool</returns>
        protected override bool RunDialog(IntPtr hwndOwner)
        {
            Win32Native.CredUIInfo credInfo = new Win32Native.CredUIInfo(hwndOwner,
                                                                         this.caption, this.message, null);
            StringBuilder usr = new StringBuilder(Win32Native.CREDUI_MAX_USERNAME_LENGTH);
            StringBuilder pwd = new StringBuilder(Win32Native.CREDUI_MAX_PASSWORD_LENGTH);

            if (!string.IsNullOrEmpty(this.User))
            {
                usr.Append(this.User);
            }
            if (this.Password != null)
            {
                pwd.Append(this.PasswordAsString);
            }
            else
            {
                if (this.passwordIn != null)
                {
                    pwd.Append(this.passwordIn);
                }
            }

            try
            {
                Win32Native.CredUIReturnCodes result = Win32Native.CredUIPromptForCredentials(
                    ref credInfo, this.target,
                    IntPtr.Zero, 0,
                    usr, Win32Native.CREDUI_MAX_USERNAME_LENGTH,
                    pwd, Win32Native.CREDUI_MAX_PASSWORD_LENGTH,
                    ref this.saveChecked, this.flags);
                switch (result)
                {
                case Win32Native.CredUIReturnCodes.NO_ERROR:
                    LoadUserDomainValues(usr);
                    LoadPasswordValue(pwd);
                    return(true);

                case Win32Native.CredUIReturnCodes.ERROR_CANCELLED:
                    this.User     = null;
                    this.Password = null;
                    return(false);

                default:
                    throw new InvalidOperationException(TranslateReturnCode(result));
                }
            }
            finally
            {
                usr.Remove(0, usr.Length);
                pwd.Remove(0, pwd.Length);
            }
        }
        public void ConfirmCredentials(bool confirm)
        {
            new UIPermission(UIPermissionWindow.SafeSubWindows).Demand();

            Win32Native.CredUIReturnCodes result = Win32Native.CredUIConfirmCredentialsW(this.target, confirm);

            if (result != Win32Native.CredUIReturnCodes.NO_ERROR &&
                result != Win32Native.CredUIReturnCodes.ERROR_NOT_FOUND &&
                result != Win32Native.CredUIReturnCodes.ERROR_INVALID_PARAMETER)
            {
                throw new InvalidOperationException(TranslateReturnCode(result));
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// The ConfirmCredentials method is called after PromptForCredentials,
        /// to confirm the validity of the credential harvested.
        /// </summary>
        /// <remarks>
        /// After calling <see cref="PromptForCredentials()"/> and before calling <see cref="ConfirmCredentials(bool)"/>,
        /// the caller must determine whether or not the credentials are actually valid by
        /// using the credentials to access the resource specified by targetName.
        /// The results of that validation test are passed to <see cref="ConfirmCredentials(bool)"/> in the
        /// bConfirm parameter.
        /// </remarks>
        /// <param name="targetName">Contains the name of the target for the credentials, typically a domain or server application name.
        ///  This must be the same value passed as targetName to <see cref="PromptForCredentials()"/>.
        /// </param>
        /// <param name="confirm">Specifies whether the credentials returned from the prompt function are valid.
        /// If TRUE, the credentials are stored in the credential manager as defined by <see cref="PromptForCredentials()"/>.
        /// If FALSE, the credentials are not stored and various pieces of memory are cleaned up.
        /// </param>
        /// <permission cref="UIPermission">Demand for <see cref="UIPermissionWindow.SafeTopLevelWindows"/> permission.</permission>
        public static void ConfirmCredentials(string targetName, bool confirm)
        {
            if (targetName == null)
            {
                throw new ArgumentNullException("targetName");
            }

            new UIPermission(UIPermissionWindow.SafeTopLevelWindows).Demand();

            Win32Native.CredUIReturnCodes result = Win32Native.CredUIConfirmCredentialsW(targetName, confirm);

            if (result != Win32Native.CredUIReturnCodes.NO_ERROR &&
                result != Win32Native.CredUIReturnCodes.ERROR_NOT_FOUND)
            {
                throw new SecurityException(TranslateReturnCode(result));
            }
        }
        private void LoadUserDomainValues(StringBuilder principalName)
        {
            StringBuilder user   = new StringBuilder(Win32Native.CREDUI_MAX_USERNAME_LENGTH);
            StringBuilder domain = new StringBuilder(Win32Native.CREDUI_MAX_DOMAIN_TARGET_LENGTH);

            Win32Native.CredUIReturnCodes result = Win32Native.CredUIParseUserNameW(principalName.ToString(),
                                                                                    user, Win32Native.CREDUI_MAX_USERNAME_LENGTH, domain, Win32Native.CREDUI_MAX_DOMAIN_TARGET_LENGTH);

            if (result == Win32Native.CredUIReturnCodes.NO_ERROR)
            {
                this.User   = user.ToString();
                this.Domain = domain.ToString();
            }
            else
            {
                this.User   = principalName.ToString();
                this.Domain = Environment.MachineName;
            }
        }
Ejemplo n.º 7
0
 private static string TranslateReturnCode(Win32Native.CredUIReturnCodes result)
 {
     return(Resource.ResourceManager[Resource.MessageKey.CredUIReturn, result]);
 }
Ejemplo n.º 8
0
        /// <summary>
        /// This method creates and displays a configurable dialog box that accepts credentials information from a user.
        /// </summary>
        /// <param name="targetName">Contains the name of the target for the credentials,
        /// typically a server name. For distributed file system (DFS) connections,
        /// this string is of the form "servername\sharename".
        /// This parameter is used to identify Target Information when storing and retrieving credentials.
        /// </param>
        /// <param name="caption">String containing the title for the dialog box.</param>
        /// <param name="message">String containing a brief message to display in the dialog box.</param>
        /// <param name="owner">Specifies the handle to the parent window of the dialog box.
        /// If this member is NULL, the desktop will be the parent window of the dialog box.
        /// </param>
        /// <returns><see cref="SecureCredential"/> object with the supplied credentials.</returns>
        /// <permission cref="UIPermission">Demand for <see cref="UIPermissionWindow.SafeTopLevelWindows"/> permission.</permission>
        public static SecureCredential PromptForSecureCredentials(string targetName, string caption, string message, IntPtr owner)
        {
            // Parameter validation
            if (targetName == null)
            {
                throw new ArgumentNullException("targetName");
            }
            if (caption == null)
            {
                caption = String.Empty;
            }
            if (message == null)
            {
                message = String.Empty;
            }

            new UIPermission(UIPermissionWindow.SafeTopLevelWindows).Demand();

            // Uncommment this lines to use custom bitmap
            // Bitmap credBMP = new Bitmap(@"..\credui.bmp");
            // replace IntPtr.Zero by credBMP.GetHbitmap()
            Win32Native.CREDUI_INFO creditUI = new Win32Native.CREDUI_INFO(owner, caption, message, IntPtr.Zero);
            int saveCredentials = 0;

            StringBuilder user = new StringBuilder(Win32Native.MAX_USER_NAME);

            byte[]   pwd       = new byte[Win32Native.MAX_PASSWORD];
            GCHandle pwdHandle = GCHandle.Alloc(pwd, GCHandleType.Pinned);

            try
            {
                Win32Native.CredUiFlags flags = Win32Native.CredUiFlags.GENERIC_CREDENTIALS |
                                                Win32Native.CredUiFlags.SHOW_SAVE_CHECK_BOX |
                                                Win32Native.CredUiFlags.ALWAYS_SHOW_UI |
                                                Win32Native.CredUiFlags.EXPECT_CONFIRMATION |
                                                Win32Native.CredUiFlags.INCORRECT_PASSWORD;

                //For more info see:
                //http://msdn.microsoft.com/library/default.asp?url=/library/en-us/security/security/creduipromptforcredentials.asp
                //http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/dpapiusercredentials.asp?frame=true
                Win32Native.CredUIReturnCodes result = Win32Native.CredUIPromptForCredentialsW(
                    ref creditUI, targetName,
                    IntPtr.Zero, 0,
                    user, Win32Native.MAX_USER_NAME,
                    pwdHandle.AddrOfPinnedObject(), pwd.Length,
                    ref saveCredentials, flags);

                switch (result)
                {
                case Win32Native.CredUIReturnCodes.NO_ERROR:
                    StringBuilder usr    = new StringBuilder(Win32Native.MAX_USER_NAME);
                    StringBuilder domain = new StringBuilder(Win32Native.MAX_DOMAIN);
                    result = Win32Native.CredUIParseUserNameW(user.ToString(), usr, Win32Native.MAX_USER_NAME, domain, Win32Native.MAX_DOMAIN);
                    if (result == Win32Native.CredUIReturnCodes.NO_ERROR)
                    {
                        if (saveCredentials == 1)
                        {
                            ConfirmCredentials(targetName, true);
                        }
                        unsafe
                        {
                            return(new SecureCredential(usr.ToString(), (char *)pwdHandle.AddrOfPinnedObject().ToPointer(), Win32Native.lstrlenW(pwdHandle.AddrOfPinnedObject()), domain.ToString()));
                        }
                    }
                    else
                    {
                        throw new SecurityException(TranslateReturnCode(result));
                    }

                case Win32Native.CredUIReturnCodes.ERROR_CANCELLED:
                    return(null);

                default:
                    throw new SecurityException(TranslateReturnCode(result));
                }
            }
            finally
            {
                // Clear pwd data.
                Array.Clear(pwd, 0, pwd.Length);

                // Zero out the memory buffer
                Win32Native.ZeroMemory(pwdHandle.AddrOfPinnedObject(), (uint)pwd.Length);

                // Free the allocated handle
                if (pwdHandle.IsAllocated)
                {
                    pwdHandle.Free();
                }
            }
        }
 private static string TranslateReturnCode(Win32Native.CredUIReturnCodes result)
 {
     return(string.Format("Invalid operation: {0}", result.ToString()));
 }